text:
Q: SAS adding new observations for longitudinal data I have a longitudinal dataset in SAS with periods of time categorized as either at risk for an event, or not at risk. Unfortunately, some time periods overlap, and I would like to recode them to have a dataset of entirely non-overlapping observations. For example, the dataset currently looks like:
Row 1: ID=123; Start=Jan 1, 1999; End=Dec 31, 1999; At_risk="Yes"
Row 2: ID=123; Start=Feb 1, 1999; End=Feb 15, 1999; At_risk="No"

The dataset I would like looks like:
Row 1: ID=123; Start=Jan  1, 1999; End=Feb  1, 1999; At_risk="Yes"
Row 2: ID=123; Start=Feb  1, 1999; End=Feb 15, 1999; At_risk="No"
Row 3: ID=123; Start=Feb 15, 1999; End=Dec 31, 1999; At_risk="Yes"

Thoughts?

A: Such tasks are exercises in debugging of program logic and fighting data assumptions, playing with old/new values...
Below my initial code for the exact example you provided, will surely need some adjustment on real data.
In case there's time overlap on more than current-next record I'm not sure it's doable this way (with reasonable effort). For such cases you'd probably be more effective with splitting original start - end intervals to day level and then summarize details to new intervals.
data orig;
format Id 16. Start End Date9.;
Id = 123;Start='1jan1999'd; End='31dec1999'd; At_risk="Yes";output;
Id = 123;Start='1feb1999'd; End='15feb1999'd; At_risk="No";output;
run;

proc sort data = orig;
by ID Start;
run;

data modified;
    format pStart oStart pEnd oEnd Date9.;
    set orig;
    length pStart pEnd 8 pAt_risk $3;
    by ID descending End ;

    retain pStart pEnd pAt_risk;

    /* keep original values */
    oStart = Start;
    oEnd = End;
    oAt_risk = At_risk;

    if first.id then do;
        pStart = Start;
        pEnd = End;
        pAt_risk = At_risk;
        /* no output */
    end;
    else do;
        if pAt_risk ne At_risk then do;
            if Start > pStart then do;
                put _all_;
                Start = pStart;
                End = oStart;
                At_risk = pAt_risk;
                output;/* first part of time span */
                Start = oStart;
                End = oEnd;
                At_risk = oAt_risk;
                output;/* second part of time span */
                if (End < pEnd ) then do;
                    Start = End;
                    End = pEnd;
                    At_risk = pAt_risk;
                    output; /*third part of time span */
                    /* keep current values as previous record values */
                    pStart = max(oStart, Start);
                    pEnd = End;
                    pAt_risk = At_risk;
                end;
            end;
        end;
    end;
run;

proc print;run;

A: Vasja may have been suggesting something like this (date level) as an alternative.
I will assume here that the most recent row read in your longitudinal dataset will have priority over any other rows with overlapping date ranges.  If that is not the case then adjust the priority derivation below as appropriate.
Are you sure your start and end dates are correct.  Your desired output still has overlapping dates.  Feb 1 & 15 are both At Risk and not At Risk.  Your End date should be at least one day before the next start date.  Not the same day.  End and Start dates should be contiguous. For that reason coding a solution that produces your desired output (with overlapping dates) is problematic.  The solution below is based on no overlapping dates. You will need to modify it to include overlapping dates as per your required output.
/*         Your longitudinal dataset .  */
data orig;
         format Id 16. Start End Date9.;
         Id = 123;Start='1jan1999'd; End='31dec1999'd; At_risk="Yes";output;
         Id = 123;Start='1feb1999'd; End='15feb1999'd; At_risk="No";output;
run;

/*         generate a row for each date between start and end dates.  */
/*         Use row number (_n_) to assign priorioty.  */
Data overlapping_dates;
         set orig;
         foramt date date9.;
         priority = _n_;
         do      date = start to end by 1;
                 output;
         end;
Run;

/*         Get at_risk details for most recent read date according to priority.  */
Proc sql;
         create  table non_overlapping_dates as
         select  id, date, at_risk
         from    overlapping_dates
         group   by      id, date
         having  priority eq max (priority)
         order   by       id, date
         ;
Quit;

/*   Rebuild longitudinal dataset .  */
Data longitudinal_dataset
    (keep= id start end at_risk)
    ;
        format id 16. Start End Date9. at_risk $3.;

        set non_overlapping_dates;
        by id at_risk notsorted;

        retain start;

    if  first.at_risk
        then start = date;

/*      output a row to longitudinal dataset if at_risk is about to change or last row for id.  */
        if      last.at_risk
                then do;
            end = date;
            output;
                    end;
Run;


text:
Q: invalid conversion from 'char*' to 'uint8_t' Arduino I'm trying to set the pin mode for all Analogue input pins at once on my Mega. So I made an array before set-up:
char* Analog_Input_List[16] = {"A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","A10","A11","A12","A13","A14","A15"};

Then I tried to run this:
 //analogue input pin set-up
 for (int i =0;i<8;i++){
 pinMode(Analog_Input_List[i], OUTPUT);
 }

But I'm getting this error:
sketch_jul24a.cpp: In function 'void setup()':
sketch_jul24a.cpp:54:40: error: invalid conversion from 'char*' to 'uint8_t'
sketch_jul24a.cpp:54:40: error:   initializing argument 1 of 'void pinMode(uint8_t, uint8_t)'

I'm new to arduino programming and the declaring and manipulation of types keeps confusing me I'm aware its something simple but not sure how to go about fixing it.
Thanks

A: The pins you are trying to initialize are described by preprocessor macros expanding to integer constants. They are not strings. What you want instead is
int inputPins[] = { A0, A1, /* etc. */ };

instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHPWord 0.11.0 font style underline I have a problem with PHPWord that I belive is version 0.11.0, I use the PHPWord for CI.
The issues is I cannot find the right php script to make the underline, this is the latest script I got,
$section->addText(
    $text,
    [ 'underline' => \PhpOffice\PhpWord\Style\AbstractStyle::UNDERLINE_SINGLE ], // Problem with this line
    [ 'align' => \PhpOffice\PhpWord\Style\Alignment::ALIGN_CENTER ] // This one fine
);

But whenever the script I got, it always display an error or didnt give me what I want, (the underlined text).
This the error I got

An uncaught Exception was encountered
Type: Error
Message: Undefined class constant 'UNDERLINE_SINGLE'
Filename:
  C:\xampp\htdocs\test\application\controllers\Print.php
Line Number: 47
Backtrace:
File: C:\xampp\htdocs\test\index.php Line: 315 Function:
  require_once

I appreciate any help, thanks in advance.

A: To implement a single underline, add an element:
array('underline' => 'single') in your styling array


text:
Q: xslt how to get the parent node position for the case same node name is also child node I would like to add color for the alternative table row. I would like to use the following method:
<xsl:template match="tr">
<xsl:attribute name="bg-color">
<xsl:choose>
<xsl:when test= position() mod 2 = 0><xsl:text>#CCCCCC</xsl:text></xsl:when>
<xsl:otherwise>#DDDDDD</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
</xsl:template>

But things is the node
is also the child of tag
. how do i get the parent
 position?

    1
    2

    1
    2

3	4

5	6

    ...

how do i filter out the
 inside of the
?

A: You can use a more discriminant match like if you can't have more than 1 level :
<xsl:template match="table/tr/td/table/tr">

The template that would be applied to your tr contained in a level 2 table could then be different from the other one.
Or you could use a call template (to a named tempate) in your match="tr" for each table/tr/td found.
Or you could check if ancestor is tr with xsl:if:
<xsl:if test="ancestor::tr">

You already check the modularity, then just add a condition if you do not want to add a template, something like:
test="position() mod 2 = 0 and not ancestor::tr"

A: If you use match="table/tr" then the template matches only tr elements that are children of a table parent element. But a tr as a child of a tr is not possible in the HTML table model.

A: <xsl:if test="ancestor::tr"> and test="position() mod 2 = 0 and not ancestor::tr" are the best choice for my case.


text:
Q: How to find the integral value of $a$ for which $f(x) = x^2 - 6ax + 3 - 2a + 9a^2$ is surjective Let $f:\mathbb{R} \to [1, \infty)$ be defined by $f(x)=x^2-6ax+3-2a+9a^2$. The integral value of $a$ for which $f(x)$ is surjective is equal to
I tried putting $f(x)=1$. Is this the right approach?

A: $f(x) = (x-3a)^2+3-2a\Rightarrow f_\text{min}= f(3a) = 1\Rightarrow 3-2a = 1\Rightarrow a = 1$.

A: As it is quadratic equation and its range defines from [-D/4a,infinity]  (a>0 in equation) so we can find D in from this equation and can equate to 1 because it is given that it is surjective .(as range is 1 to infinity given)
-D/4a=-(36a^2-4(3-2a+9a^2))/4*1
=12-8a/4
1=12-8a/4
1=a


text:
Q: google places automplete only suggestions with stress number I am working with googles api places for address autocomplete suggestions.
This is my simple working code:
<!DOCTYPE html>
<html>
<body>

<form>
   <input id="customerAddress" name="customerAddress" required autocomplete="off" />
   <input id="zip" name="zip" required readonly />
   <input id="city" name="city" required readonly />
</form>

    <script
      src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initAutocomplete&libraries=places"
      async
    ></script>

    <script>

        let autocomplete;

        function initAutocomplete() {

          autocomplete = new google.maps.places.Autocomplete(document.querySelector("#customerAddress"), {
            componentRestrictions: { country: ["de", "DE"] },
            fields: ["address_components", "geometry"],
            types: ["address"],
          });
          autocomplete.addListener("place_changed", fillInAddress);
        }

        function fillInAddress() {

          const place = autocomplete.getPlace();
          var address = ""
          var streetNumber = ""

          for (const component of place.address_components) {
            const componentType = component.types[0];

            switch (componentType) {

              case "route": {
                address = component.long_name;
                break;
              }

              case "street_number": {
                  streetNumber = component.long_name
                  break;
                }

              case "postal_code": {
                document.querySelector("#zip").value = component.long_name;
                break;
              }

              case "locality":
                document.querySelector("#city").value = component.long_name;
                break;

            }
          }

        document.querySelector("#customerAddress").value = address +" "+streetNumber

        }
    </script>
  </body>
</html>

Now I would realize the following situation:

*

*the customer should write his address into the field "customerAddress" to get the suggestions, but the address have to include a street number. how can I restrict this?

*The form should only be able to be submitted, if the customer selected a suggestions from the autocomplete list. If he / she write manually a address, which doesn't is from the autocomplete list, it has to be an error

A: Well, I think the best solution would be to have separate hidden input where you would put selected address which you would run validation against, if it is not defined you simply return error.
As for having street number you can also run the validation of selected Place. If it has selected type street_number it is valid, if not it's not.
I am not sure if you can disable Google to restricts search results to only addresses with street number.


text:
Q: Get viewport coordinates from mapView? regionDidChanged swift The following function is called when the user moved the map.
It is possible to get the viewport? Viewport is latitude and longitude of north/east and the lat. and lon. of south/west.
 func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool){
    print("The \(mapView.centerCoordinate)")
    print("the maprect \(mapView.visibleMapRect.origin)")
    print("the maprect \(mapView.visibleMapRect.size)")
    //I find just this attributes for mapView

    }

I don't know how get the viewports out of my data. I can't find anything in the www.
The destination is that I log the coordinates with google analytics and another tool evaluate the datas.
Has somebody an idea? Thanks a lot

A: Based on fel1xw answer
Swift 3 MapKit

let northEast = mapView.convert(CGPoint(x: mapView.bounds.width, y: 0), toCoordinateFrom: mapView)
let southWest = mapView.convert(CGPoint(x: 0, y: mapView.bounds.height), toCoordinateFrom: mapView)

A: MapKit
let northEast = mapView.convertPoint(CGPoint(x: mapView.bounds.width, y: 0), toCoordinateFromView: mapView)
let southWest = mapView.convertPoint(CGPoint(x: 0, y: mapView.bounds.height), toCoordinateFromView: mapView)

googleMaps
mapView has a property "projection" where you can use "coordinateForPoint" to convert a point from the mapView to a coordinate. so the following could work:
swift 3 for google maps
let northEast = mapView.projection.coordinate(for: CGPoint(x: mapView.layer.frame.width, y: 0))
let southWest = mapView.projection.coordinate(for: CGPoint(x: 0, y: mapView.layer.frame.height))

swift 2
let northEast = mapView.projection.coordinateForPoint(CGPoint(x: mapWidth, y: 0 ))
let southWest = mapView.projection.coordinateForPoint(CGPoint(x: 0, y: mapHeight))

you just need to enter your mapView width and height


text:
Q: Safari ignoring mime type The following extract from a JSP page shows the 'content-type' and 'content-disposition' settings. The page shall provide the user with an HTML table, that
can be imported to Excel.
Chrome, Firefox, IE work as expected with the settings shown below. Safari on OS X Snow Leopard adds a .html to the downloaded file resulting in report.xls.html. Is there a workaround available that brings Safari on track?
<%@ page session="false" contentType="application/vnd.ms-excel;charset=utf-8"%>
...
<meta name="content-type" content="application/vnd.ms-excel;charset=utf-8"></meta>
<meta name="content-disposition" content="attachment; filename=report.xls">

A: I am sending these headers and for a csv file and safari downloads it as report.csv
Pragma: public
Expires: 0
Cache-Control: must-revalidate, post-check=0, pre-check=0
Cache-Control: private
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="report.csv";
Content-Transfer-Encoding: binary

A: Adding the quotes around the filename fixed things for me in Safari / PHP.

A: This one worked for me to get safari to behave:
@ob_end_clean(); //turn off output buffering to decrease cpu usage

// required for IE
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');

header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="download.csv"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');

header('Cache-control: no-cache, pre-check=0, post-check=0');
header('Cache-control: private');
header('Pragma: private');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // any date in the past

Taken from Idiot-proof, cross-browser force download in PHP - the questions are asking for different slightly different things, but the answers might be similar enough to consider marking this as a duplicate...


text:
Q: Sum Duration Across Appropriate Intervals I need some help. I have a table of individual contacts (i.e. phone calls) that contains the arrival time and the duration. I need to be able to count the number of contacts received in each 15 minute interval, as well as sum the "Talk Time" across each interval. The answered count will peg in the interval in which it arrived, and the appropriate portion of the duration will count at each interval in which the "clock was running" for the contact.
For example, a contact arrives at 2018-12-06 07:15:01.000, lasts for over 15 minutes (947 seconds). How would I get 900 seconds to appear in the 7:15 interval, but the remaining 47 seconds to appear in the 7:30 interval?
Below is a bit of test data in the form of a CTE.
I've got the 15 minute interval part figured out, but I have no idea how to tackle the duration sum. I've tried a few things but my brain gets stuck. I might be able to figure it out eventually, but the direction I take on this project hinges on whether I can get this beat quickly. I know it is possible because the built in report viewer on the source GUI can do it.
I would sure appreciate any help I can get.
;with cteTestData as (
SELECT 1 as ID, '2018-12-06 07:03:27.000' as ContactStartTime, Sum(Left('00:04:28',2) * 3600 + substring('00:04:28', 4,2) * 60 + substring('00:04:28', 7,2)) as Duration
UNION ALL
SELECT 2 as ID, '2018-12-06 07:03:32.000' as ContactStartTime, Sum(Left('00:14:28',2) * 3600 + substring('00:14:28', 4,2) * 60 + substring('00:14:28', 7,2)) as Duration
UNION ALL
SELECT 3 as ID, '2018-12-06 07:08:12.000' as ContactStartTime, Sum(Left('00:10:03',2) * 3600 + substring('00:10:03', 4,2) * 60 + substring('00:10:03', 7,2)) as Duration
UNION ALL
SELECT 4 as ID, '2018-12-06 07:14:59.000' as ContactStartTime, Sum(Left('00:02:58',2) * 3600 + substring('00:02:58', 4,2) * 60 + substring('00:02:58', 7,2)) as Duration
UNION ALL
SELECT 5 as ID, '2018-12-06 07:15:01.000' as ContactStartTime, Sum(Left('00:15:47',2) * 3600 + substring('00:15:47', 4,2) * 60 + substring('00:15:47', 7,2)) as Duration
UNION ALL
SELECT 6 as ID, '2018-12-06 07:15:12.000' as ContactStartTime, Sum(Left('00:08:18',2) * 3600 + substring('00:08:18', 4,2) * 60 + substring('00:08:18', 7,2)) as Duration
UNION ALL
SELECT 7 as ID, '2018-12-06 07:18:50.000' as ContactStartTime, Sum(Left('00:10:22',2) * 3600 + substring('00:10:22', 4,2) * 60 + substring('00:10:22', 7,2)) as Duration
UNION ALL
SELECT 8 as ID, '2018-12-06 07:20:05.000' as ContactStartTime, Sum(Left('00:03:11',2) * 3600 + substring('00:03:11', 4,2) * 60 + substring('00:03:11', 7,2)) as Duration
UNION ALL
SELECT 9 as ID, '2018-12-06 07:29:32.000' as ContactStartTime, Sum(Left('00:32:53',2) * 3600 + substring('00:32:53', 4,2) * 60 + substring('00:32:53', 7,2)) as Duration
UNION ALL
SELECT 10 as ID, '2018-12-06 07:35:17.000' as ContactStartTime, Sum(Left('00:07:37',2) * 3600 + substring('00:07:37', 4,2) * 60 + substring('00:07:37', 7,2)) as Duration
)
select ID, ContactStartTime
, DATEADD(minute, (DATEDIFF( minute, 0, ContactStartTime) / 15) * 15, 0) AS ContactStartInterval
, Duration

FROM cteTestData
ORDER BY ContactStartTime

EDIT: Here is the updated query from Squirrel with added notes.
    ;with
cteTestData   /*this will not be necessary in the production query, as this CTE will be replaced with the actual source table*/
as
(
    SELECT 1 as ID, '2018-12-06 07:03:27.000' as ContactStartTime, (Left('00:04:28',2) * 3600 + substring('00:04:28', 4,2) * 60 + substring('00:04:28', 7,2)) as Duration
    UNION ALL
    SELECT 2 as ID, '2018-12-06 07:03:32.000' as ContactStartTime, (Left('00:14:28',2) * 3600 + substring('00:14:28', 4,2) * 60 + substring('00:14:28', 7,2)) as Duration
    UNION ALL
    SELECT 3 as ID, '2018-12-06 07:08:12.000' as ContactStartTime, (Left('00:10:03',2) * 3600 + substring('00:10:03', 4,2) * 60 + substring('00:10:03', 7,2)) as Duration
    UNION ALL
    SELECT 4 as ID, '2018-12-06 07:14:59.000' as ContactStartTime, (Left('00:02:58',2) * 3600 + substring('00:02:58', 4,2) * 60 + substring('00:02:58', 7,2)) as Duration
    UNION ALL
    SELECT 5 as ID, '2018-12-06 07:15:01.000' as ContactStartTime, (Left('00:15:47',2) * 3600 + substring('00:15:47', 4,2) * 60 + substring('00:15:47', 7,2)) as Duration
    UNION ALL
    SELECT 6 as ID, '2018-12-06 07:15:12.000' as ContactStartTime, (Left('00:08:18',2) * 3600 + substring('00:08:18', 4,2) * 60 + substring('00:08:18', 7,2)) as Duration
    UNION ALL
    SELECT 7 as ID, '2018-12-06 07:18:50.000' as ContactStartTime, (Left('00:10:22',2) * 3600 + substring('00:10:22', 4,2) * 60 + substring('00:10:22', 7,2)) as Duration
    UNION ALL
    SELECT 8 as ID, '2018-12-06 07:20:05.000' as ContactStartTime, (Left('00:03:11',2) * 3600 + substring('00:03:11', 4,2) * 60 + substring('00:03:11', 7,2)) as Duration
    UNION ALL
    SELECT 9 as ID, '2018-12-06 07:29:32.000' as ContactStartTime, (Left('00:32:53',2) * 3600 + substring('00:32:53', 4,2) * 60 + substring('00:32:53', 7,2)) as Duration
    UNION ALL
    SELECT 10 as ID, '2018-12-06 07:35:17.000' as ContactStartTime, (Left('00:07:37',2) * 3600 + substring('00:07:37', 4,2) * 60 + substring('00:07:37', 7,2)) as Duration
),
cteIntervalNumbers as /*tally table to generate a number for each interval*/
(
    SELECT  num = 1
    union all
    SELECT  num = num + 1
    FROM    cteIntervalNumbers
    WHERE   num < 99
)
,
cteTimes as /*CTE to calculate ContactEndTime, ContactStartInterval, ContactEndInterval*/
(
    SELECT  ID, ContactStartTime
          , Duration
          , DATEADD(second, Duration, ContactStartTime) AS ContactEndTime
          , DATEADD(minute, (DATEDIFF( minute, 0, ContactStartTime) / 15) * 15, 0) AS ContactStartInterval
          , DATEADD(minute, (DATEDIFF( minute, 0, DATEADD(second, Duration, ContactStartTime)) / 15) * 15 + 15, 0) AS ContactEndInterval
    FROM    cteTestData /*this will be the source table*/
)
SELECT IntervalStart, count(DISTINCT ID) as Contacts, SUM(DurationInterval) as TalkTime
FROM (
SELECT  *
        ,
        CASE
        /*all of the time exists in the interval; just find the difference in start and end, which will be the entire duration*/
        WHEN  ContactStartTime >= IntervalStart AND ContactStartTime < IntervalEnd
        AND   ContactEndTime >= IntervalStart AND ContactEndTime < IntervalEnd
        THEN  DATEDIFF(second, ContactStartTime, ContactEndTime)
        /*contact carries over into next interval; get time between the start time and the end of that interval*/
        WHEN  ContactStartTime >= IntervalStart AND ContactStartTime < IntervalEnd
        AND   ContactEndTime > IntervalEnd
        THEN  DATEDIFF(second, ContactStartTime, IntervalEnd)
        /*this will get the elapsed time in the carry over intervals where the contact ends within that interval*/
        WHEN  ContactStartTime < IntervalStart
        AND   ContactEndTime >= IntervalStart  AND ContactEndTime < IntervalEnd
        THEN  DATEDIFF(second, IntervalStart, ContactEndTime)
        /*this is for all intervals where the contact neither starts nor ends i.e. where the full elapsed time of the interval is needed*/
        ELSE  DATEDIFF(second, IntervalStart, IntervalEnd)
        END AS DurationInterval
FROM    cteTimes d
        CROSS JOIN cteIntervalNumbers n
        CROSS APPLY /*this calcualtes the start and end time for each interval that the contact crossed*/
        (
            SELECT   DATEADD(minute, (num - 1) * 15, ContactStartInterval) AS IntervalStart
                    ,DATEADD(minute, num * 15, ContactStartInterval) AS IntervalEnd
        ) i
/*only show intervals crossed by each contact*/
WHERE   n.num <= datediff(minute, ContactStartInterval, ContactEndInterval) / 15 /*how many intervals does the contact cross?*/
) rawdata
GROUP BY IntervalStart

A: please refer to in-query comments for explanation.
Basically it checks for how much time it falls within the interval
|--------|---------|--------|     interval
    S...E                         [1]
    S....                         [2]
          ....E                   [3]
          .........               [4]

;with
cteTestData   -- Your Sample Data
as
(
    SELECT 1 as ID, '2018-12-06 07:03:27.000' as ContactStartTime, (Left('00:04:28',2) * 3600 + substring('00:04:28', 4,2) * 60 + substring('00:04:28', 7,2)) as Duration
    UNION ALL
    SELECT 2 as ID, '2018-12-06 07:03:32.000' as ContactStartTime, (Left('00:14:28',2) * 3600 + substring('00:14:28', 4,2) * 60 + substring('00:14:28', 7,2)) as Duration
    UNION ALL
    SELECT 3 as ID, '2018-12-06 07:08:12.000' as ContactStartTime, (Left('00:10:03',2) * 3600 + substring('00:10:03', 4,2) * 60 + substring('00:10:03', 7,2)) as Duration
    UNION ALL
    SELECT 4 as ID, '2018-12-06 07:14:59.000' as ContactStartTime, (Left('00:02:58',2) * 3600 + substring('00:02:58', 4,2) * 60 + substring('00:02:58', 7,2)) as Duration
    UNION ALL
    SELECT 5 as ID, '2018-12-06 07:15:01.000' as ContactStartTime, (Left('00:15:47',2) * 3600 + substring('00:15:47', 4,2) * 60 + substring('00:15:47', 7,2)) as Duration
    UNION ALL
    SELECT 6 as ID, '2018-12-06 07:15:12.000' as ContactStartTime, (Left('00:08:18',2) * 3600 + substring('00:08:18', 4,2) * 60 + substring('00:08:18', 7,2)) as Duration
    UNION ALL
    SELECT 7 as ID, '2018-12-06 07:18:50.000' as ContactStartTime, (Left('00:10:22',2) * 3600 + substring('00:10:22', 4,2) * 60 + substring('00:10:22', 7,2)) as Duration
    UNION ALL
    SELECT 8 as ID, '2018-12-06 07:20:05.000' as ContactStartTime, (Left('00:03:11',2) * 3600 + substring('00:03:11', 4,2) * 60 + substring('00:03:11', 7,2)) as Duration
    UNION ALL
    SELECT 9 as ID, '2018-12-06 07:29:32.000' as ContactStartTime, (Left('00:32:53',2) * 3600 + substring('00:32:53', 4,2) * 60 + substring('00:32:53', 7,2)) as Duration
    UNION ALL
    SELECT 10 as ID, '2018-12-06 07:35:17.000' as ContactStartTime, (Left('00:07:37',2) * 3600 + substring('00:07:37', 4,2) * 60 + substring('00:07:37', 7,2)) as Duration
),
numbers as       -- recursive CTE as number / tally table
(
    SELECT  n = 1
    union all
    SELECT  n = n + 1
    FROM    numbers
    WHERE   n < 99
),
cte as          -- CTE for calculate ContactEndTime, ContactStartInterval, ContactEndInterval
(
    SELECT  ID, ContactStartTime
          , Duration
          , DATEADD(second, Duration, ContactStartTime) AS ContactEndTime
          , DATEADD(minute, (DATEDIFF( minute, 0, ContactStartTime) / 15) * 15, 0) AS ContactStartInterval
          , DATEADD(minute, (DATEDIFF( minute, 0, DATEADD(second, Duration, ContactStartTime)) / 15) * 15 + 15, 0) AS ContactEndInterval
    FROM    cteTestData
)
-- the main query.
SELECT  *,
        CASE
        -- [1]
        WHEN  ContactStartTime  >= IntervalStart    AND ContactStartTime    < IntervalEnd
        AND   ContactEndTime    >= IntervalStart    AND ContactEndTime      < IntervalEnd
        THEN  DATEDIFF( second, ContactStartTime, ContactEndTime)
        -- [2]
        WHEN  ContactStartTime  >= IntervalStart    AND ContactStartTime    < IntervalEnd
        AND   ContactEndTime    > IntervalEnd
        THEN  DATEDIFF( second, ContactStartTime, IntervalEnd)
        -- [3]
        WHEN  ContactStartTime  < IntervalStart
        AND   ContactEndTime    >= IntervalStart    AND ContactEndTime      < IntervalEnd
        THEN  DATEDIFF( second, IntervalStart, ContactEndTime)
        -- [4]
        ELSE  DATEDIFF( second, IntervalStart, IntervalEnd)
        END AS DurationInterval
FROM    cte d
        CROSS JOIN numbers n
        CROSS APPLY  -- this calcualtes the start and end time for each interval
        (
            SELECT   DATEADD( minute, (n - 1) * 15, ContactStartInterval) AS IntervalStart
                    ,DATEADD( minute, n * 15, ContactStartInterval) AS IntervalEnd
        ) i
WHERE   n.n <= datediff(minute, ContactStartInterval, ContactEndInterval) / 15
ORDER BY ContactStartTime, n


text:
Q: Are the right and left hand limits of an increasing function locally uniformly convergent? Let $f : \mathbb{R} \to \mathbb{R}$ be increasing. Hence we know $f$ is differentiable almost everywhere, and that the right and left hand limits, respectively $f(x+)$ and $f(x-)$, exist at every $x \in \mathbb{R}$. I would like to know whether these right and left hand limits are locally uniformly convergent.

Namely, given $[a,b] \subseteq \mathbb{R}$ and $\epsilon > 0$, does there exist a $\delta > 0$ so that for all $x \in [a,b]$, if $0 < \delta' \le \delta$,
$|g(x \pm) - g(x \pm \delta')| < \epsilon$?

Given any $\epsilon > 0$, we may cover $[a,b]$ by finitely many intervals $(x_j - \delta_j, x_j - \delta_j)$, so that, for instance, $y \in (x_j, x_j + \delta_j) \implies |g(x_j+) - g(y)| < \epsilon$. I'm not sure how to proceed from here.
This property holds for any continuous increasing $f$, and for elementary functions of bounded variation like steps functions. So if the property is false in general, one will need to cook up a more exotic BV function as a counterexample. I am particularly interested in the (rather general) case $f(x) = \int_{-\infty}^x \mu$, for $\mu$ a positive Borel measure.
Hints or solutions are greatly appreciated.


text:
Q: Retrieving LoggedIn User in Base Page Model Class in ASP.NET Core I use ASP.NET Core Identity for the user management activities along with EF Core for the database interaction. I have successfully implemented the login functionality using Identity. And I am able to get the logged in user object (as CliamsPrincipal object) in my razor page classes.
All my razor pages inherit a custom base class, and that base class inherit the default "PageModel" class. In my razor pages, I have the logic to written to save entities into the database. When saving those entities, the user who created the entity object is stored as well (db level, user ID is stored).
The user class is known as "ApplicationUser" which inherit the AspNet Core Identity "IdentityUser". ApplicationUser is stored in the database against the each save of my entities.
I can simply write this logic in each razor page model class, but it would be a duplication of the same code in each razor pages. Therefore I want to centralized the code in retrieving the logged in user as a "ApplicationUser" object in my base page model class. And expose the logged in user as property from that class.
However I am bit struggling to implement that in my base page model class and the code I have written seems not to be working. The "User" (System.Security.Claims.ClaimsPrincipal) in PageModel.User object is null. even though user is successfully logged in.
In the debugging phase I found out that during the execution the razor page constructor the User object is null, but however the User object get assigned with logged in user in the OnGet page handler method (as an example).
Below is the code that I have implemented
public class BasePageModel : PageModel
{
    private readonly UserManager<ApplicationUser>        userManager;

    public ApplicationUser LoggedInUser  {  get; set;   }

    public BasePageModel() { }

    public BasePageModel(UserManager<ApplicationUser> userManager)
    {
        this.userManager = userManager;
        GetLoggedInUser();
    }

    private async void GetLoggedInUser()
    {
        LoggedInUser =  await userManager.GetUserAsync(User);
    }
}

Page model class
[Authorize]
public class IndexModel : BasePageModel, IBasePageModel
{
    private readonly ILogger<IndexModel>                logger;

    public string ApplicationName { get; set; }

    public IndexModel(ILogger<IndexModel> logger, IOptions<ApplicationSetting> appSettings, UserManager<ApplicationUser> userManager) : base(userManager)
    {
        this.logger = logger;
        ApplicationName     = appSettings.Value.Name;
    }

    public void OnGet()
    {
      return Page();
    }

    public void OnPost()
    {
        //SaveMethod(PostObj, LoggedInUser);
    }
}

ConfigureServices method in Startup class
services.AddScoped<BasePageModel, BasePageModel>();

If there is a better way to centralize this logic or improve in retrieving the logged in user, I am all ears.


text:
Q: Unable to create account in magento 2.2.10 Unable to create account. It refresh the register form without any response

A: Try to change your base URL in core_config_data table in database

from : http://localhost:8888/magento
to : http://127.0.0.1:8888/magento

Hope this will help you!


text:
Q: Generating all binary trees of N nodes in lexigraphical order I was just curious if anyone has an algorithm for how to generate binary trees of N nodes in lexigraphical order.
The very first binary tree would be a right chain of length N. The last tree would be a left chain of length N. I would like to know how to generate the trees in between the first binary tree and last binary tree in lexigraphical order.
A tree with 4 nodes would have 14 binary trees.
A tree with 3 nodes would have 5 binary trees.
etc.
EDIT:
So, when you predorder traverse a tree, if you hit a non-null node you output a 1, if you hit a null output a 0. So the tree is ordered from 1,2,3,...N. A tree of node 5 would have a right chain of 1,2,3,4,5 in this order. I was thinking theoreticially this could work: If I just take the lowest numbered leaf node and reverse preorder traverse one position and move this node to that position. If this node was originally a child of its node-1, and after reverse preorder traversing this node is no longer a child of node-1, than I shift all LEAF nodes less than this node to the best possible preorder position (which should probably be the most right branch).

A: I won't give you a direct solution. But I will give an solution here for a similar problem: Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
I think it is not hard for you to modify my solution a little bit to solve your problem.
public class Solution {
    public List<TreeNode> generateTrees(int n) {
        return helper(1, n);
    }

    private List<TreeNode> helper(int start, int end) {
        List<TreeNode> result = new ArrayList<TreeNode>();

        if (start > end) {
            result.add(null);
            return result;
        }

        // You just need to understand how below for loop works.
        for (int i = start; i <= end; i++) {
            List<TreeNode> left = helper(start, i - 1);
            List<TreeNode> right = helper(i + 1, end);
            for (TreeNode l : left) {
                for (TreeNode r : right) {
                    TreeNode root = new TreeNode(i);
                    root.left = l;
                    root.right = r;
                    result.add(root);
                }
            }
        }

        return result;
    }
}

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; left = null; right = null; }
}

The solution is pretty straightforward using Dynamic Programming.


text:
Q: MySQL replace into and get last insert ID In MySQL, will a REPLACE INTO query work with the LAST_INSERT_ID function?
Essentially, I have to insert into one table, only where it doesn't exist, but then either way insert into the second table with a foreign key constraint of the first table.
So ie.
REPLACE INTO TABLE1(NAME) VALUES('unique');
SET @table1_id = LAST_INSERT_ID();
INSERT INTO TABLE2(TABLE1_ID, VALUE) VALUES(@table1_id, 'Test Value');

Will that function as intended on both an insert and an update?

A: Yes, REPLACE INTO query affects the result of LAST_INSERT_ID() function.
Documentation states:

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.

That means if INSERT affects LAST_INSERT_ID() then REPLACE should do it too.
I have tested it with MySQL 8.


text:
Q: PHP not working in Apache2 after system upgrade Recently upgraded my system from Karmic to Lucid. This involved Apache and PHP being updated I believe.
Now my server is unable to handle PHP files, any navigation to them is triggering downloading rather than parsing.
The PHP module is still loaded in Apache mods-enabled and I have
AddType application/x-httpd-php .php in my httpd.conf.
There are no meaningful messages in Apache access or error logs so I am stumped.
Any help would be appreciated. Thanks.

A: Well after nothing else worked and Apache was getting very confusing I finally just purged all of the Apache packages and reinstalled them.
Seems to be working fine now, who knows what was wrong with it....
EDIT
I found out what was wrong when I was setting up my Apache configuration settings again.
[This blog entry][1] explains it.
Turns out that although the userdir module is not actively in use, the rest of the sites files reside in my ~/public_html folder, and php was being disabled for everything in there.
I guess this must have been a recent addition to the php module which wasn't present in my Karmic settings.

A: /var/log/apache2/error.log should show a line like the below if PHP was succesfully loaded:

[Tue Aug 30 12:53:36 2011] [notice] Apache/2.2.14 (Ubuntu) PHP/5.3.2-1ubuntu4.9 with Suhosin-Patch configured -- resuming normal operations

Pay attention to the date, if it's something from 2009, you've misconfigured something.
AddType is useless, you need to use:
<FilesMatch "\.php$">
    SetHandler application/x-httpd-php
</FilesMatch>

See also the installation instructions on php.net for Apache 2.x.
You should not have a need to add that manually, the package libapache2-mod-php5 installs /etc/apache2/mods-available/php5.conf containing:
<IfModule mod_php5.c>
    <FilesMatch "\.ph(p3?|tml)$">
        SetHandler application/x-httpd-php
    </FilesMatch>
    <FilesMatch "\.phps$">
        SetHandler application/x-httpd-php-source
    </FilesMatch>
    # To re-enable php in user directories comment the following lines
    # (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
    # prevents .htaccess files from disabling it.
    <IfModule mod_userdir.c>
        <Directory /home/*/public_html>
            php_admin_value engine Off
        </Directory>
    </IfModule>
</IfModule>

Since it's a conffile, it's possible that it's not installed with the upgrade. To fix that purge it and then install it again:
sudo apt-get purge libapache2-mod-php5
sudo apt-get install libapache2-mod-php5

To enable PHP, you have to run:
sudo a2enmod php5

Restart the webserver after:
sudo /etc/init.d/apache2 restart

Other things to do:

*

*check for conflicting settings in /etc/apache2.

*have you built Apache from source?

*Run sudo apache2ctl configtest to check your configuration for syntax errors

*Open http://localhost/server-info to check the loaded configuration and modules. The status module must be loaded for that. If you're running a remote server, you need to add yourself to the Allow from list in /etc/apache2/mods-enabled/status.conf and restart the server afterwards

A: the php5.conf file in /etc/apache2/mods-enabled has a few lines at the bottom that keep php from executing inside of a user directory, so depending on your configuration, this could be your issue also. You can just comment these lines out and apache2 reload


text:
Q: How can I truncate latitude and longitude in Presto without rounding or cutting off 0s? I have an issue where I am attempting to truncate latitude and longitude to 3 decimal places, but I don't want to ROUND because it will change the location.
I tried CAST((TRUNCATE(lat * 100) / 100) AS VARCHAR) but if I do that, it will remove trailing zeros (if the latitude is -122.200 it will return -122.2
I thought I could use RPAD to select a portion of the string (in this case '.') and then pad it a certain number of spaces (in this case 3 spaces. But when I try RPAD(CAST(lng AS VARCHAR), 3, '.') it returns -12
Any ideas would be appreciated. Thanks!

A: You should use regular expression:
SELECT
 regexp_replace( CAST(-122.219980 as varchar), '\.(\d{1,3})\d*', '.$1' ),
 regexp_replace( CAST(-122.200911 as varchar), '\.(\d{1,3})\d*', '.$1' )

will result in:
-122.219    -122.200

like requested.


text:
Q: How can I prohibit access to all sites in Google Chrome? How can I prohibit access to all sites in Google Chrome, except for one or two sites?

A: Not too nice, but if you can somehow ensure folks won't change the settings:

*

*Make your internet settings use a non-existing proxy server (like "localhost");

*Add exceptions for the few sites you want to allow.

A: OpenDNS has web content filtering, even in the free version. The free version supports up to 25 blacklist/whitelist items. As an extra, you'll get phishing and botnet protection and your web browsing may also receive some extra speed!

A: Back these days, I used Privoxy:

Privoxy is a non-caching web proxy with advanced filtering capabilities for enhancing privacy, modifying web page data and HTTP headers, controlling access, and removing ads and other obnoxious Internet junk. Privoxy has a flexible configuration and can be customized to suit individual needs and tastes. It has application for both stand-alone systems and multi-user networks.


text:
Q: Is iteration slower than linear code? Which one is preferable? I have a question in my mind from last many days, that while writing a code in ruby, is the linear code is faster and preferable than an iteration?
Let me have an example. There is a block of code for same functionality written in two different ways:
Way 1:
['dog', 'cat', 'tiger'].each do |pet_name|
  puts "I have many pets, one of them is #{pet_name}."
end

Way 2:
puts "I have many pets, one of them is dog."
puts "I have many pets, one of them is cat."
puts "I have many pets, one of them is tiger."

So, I want to know which one is better and preferable? As per my view, I think 2nd one will take less time and memory. But I want to confirm.

A: Sequential logic is faster (see the benchmark below the fold), but it almost never matters.  The clearer and more maintainable code should always be selected.  Only a demonstrated need should cause one to cease optimizing for the programmer and begin optimizing for the machine.  By demonstrated, I mean measured--you ran it and found it to be too slow.
The second example violates the DRY (Don't Repeat Yourself) principle and is a minor maintenance problem.

require 'benchmark'

LOOPS = 100000

Benchmark.bm(10) do |x|
  x.report('iteration') do
    LOOPS.times do
      ['dog', 'cat', 'tiger'].each do |pet_name|
        "I have many pets, one of them is #{pet_name}."
      end
    end
  end
  x.report('sequence') do
    LOOPS.times do
      "I have many pets, one of them is dog."
      "I have many pets, one of them is cat."
      "I have many pets, one of them is tiger."
    end
  end
end

# =>                  user     system      total        real
# => iteration    0.200000   0.000000   0.200000 (  0.202054)
# => sequence     0.010000   0.000000   0.010000 (  0.012195)

A: In both cases, the time spent running the actual Ruby code is going to be completely dominated by the time it takes to print the text to the screen. Remember: console output is slow. Really slow. Painfully slow.
Since in both cases the code prints the same amount of text (and, in fact, the same text) to the screen, any miniscule performance differences that might or might not exist are going to be lost in the noise.

I think 2nd one will take less time and memory.

Don't think. Look.
Here's a crazy idea: if you want to know which one runs faster, run them and see which one runs faster!

A: Strictly speaking, yes, there is an overhead involved in iteration. There will be in any language you use (although some use compiler tricks to reduce this). The first version of your code will run a negligible amount quicker due to the cost of iteration, and of building the array you've defined. Also, the string building will probably add another tiny slice of cost.
That being said, it's such a tiny difference you'd have to be very picky to notice, or even care about any of this. It's negligible. Try benchmarking it yourself, you won't notice a significant difference.
I'm not prepared to write 10,000 lines like that for some method, are you? I find that iteration looks a lot cleaner, especially for non-trivial code, and is often preferable in terms of readability and clean code. Not to mention it's more DRY.

A: There is always cost for calling a function, creating an array or creating loop.. However this is what programming languages were built for, so to answer your question: yes, the second code would be faster, nanoseconds maybe. But the first code is more general, you never know when you will buy a new pet. It's more useful, maybe someone will give you list of their pets, and you will want to talk about them? Generally speaking well - second code is unnoticeably faster, but first is better and preferable.

A: I realize that your example is very simplified and unlikely to happen in real world, but taking it literally:
The first example will create intermediate objects (strings and array), so you may say that in fact it will take more memory. However these object will be garbage-collected later, so you'll get your memory back. (This would not be the case if you defined array of symbols, as symbols are not garbage-collected).
It is also faster, because it doesn't need to fetch the objects internally from the array during each iteration. But the difference if obviously unnoticeable and should not be taken into account. What should be taken into account is readability here.
If you were a performance freak that you should probably define your methods without parentheses around the arguments as well, because this would result in smaller parse tree created by Ruby interpreter.
# slower
def meth(arg)
end

# faster
def meth arg
end

But considering it a valid reason would be silly of course.
Edit: if you're looking for a good Ruby style guide check this: https://github.com/bbatsov/ruby-style-guide

A: If one of those two options were clearly better and therefore preferable, the language wouldn't provide both options. As always, it depends on the circumstances. Questions you should be asking to decide include

*

*which solution is more readable? (For habitual Ruby programmers, the first one is.) The more readable, the better.

*which solution is faster? (You can only decide this by measuring. Take care to use a realistic example - the time difference for only three animals may not even be measurable reliably.) The faster, the better.

*how much duplication is introduced by "unrolling" the more idiomatic version? (In this case, not very much - the puts and part of the string literal.) The less duplication you would introduce, the better.

As you see, the answers contradict each other, so you have to understand the context of the decision you're making and weigh the factors correctly to find out which is best overall.


text:
Q: converting a list including string and int objects to bytearray for socket communication I am trying to sent a list that contains both integer values as well as string values to a remote computer via socket communication. I tried converting the list to a bytearray that can then be sent using socket.send(), but I am receiving the following error:
TypeError: 'str' object cannot be interpreted as an integer

is there a way to send this information without splitting the integer and string parts of the list?
edit*:
the code looks as following:
list=[1,"a"]

HOST= '192.168.0.31' # Server IP or Hostname
PORT = 12345 # Pick an open Port (1000+ recommended), must match the server port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send(list)

A: From an answer to this question.
Is pickle file of python cross-platform?
Since the pickel is cross-platform compatible (if certain conditions are met !) You can dump the pickel data into the socket of one machine, and read from the socket of the other machine. But you need to guarantee few things. It is better if the python versions running on the machines are same. And not all pickle formats are cross-platform compatible, but the default format ASCII pickles are compatible, Pls refer to the tagged question for more about pickle compatibility for cross platforms
And for the coding part
In server
s.sendall(pickle.dumps(list))

In the client side
list = pickle.loads(rcvd_data)


text:
Q: Visual Studio load design form Does anyone came across a problem when you have a Class that inherits from Forms and then have all the forms inherit from Class, and then tried to load the form in design mode in visual studio? Does it loads correctly, because on mine it shows "Illegal characters in path.".
I ran the visual studio in debug mode and found that it is try to check a path for the file I suppose and gets the ´>´ of the generic definition.
So is it possible to implement generics over windows forms or do I have to get a workaround for this, I have searched the internet for some examples or clues where to follow but could find any important one. Any pointers would be much appreciated, because the application works runs fine but not the design mode of visual studio.
Thanks.
Base class
public class BaseForm<T, TU> : Form, IFormLanguageStrings
        where T : class
        where TU : class
    {
        #region Variables

        public IApplicationValues applicationValues;
        public T businessObject;
        public IEventBroker eventBroker;
        private bool hasChangesToCommit = false;
        public ILanguageManager languageManager;
        public IMessageBox messageBox;
        public TU objService;
        public DatabaseOperationType operationType;
        public event EventHandler OnNeedToCommitChanges;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseForm"/> class.
        /// </summary>
        public BaseForm()
        {
            Closing += BaseForm_Closing;
            Load += BaseForm_Load;
            if (IsInDesignMode) return;
            SetService();
        }

        #endregion

        #region Form Events

        /// <summary>
        /// Handles the Load event of the BaseForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BaseForm_Load(object sender, EventArgs e)
        {
            if (IsInDesignMode) return;
            SetLabels();
            SetControls();
            LoadCombos();
            LoadDataForForm();
            ValidateDataInput();

            if (operationType == DatabaseOperationType.View)
            {
                eventBroker.Unregister(this);
                DisableAllControls();
                InvisibleSelectControls("BtnAction");
            }
        }

        /// <summary>
        /// Handles the Closing event of the BaseForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
        private void BaseForm_Closing(object sender, CancelEventArgs e)
        {
            if (hasChangesToCommit)
            {
                if (
                    messageBox.ShowQuestion(languageManager.GetString("MSG_PerformPendingOperations"),
                                            MessageBoxButton.YesNo, MessageBoxResult.No) == MessageBoxResult.Yes)
                {
                    RaiseCommitChanges();
                }
            }
            if (eventBroker != null)
                eventBroker.Unregister(this);
        }

        #endregion

        #region Virtual Methods

        /// <summary>
        /// Sets the labels.
        /// </summary>
        public virtual void SetLabels()
        {
            Controls.All().OfType<Control>().ToList().ForEach(
                ctl =>
                    {
                        if (!string.IsNullOrEmpty(ctl.Name))
                        {
                            string label = languageManager.GetString(ctl.Name);
                            if (!string.IsNullOrEmpty(label))
                            {
                                ctl.Text = label;
                            }
                            if (ctl is ElementHost)
                            {
                                if (((ElementHost) ctl).Child is IFormLanguageStrings)
                                {
                                    (((ElementHost) ctl).Child as IFormLanguageStrings).SetLabels();
                                }
                            }
                        }
                    });
        }

        /// <summary>
        /// Sets the service.
        /// </summary>
        public virtual void SetService()
        {
            applicationValues = ServiceGateway.GetService<IApplicationValues>();
            languageManager = ServiceGateway.GetService<ILanguageManager>();
            messageBox = ServiceGateway.GetService<IMessageBox>();
            eventBroker = ServiceGateway.GetService<IEventBroker>();
            eventBroker.Register(this);
            objService = ServiceGateway.GetService<TU>();
        }

        /// <summary>
        /// Validates the data input.
        /// </summary>
        public virtual void ValidateDataInput()
        {
        }

        /// <summary>
        /// Determines whether [has to commit changes] [the specified commit].
        /// </summary>
        /// <param name="commit">if set to <c>true</c> [commit].</param>
        public virtual void HasToCommitChanges(bool commit)
        {
            switch (operationType)
            {
                case DatabaseOperationType.Update:
                    hasChangesToCommit = commit;
                    break;
            }
        }

        /// <summary>
        /// Loads the combos.
        /// </summary>
        public virtual void LoadCombos()
        {
        }

        /// <summary>
        /// Loads the data for form.
        /// </summary>
        public virtual void LoadDataForForm()
        {
        }

        /// <summary>
        /// Sets the controls.
        /// </summary>
        public virtual void SetControls()
        {
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Raises the commit changes.
        /// </summary>
        private void RaiseCommitChanges()
        {
            if (OnNeedToCommitChanges != null)
            {
                OnNeedToCommitChanges(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// Closes the form.
        /// </summary>
        protected void CloseForm()
        {
            FireEventBroker(EventTopics.CloseMdiChild, new CloseMdiChildEventArgs(this));
        }

        /// <summary>
        /// Enables or disable controls.
        /// </summary>
        /// <typeparam name="T">type of control</typeparam>
        /// <param name="isEnable">if set to <c>true</c> [is enable].</param>
        private void EnableDisableControls<TX>(bool isEnable) where TX : Control
        {
            Controls.All()
                .OfType<TX>()
                .ToList()
                .ForEach(ctl => ctl.Enabled = isEnable);
        }

        /// <summary>
        /// Visibles or invisible all controls.
        /// </summary>
        /// <param name="isVisible">if set to <c>true</c> [is visible].</param>
        private void VisibleInvisibleAllControls(bool isVisible)
        {
            Controls.All()
                .OfType<Control>()
                .ToList()
                .ForEach(ctl => ctl.Visible = isVisible);
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Gets a value indicating whether this instance is in design mode.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance is in design mode; otherwise, <c>false</c>.
        /// </value>
        public bool IsInDesignMode
        {
            get { return (Process.GetCurrentProcess().ProcessName == "devenv"); }
        }

        /// <summary>
        /// Fires the event broker.
        /// </summary>
        /// <param name="eventTopic">The event topic.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public void FireEventBroker(string eventTopic, EventArgs eventArgs)
        {
            eventBroker.Fire(eventTopic, this, eventArgs);
        }

        /// <summary>
        /// Clears all bindings.
        /// </summary>
        public void ClearAllBindings()
        {
            Controls.All().OfType<Control>().ToList().ForEach(
                ctl => { if (ctl.DataBindings.Count != 0) ctl.DataBindings.Clear(); });
        }

        /// <summary>
        /// Enables all controls.
        /// </summary>
        public void EnableAllControls()
        {
            EnableDisableAllControls(true);
        }

        /// <summary>
        /// Disables all controls.
        /// </summary>
        public void DisableAllControls()
        {
            EnableDisableAllControls(false);
        }

        /// <summary>
        /// Enables or disable all controls.
        /// </summary>
        /// <param name="isEnable">if set to <c>true</c> [is enable].</param>
        private void EnableDisableAllControls(bool isEnable)
        {
            Controls.All()
                .OfType<Control>()
                .ToList()
                .ForEach(ctl => ctl.Enabled = isEnable);
        }

        /// <summary>
        /// Enables all buttons.
        /// </summary>
        public void EnableAllButtons()
        {
            EnableDisableControls<Button>(true);
        }

        /// <summary>
        /// Disables all buttons.
        /// </summary>
        public void DisableAllButtons()
        {
            EnableDisableControls<Button>(false);
        }

        /// <summary>
        /// Enables all text boxes.
        /// </summary>
        public void EnableAllTextBoxes()
        {
            EnableDisableControls<TextBox>(true);
        }

        /// <summary>
        /// Disables all text boxes.
        /// </summary>
        public void DisableAllTextBoxes()
        {
            EnableDisableControls<TextBox>(false);
        }

        /// <summary>
        /// Enables the select controls.
        /// </summary>
        /// <param name="controlNames">The control names.</param>
        public void EnableSelectControls(params string[] controlNames)
        {
            EnableDisableSelectedControls(true, controlNames);
        }

        /// <summary>
        /// Disables the select controls.
        /// </summary>
        /// <param name="controlNames">The control names.</param>
        public void DisableSelectControls(params string[] controlNames)
        {
            EnableDisableSelectedControls(false, controlNames);
        }

        /// <summary>
        /// Enables or disable selected controls.
        /// </summary>
        /// <param name="isEnable">if set to <c>true</c> [is enable].</param>
        /// <param name="controlNames">The control names.</param>
        public void EnableDisableSelectedControls(bool isEnable, params string[] controlNames)
        {
            Controls.All()
                .OfType<Control>()
                .ToList()
                .ForEach(ctl => { if (controlNames.Contains(ctl.Name)) ctl.Enabled = isEnable; });
        }

        /// <summary>
        /// Visibles the select controls.
        /// </summary>
        /// <param name="controlNames">The control names.</param>
        public void VisibleSelectControls(params string[] controlNames)
        {
            VisibleInvisibleSelectedControls(true, controlNames);
        }

        /// <summary>
        /// Invisibles the select controls.
        /// </summary>
        /// <param name="controlNames">The control names.</param>
        public void InvisibleSelectControls(params string[] controlNames)
        {
            VisibleInvisibleSelectedControls(false, controlNames);
        }

        /// <summary>
        /// Visibles or invisible selected controls.
        /// </summary>
        /// <param name="isVisible">if set to <c>true</c> [is visible].</param>
        /// <param name="controlNames">The control names.</param>
        private void VisibleInvisibleSelectedControls(bool isVisible, params string[] controlNames)
        {
            Controls.All()
                .OfType<Control>()
                .ToList()
                .ForEach(ctl => { if (controlNames.Contains(ctl.Name)) ctl.Visible = isVisible; });
        }

        /// <summary>
        /// Visibles all controls.
        /// </summary>
        public void VisibleAllControls()
        {
            VisibleInvisibleAllControls(true);
        }

        /// <summary>
        /// Invisibles all controls.
        /// </summary>
        public void InvisibleAllControls()
        {
            VisibleInvisibleAllControls(false);
        }

        #endregion
    }
}

A: Ok so problem is that for "MyForm" designer doesn't work:
    public class MyForm : BaseForm<MyPresenter, MyView>
    {
        //designer doesn't work
    }

Workaround for this is to create helper class:
    public class MyFormWithDesign : BaseForm<MyPresenter, MyView>
    {
        //designer doesn't work
    }

so we derive from helper class and not from generic class:
    public class MyForm : MyFormWithDesign
    {
        //designer WORKS!
    }

Additional details about the problem can be found here:
Windows Form Designer can't use a component derived from a generic class


text:
Q: difference between algebraic set and affine algebraic set in hartshorne my question is basically already in the title. I just started to read the Algebraic Geometry book by Hartshorne where he defines an algebraic set but in some propositions a bit later talks about affine algebraic sets. So does he mean the same thing because i didn't see him define affine algebraic sets?
Thank you!

A: an algebraic set (or variety) is the zero set of a polynomial whose
coefficients belong to a given
field k, considered as a subset of k^n.
if k contains R k^n may be considered affine space,
in the sense that it is closed under u,v-->au+(1-a)v for all a in R,
and then the algebraic set may be called affine.
some authors use variety only to mean na irreducible algebraic set.


text:
Q: Debugging client side application I am trying to debug my client side code which i have checked-out from SVN to eclipse workspace. My server process is already up and running. I have a start-up script for our client which has the following line to start the client.
jre/bin/java splash:images/initializing.png -classpath "$CLASS_PATH" in.co.xxx.xxx.yyy.yyy.launcher.Launcher $* &

I added the debugging related arguments to it
jre/bin/java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=9045,suspend=n -splash:images/initializing.png -classpath "$CLASS_PATH" in.co.xxx.xxx.yyy.yyy.launcher.Launcher $* &

In Eclipse i went to debug configurations entered the hostname and port number(same i mentioned in the startup script (9045)). I added all the client related classes in source tab of debug configurations. Now comes the problem.
When i click debug button after all this, the remote debugger should be launching and waiting for the connection when i fire my start-up script. But it is saying
Failed to connect to remote VM. Connection refused.
Connection refused

I have tried with different port numbers as well. Nothing seems to work. Please suggest what am i missing here .

A: Did you check Eclipse logs to see if anything further got logged there? Also, when you say debug did not launch 'post authentication page', did you see on the 'server side' if there is a message to 'standard output' stating that the debug port is 'released'? (something similar to this would be emitted on standard output). If this did not show up, then the 'first successful connection' might not have actually released the debugger while you think it did.
Also this works for me here, the only difference I see is that the order of parameters in your and my debug switch are different. Hope this helps!
-Xdebug -Xrunjdwp:transport=dt_socket,address=8080,server=y,suspend=n


text:
Q: Can't load QSQLCIPHER in Qt in Release mode I've been compiled sqlcipher for Qt that used in my Qt App. In debug mode my sqlcipher plugins work fine but in release mode it said:
QSqlDatabase: QSQLCIPHER driver not loaded
Please help me.

A: Check your plugin path (QApplication::libraryPaths()) & appropriate dll-s inside it. As I remember, there are always two copies of one sql plug-in - debug & non-debug.


text:
Q: How to put the type cursor automatically in a JEditorPane? After a card panel switch I would like to automatically put the type cursor in a JEditorPane located in my new displayed card. How can I do that?

A: editorPane.requestFocusInWindow();

A: I think you are asking to place focus on the editor pane when you switch cards when using a CardLayout. If so, then check out Card Layout Focus for one approach.


text:
Q: Difficult in aligning textview and ratingbar I'm not so expert about XML and i need help to align two elements, a textview and a ratingbar.
I would to align the ratingbar (the five stars) at the same level of the textview ("user").
How to do this?

Here is the XML code:
<?xml version="1.0" encoding="utf-8"?>
<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:background="@drawable/evento_pressione" >

    <LinearLayout
        android:id="@+id/viewName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="40dp"
        android:background="@drawable/green_button_pressed" >

        <TextView
            android:id="@+id/nameMerchant"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center_horizontal"
            android:text="Users list"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#f6911e"
            android:textStyle="bold" tools:ignore="HardcodedText"/>
    </LinearLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/viewName" >

    <ImageView
        android:id="@+id/arrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/userM"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:layout_alignTop="@+id/userM"
        android:src="@drawable/arrow" />

    <TextView
        android:id="@+id/userM"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_margin="20dp"
        android:layout_marginLeft="21dp"
        android:text="Comune"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#4a4c4d"
        tools:ignore="HardcodedText" />

    <RatingBar
        android:id="@+id/rateM"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/arrow"
        android:layout_marginRight="30dp"
        android:layout_margin="20dp"
        android:indeterminate="false"
        android:isIndicator="true"
        android:numStars="@integer/five"
        android:stepSize="1.0" />

    </RelativeLayout>
</RelativeLayout>

A: <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:gravity="left" >

<LinearLayout
    android:id="@+id/viewName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="40dp" >

    <TextView
        android:id="@+id/nameMerchant"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center_horizontal"
        android:text="Users list"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#f6911e"
        android:textStyle="bold"
        tools:ignore="HardcodedText" />
</LinearLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/viewName" >

    <TextView
        android:id="@+id/userM"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_margin="20dp"
        android:layout_marginLeft="21dp"
        android:text="Comune"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#4a4c4d"
        tools:ignore="HardcodedText" />

    <RatingBar
        android:id="@+id/rateM"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_margin="20dp"
        android:layout_marginRight="30dp"
        android:indeterminate="false"
        android:isIndicator="true"
        android:numStars="5"
        android:stepSize="1.0" />

    <ImageView
        android:id="@+id/arrow"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignBottom="@+id/userM"
        android:layout_alignParentRight="true"
        android:src="@drawable/icon" />
</RelativeLayout>

A: Try this:
<?xml version="1.0" encoding="utf-8"?>
<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:background="@drawable/evento_pressione" >

    <LinearLayout
        android:id="@+id/viewName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="40dp"
        android:background="@drawable/green_button_pressed" >

        <TextView
            android:id="@+id/nameMerchant"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center_horizontal"
            android:text="Users list"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#f6911e"
            android:textStyle="bold" tools:ignore="HardcodedText"/>
    </LinearLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/viewName" >

    <ImageView
        android:id="@+id/arrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/userM"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:layout_alignTop="@+id/userM"
        android:src="@drawable/arrow" />

    <TextView
        android:id="@+id/userM"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_margin="20dp"
        android:layout_marginLeft="21dp"
        android:layout_centerVertical="true"
        android:text="Comune"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#4a4c4d"
        tools:ignore="HardcodedText" />

    <RatingBar
        android:id="@+id/rateM"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/arrow"
        android:layout_marginRight="30dp"
        android:layout_margin="20dp"
        android:layout_centerVertical="true"
        android:indeterminate="false"
        android:isIndicator="true"
        android:numStars="@integer/five"
        android:stepSize="1.0" />

    </RelativeLayout>
</RelativeLayout>

A: I got excellent alignment using  android:layout_alignBottom="@+id/textRatingBar" on TextView along with android:paddingBottom="2dp" on RatingBar, (you may have to adjust values based on your font size)

here's excerpt from layout file:
            <TextView
            android:id="@+id/textRatingBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/textDealTime"
            android:layout_marginLeft="5dp"
            android:text="Rating"
            android:textColor="@color/dark_gray"
            android:textSize="14sp" />
        <RatingBar
            android:id="@+id/ratingBar"
            style="?android:attr/ratingBarStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="2dp"
            android:numStars = "5"
            android:stepSize="0.1"
            android:isIndicator="true"
            android:progressBackgroundTint="@color/main_teal"
            android:progressTint="@color/main_teal"
            android:secondaryProgressTint="@color/main_teal"
            android:layout_alignBottom="@+id/textRatingBar"
            android:layout_toRightOf="@+id/textRatingBar"
            android:layout_toEndOf="@+id/textRatingBar" />

A: this might come in late but for those this might help in the future. Here's how I could achieve this.
The main attributes that need be applied to achieve it are
        android:layout_alignBottom="@+id/your_rating_bar_id"
        android:layout_alignTop="@+id/your_rating_bar_id"
        android:gravity="center_vertical"

put this on your TextView element ensuring there's no constraint on it's height and it will vertically align it's center with that of the rating bar element with
id="your_rating_bar_id"
Hope this helps.


text:
Q: Cannot read property 'hasOwnProperty' After an update, if the status code was an 422 i have a notification with this message : Cannot read property 'hasOwnProperty' of undefined
    TypeError: Cannot read property 'hasOwnProperty' of undefined
    at validateResponseFormat (http://localhost:4100/static/js/0.chunk.js:147058:17)
    at http://localhost:4100/static/js/0.chunk.js:147133:43
    at step (http://localhost:4100/static/js/0.chunk.js:147018:19)
    at Object.next (http://localhost:4100/static/js/0.chunk.js:146948:14)
    at next (http://localhost:4100/static/js/0.chunk.js:227925:27)
    at currCb (http://localhost:4100/static/js/0.chunk.js:228012:7)

And my api is sending this reponse :

    {
        "error": {
            "details": [{
                    "status": "week",
                    "message": "",
                    "target": "ModelState"
                }
            ],
            "innerError": null,
            "status": "422",
            "message": "Invalid model",
            "target": "ModelState"
        }
    }

A: I had this error minutes ago and found your question with no answers. It could be related with dataProvider.js.
In my case, I solved it editing the type case (GET_LIST, GET_ONE, UPDATE, etc.) into the switch. I made a data mapping into the type, specifying the resource from which I am receiving the data. Better see the code below:
// dataProvider.js

...

switch(type){
    case GET_ONE:{
        if (resource === 'users'){
            return {
                data: {
                    id: json.id,
                    email: json.email,
                    isAdmin: json.isAdmin,
                    password: json.password
                }
            }
        }

...

}

As a disclaimer, I am quite new to React-Admin and React. But I hope this answer to be helpful to somebody who finds this question.


text:
Q: Running a cURL command in a Docker build I am trying to download a jacoco jar using cURL command and copy/save the jar to this destination folder: dir/tmp/
This is how the Dockerfile looks for the above part:
RUN rm -r dir/tmp | true
RUN mkdir dir/tmp | true
RUN echo "Downloading jacoco jars"
RUN curl "https://repo1.maven.org/maven2/org/jacoco/org.jacoco.agent/0.8.5/org.jacoco.agent-0.8.5-runtime.jar" -o dir/tmp/jacoco.agent.jar
RUN echo "Done Downloading jacoco jars"

But I am getting the following error:

Failed to create the file dir/tmp: No such file or directory
curl: (23) Failed writing body (0 != 984)

What can I try to solve this?

A: mkdir command needs to pass -p to allow multi-directory creation, I have also made some rectifications to make it work as per your requirement:
RUN rm -rf dir/tmp
RUN mkdir -p dir/tmp
RUN echo "Downloading jacoco jars"
RUN curl "https://repo1.maven.org/maven2/org/jacoco/org.jacoco.agent/0.8.5/org.jacoco.agent-0.8.5-runtime.jar" -o dir/tmp/jacoco.agent.jar
RUN echo "Done Downloading jacoco jars"

Or:
RUN rm -rf dir/tmp \
    && mkdir -p dir/tmp \
    && echo "Downloading jacoco jars" \
    && curl "https://repo1.maven.org/maven2/org/jacoco/org.jacoco.agent/0.8.5/org.jacoco.agent-0.8.5-runtime.jar" -o dir/tmp/jacoco.agent.jar \
    && echo "Done Downloading jacoco jars"


text:
Q: Wireless data transmission more than a bit at a time I'm not that educated in wireless data transmission, but, the basics of frequency modulation and or amplitude modulation are quite basic. Is there any examples of transferring more than a bit at a time, like, a byte or so, 8 bit, encoded similar to how chords are encoded on a piano? (multiple frequencies at once)

A: The answer depends on the signal bandwidth. Any wireless signal will not be a single frequency, but a range of frequencies called the bandwidth. The narrower the bandwidth the more efficient the transmission but the slower the rate of data that will be conveyed. This is why FM radio sounds better than AM radio, the bandwidth is wider so you get more data per second, you get stereo audio. That comes at a cost, which is you need more power to get that signal out. Think of morse code, you get only one thing at a time, either a dit or a dah or a silence. With analogue voice radio you have a band width wide enough for most of the range of the human voice. This is usually limited to 2.7 kHz. With AM you need twice that in the band width, so a bandwidth of about 6 kHz. Any digital voice transmission will do the same, only the signal is digitalised instead of being analogue. High efficiency data transmissions use limited bandwidth and data compression and error correction algorithms to get the job done.

A:
Is there any examples of transferring more than a bit at a time,

Yes it's very common in modern wireless systems.
One (more-or-less) straightforward method is quadrature amplitude modulation (QAM). In this scheme, both an in-phase (sine, for example) and a quadratuer (cosine) signal are sent at the same time. Each of these two signals can have its take several different levels in each baud interval (not just two, as in binary phase modulation). The number of different combinations available in a system might be 4 (4-QAM), 16, 32, etc, giving 2, 4, 5, or more bits per symbol transmitted.
Modern wireless systems (4G LTE) use even more complicated modulation schemes such as orthogonal frequency domain multiple access (OFDMA). These not only carry multiple bits per symbol but also manage multiple users sharing a channel.

like, a byte or so, 8 bit,

Eight bits per symbol requires 256 different possible symbols in the symbol alphabet. This is possible in principle, but tends to be more error prone. With current technology it's usually more economical to transfer fewer (2 or 4 or maybe 6) bits per symbol at a higher symbol (baud) rate.

encoded similar to how chords are encoded on a piano?

OFDM does in effect do this, but the mechanism to keep the signals on one frequency from interfering with those on another is a bit complicate to explain.
More often, frequency divisions are used to provide separate channels for different data streams to be carried at the same time, rather than to provide more bandwidth to a single data stream (although that would be possible, it just isn't often worth the added complexity and expense).


text:
Q: TRANSIENT_ERROR for TPU in Google Colab I'm trying to run a lrcn keras model on TPUs with tensorflow 2.0. The model and generator work on CPU/GPU but I included them for reference. I also initialize the TPU and it is visible and everything looks good except for when I run .fit():
def frame_generator(self, batch_size, train_test, data_type):
    """Return a generator that we can use to train on. There are
    a couple different things we can return:
    data_type: 'features', 'images'
    """
    # Get the right dataset for the generator.
    train, test = self.split_train_test()
    data = train if train_test == 'train' else test

    #print("Creating %s generator with %d samples." % (train_test, len(data)))

    while 1:
        X, y = [], []

        # Generate batch_size samples.
        for _ in range(batch_size):
            if random.random() < .5:
                # real
                while True:
                    # Get a random sample.
                    sample = random.choice(data)

                    # Get the sequence from disk.
                    (_x,_y) = self.get_extracted_sequence(data_type, sample)

                    if _y==[0,1]:
                        break
            else:
                 # fake
                while True:
                    # Get a random sample.
                    sample = random.choice(data)

                    # Get the sequence from disk.
                    (_x,_y) = self.get_extracted_sequence(data_type, sample)

                    if _y==[1,0]:
                        break

            if _x is None:
                raise ValueError("Can't find sequence. Did you generate them?", sample)

            X.append(_x)
            y.append(_y)

        #yield [np.array(X), np.array(y)], np.array(y)
        yield np.array(X), np.array(y)

train_generator = data.frame_generator(batch_size, 'train', 'images')
val_generator = data.frame_generator(batch_size, 'test', 'images')

optimizer = Adam(lr=1e-5)

with tpu_strategy.scope():
  model = lrcn()
  model.add(tf.keras.layers.Dense(2, activation='softmax'))

  model.compile(loss='binary_crossentropy',
      optimizer=optimizer,
      metrics=['accuracy', tf.compat.v1.losses.log_loss])
  model.summary()

train_data = tf.data.Dataset.from_generator(lambda:next(train_generator),
                                        (tf.float32, tf.int64),
                                        ([4, 32,299,299,3], [4,2])
                                      )

val_data = tf.data.Dataset.from_generator(lambda:next(val_generator),
                                        (tf.float32, tf.int64),
                                      ([4, 32,299,299,3], [4,2])
                                      )

model.fit(x=train_data, steps_per_epoch=train_steps, validation_steps=test_steps,
      validation_data=val_data,
        epochs=30,
        callbacks=callbacks,
        verbose=1)

On model.fit I get:
Train on 6421.0 steps, validate on 1605.0 steps
Epoch 1/30
UnavailableError                          Traceback (most recent call last)
 in ()
     15             epochs=30,
     16             callbacks=callbacks,
---> 17             verbose=1)
11 frames
/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)
UnavailableError: channel is in state TRANSIENT_FAILURE
Additional GRPC error information:
{"created":"@1584561754.347859160","description":"channel is in state TRANSIENT_FAILURE","file":"external/grpc/src/core/ext/filters/client_channel/client_channel.cc","file_line":2294,"grpc_status":14} [Op:__inference_distributed_function_24182
channel is in state TRANSIENT_FAILURE","file":"external/grpc/src/core/ext/filters/client_channel/client_channel.cc","file_line":2294,"grpc_status":14} [Op:__inference_distributed_function_10577]
Any ideas how to fix? Looks like it's on Google's network end.
UPDATE:
Part of the solution is you should not install tensorflow2.1 with pip in the colab notebook - you should use in its own cell before "import tensorflow"
%tensorflow_version 2.x

This will change the TPU version from 1.15 to >=2.1
Now when I run the notebook I get more details:
Train for 6902.0 steps, validate for 1725.0 steps
Epoch 1/30
   1/6902 [..............................] - ETA: 20:04:55
NotFoundError                             Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/training_v2.py in on_epoch(self, epoch, mode)
    766     try:
--> 767       yield epoch_logs
    768     finally:
18 frames
NotFoundError: {{function_node __inference_distributed_function_20824}} No registered 'PyFunc' OpKernel for 'CPU' devices compatible with node {{node PyFunc}}
    .  Registered:
 [[PyFunc]]
 [[MultiDeviceIteratorGetNextFromShard]]
 [[RemoteCall]]
 [[IteratorGetNextAsOptional]]

During handling of the above exception, another exception occurred:
KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/callbacks.py in _get_file_path(self, epoch, logs)
   1053     if not self.model._in_multi_worker_mode(
   1054     ) or multi_worker_util.should_save_checkpoint():
-> 1055       return self.filepath.format(epoch=epoch + 1, **logs)
   1056     else:
   1057       # If this is multi-worker training, and this worker should not
KeyError: 'val_accuracy'

A: TL/DR
You need to install a newer build that will execute the python function before sending it to the TPU. Load newer builds via
import requests
import os
url = 'http://' + os.environ['COLAB_TPU_ADDR'].split(':')[0] + ':8475/requestversion/2.2.0-dev20200311'
resp = requests.post(url)
print(resp)
%pip install tf-nightly==2.2.0-dev20200311

From https://github.com/tensorflow/tensorflow/issues/34346
When you use Dataset.from_generator (or pass a generator to Keras which will call it under the hood), the Dataset embeds the generator in a PyFunc op in its graph, and every time that op is invoked it calls next on the generator and gets the resultant bytes. (Basically treating Python as a black box.)
When everything is running on the same machine this is fine, but the trouble is that the ways TPUs work is that there is a separate machine controlling the TPU (called, imaginatively, the TPU host controller. ^^), and you run things on the TPU by sending it a TensorFlow graph to execute. So the graph containing that PyFunc gets sent to the TPU, and the TPU can't execute it because there is no Python on the TPU host machine. (And even if there was, it wouldn't be the same interpreter with the same state as your local machine.) So it fails by telling you it can't execute the PyFunc op, but not in a very clear way unfortunately.


text:
Q: LED-flash during powerup with my ZCD/Triac-circuit Friends,
I've made a ZDC-circut to dim my 230VAC LED-chip. It works fine except for a short, flashy, annoying blink when powered up!! It happens about 8/10 times when I switch the power on/off. Any1 else had this issue before?
Below is my connection diagram:

I wish i could have posted a video of the flash, but here is my scop-screen triggered by a powerup flash:

Scoop-screen during dimming, approx 20% of max:

Scoop-screen during dimming, approx 90% of max:

I just measured my zerocross-pulses on D2, its not stable on 10ms. It changes constantly between 8-13 ms, so i have to look into the ZCD-part of the circut. Anyway, if someone had this issue before any tips would be highly appriciated =)


text:
Q: How to end nested subscriptions in spring web flux? I am trying to have my app so that when a new entry is added to the back end, the front end is notified of the new changes through event source. The code is shown below, this all seems to work well, but I am not sure if making a subscription in a method (getAllShifts) like that is good practice as I am not sure how it gets disposed? Does the subscription end when the client closes the app or the event source ends? Any guidance on that would be helpful.
@Service
public class ShiftService {

    @Autowired
    ShiftRepository shiftRepository;

    private Sinks.Many<Shift> sink = Sinks.many().replay().latest();

    public Mono<Shift> addShift(Shift shift) throws InterruptedException {
        Mono<Shift> shiftt = shiftRepository.save(shift);
        return shiftt
                .doOnSuccess(u -> this.sink.tryEmitNext(u));
    }

    public Flux<Shift> getAllShifts() {

        this.shiftRepository.findAll().subscribe(u -> this.sink.tryEmitNext(u));
        return sink.asFlux();
    }
}

Another question, if we make a subscription to a Mono, do we need to dispose it or does it take care of itself as there is just one item to be emitted?

A: Yes . Subscribe should not be used. You let the framework subscribe. You can very well use the same onSuccess on this
return this.shiftRepository.findAll().doOnsuccess(u -> this.sink.tryEmitNext(u));


text:
Q: Data model, saving product properties in a separate table? I have a product table "products"
products
- proID (PK)
- proName
- proDescription
- proPrice
- proSize
- proStatus
Now I need to add two extra properties (type and color) and in the future even more. In the futere I can get more different products, each with their own properties.
The two extra properties only apply to some (half) of the products in the products table.
Is it better to add the properties to the products table or create a seperate table to store these properties and values?
I could store them like:
product_properties
- pprID (PK)
- pprName
product_properties_values
- pprID (PK)
- proID (PK)
- ppvValue

A: If you want to have a normalized schema, you could have a product_type table listing all these properties a product can have.
product_type table:

*

*type_id

*type_name

*type_property_1

*type_property_2

*etc.

and the product table:

*

*product_id

*type_id

*etc.

The benefit of having a separate type table is that it will be probably small hence it will be relatively easier to make changes like adding new properties in the future. Also it will save disk space.
The benefit of not having separate type table is you do not have to join two tables just to list products with properties, that is the query performance will be better.

A: Another way is used field with TEXT which stores all fields in xml or json format.
In our project we use xml because we need searching by property.  You can search by any property using ExtractValue mysql function.
See http://dev.mysql.com/doc/refman/5.1/en/xml-functions.html#function_extractvalue
But if you needn't search json will be more fast.

A: It's a Entity - Attribute - Value problem. For a better scalability you should use one table for the products, one for the properties and one for the values. As you wrote:
product_properties

*

*pprID (PK)

*pprName

product_properties_values

*

*pprID (PK)

*proID (PK)

*ppvValue

You can easily query the tables with mysql left join statement. For example what are the product X properties?
select ppr.pprName, ppv.ppvValue
from products as pro
left join product_properties_values as ppv on pro.proID=ppv.proID
left join product_properties as ppr on ppr.pprID=ppv.pprID
where pro.proName='X' order by ppr.pprName desc

A: This sounds like an EAV model (Entity-Attribute-Value).
You can google for more info about it.
Some people like EAV, but many think it is a poor design of the database.
I would suggest you read this thread about database design and EAV:
single fixed table with multiple columns vs flexible abstract tables


text:
Q: How to call a swift function from TypeScript I am writing a function on a button click in my TypeScript file.
<button (click)="invokeMessage()">Submit</button>

invokeMessage() {
  const text = 'Hello iOS!';
  this.swiftMethod(text);
}

swiftMethod(text: string) { }

I need to call this function "swiftMethod()" in swift. But not getting a callback when using above code.
However I am able to achieve this through JavaScript:
<html>
    <title>
        my title
    </title>
    <head>
        <script>
            function invokeMessage() {
                var inputName = document.getElementById('name').value
                swiftMethod(inputName)
            }
        </script>
    </head>
    <body>
        <button onclick='invokeMessage()'>Submit</button>
        <input type='text' name='firstname' id='name' value='Jamie'><br>
    </body>
</html>

Swift Code:
extension ViewController: UIWebViewDelegate {

  func webViewDidFinishLoad(_ webView: UIWebView) {

    print("text")

    let ctx = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext

    let swiftMethod: @convention(block) (String) -> () = { email in

      print("Got Callback email = \(email) ")

    }

    ctx.setObject(unsafeBitCast(swiftMethod, to: AnyObject.self), forKeyedSubscript: "swiftMethod" as (NSCopying & NSObjectProtocol)?)

  }

}

How to write my function in TypeScript?

A: Glad to get some useful posts/links which helps me to answer my question.
After iOS 8, Apple recommends using WKWebView over UIWebView (I am making use of UIWebView
 above).
I got this post which explains how a communication is possible in between iOS/Android and JavaScript.
Also got this one which explains how to bridge JavaScript and WKWebView in different ways.
Finally about my code, after taking reference from above, I wrote the following TypeScript function:
<button (click)="invokeMessage()">Submit</button>

invokeMessage() {
  try {
      (window as any).webkit.messageHandlers.callbackHandler.postMessage('testValue');
    } catch (error) {
        console.log(error);
    }
}


text:
Q: How to Add an Error Message when using a Virtual Attribute I have a date field that is not a required field. I am using Chronic to format the user input string to a valid rails format for a date field. If Chronic is unable to parse the date, I would like to raise an error, rendering the edit view with the respective error message and the originally input value. Currently the update is successful if an invalid date is entered but nothing is updated for the service_date field.
new.html.erb
<%= f.text_field :service_date_text %>

bill.rb
require 'chronic'

class Bill < ActiveRecord::Base

  def service_date_text
    service_date.try(:strftime, "%m/%d/%Y")
  end

  def service_date_text=(date)
    if date.present?
      if Chronic.parse(date)
        self.service_date = Chronic.parse(date)
      else
        self.errors.add(:service_date_text, "invalid date format hello.")
      end
    else
      self.service_date = ''
    end
  end
end

bills_controller.rb
  def update
    @bill = current_account.bills.find(params[:id])
    if @bill.update_attributes(bill_params)
      redirect_to @bill, notice: 'Bill has been successfully updated.'
    else
      render :edit
    end
  end

  private

  def bill_params
    params.require(:bill).permit(:description, :notes, :po_number, :service_date_text)
  end

A: errors is cleared whenever you run valid?, which update_attributes does.
Example:
irb(main):001:0> album = Album.new
=> #<Album id: nil, name: nil, release_date: nil, rating: nil, genre_id: nil,
artist_id: nil, created_at: nil, updated_at: nil>

irb(main):004:0> album.errors.add :artist, "You've selected Justin Bieber (!!!)"
=> ["You've selected Justin Bieber (!!!)"]

irb(main):006:0> album.errors.messages
=> {:artist=>["You've selected Justin Bieber (!!!)"]}

irb(main):007:0> album.valid?
=> true

irb(main):008:0> album.errors.messages
=> {}

Don't abuse setters, use proper validations. For example (not tested):
  require 'chronic'

  class Bill < ActiveRecord::Base
    validate :service_date_validation

    def service_date_text
      service_date.try(:strftime, "%m/%d/%Y")
    end

    def service_date_text=(date)
      if date.present?
        if Chronic.parse(date)
          self.service_date = Chronic.parse(date)
        else
          self.service_date = false
        end
      else
        self.service_date = ''
      end
    end

    private

      def service_date_validation
        if self.service_date == false
          self.errors.add(:service_date_text, "invalid date format hello.")
        end
      end
  end

... There are also some gems which provide date validations, such as:

*

*https://rubygems.org/gems/validates_timeliness

*https://rubygems.org/gems/date_validator

*https://rubygems.org/gems/rails_validations (disclaimer: I am the author)

... as well as some others...

A: I'll bet the issue is that Rails doesn't expect setter methods to add errors. I would make service_date_text just an attr_accessor and then call a validate method which sets service_date or adds an error.
attr_accessor :service_date_text

validate :service_date_text_format

private

def service_date_text_format
  return unless service_date_text # or self.service_date ||= '' and then return
  if date = Chronic.parse(date)
    self.service_date = date
  else
    errors.add(:service_date, 'invalid format')
  end
end


text:
Q: angular + jasmine: mock a directive I have a controller that "feeds" a directive with data:
HTML

    <my-drtv data="ctrl.data"></my-drtv>

javascript
function MyCtrl(){
    this.data = "dummy";
}

function myDrtv() {
   return {
      template:'
{{myData}}
'
      scope:{
        data:'='
      },
      link:function(scope){
        scope.myData = scope.data.toUpperCase();
      }
   }
}

I need to mock the directive in order to verify that the controller has passed the correct data.

A: Ok, got it.
This is a bad approch.
Since I want to test my controller, I should test it's output (ctrl.data) directly.