text:
Q: Why didn't Kirk mention Khan Noonien Singh when admonishing Dr. Korby? In the Star Trek episode "What Are Little Girls Made Of?" Kirk finds out that Dr. Korby wants to perfect humanity by replacing humans with androids. The two have the following exchange:

KORBY: What you saw was only a machine, only half of what I could've accomplished. Do you understand? By continuing the process I could've transferred you – your very consciousness – into that android. Your soul, if you wish. All of you. In android form, a human being can have practical immortality. Can you understand what I'm offering mankind?
KIRK: Programming. Different word, but the same old promises made by Genghis Khan, Julius Caesar, Hitler, Ferris, Maltuvis.

Why didn't Kirk mention Khan as part of this list? I'd assume that one of the most prominent figures of the Eugenics Wars – and one having been prominent more recently than the three non-fictional characters in the list – would be a prime example for Kirk, especially given how strongly characters associated with the Federation throughout the franchise react to ideas related to improving humanity through scientific augmentation – because of the Eugenics Wars.
Clearly, the character of Khan had not yet been invented by the time this episode was written, but I'm wondering if there's any in-universe explanation for this omission.

A: Kirk didn't know who Khan was until he met him,
...which occurred after the events of "TOS: What are Little Girls Made Of?" - Kirk had only a vague understanding of the events of the late 90's Eugenics Wars, none of the specifics relating to Khan. Kirk did not recognize Khan on sight, nor his name.
From the transcript of the episode "Space Seed":

KIRK: This Khan is not what I expected of a twentieth century man.
SPOCK: I note he's making considerable use of our technical library.
KIRK: Common courtesy, Mister Spock. He'll spend the rest of his days
  in our time. It's only decent to help him catch up. Would you estimate
  him to be a product of selective breeding?
SPOCK: There is that
  possibility, Captain. His age would be correct. In 1993, a group of
  these young supermen did seize power simultaneously in over forty
  nations.
KIRK: Well, they were hardly supermen. They were aggressive,
  arrogant. They began to battle among themselves.
SPOCK: Because the
  scientists overlooked one fact. Superior ability breeds superior
  ambition.
KIRK: Interesting, if true. They created a group of
  Alexanders, Napoleons.
SPOCK: I have collected some names and made
  some counts. By my estimate, there were some eighty or ninety of these
  young supermen unaccounted for when they were finally defeated.
KIRK: That fact isn't in the history texts.

Later, after Spock reviews the historical files, Kirk and the officers have a discussion about the history of Khan, seemingly after reading up on him, in which the officers seem to have some manner of understanding of the history, but clearly neither Kirk nor knew enough of Khan to recognize him on sight, which would seem to imply that Khan wasn't well known enough (or on the top of his mind) to categorize at the time w/ those other dictators)

A: Khan was no Kodos
In 2246 — twenty years before the events of TOS season one — thirteen-year-old James Kirk was on Tarsus IV when Governor Kodos ordered the deaths of four thousand people (half the population of the colony):

"The revolution is successful. But survival depends on drastic measures. Your continued existence represents a threat to the well-being of society. Your lives mean slow death to the more valued members of the colony. Therefore, I have no alternative but to sentence you to death. Your execution is so ordered, signed Kodos, Governor of Tarsus IV."
– Kodos, "The Conscience of the King" (TOS 1x12; 13th in order of production)

This childhood experience with the genocide of Tarsus IV's so-called less worthy population — and the resulting survivors' guilt — must have set the standard (in terms of deaths caused) for how the adult Kirk would evaluate tyrants.
Khan, compared to Kodos, apparently didn't cause that sort of harm on that scale:

"There were no massacres under [Khan's] rule."
— Scotty, "Space Seed" (TOS 1x24; 25th in order of production) ; quote from chakoteya.net transcript

"What Are Little Girls Made Of?" (TOS 1x09; 10th in order of production) may have been produced with Kirk's "The Conscience of the King" experience in mind; the two episodes were in development around the same time, much earlier than "Space Seed".

A: Korby made his mistake when he asked Kirk instead of just plopping them on the carosale & fabricating them.  Also, I can't imagine a mid-23rd century space-colony being so far out that Kodos couldn't wait for supplies.  Or at least place the "unproductive members" under cryogenic-freeze.


text:
Q: Uiimageview border is distroted with zigzag border? I am using UICollectionView in my iphone app and i have somwhat modified the uicollection view for horizinatcl rotation in circular way. following is the image.
Now what i am facing problem is why the border of this images is distroted with zigzaging border.
i don't know why this coming and for what reason. anyone knows how can i solve the distrotation of this images border.
any help would be appreciable..

A: Here's the code to create the image and imageview, add a border and round the corners:
// Define a new image object
  UIImage *image = [UIImage imageNamed:@"lake.png"];

// Define a new image view
  UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 157, 125)];

// Set image in imageview and add to view
  [imgView setImage:image];
  [[self view] addSubview:imgView];

// Create a white border with defined width
  imgView.layer.borderColor = [UIColor whiteColor].CGColor;
  imgView.layer.borderWidth = 1.5;

// Set image corner radius
  imgView.layer.cornerRadius = 5.0;

// To enable corners to be "clipped"
  [imgView setClipsToBounds:YES];

Hope this can help you.

A: Try something like this with your image
UIImage *image = [[UIImage imageNamed:[self.imgArray objectAtIndex:indexPath.row]] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];

If need, change UIEdgeInsets values...

A: Rasterization should fix this issue. https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CALayer_class/#//apple_ref/occ/instp/CALayer/shouldRasterize
imageView.layer.shouldRasterize = YES;
imageView.layer.rasterizationScale = [[UIScreen mainScreen] scale];

redpajama_set_name: RedPajamaStackExchange


text: Q: linq to sql throwsGlobal.System.Data.Linq.Mapping is not defined error Im using windows forms with vb code to link to my own server using linq to sql but when i generate the DataClass1.designer.vb i get errors  BC30002 Type 'Global.System.Data.Linq.Mapping.DatabaseAttribute' is not defined. im using net 6.0 as any othter net framework gives me form errors


text:
Q: MQTT message from server to client by bridge How to check, that client, connected by bridge really get messege from server.

A: You don't (at a MQTT protocol level).
There is no end to end delivery notification in MQTT, if you want to know if a message was delivered you will have to publish another message as an acknowledgement with some unique id from the original message.

A: MQTT has 3 components subscriber, broker, and producer.
Producer sends a data for a topic to broker
Broker forwards the same data to all the subscribers for that topic
Subscriber gets the data for the subscribed topic
In case you want to know the id of subscribers received the data, just create a Acknowledge topic and whoever received the data need to send its ID to Acknowledge Topic. Note this is only if you really want to know the Id's who has received the response.


text:
Q: Duplicates needed as well as latest date I am using SQL-Server Enterprise Version 8.0.
I have this query that's becoming incredibly complicated that is not giving me the results I need.  The query runs but I get no results with the addition of the latest date.
There are three main problems so far.
Basically, I need to find duplicate names in a database and identifying information about them.  Preferably, I'd like to put the duplicate name columns and addresses next to each other so it can be compared as many times as they appear in the database.  So, if a name is repeated 3 times in the database, I'd like for there to be a C1 name, C2 name and C3 name.
I'd also like to join other tables so I can get information such as child's name and what the latest activity (the subquery) on the client was.
Problem #1: The natural join is not working here in combination with the left outer joins. Do I need to use a union?
Problem #2: I am trying to get the Most Recent Activity.  While the Case..When works alone, when put in together with the rest of the query (minus the left outer joins) does not produce any results.  Ideally, I'd like the Most Recent Activity to be returned for each contact, C1 and C2 in the select.  I used the contactid but maybe that's not what I'm supposed to use?
Problem #3: If a name appears more than 2 times in the database, I'm getting all sorts of combinations for them in different rows.  How can I get them in the result list to appear as one row and not multiple combinations?  Do I need to add C3?  There as many as 7 and 8 duplicate names..how do I keep the query from becoming more cumbersome?  Are there any other ways to do this?
To provide an example, I'd like the results to appear as such:
'ContactID 1', 'ContactID 2', 'ContactID 3','Last Name', 'First Name', 'Contact 1 Address', 'Contact 2 Address', 'Contact 3 Address', 'C1 Home phone and Work phone', 'C2 Home phone and Work phone',
'C3 Home phone and Work phone', 'C1 Child's Name','C2 Child's Name', 'C3 Child's Name', 'C1 Most Recent Activity', 'C2 Most Recent Activity', 'C3 Most Recent Activity'
I would reduce the query to basics to keep it simple, but at this point, I don't know what to leave out.  Forgive the cumbersome query and I appreciate you taking the time:
SELECT DISTINCT (c1.contactid) as 'ContactID 1', (c2.contactid) as 'ContactID 2', c1.lastname as
  'Last Name', c1.firstname as 'First Name',
  (c1.address+' '+c1.city+', '+ c1.state +' '+ c1.postalcode) as 'Contact 1 Address',
  (c2.address+' '+c2.city+', '+ c2.state +' '+ c2.postalcode) as 'Contact 2 Address',
  (c1.homephone+' '+ c1.workphone) as 'C1 Home phone and Work phone',
  (c2.homephone+' '+ c2.workphone) as 'C2 Home phone and Work phone',
  (cg.childfirst+' ' +cg.childlast) as 'C1 Child''s Name',
  (cv.childfirst+ ' '+cv.childlast) as 'C2 Child''s Name'
FROM contacts c1, contacts c2
WHERE (c1.child=0) and (c1.contactid<c2.contactid) and ((c1.lastname + c1.firstname)=
  (c2.lastname + c2.firstname))
LEFT OUTER JOIN caregiverlabel cg on c1.contactid=cg.contactid,
  contacts c2
LEFT OUTER JOIN caregiverlabel cv on c2.contactid=cv.contactid
  AND c1.contactid IN
   (SELECT max(MostRecentActivity)
   FROM (select case
            WHEN c1.modifieddate >= sl.starttime AND c1.modifieddate >= cl.createdate
                    AND c1.modifieddate >= pr.created AND c1.modifieddate >= pm.created THEN
                    c1.modifieddate
                    WHEN sl.starttime >= c1.modifieddate AND sl.starttime >= cl.createdate AND
                    sl.starttime >= pr.created AND sl.starttime >= pm.created THEN sl.starttime
                    WHEN cl.createdate >= c1.modifieddate AND cl.createdate >= sl.starttime AND
                    cl.createdate >= pr.created AND cl.createdate >= pm.created THEN
                    cl.createdate
        WHEN pr.created >= c1.modifieddate AND pr.created >= sl.starttime AND
                    pr.created >= cl.createdate AND pr.created >= pm.created THEN pr.created
        WHEN pm.created >= c1.modifieddate AND pm.created >= sl.starttime AND
                    pm.created >= cl.createdate AND pm.created >= pr.created THEN pm.created
                    ELSE c1.modifieddate
            END AS MostRecentActivity
    FROM contacts c1
         left outer join serviceslabel sl on c1.contactid=sl.contactid
         left outer join calls cl on c1.contactid=cl.contactid
         left outer join procall pr on c1.contactid=pr.contactid
         left outer join pmpcall pm on c1.contactid=pm.contactid
) AS date_query
)
order by c1.lastname, c1.firstname

A: The query you post is too complex for us. Nobody will take the time to decypher it. However here is how you get all duplicate rows:
select *
from T
join (select col1, col2 from T group by col1, col2 having count(*) > 1) dups on T.col1 = dups.col1 and ...
The trick is to first find the duplicate "keys" and then find all rows which have one of the duplicate keys in them.


text:
Q: How to trim NULL address values in SQL I have a table (fairly standard) which has the following columns
ADDRESS1
ADDRESS2
ADDRESS3
ADDRESS4
POSTCODE

I would like some T-SQL that I can apply to remove NULL values and shift the values up (I'd like to avoid cursors and loops where possible)
So if my data is
ID  ADDRESS1  ADDRESS2  ADDRESS3  ADDRESS4  POSTCODE
-----------------------------------------------------
1  50 The Street  NULL  The Town  The City  AB12 3GG
2  100 Avenue  Townsville  NULL  Metropolis  SG33 5WW
3  My House  NULL  NULL  FutureCity  KL21 6TT

it becomes
ID  ADDRESS1  ADDRESS2  ADDRESS3  ADDRESS4  POSTCODE
-----------------------------------------------------
1  50 The Street  The Town  The City  NULL  AB12 3GG
2  100 Avenue  Townsville  Metropolis  NULL  SG33 5WW
3  My House  FutureCity  NULL  NULL  KL21 6TT

(ie: all non NULL values are shifted left yet the postcode remains static)
Many thanks

A: I think you need three update statements to shift from each column.
UPDATE YourTable
SET ADDRESS1 = ADDRESS2,
    ADDRESS2 = ADDRESS3,
    ADDRESS3 = ADDRESS4,
    ADDRESS4 = NULL
WHERE ADDRESS1 IS NULL

GO

UPDATE YourTable
SET ADDRESS2 = ADDRESS3,
    ADDRESS3 = ADDRESS4,
    ADDRESS4 = NULL
WHERE ADDRESS2 IS NULL

GO

UPDATE YourTable
SET ADDRESS3 = ADDRESS4,
    ADDRESS4 = NULL
WHERE ADDRESS3 IS NULL

GO

A: no problem, no loop or cursor is required,
use update from and every time check against value itself or above level
sample :  http://sqlfiddle.com/#!6/ba1cb/3

A: A solution provided by "Low Chee Mun" is almost correct. It is correct if only one address is null, but you have call the update statement 3 times like below(for case if 3 addresses are null).
update T
set ADDRESS1 = (case when ADDRESS1 is null then ADDRESS2 else ADDRESS1 end),
ADDRESS2 = (case when ADDRESS1 is null or ADDRESS2 is null then ADDRESS3 else ADDRESS2 end),
ADDRESS3 = (case when ADDRESS1 is null or ADDRESS2 is null or ADDRESS3 is null then ADDRESS4 else ADDRESS3 end),
ADDRESS4 = (case when ADDRESS1 is null or ADDRESS2 is null or ADDRESS3 is null or ADDRESS4 is null then null else ADDRESS4 end)
from ADDR T;

update T
set ADDRESS1 = (case when ADDRESS1 is null then ADDRESS2 else ADDRESS1 end),
ADDRESS2 = (case when ADDRESS1 is null or ADDRESS2 is null then ADDRESS3 else ADDRESS2 end),
ADDRESS3 = (case when ADDRESS1 is null or ADDRESS2 is null or ADDRESS3 is null then ADDRESS4 else ADDRESS3 end),
ADDRESS4 = (case when ADDRESS1 is null or ADDRESS2 is null or ADDRESS3 is null or ADDRESS4 is null then null else ADDRESS4 end)
from ADDR T;

update T
set ADDRESS1 = (case when ADDRESS1 is null then ADDRESS2 else ADDRESS1 end),
ADDRESS2 = (case when ADDRESS1 is null or ADDRESS2 is null then ADDRESS3 else ADDRESS2 end),
ADDRESS3 = (case when ADDRESS1 is null or ADDRESS2 is null or ADDRESS3 is null then ADDRESS4 else ADDRESS3 end),
ADDRESS4 = (case when ADDRESS1 is null or ADDRESS2 is null or ADDRESS3 is null or ADDRESS4 is null then null else ADDRESS4 end)
from ADDR T;


text:
Q: Calling an async function inside of a if/else statement - Javascript I wonder if I making any mistake here.
 let id;
    if (window.location.hash.slice(0, 1) === '#') {
      id = window.location.hash.slice(1);
      console.log(id);
      await model.loadRecipe(id);
    } else {
      id = window.location.hash.slice(0);
      await model.loadRecipe2(id);
    }

Only when the else statement is returned, i get the id 'undefined'.
Am i doing something wrong here?


text:
Q: Authentication for BandPage API I am trying to access the BandPage API using this script which I found on Github. I have very little experience with PHP so can't really figure out what is wrong with this. This is the script:
<?php

function bandpageToken($client_id,$shared_secret) {

        if($_COOKIE['bp_access_token']) {

                $access_token = $_COOKIE['bp_access_token'];

        } else {

                //set POST variables
                $url = 'https://api-read.bandpage.com/token';
                $fields = array(
                    'client_id' => $client_id,
                    'grant_type' => "client_credentials"
                );

                //open connection
                $ch = curl_init();

                //set the url, number of POST vars, POST data
                curl_setopt($ch,CURLOPT_URL, $url);
                curl_setopt($ch,CURLOPT_POST, count($fields));
                curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($fields));
                curl_setopt($ch,CURLOPT_USERPWD, $client_id . ':' . $shared_secret);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                //execute post
                $result = curl_exec($ch);

                $obj = json_decode($result);

                setcookie("bp_access_token", $obj->access_token, time()+$obj->expires_in-10);
                $access_token = $obj->access_token;

                //close connection
                curl_close($ch);

        }

        return $access_token;

}

$app_id = 'MyIdIsHere';
$client_id = 'clientIdIsHere';
$shared_secret = 'sharedSecerecIsHere';
$access_token = bandpageToken($client_id,$shared_secret);

?>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Bandpage Connect</title>

and the error seems to be with the bp_access_token, errors below.

Notice: Undefined index: bp_access_token in C:\wamp\www\Testing\index.php on line 5
Notice: Trying to get property of non-object in C:\wamp\www\Testing\index.php on line 33
Notice: Trying to get property of non-object in C:\wamp\www\Testing\index.php on line 34

Do I need to declare bp_access_token somewhere or am I missing something else?

A: add error_reporting(E_ALL ^ E_NOTICE);
just after <?php tag.
if your script is working perfectly but warning/notices are showing, you can add
error_reporting(0);
keep in mind to comment out this line as soon as you face some problem with this script next time.

A: The script hasn't been written very well. On line 5, an array access is made in the cookies array without first checking it exists. The author may have display_errors turned off, but not everyone does.
This:
if($_COOKIE['bp_access_token']) {

would be better expressed as:
if(isset($_COOKIE['bp_access_token']) && $_COOKIE['bp_access_token']) {

That will fix your first notice. As for the other two, you are making object accesses on null values in these lines:
setcookie("bp_access_token", $obj->access_token, time()+$obj->expires_in-10);
$access_token = $obj->access_token;

My guess would be that your authentication to BandPage has failed, and you don't have a valid response object to work with. Double-check the values of these in the script, which must be supplied by you:

*

*$app_id

*$client_id

*$shared_secret

You can probably get these from a control panel somewhere in your BandPage account screen.


text:
Q: Regex Ignore Proceeding Words I am trying to create a regex expression that starts with a certain word and ignores any other same proceeding words.
For example, if my string starts with the word "dog" and ends with "fish", how do I ignore any proceeding "dog" words and only match the last one?
dog cat fish
dog dog cat fish <- ignore first word "dog" and match second "dog" word.
dog dog dog cat fish <- ignore first and second "dog" words and match third "dog" word.

A: The following regex works:
(\b\w+\b |\b\w+\b$)(?!\1) with the m and g flags enabled
Demo: http://regex101.com/r/dW9fP5
As per your new request:
(\b\w+\b|\b\w+\b$)(?!\1) with the m and g flags enabled

A: To strip out space separated duplicates:
dog dog dog cat cat fish:
(?>(\w+) (?=\1\b))+
test at: regex101, eval.in (if php)
Using a lookahead to check if match of first parenthesized group is ahead (preceded by a space).

To match duplicates only at string start, add the ^ anchor at the beginning:
dog dog dog cat cat fish
^(?>(\w+) (?=\1\b))+
test at regex101

EDIT: Question has obviously changed to matching consecutive character sequences in one long string without spaces. Pattern modified a bit to strip out sequences of at least 3 characters at start:
dogdogdogcatcatfish
^(?>(\w{3,})(?=\1))+
test at regex101

Replace with empty string ""
Regex FAQ

A: Here's a simple (literal) pattern:
.*(dog)

Replace Pattern:
\1

Not the most exciting, but might as well show it. The target word in parentheses sets to match group \1
example: http://regex101.com/r/yU6xO8


text:
Q: How to remove excess arrows using commands? A friend and I were messing around with admin accounts and I spawned in too many arrows. We want our world back but don't know how to clear the arrows. We hosted in minehut and have a command window to run commands in. Any suggestions?

A: The command is if you shot the arrows:
kill @e[type=arrow]

And if you dropped arrow items you can clear all items with:
kill @e[type=item]

If you don't know which just run both.


text:
Q: Change tags in quill editor? I tried to look in the documentation but nothing explain how for example I could change the bold format to wrap text between text tag instead of text tag ?
var options = {
    modules: {
        placeholder: { text: attrs.rtePlaceholder, style: { color: '#A9A9A9' } }
    }
};
var quil = new Quill('#' + element.attr('id'), options);
var Normalizer = Quill.require('normalizer');
delete Normalizer.ALIASES["STRONG"];
Normalizer.ALIASES["B"] = "STRONG";
quil.addFormat('bold', { tag: 'STRONG', prepare: 'bold' });

A: Official support is still forthcoming but this should work for now:
var Normalizer = Quill.require('normalizer');
delete Normalizer.ALIASES["STRONG"];
Normalizer.ALIASES["B"] = "STRONG";
quill.addFormat('bold', { tag: 'STRONG', prepare: 'bold' });


text:
Q: How can I change dots by text in a slick slider? A codepen I found : https://codepen.io/norman_pixelkings/pen/NNbqgG
HTML:

CSS:
.slider {
 width: auto;
 margin: 30px 50px 50px;
}

.slick-slide {
 background: #cee5ea;
 color: white;
 padding: 20px 0;
 font-size: 30px;
 font-family: "Arial", "Helvetica";
 text-align: center;
}
.slick-slide img {
 display: inline-block;
}

.slick-prev:before,
.slick-next:before {
 color: black;
}

.slick-dots li {
 width: auto;
}

.pager__item {
 padding: 0 12px;
 display: block;
 border: 1px solid red;
}

.slick-dots {
 bottom: -40px;
}

.slick-slide:nth-child(odd) {
 background: #efdfda;
}

JS (jQuery):
$(".slider").slick({
dots: true,
            arrows: false,
            infinite: false,
            slidesToShow: 2,
            slidesToScroll: 2,
    customPaging : function(slider, i) {
        var title = $(slider.$slides[i]).data('title');
        return ' '+title+' ';
    }
});

How can I display the content of the data-title in HTML to replace the dots navigation?
I need to get the content of the data-title and display it the HTML.
Thanks :)

A: Your code works fine with 1.8.0 slick slider version. Doesn't work with 1.9.0 version.
But if you want to keep this version of Slick Slider, you can replace this line in your code :
var title = $(slider.$slides[i]).data('title');

by
var title = $(slider.$slides[i]).find('[data-title]').data('title');

Tested on your codepen and works.


text:
Q: How do you hide and show specific menu items based on a set cookie in 1.9 First off I have found this site SUPER helpful in the past dozen years for my days working with Oscommerce and now with Magento. So thanks to all the contributors to stackexchange.  I am only 6 months in with Magento now and want to do things the right way and not code around the features and proper methods in Magento.
Ok, so I know how to set a cookie for what I am doing I just need to know the best way to change a menu button.  Basically I am trying to accomplish the following.
Show a menu item which I currently have that says "Select Vehicle" and once selected I have it set a cookie already.  Here is the part I need help with. I would like to then have that same menu item show up as "Shop Now".   I think the best way is to make both buttons and have them do what I want them to do and then make one visable and the other not visable based on the cookie set?  Or is there a better way.  So far I have conformed to Magento by only messing with my theme and by adding CMS blocks and what not.  Obviously I could "hard code" this but I know this is bad in case of a future migration.  So yeah help me with ideas and approaches please to accomplish this.
Thanks in advance.


text:
Q: Which word(s) does "nuclear" modify in "by nuclear action or radiation or radioactive contamination" Is the word nuclear assumed after the "or" in the following sentence?
"by nuclear action or radiation or radioactive contamination"
In other words, does the or assume that the nuclear applies to radiation and radioactive contamination?

A: The phrase "by nuclear action or radiation or radioactive contamination" can be read in at least three possible ways:

"by nuclear action or [by] radiation or [by] radioactive contamination"

or

"by nuclear action or [nuclear] radiation or [by] radioactive contamination"

or

"by nuclear action or [by] radiation [contamination] or radioactive contamination"

The first interpretation treats the three phrases "nuclear action." "radiation," and "radioactive contamination" as interchangeable options—you could put them in any order, and each of the three would remain an independent option.
The second interpretation treats "nuclear action or radiation" as a nested pair that share the adjective nuclear. To move them apart in the sentence, you would have to make the word nuclear an explicit part of the second term, "nuclear radiation"; but at that point the three options would again be independent and interchangeable.
The third interpretation treats "radiation or radioactive contamination" as the nested pair, with contamination as their shared element. In this case to make the three terms interchangeable and independent, you'd have to change the second term to explicitly say "radiation contamination."
Less likely is the possibility that the adjective nuclear is supposed to attach to each of the three elements in the phrase, or that the noun contamination is supposed to apply to all three.
Unfortunately, the author has left every reader to try to figure out which combination the author had in mind. Obviously that's not a problem for readers who know enough about the subject to recognize what the author must have meant. But some readers won't be so lucky, and the author's failure to clarify (through additional punctuation or wording) precisely how he or she wanted readers to understand the phrase is directly responsible for their their difficulty.

A: The fragment does not reveal the answer directly.  There is a clue in the last two items.  "Radiation" and "radioactive contamination" refer two two separate ways an item can indicate "hot" on a meter.  The first occurs if object is exposed to a radioactive source and the second occurs if the object has been "dusted."
They are quite different with regard to decontamination.  From this I assume that the items in the sentence are completely separate and "nuclear" applies only to the first item.


text:
Q: Linking payables and general ledger in the database schema A December 13, 2010 a question was asked:

I am looking for industry standard logical data model of general ledger and accounts >payable. Are there any readily available accounting data models?

Ken Downs replied:
Excerpt:

The most basic ledger is 3 tables: Accounts, Batches, and Transactions. All transactions >must be in a batch. Some people make two columns for debit and credit, I always did one >column, with Debits and credits having opposite signs.
Payables is also very simple. At its heart is a table of vendors and a table of >vouchers/invoices. Finally a table of checks generated...After that, embellish to taste :)

Since both the invoice and check table would affect the general ledger, am I correct to assume each would need to store a unique batch number? Would the schema show a 1:1 relationship for the invoice:batch and checks:batch tables? Thank you so much for your advice.

A: There won't be any 1:1 relationships here.  You can always pay multiple invoices in a single batch, for example.  The idea of the batch table is that it is a single "unit of work" from an accounting perspective rather than from a programming perspective.
There is no special need for batch except that it is helpful for organizing information in terms of who did what and when - especially insofar as it provides an indication that a bunch of transactions are logically related to one-another from a business perspective.
Accounts is a lookup table.  Transactions is the transaction detail, as opposed to Batch which is the transaction header.  I agree with Ken Downs from the @OP's question that a single amount field is sufficient.  There is no point in separate debit and credit columns.  This idea comes from the paper accounting world and is useful from back in the day when all of the arithmetic was done by hand.  In a computerized scenario that idea is anachronistic and actually causes more trouble than it's worth.  I would disagree with Ken Downs insofar as his debits and credits having opposite signs.  This is true within the context of a particular account, but accounts of different types will have debits with either positive or negative amounts according to accounting conventions.  Assets and Revenues go in one direction and Liabilities and Expenses go in the other direction.  Whether a number is positive or negative in the transaction table will be a matter of which type of account the transaction applies to.
One of your edits will need to be that every batch should balance to zero when you apply debits and credits appropriately.  The logic for testing this edit needs to know whether each account in the the batch is an asset, liability, income or expense - so that needs to be an attribute of your account table.
As to checks, vouchers, invoices and all the rest - you probably want, but don't necessarily need all of that.  The reason to have them is not for the strict account balance tracking, but rather for all of the other indicative information that you can keep there.  You could keep all of this indicative information in a "dumb" text field on the batch table (i.e. "memo").  This is how they did it in the old tall chair, visor and quill days.  However, having a vendor invoice table is handy because it lets you do convenient things like querying for a list of all of the invoices from a particular vendor.  The same goes for other concrete business entities like cheques, invoices (receivables), statements, etc. etc.


text:
Q: How does the branch predictor know it has made a wrong guess? My question comes out of Mystical's answer. As I have understood, you have a branch instruction, it can either go to another instruction, say like, 0x123344 or it can continue executing.
If a branch predictor makes guess from either of them from past patterns, how does it realize it has made a mistake, and revert it?

A: This all comes from staged processors where portions of the CPU in the past remained idle, now we make use of every little piece as much as possible.  If there were no branching or conditional events this would be smooth, but now and then we need to change what's happening.
Thus as mentioned by Mystical the predictor makes a guess so that most of the time idle computing power isn't waiting.  The processor continues forward with what was guessed at, and when the previous instruction that was being waited on completes the predictor is compared to.  If it guessed right nothing happens, if it guessed wrong a signal is sent and the stages after the prediction point are thrown out and run again with the correct values.
How this is done at the technical level varies between architectures.  It isn't so much a reverting action so much as it invalidates everything that was computed after the incorrect prediction and those processes are redone.


text:
Q: Writing Dirichlet series in infinite product. In Serre's $A \, Course\, In \,Arithmetic$, it says the following:

$\sum\limits_{n=1}^{\infty}c(n)/n^s= \prod\limits_{p \,\rm prime}\frac{1}{1-c(p)p^{-s}+p^{2k-1-2s}}$
$\Longleftrightarrow$
$\left\{\begin{array}{ll}
c(m)c(n)=c(mn) && (m,n)=1 \\
c(p)c(p^n)=c(p^{n+1})+p^{2k-1}c(p^{n-1})&& p \,{\rm prime} \,{\rm and} \, n\geq 1,
\end{array}\right.$

${}$
It proves the $\Longleftarrow$ part in the book by $\sum\limits_{n=1}^{\infty}c(n)/n^s=\prod\limits_{p \, {\rm prime}}(\sum\limits_{n=0}^\infty{c(p^n)p^{-ns}})$, and expands  $(\sum\limits_{n=0}^\infty{c(p^n)p^{-ns}})(1-c(p)p^{-s}+p^{2k-1-2s})$ to get a power series in $p^{-s}$, and by relations of $c(mn), c(p^n)$ above, get it is equal to $c(1)=1$, hence $\prod\limits_{p \,\rm prime}(\sum\limits_{n=0}^\infty{c(p^n)p^{-ns}})({1-c(p)p^{-s}+p^{2k-1-2s}})=\prod\limits_{p \,\rm prime}1=1$, and the $\Longleftarrow$ part is done.
${}$
But the book doesn't prove the $\Longrightarrow$ part. In order for
$\sum\limits_{n=1}^{\infty}c(n)/n^s=\prod\limits_{p \, {\rm prime}}(\sum\limits_{n=0}^\infty{c(p^n)p^{-ns}})$ to be true, we must have $c(mn)=c(m)c(n)$ first, but this is the property to be proved, so how to prove the $\Longrightarrow$ part?

A: You start with a Dirichlet sum
$
\sum_{n\geq 1} \frac{c(n)}{n^s}
$
and get a product over primes: this is possible if the coefficients $c(n)$ are given by a multiplicative function (then $c(1)=1$), in other words it's an Euler product.
In general you can only say that
$$
\sum_{n\geq 1} \frac{c(n)}{n^s} =\prod_p\sum_{j\geq0}\frac{c(p^{js})}{p^{js}}\;.
$$
If the function $c$ is completely multiplicative, you get
$$
\prod_p\sum_{j\geq0}\frac{c(p^{js})}{p^{js}}=
\prod_p\sum_{j\geq0}\frac{c(p^{s})^j}{p^{js}}=\prod_p\frac1{1-c(p)p^{-s}}\;,
$$
as for the Dirichlet $L$-series, where $c(n)=\chi(n)$ is a Dirichlet character.
In Serre's example, you don't have this expression, so you can deduce that $c$ is only multiplicative but not completely multiplicative. Then you should focus on the expression for a single prime $p$, investigating the powers of such $p$ to prove the relation you want.


text:
Q: Draw text follow the path: how to snap text on one side of path? Illustration.
<text>
    <textPath xlink:href="#pseudo_c" startOffset="0%" style="font-family: Roboto Black; font-size: 2vw;">Sample text</textPath>
</text>

The problem is the text appears on both sides of the path if font-size is big enough and on inner side – if size is small, but I want to text will be on the single outer side.
How can I do this?
Generally, there are side property, but it doesn't work in my example (probably because it was made for closed shapes).


text:
Q: Trying to use ModalService. Getting "ModalService is undefined" error I have loaded jquery, bootstrap, angularjs and modalservice in the right order. I am getting the error: "ModalService is undefined". Even though the ModalService has loaded properly. Can someone please help me to understand what is wrong:

app.js:
var myApp=angular.module('App',['ngRoute','listApp']);
myApp.config(function($routeProvider) {
  $routeProvider
  .when('/', {
        templateUrl: 'list.html',
        controller: 'listCtrl'
    })
 .otherwise({
        templateUrl: 'list.html',
        controller: 'listCtrl'
    });
});

controllers.js:
var listApp=angular.module('listApp',['angularModalService']);
listApp.controller('listCtrl', ['$scope', function(scope,ModalService){
scope.show = function() {
ModalService.showModal({
 templateUrl: 'modal.html',
 controller: "ModalController"
}).then(function(modal) {
 modal.element.modal();
 modal.close.then(function(result) {
  scope.message = "You said " + result;
 });
});
};
}]);
listApp.controller('ModalController', function(scope, close) {
scope.close = function(result) {
close(result, 500);
};
});
index.html:
<link rel="stylesheet" href="css/bootstrap.css"/>
<link rel="stylesheet" href="css/index.css"/>

list.html:

Show a Modal

A: Inject Your Dependency properly.
In your Controller added "ModalService" Dependency.
listApp.controller('listCtrl', ["$scope", "ModalService", function(scope, ModalService){
}]);

Note:
I highly recommend to use angular ui-bootstrap for modal service instead of separate plugin. It Provide a lot of handy options parameter to configure modal according to your requirement.
https://angular-ui.github.io/bootstrap/#/modal
Hope This Helps!


text:
Q: How to change a text variable to a number variable. Tkinter, Python 2.7 I need help with changing "textvariable" to a int var. Here is my code:
from Tkinter import *

root = Tk()

strfname = IntVar()

strlname = IntVar()

labelf = Label(root, text = 'number').pack()
fname = Entry(root, justify='left', textvariable = strfname).pack()

labell = Label(root, text = 'number 2').pack()
lname = Entry(root, justify='left', textvariable = strlname).pack()

root.mainloop()

Thanks!

A: use .get
number_variable = strfname.get()


text:
Q: Recreate visreg() data ticks in border using ggplot() I would like to recreate the data ticks found in the border of visreg() logistic regression plots using ggplot().

I can get the data points plotted with geom_point(), but these are in the axis space, and I would like to get them in the border.

I've tried looking at the source code with getAnywhere() for the visreg() function but I can't see anything informative there. Any ideas?
A reproducible example:
library(ggplot2)
library(visreg)

y <- rep(c("0","1"), each = 50)
x <- c(rnorm(50,70,20),rnorm(50,30,20))
y <- as.numeric(y)
df <- data.frame(x,y)
glm1 <- glm(y~x, data = df, family = binomial)

visreg(glm1, type="conditional", scale = "response")

df$fit <- predict(glm1)
df$fit.response <- exp(df$fit)/(1+exp(df$fit))

# For simple ribbon
df$lower <- df$fit - predict(glm1, se.fit = TRUE)$se.fit
df$upper <- df$fit + predict(glm1, se.fit = TRUE)$se.fit
df$low.response <- exp(df$lower)/(1+exp(df$lower))
df$upp.response <- exp(df$upper)/(1+exp(df$upper))

ggplot(data = df, aes(x = x, y = fit.response))+
geom_ribbon(aes(x=x, ymin = low.response, ymax = upp.response), alpha = 0.3)+
geom_line(colour = "blue")+
geom_point(data = df, aes(x=x, y=y))+
theme_bw()

getAnywhere(visreg)


text:
Q: Using both multiboot and floppy with QEMU I am trying to develop an operating system. I have finished the Barebones tutorial from OSDev but still have some issues with multiboot.
As I understand, when I create a multiboot image following the tutorial, I have an ELF format binary file. This ELF executable is loaded into memory by QEMU when I specify the -kernel option. So I have a single executable program in memory and it has an entry point. It has some functions and libraries alongside it. There is nothing else in the memory. There is also no floppy or disk image from which I can read or write sectors. This is mainly because I haven't specified anything to QEMU in that regard.
However, what I want to achieve is after QEMU loads my ELF executable, I want to have a disk or floppy architecture from which I can read or write sectors. I also want to load some user programs from it or maybe set up a file system on it. So far, what I'm think is this:
qemu-system-i386 -kernel myKernel.bin -fda myDisk.image
Or maybe, I should take my myKernel.bin file, pad it with zeros until it is aligned to 512 bytes, then append the rest of the disk image to it.
My question is how can I achieve this functionality with QEMU. I need to know whether a task like this is possible before diving into writing a disk driver. If not possible, I can take a different approach but these are the ideas I have right now. I have already looked into -initrd and it isn't quite what I want. I also don't want to have any files loaded into the RAM by QEMU. Instead, I want to manipulate the disk image myself. Any suggestions on how to do that?

A: You don't need both a floppy image and a multiboot kernel, unless you've written some kind of loader. The -kernel flag works similarly to grub and it's much faster than loading from virtual media. This is how many linux kernel and driver devs test their code rather than creating a virtual media image every time.


text:
Q: Symfony Database-No connection could be made because the target machine actively refused it I'm following a guide online to make a registration form and when it comes to generating an entity called member I issue this command in the cmd:
php bin/console doctrine:generate:entity

All is good at this point. It then asks me to make the entity shortcut name. I call it AppBundle:User and it returns this error.
  [Doctrine\DBAL\Exception\ConnectionException]
  An exception occured in driver: SQLSTATE[HY000] [2002] No connection could
  be made because the target machine actively refused it.

  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[HY000] [2002] No connection could be made because the target
  machine actively refused it.

  [PDOException]
  SQLSTATE[HY000] [2002] No connection could be made because the target
  machine actively refused it.

This is my config.yml file
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }

# Put parameters here that don't need to change on each machine where the
app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    locale: en

framework:
    #esi: ~
    #translator: { fallbacks: ['%locale%'] }
    secret: '%secret%'
    router:
    resource: '%kernel.project_dir%/app/config/routing.yml'
    strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
#serializer: { enable_annotations: true }
templating:
    engines: ['twig']
default_locale: '%locale%'
trusted_hosts: ~
session:
    # https://symfony.com/doc/current/reference/configuration/framework.html#handler-id
    handler_id: session.handler.native_file
    save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'
fragments: ~
http_method_override: true
assets: ~
php_errors:
    log: true

# Twig Configuration
twig:
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
cache:  false

# Doctrine Configuration
doctrine:
dbal:
    driver: pdo_mysql
    host: '%database_host%'
    port: '%database_port%'
    dbname: '%database_name%'
    user: '%database_user%'
    password: '%database_password%'
    charset: UTF8
    # if using pdo_sqlite as your database driver:
    #   1. add the path in parameters.yml
    #     e.g. database_path: '%kernel.project_dir%/var/data/data.sqlite'
    #   2. Uncomment database_path in parameters.yml.dist
    #   3. Uncomment next line:
    #path: '%database_path%'

orm:
    auto_generate_proxy_classes: '%kernel.debug%'
    naming_strategy: doctrine.orm.naming_strategy.underscore
    auto_mapping: true

# Swiftmailer Configuration
swiftmailer:
transport: '%mailer_transport%'
host: '%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
spool: { type: memory }

And my parameter.yml file
# This file is auto-generated during the composer install
parameters:
database_host:     127.0.0.1
database_port:     ~
database_name:     some_db_name
database_user:     your_db_username
database_password: your_db_password
mailer_transport: smtp
mailer_host: 127.0.0.1
mailer_user: null
mailer_password: null
secret: ThisTokenIsNotSoSecretChangeIt

Any help would be appreciated thank you


text: Q: why is E(xx') the var-covar matrix in regression? In regression people often refer to the $X'X$ term as the estimate of $E(xx')$ which makes sense by the law of large numbers. However, people also refer to $E(xx')$ as the covariance matrix of $x$ which only seems to make sense if $E(x)=0$. Why does it makes sense if the $x$'s are not demeaned?


text:
Q: Where are the colours of bluej syntax highlighting defined? Where are the colours of the bluej editor syntax highlighting are defined, e.g. that /** comments are blue?

A: Open the directory where BlueJ is installed (depends on your OS and how you installed it).
From there, you should notice a "stylesheet" folder. In this folder, you will find CSS files. The one that you seem to look for is "java-colors.css".


text:
Q: Iframe with popup to center on parent frame Basically all I want to do is have the modal popup from within the iframe to center on the entire page instead of just the iframe... How can I do this?

A: You cannot do this easily.  Elements that exist in the IFrame are bound to the IFrame.
I would suggest making the modal a part of the Parent and not a part of the IFrame

A: short answer: you can't
long answer: if both documents are on the same domain in the same zone, you can call back from the iframe to the parent document and have IT initiate the popup but this will ONLY work on same domain/zone using parent.document


text:
Q: Hiding "Enter PIN" screen from Windows mobile With Windows mobile 6.1, how do you remove/hide the "Enter PIN" screen?
I need to unlock the sim programmatically, which is working fine, but I'm having problems hiding the "Enter PIN" screen. I need to hide it because I don't want users to try and guess the pin, thereby blocking the sim card.


text:
Q: Vue Listening to an event  <router-view @loggedIn="changed"></router-view>

Hi , I just need to know what is @loggedIn in this context of vue js. I can't seem to find this syntax in the documentation. Is this a custom event of loggedIn which calls the changed method?

A: @ is a shorthand for v-on. See here https://v2.vuejs.org/v2/guide/syntax.html#v-on-Shorthand
In your markup it means that you listen to event loggedIn emited from router-view and use method changed as handler of event


text:
Q: Is there a way to get location in C# other than GeoCoordinate Watcher? I am trying to implement a current location method in my app for ESRI ArcGIS it requires getting current latitude and longitude so i used geo coordinate watcher for it unfortunately i got system.device doesn't exist , i tried to rectify it but did not work also i know in unity we can use something like input.location.lastData.longitude and so on can we do the same thing here? I need an alternative if possible

A: I haven't been able to find any answer but there is a solution that closely matches my requirements basically i only needed latitude and longitude in ArcGIS maps so i could initialize the buffer at the point but i have taken care of it with this tutorial.
Device Location Display in ArcGIS


text:
Q: Maximizing linear equation with integer
If I have a linear equation like
$$ c_1x_1 + c_2x_2 + ... + c_nx_n = m \leq M $$
with the constraint $x_i \in \mathbb{N}$ for $0 \le i \le n$,
  where $M$ and the $c_i$ are constants, and where the $c_i$ are
  rational, how do I maximize $m$?

A friend suggested looking at the least squares method, which I didn't really understand, or possibly at trying to find the least common multiple of a subset of the $c_i$ values and checking if that divides M, but that's a little more trial-and-error than I'm hoping for.
Note: I apologize if this has been answered elsewhere; I didn't see any solutions that matched this problem but I also didn't really know how to search for it.

A: Knowing your $\mathbb{N}$ does contain the zero, you can model this problem as integer linear program
$$
\max_{x \in \mathbb{Z}^n} \left\{ c^\top x \mid A x \le b , x \ge 0\right\}
$$
where $A = c^\top \in \mathbb{R}^{1 \times n}$ and $b = M \in \mathbb{R}^1$.
For an actual calculation, your could try standard software like lpsolve.


text:
Q: Apache beam stops to process PubSub messages after some time I'm trying to write a simple Apache Beam pipeline (which will run on the Dataflow runner) to do the following:

*

*Read PubSub messages containing file paths on GCS from a subscription.

*For each message, read the data contained in the file associated with the message (the files can be of a variery of formats (csv, jsonl, json, xml, ...)).

*Do some processing on each record.

*Write back the result on GCS.

I'm using a 10 seconds fixed window on the messages. Since incoming files are already chunked (max size of 10MB) I decided not to use splittable do functions to read the files, in order to avoid adding useless complexity (especially for files that are not trivially splittable in chunks).
Here is a simplified code sample that gives the exact same problem of the full one:
package skytv.ingester

import java.io.{BufferedReader, InputStreamReader}
import java.nio.charset.StandardCharsets

import kantan.csv.rfc
import org.apache.beam.sdk.Pipeline
import org.apache.beam.sdk.io.{Compression, FileIO, FileSystems, TextIO, WriteFilesResult}
import org.apache.beam.sdk.io.gcp.pubsub.{PubsubIO, PubsubMessage}
import org.apache.beam.sdk.options.PipelineOptionsFactory
import org.apache.beam.sdk.transforms.DoFn.ProcessElement
import org.apache.beam.sdk.transforms.windowing.{BoundedWindow, FixedWindows, PaneInfo, Window}
import org.apache.beam.sdk.transforms.{Contextful, DoFn, MapElements, PTransform, ParDo, SerializableFunction, SimpleFunction, WithTimestamps}
import org.apache.beam.sdk.values.{KV, PCollection}
import org.joda.time.{Duration, Instant}
import skytv.cloudstorage.CloudStorageClient
import skytv.common.Closeable
import kantan.csv.ops._
import org.apache.beam.sdk.io.FileIO.{Sink, Write}

class FileReader extends DoFn[String, List[String]] {

  private def getFileReader(filePath: String) = {
    val cloudStorageClient = new CloudStorageClient()
    val inputStream = cloudStorageClient.getInputStream(filePath)
    val isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8)
    new BufferedReader(isr)
  }

  private def getRowsIterator(fileReader: BufferedReader) = {
    fileReader
      .asUnsafeCsvReader[Seq[String]](rfc
        .withCellSeparator(',')
        .withoutHeader
        .withQuote('"'))
      .toIterator
  }

  @ProcessElement
  def processElement(c: ProcessContext): Unit = {
    val filePath = c.element()

    Closeable.tryWithResources(
      getFileReader(filePath)
    ) {
      fileReader => {

        getRowsIterator(fileReader)
          .foreach(record => c.output(record.toList))

      }
    }

  }
}

class DataWriter(tempFolder: String) extends PTransform[PCollection[List[String]], WriteFilesResult[String]] {

  private val convertRecord = Contextful.fn[List[String], String]((dr: List[String]) => {
    dr.mkString(",")
  })

  private val getSink = Contextful.fn[String, Sink[String]]((destinationKey: String) => {
    TextIO.sink()
  })

  private val getPartitioningKey = new SerializableFunction[List[String], String] {
    override def apply(input: List[String]): String = {
      input.head
    }
  }

  private val getNaming = Contextful.fn[String, Write.FileNaming]((destinationKey: String) => {
    new Write.FileNaming {
      override def getFilename(
                                window: BoundedWindow,
                                pane: PaneInfo,
                                numShards: Int,
                                shardIndex: Int,
                                compression: Compression
                              ): String = {
        s"$destinationKey-${window.maxTimestamp()}-${pane.getIndex}.csv"
      }
    }
  })

  override def expand(input: PCollection[List[String]]): WriteFilesResult[String] = {
    val fileWritingTransform = FileIO
      .writeDynamic[String, List[String]]()
      .by(getPartitioningKey)
      .withDestinationCoder(input.getPipeline.getCoderRegistry.getCoder(classOf[String]))
      .withTempDirectory(tempFolder)
      .via(convertRecord, getSink)
      .withNaming(getNaming)
      .withNumShards(1)

    input
      .apply("WriteToAvro", fileWritingTransform)
  }

}

object EnhancedIngesterScalaSimplified {

  private val SUBSCRIPTION_NAME = "projects/<project>/subscriptions/<subscription>"
  private val TMP_LOCATION = "gs://<path>"

  private val WINDOW_SIZE = Duration.standardSeconds(10)

  def main(args: Array[String]): Unit = {

    val options = PipelineOptionsFactory.fromArgs(args: _*).withValidation().create()

    FileSystems.setDefaultPipelineOptions(options)

    val p = Pipeline.create(options)

    val messages = p
      .apply("ReadMessages", PubsubIO.readMessagesWithAttributes.fromSubscription(SUBSCRIPTION_NAME))
//      .apply("AddProcessingTimeTimestamp", WithTimestamps.of(new SerializableFunction[PubsubMessage, Instant] {
//        override def apply(input: PubsubMessage): Instant = Instant.now()
//      }))

    val parsedMessages = messages
      .apply("ApplyWindow", Window.into[PubsubMessage](FixedWindows.of(WINDOW_SIZE)))
      .apply("ParseMessages", MapElements.via(new SimpleFunction[PubsubMessage, String]() {
        override def apply(msg: PubsubMessage): String = new String(msg.getPayload, StandardCharsets.UTF_8)
      }))

    val dataReadResult = parsedMessages
      .apply("ReadData", ParDo.of(new FileReader))

    val writerResult = dataReadResult.apply(
      "WriteData",
      new DataWriter(TMP_LOCATION)
    )

    writerResult.getPerDestinationOutputFilenames.apply(
      "FilesWritten",
      MapElements.via(new SimpleFunction[KV[String, String], String]() {
      override def apply(input: KV[String, String]): String = {
        println(s"Written ${input.getKey}, ${input.getValue}")
        input.getValue
      }
    }))

    p.run.waitUntilFinish()
  }
}

The problem is that after the processing of some messages (in the order of 1000), the job stops processing new messages and they remain in the PubSub subscription unacknowledged forever.
I saw that in such a situation the watermark stops to advance and the data freshness linearly increases indefinitely.
Here is a screenshot from dataflow:

And here the situation on the PubSub queue:

Is it possible that there are some messages that remain stuck in the dataflow queues filling them so that no new messages can be added?
I thought that there was some problem on how timestamps are computed by the PubsubIO, so I tried to force the timestamps to be equal to the processing time of each message, but I had no success.
If I leave the dataflow job in this state, it seems that it continuously reprocesses the same messages without writing any data to storage.
Do you have any idea on how to solve this problem?
Thanks!

A: Most likely the pipeline has encountered an error while processing one(or more) elements in the pipeline (and it shouldn't have anything to do with how timestamps are computed by the PubsubIO), which stops the watermark from advancing since the failed work will be retried again and again on dataflow.
You can check if there's any failure from the log, specifically from worker or harness component. If there's an unhandled runtime exception such as parse error etc, it is very likely being the root cause of a streaming pipeline getting stuck.
If there's no UserCodeException then it is likely some other issue caused by dataflow backend and you can reach out to Dataflow customer support so engineers can look into the backend issue for your pipeline.


text:
Q: javascript loop only applying to every other element i have the following javascript below after i finish an ajax query
all of my images have name="pic"
<script type="text/javascript">
 function done() {
     var e = document.getElementsByName("pic");
     alert(e.length);
     for (var i = 0; i < e.length; i++) {
         cvi_instant.add(e[i], { shadow: 75, shade: 10 });
     }
 }

my goal is to apply an image border around using this library:
http://www.netzgesta.de/instant/
the problem is that for some reason this works but it only seem to apply to every other picture instead of every one.  any clue why the code above would skip every other element??
EDIT: I added an alert in the loop and it does correctly go 0, 1,2,3,4,5,6 . .
     for (var i = 0; i < e.length; i++)
     {
         alert(i);
         cvi_instant.add(e[i], { shadow: 75, shade: 10 });
     }

A:
it only seem to apply to every other picture instead of every one

That's a classic sign of destructive iteration.
Consider what happens if, as I'm guessing, the function cvi_instant.add replaces the element named pic with some other element or elements.
getElementsByName returns a 'live' NodeList: it is kept up to date every time you make a change to the DOM. So if it had five elements before, after your call to cvi_instant.add it now contains only four: the first node is gone and nodes 1–4 have moved down to positions 0–3.
Now you go around the loop again. i++, so we're looking at element 1. But element 1 is now what was originally element 2! We skipped the original element 1, and we will continue skipping every other element until we reach the end of the (now half as long) list.
Altering a list at the same time as iterating it causes this kind of problem. If the process inside the iteration actually adds elements to the list you can even get an infinite loop!
The quick fix is to iterate the loop backwards. Now you do the last element first, leaving all the other elements in their original positions and causing no skipping:
 var e= document.getElementsByName("pic");
 for (var i= e.length; i-->0;) {
     cvi_instant.add(e[i], { shadow: 75, shade: 10 });
 }

Another simple solution if you know you're always going to be removing the element from the list on each call is:
 var e= document.getElementsByName("pic");
 while (e.length>0) {
     cvi_instant.add(e[0], { shadow: 75, shade: 10 });
 }

The most general solution is needed when your loop body can do anything to the list, such as inserting new elements named pic at the start of the document or removing other elements from the middle. It is slightly slower but always safe to make a static copy of the list to work from:
 function Array_fromList(l) {
     var a= [];
     for (var i= 0; i<l.length; i++)
         a.push(l[i]);
     return a;
 }

 var e= Array_fromList(document.getElementsByName("pic"));
 for (var i= 0; i<e.length; i++) {
     cvi_instant.add(e[i], { shadow: 75, shade: 10 });
 }

A: My guess is that cvi_instant.add() is doing some incrementing or iteration on the values passed to it. Try doing this instead - it's easier, and I believe it will fix your problem:
function done() {
  var e = document.getElementsByName('pic');
  for (pic in e) { cvs_instant.add(pic, { shadow: 75, shade: 10 }); }
}

A: Hi I came across the same problem.
My script was skipping every other
element. I finally solved it by simply
changing the variable name from i to
k in my loop. My guess is therefor
that the variable i is used by
getElementsByTagName internally to
keep track of where it is in the
live nodelist and is leaking out
to the programmers interface somehow.
So its a bug! :-)

A: -- EDIT:
All of what I claim below appears to be totally wrong. I leave this here as a point for anyone who thought the same :) I tested in FF3. I would love to claim that I saw this behaviour once, in IE, but maybe it was many years ago (come to think of it, it was probably 7 years ago). My memory is probably bad :)
-- OLD:
To slightly expand on my wild guess, if it turns out to be accurate:
From memory, if you don't declare a variable ('var ...') it'll use one from somewhere else.
Thus, without testing, this code:
for(var k = 0; k < 2; k++){
    f();
    alert("k: " + k);
}

function f () {
  k++;
}

Should show the same behaviour. I think TML's solution is quite nice, from a 'defensive coding' point of view, it my analysis turns out to be correct.


text:
Q: PHP image gallery. CSS issue with flexbox. only first image is inside the flex box Can anyone please tell me what is wrong with my code that only the fist image is inside the flexbox and the other two are floating outside?
What it should do is display a gallery of images with three per row. The first piece of PHP code is to give an image count above the gallery.
Here is the HTML/PHP
...

        <title>GALLERY TEST</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width-device-width, initial-sacle 1.0">
        <link rel="stylesheet" href="styles/master-style.css">

<?php
    include_once 'include/dbh.inc.php';

        $sql3 = "SELECT * FROM bth_gal_data WHERE GAL_TLC='LSF'";
        $result3 = mysqli_query($conn, $sql3);
        $queryResults3 = mysqli_num_rows($result3);

        echo "

Welcome to the TEST Image gallery. There are $queryResults3 images.
";
?>

<?php

            $stmt4 = mysqli_stmt_init($conn);
            if (!mysqli_stmt_prepare($stmt4, $sql3)) {
              echo "SQL statement failed!";
            } else {
              mysqli_stmt_execute($stmt4);
              $result4 = mysqli_stmt_get_result($stmt4);
                while ($row = mysqli_fetch_assoc($result4)) {
                echo "

        ";
        }
    }

?>

...

Here is the CSS
...
@font-face {
  src url(../fonts/Catamaran-Regular.ttf);
  font-family: Catamaran;
}

@font-face {
  src url(../fonts/CormorantGaramond-Regular.ttf);
  font-family: Cormorant Garamond;
}

.GALLERY_WRAPPER p {
  margin: 10px 0px;
  font-family: Catamaran;
  font-size: 24px;
  font-weight: 900;
  color: #111;
}
.GALLERY_WRAPPER {
  width: 1000px;
  margin: 30px auto;
}
.GALLERY_FLEX {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: flex-start;
  background-color: blue;
}
.GALLERY_FLEX a {
  width: 300px;
  margin: 10px 5px 0;
}
.GALLERY_FLEX img {
  width: 100%;
  height: auto;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

...

A: I think I figured it out.  I belevie you are closing off your
 and  early in the while loop.  Those 2 parts should be outside of it. So like this. Edit: I think they should be out of the PHP loop entirely, so like this.
    <?php

                $stmt4 = mysqli_stmt_init($conn);
                if (!mysqli_stmt_prepare($stmt4, $sql3)) {
                  echo "SQL statement failed!";
                } else {
                  mysqli_stmt_execute($stmt4);
                  $result4 = mysqli_stmt_get_result($stmt4);
                    while ($row = mysqli_fetch_assoc($result4)) {
                    echo "

                    "; }

        }

    ?>


text:
Q: Angular 6 Dependency Injection in a Class I have a problem of knowledge about dependency injection with Angular 6.
The scene is the following :
A single class (used as Model) :
import { NgModule } from '@angular/core';
import { ContactProviderService } from './../services/contact-provider.service';
import { SuiviInterface } from './../interfaces/suiviinterface';
import { WebapiService } from './../services/webapi.service';
import { QuotationInterface } from './../interfaces/quotationinterface';

import { DeserializableInterface } from './../interfaces/deserializableinterface';

import { MomentDate } from './momentdate';
import { User } from './user';
import { Feature } from './feature';
import { Suivi } from './suivi';

@NgModule({
  providers: [
    WebapiService,
    ContactProviderService
  ]
})

export class Quotation implements QuotationInterface, DeserializableInterface<Quotation> {
  public id: number;

  public date: MomentDate;

  public user: User;

  public feature: Feature;

  public dateValidation?: MomentDate;

 public dateProposition?: MomentDate;

 public dateAcceptation?: MomentDate;

 public isArchive: Boolean;

 public isDeleted: Boolean;

 public numParcelle: string;

 public commentaire: string;

 public lead?: string;

 public suivi: Array<Suivi>;

 public propositionDone: boolean = false;

 private nbAttributions: number = 0;
 private nbPropositions: number = 0;

 public constructor(
    private webApi: WebapiService,
    private contactProvider: ContactProviderService) {
    this.dateValidation = null;
  }

 ... some getters / setters

public deserialize(input: any): Quotation {

    Object.assign(this, input);

    // some other stuff

   return this;
 }
 }
 }

In this class, both WebapiService and ContactProviderService are Injectable, so, i thaught that it was self sufficient to inject them in the contuctor of the class.
I added @NgModule to try... but when i create an instance of a Quotation, have the following error :
Expected 2 arguments but got 0

What i'm doing wrong ?
Thx,
Jean-Luc

A: I think it's because you're missing the @Component Decorator, and then inside there you can provide your services if they're unique to that component. (Wont be shared with entire app if declared in component)
@Component({
   selector: 'some-selector',
   templateUrl: ['./'],
   stylesUrl: ['./'],
   providers:[ WebapiService, ContactProviderService ]
})


text:
Q: Unity Android build crashes on start due Proguard A development build works fine, but when I try a release build, it crashes immediately on start due to the Proguard.
I installed Crashlytics to try getting any error but it does not show any error (crashlytics works).
Might be important to add:
Just added Firebase and Facebook SDK.
How should the proguard.txt file look like?
Thank you in advance.


text:
Q: DFS in adjacency matrix I am having trouble with my DFS it is giving out the wrong traversal. I also need to get the first encounter of the DFS and save it so it can be printed for later. The first encounter would be 1 2 6 7 4 3 5 8
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;

public class DFS {

private Stack<Integer> stack;

String line;
int row = 0;
static int size = 0;

public DFS(){

stack = new Stack<Integer>();

}

public void dfs(int adjMatrix[][], int vert)
{
int number_of_nodes = adjMatrix[vert].length - 1;

int visited[] = new int[number_of_nodes + 1];
int element = vert;
int i = vert;
System.out.println(element + "\t");
visited[vert] = 1;
stack.push(vert);

while (!stack.isEmpty())
{
    element = stack.peek();
    i = element;
while (i <= number_of_nodes)
{

        if (adjMatrix[element][i] == 1 && visited[i] == 0)
    {

            stack.push(i);

            visited[i] = 1;
            element = i;

            i = 1;

            System.out.print(element + "\t");

        continue;
        }
        i++;
}
    stack.pop();

 }
}

public static int[][] create2DIntMatrixFromFile(String filename) throws                 Exception {
int[][] matrix = null;

BufferedReader buffer = new BufferedReader(new FileReader(filename));

String line;
int row = 0;
int size = 0;

while ((line = buffer.readLine()) != null) {
    String[] vals = line.trim().split(" ");

    // Lazy instantiation.
    if (matrix == null) {
        size = vals.length;
        matrix = new int[size+1][size+1];
    }

    for (int col = 0; col < size; col++) {
        matrix[row][col] = Integer.parseInt(vals[col]);
    }

    row++;
}

return matrix;
}

public static void printMatrix(int[][] matrix) {
String str = "";
int size = matrix.length;

if (matrix != null) {
    for (int row = 0; row < size; row++) {
        str += " ";
        for (int col = 0; col < size; col++) {
            str += String.format("%2d",  matrix[row][col]);
            if (col < size - 1) {
                str += "  ";
            }
        }
        if (row < size - 1) {
            str += "\n";
            for (int col = 0; col < size; col++) {
                for (int i = 0; i < 4; i++) {
                   // str += " ";
                }
                if (col < size - 1) {
                    //str += "+";
                }
            }
            str += "\n";
        } else {
            str += "\n";
        }
    }
}

System.out.println(str);
}

public static void main(String[] args)
{

 int[][] matrix = null;

 try {
     matrix = create2DIntMatrixFromFile("sample.txt");
 } catch (Exception e) {
     e.printStackTrace();
 }

    System.out.println("The DFS Traversal for the graph is given by ");
    DFS dfs = new DFS();
    dfs.dfs(matrix, size);
    System.out.println(" ");
    printMatrix(matrix);
   }

}

The output for this is
The DFS Traversal for the graph is given by
0
1   5   4   6   2   3   7
 0   1   0   0   1   1   0   0   0

   1   0   0   0   0   1   1   0   0

   0   0   0   1   0   0   1   0   0

   0   0   1   0   0   0   0   1   0

   1   0   0   0   0   1   0   0   0

   1   1   0   0   1   0   0   0   0

   0   1   1   0   0   0   0   1   0

   0   0   0   1   0   0   1   0   0

   0   0   0   0   0   0   0   0   0

The traversal is suppose to be
1 2 6 5 7 3 4 8
Thanks in advance for your help!


text:
Q: How to save a screenshot of a Form containing TRichEdit to a file? I use this code to save a screenshot of a Form to a bitmap file:
var
  Bmp : Graphics.TBitmap;
begin
  Bmp := GetFormImage;
  try
    Bmp.SaveToFile( _DestFilePath );
  finally
    Bmp.Free;
  end;
end;

However, it doesn't seem to work well when a TRichEdit control is placed on the Form. Instead of a TRichEdit control and all its content, a white rectangle is saved into the final image.
How can I get a complete screenshot of a Form that contains a non-blank TRichEdit control?
I use Delphi 2009.

A: If GetFormImage() fails, you should try to BitBlt() the Form's contents yourself, eg:
var bm := TBitmap.Create(ClientWidth, ClientHeight);
try
  BitBlt(bm.Canvas.Handle, 0, 0, ClientWidth, ClientHeight, Self.Canvas.Handle, 0, 0, SRCCOPY);
  // use bm as needed...
finally
  bm.Free;
end;

This successfully copies a Form with a TRichEdit for me.


text:
Q: Right-to-Left characters reversed in Android Emulator It'ss my first time developing an app in a RTL language (Hebrew). I've been struggling for two days with reversed characters.
My String XML:
<resources>
   <string name="app_name">SomeApp</string>

   <string name="hello_world">מה המצב?</string>
   <string name="action_settings">Settings</string>
</resources>

With the string hello_world I want to create a textView which will use this string. The result should be:

?מה המצב

However the emulator shows:

As you can see its not only change the order of the sentence and the question mark. it also changing the order of the letters.
Things I have tried so far:

*

*API level 20 and above. Some places implied that the problem is known in fixed after 4.2 version.

*Using the mark \u200F in begin or end or both of a sentence.

*Using \u200e after each special char like ", ,, ., ?, !, etc. When I write in Hebrew without special chars at all everything works fine.

activity_my.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"        android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MyActivity"
android:id="@+id/StudentLife">

<TextView android:text="@string/hello_world"             android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

   </RelativeLayout>

I've searched around but nothing works, maybe I missed something.

A: The screenshot shows not an emulator, but the visual layout manager of Android Studio. This seems to be a weird bug in the layout manager, but it will not effect the application - whether on emulator or on a real device.
You are right, RTL support prior to Android 4.2 was not standardized, and some devices may perform in a strange way. But the emulator even for 2.3.3 does not revert the Hebrew letters for me.
Well, it does not put ? on the left, and you need to append \u200F to cure this. But for 4.2 and higher, you can specify android:textDirection="rtl" instead of the mark.


text:
Q: anti-hackers coding(anti XSS coding behaviors)? i am into php coding for 1 year now. i don't know everything or consider myself professional.but i want to write clean hacker proof coding. i tried to research for example how to stop XSS attacks.but it seems that there is a lot of expressions and a lot of vulnerabilities. i tried htmlawed and html purifiers. but not every simple form or script i write will need heavy script to make it secure. so what i need is : is there a coding style that i can follow that make my coding secure?

A: Basically, to avoid XSS, you have to make sure no HTML can be injected by the users into the HTML output of your page.
The simplest way of doing that is to use functions such as htmlspecialchars() on any output that goes to the browser as HTML.

This means that, if anyone inputs something like this (simple example) :
<script>alert('plop');</script>

The HTML of your page will contain :
<script>alert('plop');</script>

And no HTML / Javascript code that could be interpreted.


text:
Q: Show field history on Accounts page I am working on a SalesCloud application for a non-profit. In the Accounts there are 2 custom fields, Amount Fundraised (by that account) and # of Coats Shipped (to that account). These numbers change annually, and I'd like to keep track of the changes year-to-year on the account page. I've already set these fields to track history in Setup->Customize->Accounts->Fields, but I can't figure out if I can show this history on the Accounts page.  Is this possible? Also, I've looked but couldn't find any information on how long this information is kept for.

A: You can show the field history as a related list by adding it to the account page layout (if you have enabled field history it should show up as one of the related lists when editing the page layout).
SF's field history policy was actually changed in spring 13. From the release notes:

Salesforce.com has changed its policy on how long you can store field
  history data. Field history data does not count against your
  organization's storage limit, however, Salesforce deletes field history
  data that is 18 months or older for organizations created after 12:00
  A.M. on June 2, 2011. You can request disabling of the auto-delete
  mechanism by contacting salesforce.com support. There is no
  user-enabled method for turning the delete mechanism on or off.

A:
Go to any record in the account click on edit layout( If you are a system admin you can see this option)
From the left side options click on "Related List" you should be able to see/search for Account history add it to the layout. click save
you should be able to see the history changes in the related list down below.
The history tracking is available for all salesforce objects and can be added through the pagelayout if not enabled by default


text:
Q: Python argparse - option with options to dict I am trying to parse some options with argparse.  I have found some similar problems discussed and found what I thought was a similar issue with a sensible solution given by Owen in Options with Options with Python argparse?
I want to be able to specify, for example:
script.py infile --line <path to file1> beglab='str1' endlab='str2'
                 --line <path to file2>
                 --line <path to file3> beglab='str3'
                 outfile

--line  can be specified multiple times.  Initially I had no extra arguments for the line option and I was able to create a list of the files without a problem using:
parser.add_argument("--line", action='append')

Now I need to optionally add labels to go with the lines.  There can be 0, 1 or 2 labels associated with a given line as shown above.  This is why I felt the example in the link provided seemed appropriate, unfortunately when I try:
parser.add_argument("--line", action='append', nargs="+")

And run:
script.py infile --line somefile beglab='A' endlab='B'
                 --line otherfile beglab='a' endlab='b' outfile

or
script.py infile --line somefile outfile

I get an error stating that there are too few arguments.  If I remove the --line options from the command so I have just the positional ones, it works, so I know I haven't missed anything required.  So I went and I read up on the nargs options.  If --line is specified, it must have at least the filename, therefore I think that nargs='+' is the appropriate option, it looks about right in the help [--line LINE [LINE ...]], so I am really confused about where this error has come from.
I am happy to consider alternative methods of dealing with this, I just liked the simplicity of providing the inputs like this and creating a dictionary with them.

A: The parser you want to build is ambiguous. If endlab='b' is optional, then argparse can't tell if the operator intends that outfile is a parameter to --line or a positional argument.
You don't have to change your parser, but you do have to change your command line:
Try:
script.py infile outfile
          --line somefile beglab='A' endlab='B'
          --line otherfile beglab='a' endlab='b'

Or:
script.py infile
          --line somefile beglab='A' endlab='B'
          --line otherfile beglab='a' endlab='b'
          --
          outfile

A: I'm not sure about how to accomplish this with argparse, but for simplicity, I would consider doing something like:
--line <path_to_file>,<beglab>,<endlab>
And then parse the argument either in code or using argparse's custom type functionality.  You can have the custom type function return a dict like {'filepath':'<path_to_file>', 'beglab':'<beglab>', 'endlab':'<endlab>'}


text:
Q: Bug in showing progress towards badges? Someone on Math.StackExchange got the Informed badge several hours ago, but it still shows 1/1 for Informed:

This is weird, because normally, the next badge already says that you got it while you didn't get it already. It is also weird that after several hours, it hasn't been fixed if it was catching.
I've found several cases of this on Math.SE and StackOverflow. It also happens in the Autobiographer badge where the badge was awarded 15h ago.


text:
Q: Rename multiple columns by extracting contents in parentheses for a list of dataframes Given data and code as follows, I'm able to generate a list of dataframes dfs:
library(data.table)
library(purrr)
library(glue)
library(gt)
library(tidyverse)
library(purrr)

df <- structure(list(id = c("M0000607", "M0000609", "M0000612"), `2021-08(actual)` = c(12.6,
                                                                                19.2, 8.3), `2021-09(actual)` = c(10.3, 17.3, 6.4), `2021-10(actual)` = c(8.9,
                                                                                15.7, 5.3), `2021-11(actual)` = c(7.3, 14.8, 3.1), `2021-12(actual)` = c(6.1,
                                                                                14.2, 3.5), `2021-08(pred)` = c(11.65443222, 14.31674997, 7.084180415
                                                                                ), `2021-09(pred)` = c(12.29810914, 17.7143733, 6.057927385),
                     `2021-10(pred)` = c(9.619846116, 15.54553601, 6.525992602
                     ), `2021-11(pred)` = c(8.352097939, 13.97318204, 3.164682627
                     ), `2021-12(pred)` = c(6.113631596, 14.16243166, 3.288372517
                     ), `2021-08(error)` = c(2.082307066, 1.146759554, 0.687406723
                     ), `2021-09(error)` = c(1.631350383, 2.753457736, 2.952737781
                     ), `2021-10(error)` = c(0.945567783, 4.883250027, 1.215819585
                     ), `2021-11(error)` = c(1.998109138, 0.414373304, 0.342072615
                     ), `2021-12(error)` = c(0.719846116, 0.154463985, 1.225992602
                     )), class = "data.frame", row.names = c(NA, -3L))

year_months <- c('2021-12', '2021-11', '2021-10')
curr <- lubridate::ym(year_months)
prev <- curr - months(2L)
dfs <- mapply(function(x, y) {
  df[c(
    "id",
    format(seq.Date(y, x, by = "month"), "%Y-%m(actual)"),
    format(x, "%Y-%m(pred)"),
    format(x, "%Y-%m(error)")
  )]
}, curr, prev, SIMPLIFY = FALSE)

I want to rename last two column by extracting content in parentheses as new column names:
[[1]]
        id 2021-10(actual) 2021-11(actual) 2021-12(actual)          pred          error
1 M0000607             8.9             7.3             6.1      6.113632      0.7198461
2 M0000609            15.7            14.8            14.2     14.162432      0.1544640
3 M0000612             5.3             3.1             3.5      3.288373      1.2259926

[[2]]
        id 2021-09(actual) 2021-10(actual) 2021-11(actual)          pred          error
1 M0000607            10.3             8.9             7.3      8.352098      1.9981091
2 M0000609            17.3            15.7            14.8     13.973182      0.4143733
3 M0000612             6.4             5.3             3.1      3.164683      0.3420726

[[3]]
        id 2021-08(actual) 2021-09(actual) 2021-10(actual)          pred          error
1 M0000607            12.6            10.3             8.9      9.619846      0.9455678
2 M0000609            19.2            17.3            15.7     15.545536      4.8832500
3 M0000612             8.3             6.4             5.3      6.525993      1.2158196

How could I do that using R? Thanks.
Reference link:
Extract info inside all parenthesis in R

A: Here's a tidyverse alternative -
library(dplyr)
library(purrr)

map(dfs, ~.x %>%rename_with(~sub('.*\\((.*)\\)$', '\\1', .x), last_col(c(0, 1))))

#[[1]]
#        id 2021-10(actual) 2021-11(actual) 2021-12(actual)      pred     error
#1 M0000607             8.9             7.3             6.1  6.113632 0.7198461
#2 M0000609            15.7            14.8            14.2 14.162432 0.1544640
#3 M0000612             5.3             3.1             3.5  3.288373 1.2259926

#[[2]]
#        id 2021-09(actual) 2021-10(actual) 2021-11(actual)      pred     error
#1 M0000607            10.3             8.9             7.3  8.352098 1.9981091
#2 M0000609            17.3            15.7            14.8 13.973182 0.4143733
#3 M0000612             6.4             5.3             3.1  3.164683 0.3420726

#[[3]]
#        id 2021-08(actual) 2021-09(actual) 2021-10(actual)      pred     error
#1 M0000607            12.6            10.3             8.9  9.619846 0.9455678
#2 M0000609            19.2            17.3            15.7 15.545536 4.8832500
#3 M0000612             8.3             6.4             5.3  6.525993 1.2158196

A: Using lapply to manipulate the elements of the list dfs, we can use some regex to do the job.
dfs <- lapply(dfs, function(x) {
  col_num <- grep('pred|error', colnames(x))
  colnames(x)[col_num] <- gsub('.*\\(|\\)', '', colnames(x)[col_num]); x
})

Output
> dfs
[[1]]
        id 2021-10(actual) 2021-11(actual) 2021-12(actual)      pred     error
1 M0000607             8.9             7.3             6.1  6.113632 0.7198461
2 M0000609            15.7            14.8            14.2 14.162432 0.1544640
3 M0000612             5.3             3.1             3.5  3.288373 1.2259926

[[2]]
        id 2021-09(actual) 2021-10(actual) 2021-11(actual)      pred     error
1 M0000607            10.3             8.9             7.3  8.352098 1.9981091
2 M0000609            17.3            15.7            14.8 13.973182 0.4143733
3 M0000612             6.4             5.3             3.1  3.164683 0.3420726

[[3]]
        id 2021-08(actual) 2021-09(actual) 2021-10(actual)      pred     error
1 M0000607            12.6            10.3             8.9  9.619846 0.9455678
2 M0000609            19.2            17.3            15.7 15.545536 4.8832500
3 M0000612             8.3             6.4             5.3  6.525993 1.2158196


text:
Q: Flutter : The method 'animateCamera' was called on null I have this app :

I want when click on floatingActionButton zoom out a little but it throw this exception
The method 'animateCamera' was called on null.
Receiver: null
Tried calling: animateCamera(Instance of 'CameraUpdate')

and this is my code :
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
  }

  @override
  Widget build(BuildContext context) {
    GoogleMapController _controller;
    final CameraPosition _initialPosition = CameraPosition(target: LatLng(24.903623, 67.198367));
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: GoogleMap(
        initialCameraPosition: _initialPosition,
        mapType: MapType.normal,
        onMapCreated: (controller){
          setState(() {
            _controller = controller;
          });
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          _controller.animateCamera(CameraUpdate.zoomOut());
        },
        child: Icon(Icons.zoom_out),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

}

how to fix it ?

A: This is Because your mapController is null on which you call !
mapController.animateCamera();

sounds like you Decleare "GoogleMapController mapController;" like this
i will recommemd you to use Completer of type GoogleMapController and then intilize it within "OnMapCreated:" with the controller return by "OnMapCreated" function
First Decleare Controller in Global section like this: Completer<GoogleMapController> _controller = Completer();
then Inside GoogleMaps use onMapCreated: function like below
GoogleMaps(
onMapCreated: (GoogleMapController controller) {
              _controller.complete(controller);
            },
)

and now how to use this
1st) : before calling to animateCamera function use this
final GoogleMapController mapController = await _controller.future;

this will initilize mapController and then Call
 mapController.animateCamera()

A: Restart your app.
Also consider moving
GoogleMapController _controller;
    final CameraPosition _initialPosition = CameraPosition(target: LatLng(24.903623, 67.198367));

either into initstate or declare it as a member variable


text:
Q: How to get TimeSpan from DateTime Scenario:
Third party web service returns datetime in two separate fields i.e. date and time. I need a way to concatenate into single field.
e.g.

 startDate='24-06-2012'
 startTime='1-01-1970 1:00:00 AM'

Expected result:
 fullStartDateTime='24-06-2012 1:00:00 AM'

I tried to get the TimeSpan part from startTime and got no where. Could someone let me know if there's a smart way to achieve above.

A: TimeOfDay is the property of DateTime that you're looking for:
TimeSpan timeOfDay = startTime.TimeOfDay;
DateTime fullStartDateTime = startDate.Add(timeOfDay);

A: timespan fr = new timespan();
fr.parse(string date)


text:
Q: How to make a folder/directory undeletable/unremovable for a user but still writable This is needed for a case when it is necessary to create a folder in home directory of a user, to allow user read/write/remove files in the folder, but not allow to remove the folder itself (considering a regular user and not a sudoer).
In my case (i.e. RedHat) it was not enough just to put a file with root rights inside user`s folder, because the user owns the folder.
In my case if a user owns (or has all permissions on) a folder, he can remove it even with root file or empty folder inside.
I have made quite a number of experiments including playing with chown and permissions like 400, 000, o+t, 1775 etc. Initially  I did not want to use chattr.
Meanwhile I have found a solution, which I share as an answer below; a variant that suits my needs so far.

A: Here is the solution I found myself.
Basically it uses the fact that when root subfolder is not empty, the user cannot remove it anymore.
In the below example superuser (root) each time creates (if does not exist already) a folder with user rights in user`s home directory, then puts inside a folder with root rights (if does not exist already), and inside that root folder puts a file with root rights.
## prepare directory for the external configuration
EXT_CONFIG_PATH="~user/.EXT_CONFIG"
mkdir -p ${EXT_CONFIG_PATH}
chown user:user ${EXT_CONFIG_PATH}
chmod 555 ${EXT_CONFIG_PATH}
mkdir -p ${EXT_CONFIG_PATH}/.rootguard
chmod o+t ${EXT_CONFIG_PATH}/.rootguard
touch ${EXT_CONFIG_PATH}/.rootguard/.rootguard
chmod 400 ~user/.EXT_CONFIG/.rootguard/.rootguard


text:
Q: SQLite Database written on read I have been playing around with inotify and a sqlite database as I wanted to know how often the database file was written.
The thing is that the database file is written everytime I send a query. It does not matter if it is to read (SELECT) or to modify (UPDATE). The inotify flag IN_CLOSE_WRITE is always activated after that.
I wanted to avoid as much writing as possible. Am I missing anything here? Should not the database only be written when performing operations to modify it?

A: The IN_CLOSE_WRITE flag does not indicate that something was written, only that the file was openend for writing.
The database does not know whether you will write something later, so it opens the file with write access to avoid having to reopen it.
If you know you never want to write, use the SQLITE_OPEN_READONLY flag.


text:
Q: Is it possible to integrate Apache Solr with Spring Batch? I read about Apache Solr and Spring Batch. Apache Solr is powerful search technology. Now, we want to read data from Apache Solr and then Spring Batch will process that data and will write to database.
I searched a lot, but I could not get demo about this integrartion.
Is it possible to integrate Apache Solr with Spring Batch?

A: We have done a spring batch based application that do indexing on solr cloud which is equivalent to Solr "Data Import Request Handler".
Step 1: Read from database
 <bean id="itemReader" class="org.springframework.batch.item.database.JdbcPagingItemReader" scope="step">
        <property name="dataSource" ref="mysqlDataSource"/>
        <property name="queryProvider">
            <bean class="org.springframework.batch.item.database.support.MySqlPagingQueryProvider">
            </bean>
        </property>
        <property name="rowMapper">
         <bean class="implement org.springframework.jdbc.core.RowMapper">
         <!-- public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
        return SolrInputDocument }
        -->
            </bean>
        </property>
    </bean>

Step 2: process the read data
   <bean id="intermediateProcessor" class="our.own.intermediate.Processer" scope="step">
    </bean>

Step 3: write/post data to apache solr
<bean id="solrItemWriter" class="our.own.writer.SolrItemWriter" scope="step">
    <property name="solrServer" ref="solrServer"/>
</bean>

<bean id="solrServer" class="org.apache.solr.client.solrj.impl.CloudSolrServer" destroy-method="shutdown" >
    <constructor-arg index="0"><value>solr cloud zookeeper host</value></constructor-arg>
    <constructor-arg index="1"><value>false</value></constructor-arg>
</bean>

    import org.apache.solr.client.solrj.SolrServer;
    import org.apache.solr.client.solrj.response.UpdateResponse;
    import org.apache.solr.common.SolrInputDocument;
    public class SolrItemWriter implements ItemWriter {
        @Override
        public void write(List items) throws Exception {
            for (Object object : items) {
                SolrInputDocument solrInputDocument = (SolrInputDocument) object;
                UpdateResponse response = solrServer.add(solrInputDocument);
            }
            UpdateResponse commitResponse = solrServer.commit();

        }
    }

I am not sure my answer will help you as your question is not very clear about the requirements. why you want read data from apache solr and write it to mysql database

A: I don't really know Apache Solr, but from its website description :

Solr is a standalone enterprise search server with a REST-like API.
  You put documents in it (called "indexing") via JSON, XML, CSV or
  binary over HTTP. You query it via HTTP GET and receive JSON, XML, CSV
  or binary results.

So, a possible solution would be to write a custom ItemWriter which queries via HTTP GET your Solr server and returns the result as a POJO (or a simple String). You can then use a classic "chunk" with your custom reader, a processor (optionnal) and a JBDC Writer.


text:
Q: Powershell: Copy files while stripping ReadOnly from each written file I would like a copy routine which accepts potentially readonly files, but the copied destination file always comes out NOT readonly. The trouble is knowing the path of the written file in order to change it to not be read only. I'm not willing to accidentally touch a file that wasn't moved by this copy routine, so I can't just strip readonly from everything under the destination path. Do I really have reconstruct each written filepath myself so I can call set-itemproperty on it?
Is there any clean way to implement a function like Copy-Item-StripReadOnly "F:\*" "G:\", such that nothing written to G comes out with readonly, and the rest of G:\ is not touched?

A: Just use the -PassThru argument of copy-item which will pass each destination file onto the pipeline, then loop through each, stripping the readonly:
Copy-Item "F:\*" "G:\" -PassThru | Set-ItemProperty -name isreadonly -Value $false

A: To improve on the accepted answer, if you want to recursively copy a whole directory tree:
Copy-Item "$sourceDirectoryName\*" $targetDirectoryName -Force -Recurse -PassThru | Where-Object { -not $_.PSIsContainer } | Set-ItemProperty -Name IsReadOnly -Value $false

The -PassThru will include both files and sub-directories. Because directories do not have an IsReadOnly attribute, Set-ItemProperty will throw an exception, unless we use -not $_.PSIsContainer to filter out directories.

A: The piece you need would be to check it the copied file is read-only and remove the file attribute which is fairly simple.
$attribute = [io.FileAttribute]::ReadOnly
If((Get-ItemProperty -Path $file.fullname).attributes -band $attribute)
{
   Set-ItemProperty -Path $file.fullname -Name attributes -Value ((Get-ItemProperty $file.fullname).attributes -bxor $attribute)
}

This will check if the file $file is read-only. If it is remove the read-only bit. Insert this either inside your pipe statement or inside your copy loop.
I know this is not a complete solution as per your question but it is not easily readable as a comment. Also you don't really show any effort in research for this. If you show us what you might have for a function so far please include it in the code.


text:
Q: Selenium WebDriver Java. Не могу получить Iframe и элементы из него В процессе теста выскакивает окно
Необходимо нажать на кнопку "no" и продолжить тест.
Как я выяснил, необходимо переключиться на данный фрейм, с него стащить необходимые элементы, их обработать, вернуться на стартовый и продолжить работу.
К сожалению, фрейм я получить не могу, выбивает исключение "No frame element found by name or id"
HTML
<iframe ng-non-bindable="" hspace="0" marginheight="0" marginwidth="0" scrolling="no" style="width: 650px; height: 274px; display: block;" tabindex="0" vspace="0" id="I0_1538262420041" name="I0_1538262420041" src="https://www.google.com/shopping/customerreviews/optin?usegapi=1&merchant_id=113673673&hl=en_US&origin=https%3A%2F%2Fwww.wrike.com%2Fresend%2F&order_id=1539472019408&usegapi=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.ru.ORo9oPl_ChI.O%2Fam%3DwQ%2Frt%3Dj%2Fd%3D1%2Frs%3DAGLTcCN98n80Z9-t_27i1mUuOy6E-T563g%2Fm%3D__features__#id=I0_1538262420041&_gfid=I0_1538262420041&parent=https%3A%2F%2Fwww.wrike.com&pfname=&rpctoken=22527236" width="100%" frameborder="0"></iframe>

Java
driver.switchTo().frame("//*[@id=\"I0_1538262420041\"]");
    webElement = driver.findElementByXPath("/html/body/c-wiz/div/div/div[2]/div[4]/span[1]/div/content/span");
    webElement.click();

Пробовал добавлять в начало driver.switchTo().defaultContent(); и лишь затем переходить на нужный фрейм по xPath. Не помогает.
Используется firefox webdriver.
Source -> https://www.wrike.com/ -> get started for free button.
P.S. Только разбираюсь в Selenium и в вебе в частности, если проблема проста просьба ногами не пинать :)

A: Вот так срабатывает:
driver.switchTo().frame(driver.findElement(By.name("I0_1538262420041")));

A: Опытным путем выяснил, что webdriver находит верхний div контейнер фрейма.
Предложенный выше вариант действительно рабочий, но сработал он с xPath вида /html/body/div[6]/div/iframe. Непосредственно по id и name селениум фрейм не находит.
Спасибо за помощь!