Q:

Why is the instruction to swap stderr with stdout backward?

In numerouse places, I've found people suggesting that you can swap stderr with stdout as follows:
command 3>&2 2>&1 1>&3
This looks backwards to me.  If we send 3 to 2 and then immediately send 2 to 1 (which now would appear to be sending both 3 and 2 to 1).  I think there's something basic I don't understand about IO redirection, but I can't find anything which clarifies it.

A:

You will find a detailed explanation at http://www.catonmat.net/blog/bash-one-liners-explained-part-three/ , section 21:

$ command 3>&1 1>&2 2>&3 Here we first duplicate file descriptor 3 to
  be a copy of stdout. Then we duplicate stdout to be a copy of stderr,
  and finally we duplicate stderr to be a copy of file descriptor 3,
  which is stdout. As a result we've swapped stdout and stderr.

There is more detail, and pictures, at the link given. The key insight is:
3>&1 means "3 points to where 1 is pointing". Then 1>&2 says "now 1 points to where 2 is pointing" (1 now points to stream 2, but 3 doesn't follow...), and finally 2>&3 says "now 2 points to where 3 is pointing (which is stream 1).
Graphically (but see link - it's much better than my ascii-art):
0 --> /dev/tty0
1 --> /dev/tty1
2 --> /dev/tty2

After 3>&1:
0 --> /dev/tty0
1 --> /dev/tty1
2 --> /dev/tty2
3 --> /dev/tty1

After 1>&2:
0 --> /dev/tty0
1 --> /dev/tty2
2 --> /dev/tty2
3 --> /dev/tty1

After 2>&3:
0 --> /dev/tty0
1 --> /dev/tty2
2 --> /dev/tty1
3 --> /dev/tty1

As you can see, 1 and 2 have been swapped. The same link recommends closing temporary stream 3 with 3>&-


Q:

Bake and share Fair and square

The chef ask each of the 4 judges to make
a single slice on the whole round cake,
so they'll all have a 1/5th piece to take.
How the judges do it for fairness sake?

A:

The judges can cut the cake like this:

 Let X be the cake's volume. Each judge, in turn, uses a vertical cut to remove a piece of volume X/5 off of the remaining cake. The final piece of the cake also has volume X/5 and goes to the chef.

Since the cake as depicted is homogeneous in each layer, the outcome is fair.

Edit: New solution for updated rules:

 > The rule is simple 4 cuts to make 4 equal or same object (piece of cake)

Maybe you mistyped and wanted 5 equal objects?

Or maybe you really only wanted 4 equal objects, each of which should contain 1/5 of the cake?


Q:

Create a new column adding days based in two columns one have data and another ID

I have one data.frame loc_teste2 with columns: Ptt (I have 36 differents Ptt's) and Date, like this:
Ptt      Date
88734    05:39:18 23-Oct-2016
88734    06:53:13 23-Oct-2016
88734    08:32:18 24-Oct-2016
88734    06:45:27 19-Dez-2016
88734    12:30:43 20-Dez-2016
129041   02:45:35 18-Nov-2016
129041   04:55:24 19-Nov-2016
129041   06:45:30 19-Nov-2016
129041   07:10:32 20-Nov-2016
129041   03:43:54 10-Jan-2017
120941   14:54:39 11-Jan-2017
...

So, I split the column Date in another column Days
loc_teste2$Date<- as.character(loc_teste2$Date)

loc_teste2$Days <- sapply(strsplit(loc_teste2$Date, split=' ', fixed=TRUE), function(x) (x[2]))

loc_teste2$Days <- as.POSIXct(loc_teste2$Days, format = "%d-%b-%Y",tz = "GMT",usetz = TRUE)

loc_teste2$Date <- as.POSIXct(loc_teste2$Date, format = "%H:%M:%S %d-%b-%Y",tz = "GMT",usetz = TRUE)

Returns:
Ptt      Date                       Days
88734    2016-10-23 05:39:18    2016-10-23
88734    2016-10-23 06:53:13    2016-10-23
88734    2016-10-23 08:32:18    2016-10-24
88734    2016-12-19 06:45:27    2016-12-19
88734    2016-12-20 12:30:43    2016-12-20
129041   2016-10-23 02:45:35    2016-10-18
129041   2016-10-23 04:55:24    2016-11-19
129041   2016-10-23 06:45:30    2016-11-19
129041   2016-10-23 07:10:32    2016-11-20
129041   2017-01-10 03:43:54    2017-01-10
120941   2017-01-11 14:54:39    2017-01-11
...

Then, I want to create a new column Mig adding 40 days based at the first date for each Ptt in column Days, where:
If the date is up to 40 days from the first date of the Ptt, returns 1
If the date is after 40 days from the first date of the Ptt, it returns 2, like this:
Ptt      Date                       Days        Mig
88734    2016-10-23 05:39:18    2016-10-23     1  #based in this date (the first date for this Ptt)
88734    2016-10-23 06:53:13    2016-10-23     1
88734    2016-10-23 08:32:18    2016-10-24     1
88734    2016-12-19 06:45:27    2016-12-19     2
88734    2016-12-20 12:30:43    2016-12-20     2
129041   2016-10-23 02:45:35    2016-10-18     1  #based in this date (the first date for this Ptt)
129041   2016-10-23 04:55:24    2016-11-19     1
129041   2016-10-23 06:45:30    2016-11-19     1
129041   2016-10-23 07:10:32    2016-11-20     1
129041   2017-01-10 03:43:54    2017-01-10     2
120941   2017-01-11 14:54:39    2017-01-11     2
...

Anybody have an idea how can do this?
Ps:It's better create an column Mig with the dates + 40 days, and then create another column Mig2 with 1 or 2?

A:

If you use the tidyverse and lubridate packages, you could take advantage of the group_by function and more easily manipulate dates. The code below has some intermediary steps to reproduce part of your data, but you may be able to just use the chunk after "group_by". It'll return a true or false instead of one or two, but you can edit the code with ifelse() function if you need that.
library(lubridate)
df <- read.delim(text = "Ptt      Date
88734    05:39:18 23-Oct-2016
88734    06:53:13 23-Oct-2016
88734    08:32:18 24-Oct-2016
88734    06:45:27 19-Dez-2016
88734    12:30:43 20-Dez-2016
129041   02:45:35 18-Nov-2016
129041   04:55:24 19-Nov-2016
129041   06:45:30 19-Nov-2016
129041   07:10:32 20-Nov-2016
129041   03:43:54 10-Jan-2017
120941   14:54:39 11-Jan-2017", sep = "\t")

df %>%
  separate("Ptt......Date", into = c("ptt", "time", "date"), sep = "\\s+") %>%
  mutate(date = str_replace(date, pattern = "Dez", replacement = "Dec"), date2 = dmy(date)) %>%
  group_by(ptt) %>%
  mutate(threshold = min(date2)+days(40), past_threshold = date2 > threshold)

Starting from the first dataframe with just Ptt and Date. Maybe try the following with lubridate and tidyverse loaded.
library(tidyverse)
library(lubridate)
loc_teste2 %>%
  mutate(Ptt = as.character(Ptt), Date = as.character(Date), Date = str_replace(Date, pattern = "Dez", replacement = "Dec"), Date = parse_date_time(Date, order = "hmsdmy")) %>%
  group_by(Ptt) %>%
  mutate(Threshold = min(Date) + days(40)) %>%
  ungroup() %>%
  mutate(Past_Threshold = Date > Threshold)


Q:

Programmatically swap colors from a loaded bitmap to Red, Green, Blue or Gray, pixel by pixel

Download source code here: http://www.eyeClaxton.com/download/delphi/ColorSwap.zip
Yes, I want to convert something "mostly blue" to something "mostly green".
I would like to take a original bitmap (light blue) and change the colors (Pixel by Pixel) to the red, green, blue and gray equivalence relation.  To get an idea of what I mean, I have include the source code and a screen shot. Any help would be greatly appreciated.  If more information is needed, please feel free to ask.
If you could take a look at the code below, I have three functions that I'm looking for help on.  The functions "RGBToRed, RGBToGreen and RGBToRed" I can't seem to come up with the right formulas.

unit MainUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, StdCtrls;

type
  TMainFrm = class(TForm)
    Panel1: TPanel;
    Label1: TLabel;
    Panel2: TPanel;
    Label2: TLabel;
    Button1: TButton;
    BeforeImage1: TImage;
    AfterImage1: TImage;
    RadioGroup1: TRadioGroup;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  MainFrm: TMainFrm;

implementation

{$R *.DFM}
function RGBToGray(RGBColor: TColor): TColor;
var
  Gray: Byte;
begin
  Gray := Round(
    (0.90 * GetRValue(RGBColor)) +
    (0.88 * GetGValue(RGBColor)) +
    (0.33 * GetBValue(RGBColor)));

  Result := RGB(Gray, Gray, Gray);
end;

function RGBToRed(RGBColor: TColor): TColor;
var
  Red: Byte;
begin
  // Not sure of the algorithm for this color
  Result := RGB(Red, Red, Red);
end;

function RGBToGreen(RGBColor: TColor): TColor;
var
  Green: Byte;
begin
  // Not sure of the algorithm for this color
  Result := RGB(Green, Green, Green);
end;

function RGBToBlue(RGBColor: TColor): TColor;
var
  Blue: Byte;
begin
  // Not sure of the algorithm for this color
  Result := RGB(Blue, Blue, Blue);
end;

procedure TMainFrm.FormCreate(Sender: TObject);
begin
  BeforeImage1.Picture.LoadFromFile('Images\RightCenter.bmp');
end;

procedure TMainFrm.Button1Click(Sender: TObject);
var
  Bitmap: TBitmap;
  I, X: Integer;
  Color: Integer;
begin
  Bitmap := TBitmap.Create;
  try
    Bitmap.LoadFromFile('Images\RightCenter.bmp');

    for X := 0 to Bitmap.Height do
    begin
      for I := 0 to Bitmap.Width do
      begin
        Color := ColorToRGB(Bitmap.Canvas.Pixels[I, X]);

        case Color of
          $00000000: ;   // Skip any Color Here!
        else
          case RadioGroup1.ItemIndex of
            0: Bitmap.Canvas.Pixels[I, X] := RGBToBlue(Color);
            1: Bitmap.Canvas.Pixels[I, X] := RGBToRed(Color);
            2: Bitmap.Canvas.Pixels[I, X] := RGBToGreen(Color);
            3: Bitmap.Canvas.Pixels[I, X] := RGBToGray(Color);
          end;
        end;
      end;
    end;
    AfterImage1.Picture.Graphic := Bitmap;
  finally
    Bitmap.Free;
  end;
end;

end.

Okay, I apologize for not making it clearer.  I'm trying to take a bitmap (blue in color) and swap the blue pixels with another color. Like the shots below.

A:

I have no idea what you are trying to achieve. First, what does the question have to do with equivalence relations?
Secondly, the code
function RGBToRed(RGBColor: TColor): TColor;
var
  Red: Byte;
begin
  // Not sure of the algorithm for this color
  Result := RGB(Red, Red, Red);
end;

is meaningless. The return value is undefined. The RGB functions takes red, green, and blue intensities in the range 0 to 255 and returns the TColor having these components. For instance, RGB(255, 0, 0) is pure red, that is, 255 red, 0 green, and 0 blue. In the code above, however, Red is not initialized, so Result can be any grey colour (depending on what Red happens to be). [And, as you probably know, if you mix equal amounts of red, green, and blue, as you do, you get grey.] For instance, Red might happen to be 45 one time you run the application, and then the result will be the grey colour RGB(45, 45, 45). Next time it might be 163.
Maybe you want a function that accepts a TColor and returns the red component of it? Then GetRValue will do, and - of course - there is also GetGValue and GetBValue.
Or, maybe you want to create a grey colour from a given TColor, as you do when you use Photoshop to create a greyscale image from a colour image. Then, if Color is the TColor, the appropriate grey value is
grey := (GetRValue(Color) + GetGValue(Color) + GetBValue(Color)) div 3;

There are other ways of doing this (resulting in subtly different greyscale images, but this is the easiest (and fastest)). (For instance, you can convert the colour from RGB to HSV or HSL and then set the saturation equal to zero.)
Update
I think I see what you want to do. Maybe you want to extract the red, green, and blue channels. That is, you want to transform each pixel RGB(R, G, B) to RGB(R, 0, 0) in the red case. If this is what you want to do, then you should do
function RGBToRed(RGBColor: TColor): TColor;
begin
  Result := RGB(GetRValue(RGBColor), 0, 0);
end;

and similarly for the other components, that is
function RGBToGreen(RGBColor: TColor): TColor;
begin
  Result := RGB(0, GetGValue(RGBColor), 0);
end;

and
function RGBToBlue(RGBColor: TColor): TColor;
begin
  Result := RGB(0, 0, GetBValue(RGBColor));
end;

Or, maybe
Or maybe you just want to make the image greyscale, and then "colour" it red (or green, or blue). Then you need the heavy machinery. Theoretically, you wish to replace each pixel from HSV(h, s, v) to HSV(0, s, v) in the red case, HSV(120, s, v) in the green case, and HSV(240, s, v) in the blue case. Or, maybe you also wish to set the saturation s to 1.
I use the following rutines to convert between RGB and HSV:
function RGBToHSV(const Color: TRGB): THSV;
var
  cmax, cmin, cdiff: real;
begin
  cmax := MaxComponent(Color);
  cmin := MinComponent(Color);
  cdiff := cmax - cmin;

  with Color, result do
  begin

    // Hue
    if cmax = cmin then
      hsvHue := 0
    else if cmax = rgbRed then
      hsvHue := (60 * (rgbGreen - rgbBlue) / cdiff)
    else if cmax = rgbGreen then
      hsvHue := (60 * (rgbBlue - rgbRed) / cdiff) + 120
    else
      hsvHue := (60 * (rgbRed - rgbGreen) / cdiff) + 240;

    hsvHue := Fix360(hsvHue);

    // Saturation
    if cmax = 0 then
      hsvSaturation := 0
    else
      hsvSaturation := 1 - cmin / cmax;

    // Value
    hsvValue := cmax;

  end;

end;

and
function HSVToRGB(const Color: THSV): TRGB;
var
  hi: integer;
  f, q, p, t: real;
begin

  with Color do
  begin

    hi := floor(hsvHue / 60) mod 6;
    f := hsvHue / 60 - floor(hsvHue / 60);
    p := hsvValue * (1 - hsvSaturation);
    q := hsvValue * (1 - f * hsvSaturation);
    t := hsvValue * (1 - (1 - f) * hsvSaturation);

    case hi of
      0: result := RGB(hsvValue, t, p);
      1: result := RGB(q, hsvValue, p);
      2: result := RGB(p, hsvValue, t);
      3: result := RGB(p, q, hsvValue);
      4: result := RGB(t, p, hsvValue);
      5: result := RGB(hsvValue, p, q);
    end;

  end;

end;

where
type
  TRGB = record
    rgbRed,            // red intensity between 0 and 1
    rgbGreen,          // green intensity between 0 and 1
    rgbBlue: double;   // blue intensity between 0 and 1
  end;

  THSV = record
    hsvHue,            // hue angle between 0 and 360
    hsvSaturation,     // saturation between 0 (grey) and 1 (full colour)
    hsvValue: double;  // value between 0 (dark) and 1 ("normal")
  end;

The end result, in the green case, will be like

in the first case (hue fixed to 120) and

in the latter case (hue fixed to 120, saturation fixed to 1).
Or, possibly
Your question is very vauge, even with the edit. You want to convert something "mostly blue" to something "mostly green". But there are a thousand ways of doing that! A very simple way, of course, is just to swap the blue and green channels, that is, replace RGB(r, g, b) with RGB(r, b, g), or, explicitly,
function SwapBlueGreen(Color: TColor): TColor;
begin
  result := RGB(GetRValue(Color), GetBValue(Color), GetGValue(Color));
end;

Then you get something like

where the red and green channels have been swapped. Notice that the red stick is now green, and the green grass is now red. What's white remains white.
Finally
Welcome to the world of pixmap manipulation! There is a lot of easy and fun things to do. Some more of my examples: https://english.rejbrand.se/algosim/manual/pmproc/pmproc.html


Q:

Parsing hevc bitstream

Is there a way to parse an HEVC bitstream file?
I want to be able to create a new bitstream file having selected nal unit packets selected from the original bitstream file.
Edit: I inserted my code. Please find my bitstream file here.
#library for searching in a string
import re

#library to keep dictionary order
import collections
import bitstring
from bitstring import BitStream, BitArray, ConstBitStream, pack
from bitstring import ByteStore, offsetcopy

#read bitstream file
s = BitStream(filename='11LTCCA_560x416_50Hz_8b_P420_GOP8_IP48_200frms_QP28.HEVC.str')

#find no of packets
pcks = list(s.findall('0x000001', bytealigned=True))

print len(pcks)

#set the current position, in the beginning of the nal unit.
s.pos =pcks[0]-8
print s.pos

#find the number of bits of first nal packet
no_p = pcks[1]-pcks[0]

forbidden_zero_bit = s.read(1)
nal_unit_type = s.read('uint:6')

# go to the beginning of the second nal unit
s.read(no_p)
# print nal unit type of the 1st packet
print nal_unit_type

no_p = pcks[2]-pcks[1]
s.pos = pcks[1]-8
print s.pos
forbidden_zero_bit = s.read(1)
nal_unit_type = s.read('uint:6')
s.read(no_p)
print nal_unit_type

A:

If all you want to do is take some nal unit packets (e.g. depending on layer id and temporal id), and you don't need to modify the VPS, SPS, PPS, Slice Header etc., then you can also easily implement this yourself:
The corresponding syntax is stated in the Annex B "Byte Stream Format" of the HEVC standard.
In short:

Search the bitstream file for the pattern 0x000001, which separates all the nal units. Additionally, there can be a 0x00 byte before this pattern, if the next nal unit is the first nal unit of an access unit (access unit = all nal units for decoding a whole frame).
Read the nal unit header according to section 7.3.1.2 of the HEVC standard and keep/delete the nal units based on whatever criteria you want. Make sure you keep the parameter sets (nal unit types 32, 33 and 34 according to Table 7-1 of the HEVC standard).
Assemble all the nal units in a new file and make sure you always have the 0x000001 sequence inbetween.

I once did something similar using Python, which worked pretty well. If you want to make reading the nal unit headers easier, use the bitstring module. If you want to do this and have more detailed questions, you can pm me for help if you want to.
Edit:
Regarding the code you posted:
Why do you put "-8" when assigning the position in the BitStream object (s.pos =pcks[0]-8 and s.pos = pcks[1]-8)? This should be +24 (24 bits = 3 bytes = length of the nal unit separator 0x000001), to start reading after the separator to get the nal unit. However, you have to take this into account when reading data: no_p = pcks[1]-pcks[0] should be no_p = pcks[1]-pcks[0]-24, because you start reading after the nal unit separator.
If you got confused that the first found position (pcks[0]) is 8, not 0: Before each nal unit separator, there can be an arbitrary number of zero-bytes, according to the annex B of the HEVC standard. Usually, there is always one zero-byte before each access unit.


Q:

Конвертация изображения в png (PHP)

Как средствами php конвертировать изображения (.jpg, jpeg, gif) в png ? Если кто знает дайте пример

A:

Поможет GD:
imagepng(
    imagecreatefromstring(
        file_get_contents($filename)
    ),
    "output.png"
);


Q:

MPMoviePlayerController Black Window, Not loading audio file

Making an app for my church and need mp3 file to play after being downloaded from xml.  NSLog displays the url correctly, but when I run it, I just get a spinning "loading" and a black box. Any suggestions as to why?
Thanks!
-(void)viewDidAppear:(BOOL)animated
{
RSSItem* item = (RSSItem*)self.detailItem;
self.title = item.title;
MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:item.link];
NSLog(@"The url is %@", item.link);
moviePlayerController.view.frame = CGRectMake(73, 203, 640, 360);
[self.view addSubview:moviePlayerController.view];
[moviePlayerController prepareToPlay];
moviePlayerController.fullscreen = YES;
[moviePlayerController play];

A:

TRY this one..
RSSItem* item = (RSSItem*)self.detailItem;
self.title = item.title;
if(item.link)
{
//NSURL *url = [NSURL fileURLWithPath:item.link];
MPMoviePlayerViewController *moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:item.link];
moviePlayer.view.frame = CGRectMake(0, 0, 500, 500);
moviePlayer.moviePlayer.shouldAutoplay=YES;
moviePlayer.moviePlayer.controlStyle = MPMediaTypeMusicVideo;
[moviePlayer.moviePlayer setFullscreen:YES animated:YES];
[self.view addSubview:moviePlayer.view];
[moviePlayer.moviePlayer play];
}
else
{
NSLog(@"no url");
}


Q:

Creating a fast hash function for fixed-length input

Currently I working on a project where some information have to be hashed. As the dataset is huge (millions of records created every day) the algorithm for data transformation has to be fast.
The pieces of data that have to be hashed are fixed length (11 decimal numbers - example: 05018144298). So what I would like to know is whether it is worth to create own hash function instead of using some of the existing (for example MD5) in order to significantly decrease the processing time and if so then what would be the best way to do it. Is it a good way to modify some of the existing algorithm (for example MD5 but break the input into chunks of smaller size and modify other parameters for fixed input of 11 decimal numbers) or is it better to design a hash function from scratch?
Thank you!

A:

It is not worth doing anything, performance-wise, until you have actually measured that using an existing hash function really has some non-negligible impact. A typical MD5 implementation, on a typical PC, will be able to process a few millions small messages per second, using a single core on the main CPU. Chances are that your "millions per day" are a piece of cake.
Designing your own hash function, while keeping the security features of a hash function, is a very bad idea. Right now, the top cryptographers in the world are involved in the design of a new standard hash function, in an open competition organized by NIST. Dozens of very specialized researchers have worked on those for several years, and will keep on doing so for about two more years. A lone programmer, not very specialized in the subject, trying to do better within a few days or weeks, verges on the preposterous. Designing a secure hash function is hard.

The right thing to do, for you, is to use an existing, standard cryptographic hash function. That's not MD5, by the way; serious weaknesses have been uncovered in that function (actually, serious weaknesses have been uncovered around 1996, and MD5 has been unrecommended for the last 15 years). You'd better use SHA-256.
If you do not need the cryptographic properties of a hash function but just a kind of randomizing function for hashtable-like indexing, then any hash function will be good enough. Just profile it, notice that there is no performance issue whatsoever, and be happy.


Q:

Equation of the Plane

I have been working through all the problems in my textbook and I have finally got to a difficult one.
The problem ask

Find the equation of the plane.The plane that passes through the points $(-1,2,1)$ and contains the line of intersection of the planes $x+y-z =2$ and $2x-y+3z=1$

So far I found the direction vector of the line of intersection to be $<1,-2,1>$ and I have identified a point on this line when $x=0$ to be $(0,5,-1)$.
I do not know how to find the desired plane from here.
Any assistance would be appreciated.

A:

The following determinant is another form of what Scott noted: $$\begin{vmatrix}
(x-x_0)&  (y-y_0)&  (z-z_0)\\1&  1&  -1\\2&  -1&  3
\end{vmatrix}$$

A:

Here is a related problem. To find the equation of the plane, you need three points which lie in the plane. Already, you have one, you can get the other two from the equation of the line, since the line lies in the plane. Once you have the three points, construct two vectors say $v_1$ and $v_2$ and find the cross product $n=v_1 \times v_2$. Then, the equation of the plane is given by
$$ n.((x,y,z)-(-1,2,1))=0 .$$


Q:

php will date function with week ever return 0?

I came across this conditional in a function I'm working with:
<?php
$thisweek = date('W');
if ($thisweek == 0) {
  // ...
}

I didn't write this conditional and when I went to look up the range of the date('W') http://us3.php.net/manual/en/function.date.php it gives an example but no range like 00-52 or 01-52.
My question is will date('W') ever return zero meeting this conditional?

A:

The PHP date('W') function will never1 return 0.
Look it up in the source code of PHP, ext/date/php_date.c.
Slightly formatted around line 950-1000:
timelib_sll isoweek, isoyear;
int weekYearSet = 0;
...
/* week */
case 'W':
    if(!weekYearSet) {
        timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear);
        weekYearSet = 1;
    }
    length = slprintf(buffer, 32, "%02d", (int) isoweek); break; /* iso weeknr */

What is timelib_isoweek_from_date? Well... looking at the logic in ext/date/lib/dow.c, from line 82 it can be concluded that the week number varies from 1 to 53:
/* Find if Y M D falls in YearNumber Y-1, WeekNumber 52 or 53 */
...
/* 8. Find if Y M D falls in YearNumber Y+1, WeekNumber 1 */
...
/* 9. Find if Y M D falls in YearNumber Y, WeekNumber 1 through 53 */

If you do not believe me, look in the code yourself:

http://git.php.net/?p=php-src.git;a=blob;f=ext/date/php_date.c
http://git.php.net/?p=php-src.git;a=blob;f=ext/date/lib/dow.c

1) "Never" means "as long as there is no bug in PHP".


Q:

How does Data maintain his personal hygiene?

I'm assuming Data doesn't need to go number 1 or 2, but an android's bioplast sheeting (his skin) can and has been seen dirty on-screen (in Star Trek: Nemesis, B-4 was found quite dirty from dust/dirt).
How does Data keep himself appearing clean?

A:

As there are no legitimate case examples in the canon stating that Data is incapable of using normal tools/methods for his personal hygiene, it is reasonable enough to suggest that he simply uses a sonic shower like the rest of his crew mates.  I can't find any reference which states that Data is somehow damaged or susceptible to some negative effect from sonic waves.  Even if this were the case, there would always be the option for him to simply use water to remove said dirt/dust/grime.  From what I understand of Data's composition, he has a fully enclosed artificial integumentary system which, though it doesn't perfectly simulate human skin, does protect the parts of his internal framework.  Also, though Data is not completely waterproof, that wouldn't stop him from actually washing the surface of his skin if he kept any orifices sealed (just like we as humans should probably not take deep breaths underneath the water while take a bath).  In fact, there are several times in the series which show him fully capable of operating while wet, even when submerged.
I'm not seeing any sparks shooting out of his ears here...

Now, the argument against his ability to use water might be that "there are no water showers/sources of water for cleanliness on the Enterprise!"  However, that would be a wrong assessment of the situation as well.  There are multiple examples throughout the franchise of water being used as a method of hygiene: Captain Archer had his infamous shower malfunction, the first scene of Neelix actually on Voyager was one in which he bathed water, captain Janeway had her own personal bathtub, etc, etc.  However, the one example that is most relevant would be the fact that Dianna Troi had a bathtub in her quarters (which she was pictured as starting devolving into an amphibian in) on the Enterprise.  It wouldn't be to far of a stretch for Data to have one too if need be.
I hope this helped a little.  If Data used some other kind of device or method for keeping clean, there isn't any reference I can find that states so, and the evidence would seem to suggest that he is capable of using the exact same facilities that his biological counterparts use as well.


Q:

inspect script in chrome debug without losing ability to scroll webpage

When I have some breakpoints set up in a script google chrome removes the ability to scroll the webpage, saying at the top of the screen Paused in debugger. Is there a way to disable this so that I can look at elements in various parts of the page, while also looking at the script in the debugger?

A:

Taken from here.
An easy workaround for the scrolling lock-up is to just jump to the console, and:
window.scrollTo(0, 800). (Replace 800 as needed)

A:

You can click on the Elements tab and then hover over the HTML to the element you are interested in and right click to "Scroll into view". Not the most natural and fast, but it works...


Q:

What causes a 20% difference in fuel economy between winter and summer?

I've been keeping track of the fuel my car, a Ford Fiesta Ecoboost 100 hp, uses since the day I got it. In the last three years I've owned it, I've noticed a large (>20%) difference in fuel consumption between driving in winter and driving in summer.
My driving patterns are identical in winter and summer, yet my fuel consumption is much higher in winter.
I understand that cars have slightly more power when cold, but is the difference that big?
Fuel consumption in liters/100 km:

A:

Your fuel economy change is caused by the fact you're not using the same fuel. Fuel changes twice per year from summer blend to winter blend and back again causing a change in the Reid Vapor Pressure (RVP).
In summer, the hotter temperature evaporates liquids easier causing more pollution, so it is blended to lower the RVP. This blend is more costly to produce.
While in the winter time, the RVP can be much higher so additives such as butane are used. While this lowers the manufacturing cost, it also burns more quickly resulting in a hit on the MPG fuel economy.

A:

Your vehicle does not operate at maximum efficiency until the engine has reached its normal operating temperature. This is generally when the coolant temperature reaches about 200 degrees Fahrenheit. In the winter it takes the engine longer to reach that temperature simply due to the colder ambient temperature.

A:

Another reason: Winter tires. Choose between hard tires (good fuel economy, REALLY bad on snow) or soft tires (worse fuel economy, good on snow).


Q:

Restart consumption from last checkpoint in EventHostProcessor

Given an implementation of the EventHostProcessor, how can I force replay of events from the last checkpoint within the same processor?
To be clear, assume my partition is 100 deep and I have consumed 10 messages. When I invoke this replay method, I would then want onEvent to return the first message from my previously consumed 10.
In C# this seems possible through the use of the Stopwatch but I do not see the Java equivalent.

A:

The solution seems to be that you can either checkpoint to the high-water mark of the last consumed EventData or you can checkpoint to another EventData instance.
Such as context.checkpoint(data);
There does not seem to be a way to arbitrarily rewind to an earlier event within an EventProcessorHost.


Q:

Undefined variables passed to data

In this block of code undefined variables passed to data
 var data, expContainerSettings;
 $( this ).hide();
 $( '' ).insertAfter( this );
 $( this ).detach().prependTo( target ).data( 'collapsibleTabsSettings', data );
 $( this ).attr( 'style', 'display: list-item;' );
 data = $.collapsibleTabs.getSettings( $( ele ) );
 if ( data )
 {
   expContainerSettings = $.collapsibleTabs.getSettings( $( data.expandedContainer ) );
   if ( expContainerSettings )
   {
       expContainerSettings.shifting = false;
       $.collapsibleTabs.handleResize();
   }
 }

It looks like the mistake here
$( this ).detach().prependTo( target ).data( 'collapsibleTabsSettings', data );

how i can fix this?

A:

You need to set the value you want on the data variable before you pass it to the data method. As it stands, you are passing undefined, because you simply declare the variable:
var data, expContainerSettings; // <-- Both of these are undefined.

In JavaScript, you don't have access to change the value of a variable after you pass it to a function.
As long as no asynchronous operations are happening, the solution might be as simple as executing this line:
data = $.collapsibleTabs.getSettings( $( ele ) );

Before executing this line:
$( this ).detach().prependTo( target ).data( 'collapsibleTabsSettings', data );


Q:

MySQL: Comparing records within the same table to each other

In a database that represents a store, I have the following table:
table name:
  CLIENTS_PRODUCTS
columns:
  client_id (INT)
  product_name (CHAR(256))

As you can see, each product purchase is stored as a record in the table.
Given a client A, I want to find all clients X where there is any product of A (pA) and any product of X (pX) such that pA is a prefix of pX.
To make it short: I need to execute a comparison between different records within the same table. I thought doing it by JOINing CLIENTS_PRODUCTS on itself. Is this the right way?
I searched around in SO and couldn't find a direct answer to this one.

A:

This version assumes that product_names contains a single product (despite the name of the column):
select distinct cp.client_id
from (select
      from clients_products cp
      where client_id = A
     ) a join
     client_products cp
     on cp.product_names like concat(a.product_names, '%') and
        cp.client_id <> a.client_id

If product_names is really a comma delimited list of products, then we can modify this as:
select distinct cp.client_id
from (select
      from clients_products cp
      where client_id = A
     ) a join
     client_products cp
     on concat(',', cp.product_names, ',') like concat('%,', a.product_names, '%,%') and
        cp.client_id <> a.client_id


Q:

TicTacToe game in more pythonic style

I wrote a simple TicTacToe console game in Python3. I would like to make my program more pythonic than it is now. For example, instead of if a == 5 and b == 5 and c == 5: you can write if a == b == c == 5:. So I expect hints of how can I rewrite my code to take adventage of Python language.
I don't ask for algorithm optimization (it contains some bugs, I know). The code should be rather understood for you except computer_turn() method which simulates computer's move. But since I don't ask for optimization I don't see a need to explain what exacly happens inside this method.
You may find my code on Github.
from random import randint, choice
import time, sys, os

class TicTacToe:
    board = [None for i in range(9)] # list representing game's board
    turn = 1 # counter of computer's turns

    def print_board(self, board = None): # printing game board
        board = self.board if board == None else board

        os.system("clear") # use "cls" for windows
        print("|---|---|---|")
        for i, cell in enumerate(board, 1):
            print("| {} ".format(" " if cell == None else cell), end = "")
            if i % 3 == 0:
                print("|")
                print("|---|---|---|")

    def get_game_winner(self, board = None):
        board = self.board if board == None else board

        for i in range(0, 9, 3):
            if board[i] == board[i + 1] == board[i + 2]:
                if board[i] != None: return board[i]

        for i in range(0, 3):
            if board[i] == board[i + 3] == board[i + 6]:
                if board[i] != None: return board[i]

        if board[0] == board[4] == board[8] or board[2] == board[4] == board[6]:
            if board[4] != None: return board[4]

        return None

    def computer_turn(self):
        position = None

        def get_line(cell):
            if cell <= 3: return 1
            if cell <= 6: return 2
            return 3

        if self.turn == 1:
            self.turn = 2
            oponent_choice = self.board.index("X")
            if oponent_choice + 1 in [1, 3, 7, 9]:
                position = 5 - 1
            else:
                position = choice([1, 3, 7, 9]) - 1

        elif self.turn == 2:
            self.turn = 3
            for i in [1, 3, 7, 9]:
                if self.board[i - 1] == "X":
                    if self.board[5 - 1] == "X":
                        position = 10 - i - 1
                        if self.board[position] == "O":
                            position = choice([item - 1 for item in [1, 3, 7, 9] if item not in [position + 1, i]])
                        break

                    for j in [1, 3, 7, 9]:
                        if i != j and self.board[j - 1] == "X":
                            position = i + (j - i) // 2 - 1
                            if self.board[position] == "O":
                                position = choice([2, 4, 6, 8]) - 1
                            break

                    for j in [2, 4, 6, 8]:
                        if self.board[j - 1] == "X":
                            diff = abs(j - i)
                            if get_line(i) != get_line(j) and diff == 1:
                                position = 5 - 1
                            else:
                                position = max(i, j) + diff
                                if position > 9: position = min(i, j) - diff
                                if self.board[position - 1] == "O": position = 5
                                position -= 1

            if position == None:
                for i in [2, 4, 6, 8]:
                    if self.board[i - 1] == "X":
                        if self.board[5 - 1] == "X":
                            position = 10 - i - 1
                        else:
                            position = 5 - 1

        if self.turn > 2:
            tmp_board = self.board[:]
            candidates = [i for i in range(9) if self.board[i] == None]
            for candidate in candidates:
                tmp_board[candidate] = "O"
                if self.get_game_winner(tmp_board) == "O":
                    position = candidate
                    break
                tmp_board[candidate] = None

            if position == None:
                for candidate in candidates:
                    tmp_board[candidate] = "X"
                    if self.get_game_winner(tmp_board) == "X":
                        position = candidate
                        break
                    tmp_board[candidate] = None

            if position == None: position = candidates[0]

        self.board[position] = "O"

    def ask_for_choice(self):
        while True:
            try:
                print("Your choice: ", end = "")
                position = int(input())
            except ValueError:
                print("That's not an integer!")
                continue

            if 1 <= position <= 9:
                return position - 1
            else:
                print("Number must be in range 1 to 9!")

    def user_turn(self):
        position = self.ask_for_choice()

        while self.board[position] != None:
            print("This position is filled")
            position = self.ask_for_choice()

        self.board[position] = "X"

    def is_game_finished(self):
        if None not in self.board:
            print("The game ended with a draw")
            sys.exit()

        winner = self.get_game_winner()
        if winner == None: return

        if winner == "X": print("You won the game!")
        else: print("Computer won the game")
        sys.exit()

    def start(self):
        self.print_board([i for i in range(1, 10)])
        print()
        print("Hello, the game just started!")
        while True:
            self.user_turn()
            self.print_board()
            self.is_game_finished()

            time.sleep(0.5)
            self.computer_turn()
            self.print_board()
            self.is_game_finished()

game = TicTacToe()
game.start()

A:

It is better to write:
import time
import sys
import os

instead of import time, sys, os (this is recommended PEP 8,  in imports section)

You declared board and turn as class attributes, but they evolve through your program as instance variables instead. This is wrong per design.
Your program presents condition checking in the forms of if something == None: and if something != None:  13 times. But you can simply write: if not something: and if something: (respectively) instead.
In ask_for_choice(), you can safely get rid of the continue instruction as this is already done by default given the way the exception is handled.
In user_turn(), it is more appropriate, in your context, to write: while self.board[position]: instead of while self.board[position] != None:
In Python, if you do not specify a return value to a function, this later one will return None. This means you can safely get rid of return None instruction in the get_game_winner() function.
In is_game_finished(), you can safely get rid of if winner == None: return because this achieved anyway if the other conditions are not met.
The reader of your code would expect the function is_game_finished() to return True or False, but this is not the case. You should either rename this function or modify its design.
In start(), you could write print("\nHello, the game just started!")instead of print() followed by print("Hello, the game just started!"). In the same time, there is nothing that justifies the blank line which exists in the while statement.
Inner functions, in Python, are more appropriate to use to design decorators. I personally do not like the definition of a function called get_line() within computer_turn().
The computer_turn() function is, IMHO, quite long (but others may argue about it). I would have divided those tasks between smaller functions for the sake of easier unit testing and, more importantly, SRP.
Throughout your code, several empty lines are left where this is not justified. You may help yourself by reading blank lines on PEP8.
It would be nice to put "a guard" to your program. I mean something like this:
if __name__ == '__main__':
   game = TicTacToe()
   game.start()

You may read on StackOverflow: What does if name == “main”: do?


Q:

Formatear fecha en Javascript menor a 1970

Tengo una fecha menor a 1970, en este caso 06/10/1943, y la mando desde ASP.NET a Javascript por AJAX, y esta llega con el formato /Date(-828046800000)/. En JS tengo una funcion para transformar estos formatos a texto, es esta:
function fixFecha(fecha) {
    debugger;
    if (fecha == null) {
        return '';
    }
    else {
        var codigo_fecha = parseInt(fecha.replace("/Date(", "").replace(")/", ""));
        var fecha1 = new Date(codigo_fecha).toLocaleDateString("es-AR");
        var fecha_formato = $.format.date(fecha1, "dd-MM-yyyy");

        return fecha_formato;
    }
}

Estoy seguro que funciona bien, pero hoy probe con una fecha menor a 1970, y me lo convierte a 05/10/1943, es decir, me esta restando un dia, alguien sabe por que puede pasar esto? Me imagino que sera por algo de que es menor a 1970 pero no estoy seguro.
Gracias.

A:

Intenté usar $.format.date(), pero no encontré referencia, supongo que puede ser un plugin de jQuery u otra librería, pero se puede hacer directamente con objetos de fecha.
Seguramente la diferencia se debe a la zona horaria. Creando una variable global almacenas los milisegundos a agregar/descontar y luego lo aplicas en la función.

// Diferencia horaria en minutos * 60 (segundos) * 1000 (milisegundos)
let diferencia = new Date().getTimezoneOffset() * 60000;

function fixFecha(fecha) {
    if (fecha == null) {
        return '';
    } else {
        // Obtener milisegundos pasados por parámetro
        // y aplicar diferencia horaria
        let miliSec = parseInt(fecha.replace('/Date(', '').replace(')/', '')) + diferencia;
        // Crear fecha y establecer formato
        let fecha1 = new Date(miliSec).toLocaleDateString("es-AR", {year: 'numeric', month: '2-digit', day: '2-digit'});
        return fecha1;
    }
}

console.log(fixFecha('/Date(-828046800000)/')); // 06/10/1943
console.log(fixFecha('/Date(0)/'));             // 31/12/1969
console.log(fixFecha('/Date(84600000)/'));      // 01/01/1970


Q:

issue with `for` loop, causes game to crash when button to run loop is clicked

in trying to get a few numbers (var belief and trinkets) to go up per second (using for loop), i run into the error "expected a conditional expression but instead saw an assignment" when using the analyse function over the following piece of code:
function trinketCount(number) {
    if(towers >= 1) {
        var trinketCap = 500;
        for(; trinkets = trinketCap;) {
            trinkets = trinkets + (towers * 2);
        }
        document.getElementById('trinkets').innerHTML = trinkets;
    }
}

and also in the following, very similar, loop:
function beliefCount(number) {
    if(towers >= 1) {
        var beliefCap = 600;
        for(; belief = beliefCap;) {
            belief = belief + towers;
            document.getElementById('belief').innerHTML = belief;
        }
    }
}

clicking the button to build a 'tower' also causes the whole thing to crash.
i am fairly new to js so i apologise if the problem is obvious! also check it out for yourself at https://codepen.io/dirtbf/project/full/XjvdMX

A:

"expected a conditional expression but instead saw an assignment"
This is exactly the problem.
for(; trinkets = trinketCap;) {
for(; belief = beliefCap;) {
You're assigning the values in here instead of checking whether they equal each other. Did that error come with a line number?
Fixed function versions:
function trinketCount(number) {
    if(towers >= 1) {
        var trinketCap = 500;
        for(; trinkets == trinketCap;) {
            trinkets = trinkets + (towers * 2);
        }
        document.getElementById('trinkets').innerHTML = trinkets;
    }
}

function beliefCount(number) {
    if(towers >= 1) {
        var beliefCap == 600;
        for(; belief = beliefCap;) {
            belief = belief + towers;
            document.getElementById('belief').innerHTML = belief;
        }
    }
}


Q:

How can I animate an overlayed div with :hover? Do I need JS or can it be done in CSS?

What I am trying to achieve: As the mouse scrolls over a color section, that specific color section slides and overlays the other three, revealing more content.
What I tried:
Each time I add a div it affects the previous div because of its parent.
If a div gets added without a parent, the result was that each div animated solo.
Perhaps I am approaching this the wrong way. Do I need javascript to hide each individual div? Whats the best way to achieve this? Thank you
Heres a code pen of what I have so far:
https://codepen.io/habsqrd/pen/WNbrNLL
Here is the body:

CSS:
body
{
  background-color: #d6d6d6;
  margin: auto;
}

.center {

}

.one {
  position: absolute;
  margin: auto;
  background-color:rgb(94, 226, 94);
  width: 90%;
  height: 90%;
  { transition: all .2s ease-in-out; }

}

.one:hover {
    position: absolute;
    background-color:rgb(6, 179, 6);
    width: 90%;
    height: 90%;
    z-index: 4;
    transition: all .2s ease-in-out;
  }

.two {
    position: absolute;
    background-color:rgb(247, 82, 82);
      width: 75%;
    height: 100%;
    z-index: 1;

  }

.three {
    position: absolute;
    background-color:rgb(86, 86, 255);
    width: 50%;
    height: 100%;
    z-index: 2;
  }

.four {
  position: absolute;
  background-color:rgb(240, 240, 96);
  width: 25%;
  height: 100%;
  z-index: 3;
}

A:

im hope i understand you correctly:
https://codepen.io/shahry4r/pen/yLyeyGV
<!DOCTYPE html>

 <link rel="stylesheet" type="text/css" href="styles.css">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

CSS

body
{
  background-color: #d6d6d6;
  margin: auto;
}

.center {

}

.one {
  display: inline-block;
  background-color:rgb(94, 226, 94);
  width: 25%;
  height: 100%;
  position: absolute;
  left:auto;
  { transition: all .2s ease-in-out; }

}

.one:hover {
    position: absolute;
    background-color:rgb(6, 179, 6);
    width: 100%;
    z-index: 4;
    transition: all .2s ease-in-out;
  }

.two {
      display: inline-block;
      background-color:rgb(247, 82, 82);
      width: 25%;
      height: 100%;
      position: absolute;
      left:25%;
      z-index: 1;

  }

.two:hover {
    position: absolute;
    background-color:rgb(247, 82, 82);
    width: 100%;
    z-index: 4;
    left:0%;
    transition: all .2s ease-in-out;
  }

.three {
  display: inline-block;
  background-color:rgb(86, 86, 255);
  width: 25%;
  height: 100%;
  position: absolute;
  left:50%;
}

.four {
  display: inline-block;
  background-color:rgb(240, 240, 96);
  width: 24%;
  height: 100%;
  left: 75%;
  position: absolute;
}


Q:

is there anybody who can help me parsing json data to another page using Hero Widget?

I want somebody to help me to parse JSON data to another Page in HERO widget in the flutter. I parse data to the first page but failed to parse data to another page

A:

make the model for JSON data use PODO style
 like this which will deal with all JSON data to parsed to the view class.
class ProductResponse{
  List<ProductDetail> results;
  ProductResponse({this.results});
  ProductResponse.fromJson(Map<String,dynamic> json){
    if(json['results'] !=null){
      results=new List<ProductDetail>();
      json['results'].forEach((v){
        results.add(new ProductDetail.fromJson(v));
      });
    }
  }
Map<String,dynamic> toJson(){
  final Map<String, dynamic> data = new Map<String, dynamic>();
  if (this.results != null) {
    data['results'] = this.results.map((v) => v.toJson()).toList();
  }
  return data;
}
}
class ProductDetail{
  int phone;
  int price;
  int qty;
  String amount;
  String place;
  String image_name;
  String image_url;
  String vendor_name;
  String description;
  String category;
  String productName;
  String images;
  ProductDetail({this.phone, this.price, this.qty, this.amount, this.vendor_name,
    this.description, this.category, this.productName, this.images,this.image_name,this.image_url,this.place});
   ProductDetail.fromJson(Map<String,dynamic> json){
        phone = json['phone'];
        price = json["price"];
        qty = json['qty'];
        amount =json['amount'];
        vendor_name =json['vendor_name'];
        description = json['description'];
        category = json['category'];
        images = json['images'];
        productName = json['productName'];
        image_url =json['image_url'];
        image_name =json['image_name'];
        place =json['place'];
  }
  Map<String,dynamic> toJson(){
     final Map<String,dynamic> data =new Map<String,dynamic>();
     data['phone'] =this.phone;
     data['price'] =this.price;
     data['qty'] =this.qty;
     data['amount'] =this.amount;
     data['vendor_name'] =this.vendor_name;
     data['description'] =this.description;
     data['category'] =this.category;
     data['productName'] =this.productName;
     data['images'] =this.images;
     data['place'] = this.place;
     data['image_url'] =this.image_url;
     data['image_name'] =this.image_name;
     return data;
  }
}

make the class which will make the request to the server
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:kilimo_biashara1/Model/Dialogs.dart';
import 'package:kilimo_biashara1/Model/ProductDetail.dart';
import 'package:kilimo_biashara1/Products/ProductPage.dart';

class Products extends StatefulWidget {
  @override
  _ProductsState createState() => _ProductsState();
}
class _ProductsState extends State<Products> {
  String url = "put your api url here";
  ProductResponse detail;// declare the class from PODO

  fetchProduct() async {
    var response = await http.get(url);
    var decodeJson = jsonDecode(response.body);
    print("response" + response.body);
    setState(() {
      detail = ProductResponse.fromJson(decodeJson);
    });
    print(detail);//debug
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        body: detail == null
            ? Center(
          child: CircularProgressIndicator(),
        )

          : StaggeredGridView.countBuilder(
          crossAxisCount: 4,
          itemCount: detail.results.length,
          itemBuilder: (BuildContext context, int index) {
            return ProductPage(
                detail: detail.results[index]
            ); //Return the product page
          },
          staggeredTileBuilder: (_) => StaggeredTile.fit(2),
          mainAxisSpacing: 4.0,
          crossAxisSpacing: 4.0,
        )

    );
  }

}

here are sample codes of the product page.in this product page it will show cards with few details in it
import 'package:flutter/material.dart';
import 'package:kilimo_biashara1/Products/DetailProduct.dart';
import 'package:kilimo_biashara1/Model/ProductDetail.dart';
 class ProductPage extends StatelessWidget {
   final ProductDetail detail;
   ProductPage({@required this.detail});
   @override
   Widget build(BuildContext context) {
     return Card(
       shape: RoundedRectangleBorder(
         borderRadius: BorderRadius.circular(4.0),
       ),
       elevation: 4.0,
       margin: EdgeInsets.all(4.0),
       child: InkWell(
         radius: 4.0,
         child: getCardView(context),
         onTap: (){
           Navigator.push(
            context,
            MaterialPageRoute(builder: (context) =>
            DetailProduct(
              detail: detail,
            ),
            ),
           );
         },
       ),
     );
   }
   //////
   getCardView(BuildContext context){
     return Column(
       mainAxisSize: MainAxisSize.min,
       crossAxisAlignment: CrossAxisAlignment.start,
       children: <Widget>[
         Hero(
             tag: detail,//this key /tag will be the same with another page also
             child: Container(
               height: 200.0,
             decoration: BoxDecoration(
               borderRadius: BorderRadius.circular(8.0),
               image: DecorationImage(
                   image: NetworkImage("${detail.image_url}"
                      ,
                   ),
                   fit: BoxFit.cover),
             ),
             ), ),
      //   Image.asset("images/ndz.jpg"),
         Padding(
           padding: const EdgeInsets.all(4.0),
           child: Column(
             crossAxisAlignment: CrossAxisAlignment.start,
             children: <Widget>[
               Text("sold by: "+
                 detail.vendor_name,
                 overflow: TextOverflow.ellipsis,
                 style: Theme
                     .of(context)
                     .textTheme
                     .body2,
               ),
               Text("product: "+
                 detail.productName,
                 softWrap: true,
                 overflow: TextOverflow.ellipsis,
                 style: Theme
                     .of(context)
                     .textTheme
                     .body2,
               ),
               Text("price: ${detail.price} ${detail.amount}"
                ,
                 softWrap: true,
                 overflow: TextOverflow.ellipsis,
                 style: Theme
                     .of(context)
                     .textTheme
                     .body2,
               ),
             ],
           ),
         ),
       ],
     );
   }
 }

when it is clicked/tapped it will direct to the other page which will provide full details about the products
import 'package:flutter/material.dart';
import 'package:kilimo_biashara1/Model/ProductDetail.dart';
import 'package:kilimo_biashara1/payment/Payment.dart';
class DetailProduct extends StatelessWidget {
  final ProductDetail detail;
  DetailProduct({this.detail});
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        persistentFooterButtons: <Widget>[
             Padding(
               padding: const EdgeInsets.fromLTRB(15.0, 5.0, 40.0, 5.0),
               child: new Text("SHOPPING",
                  style: new TextStyle(fontSize: 25.0,color: Colors.green,fontWeight: FontWeight.bold),
                ),
             ),
            new FlatButton(
            child: new Icon(Icons.shopping_cart,size: 35.0,),
            onPressed:(){
    Navigator.of(context).push(
    new MaterialPageRoute(
    builder: (BuildContext context)=>new Payment()));
    } ,
          ),
        ],
        body:new Scaffold(
    body:ListView(
    children: <Widget>[
      Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Hero(
              tag: detail,
              child: Container(
                height: 250.0,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(16.0),
                  shape: BoxShape.rectangle,
                  image: DecorationImage(
                    image: NetworkImage(
                      "${detail.image_url}",
                    ),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),

           // Image.asset("images/ndz.jpg"),
            SizedBox(
              height: 16.0,
            ),
            Text("vendor name:  "+
              detail.vendor_name,
              style: Theme.of(context).textTheme.title,
            ),
            SizedBox(
              height: 16.0,
            ),
            Text("product name: "+
              detail.productName,
              style: Theme.of(context).textTheme.subhead,
            ),
            SizedBox(
              height: 16.0,
            ),
            Text("vendor place: "+
              detail.place,
              style: Theme.of(context).textTheme.subhead,
            ),
            SizedBox(
              height: 16.0,
            ),
            Text("price:  ${detail.price}  ${detail.amount}",
              style: Theme.of(context).textTheme.subhead,
            ),
            SizedBox(
              height: 16.0,
            ),
            Text("short description:  "+
              detail.description,
              style: Theme.of(context).textTheme.subhead,
            ),
            SizedBox(
              height: 16.0,
            ),
            Text("Category:  "+detail.category,
              style: Theme.of(context).textTheme.subhead,
            ),
            SizedBox(
              height: 16.0,
            ),
            Text("contacts:  ${detail.phone}",
              style: Theme.of(context).textTheme.subhead,
            ),
          ],
        ),
      ),
    ],
    ),

    ),
    ),
    );
  }
}

after following these steps you should reach to a point where you parse data from the API with hero widget


Q:

Bizarre exceptions being thrown in android activity

So, I have an android app to finish making for a project, the same one as I asked questions about here before but this time I'm having trouble with a completely different aspect. Since the app is about Pokémon, in one activity I have some TextViews, EditTexts and a button set up to make an IV calculator. If you're curious and don't know what "IVs" are in Pokémon, google it of course. Anyway, getting back on track...this image here I put together highlights my problem

Above the boxed line you see there is a ClassCastException thrown  saying cannot cast from type TextView to EditText...I know what that means in a general sense but I cannot fathom why it is occurring here because as you can see in the relevant line of code (which i pasted into the image) the part of that line that involves casting is casting from View (return type of findViewById) to EditText. The arg R.id.EditText06 IS referring to an EditText in my activity so I don't see where the bad casting attempt is supposedly occurring. Just for a little clarification of the context of this, this is part of stuff coded into the OnClickListener of the button.
Apologies if this question seems perhaps incomplete as regards content shown about the problem but it is quite late for me (so much so that I'm going to bed upon posting this) and please do ask for me to post other stuff if you feel you need it to try to help me.
EDIT: here is my xml file for the activity in question. http://pastebin.com/g5B8d393
EDIT2: OK now this is getting worse :( My current setup is that I have a sort of dummy main activity with just a button to launch an activity. While testing I changed which one it was to launch as desired...until some time last night (and I really don't see what could've started this problem) it worked fine with my IVCalculatorActvity once I had it working fully and properly, and with the other activity. But now, it just crashes when I hit the button in the main activity...I'm just going to upload the project somewhere. (http://www.filehosting[DOT]org/file/details/429262/PokeUtility.zip)
Grrr...curse this reputation restriction on link posting >.>
I understand the reasoning but meh...
EDIT3: apologies for ssuch sudden editing but I only just saw you latest post now HalR. Testing app atm.

A:

findViewById doesn't return an object of class View, but of whatever class that object is indicated in your XML file.  Whatever you think you are describing your EditText06 as in your XML, it thinks its a TextView instead of and EditText.  Double check and make sure you aren't defining the id="EditText06" in more than one spot.
If you show your xml, It would likely be easier for someone to point out the specific problem in your xml file.
You need to use the format "@+id/..." once for each label, the first time it shows up (either as a reference or as an id".  Otherwise you generate multiple labels. I edited your file the way I think it needs.
<?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:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                tools:context=".IVCalculatorActivity" >

    <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:text="@string/calculate" />

    <EditText
            android:id="@+id/EditText01"
            android:layout_width="140dp"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/textViewD"
            android:layout_alignBottom="@id/textViewD"
            android:layout_alignLeft="@+id/EditText05"
            android:ems="10" />

    <EditText
            android:id="@+id/EditText03"
            android:layout_width="140dp"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/textView5"
            android:layout_alignBottom="@id/textView5"
            android:layout_alignLeft="@+id/EditText02"
            android:ems="10" />

    <EditText
            android:id="@+id/EditText04"
            android:layout_width="140dp"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/textView6"
            android:layout_alignBottom="@id/textView6"
            android:layout_alignLeft="@+id/EditText03"
            android:ems="10" />

    <TextView
            android:id="@+id/textViewA"
            android:layout_width="400dp"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textViewC"
            android:layout_alignParentTop="true"
            android:text="@string/IVcalcHeader" />

    <TextView
            android:id="@id/textViewC"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/textViewD"
            android:layout_below="@id/textViewA"
            android:layout_marginTop="26dp"
            android:text="Stat" />

    <EditText
            android:id="@id/EditText05"
            android:layout_width="140dp"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/textViewC"
            android:layout_alignBottom="@id/textViewC"
            android:layout_alignRight="@id/textViewA"
            android:ems="10" />

    <TextView
            android:id="@id/textViewD"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textViewB"
            android:layout_below="@id/EditText05"
            android:layout_marginTop="27dp"
            android:text="Stat value" />

    <EditText
            android:id="@+id/EditText02"
            android:layout_width="140dp"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/textViewB"
            android:layout_alignBottom="@id/textViewB"
            android:layout_alignLeft="@id/EditText01"
            android:ems="10" />

    <TextView
            android:id="@id/textViewB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/textView5"
            android:layout_below="@id/EditText01"
            android:layout_marginTop="28dp"
            android:text="Level" />

    <TextView
            android:id="@id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/textView6"
            android:layout_centerVertical="true"
            android:text="EV count" />

    <TextView
            android:id="@id/textView6"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:layout_alignRight="@id/button3"
            android:layout_below="@+id/EditText03"
            android:layout_marginTop="29dp"
            android:text="Base Stat" />

    <TextView
            android:id="@+id/textViewE"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/textView6"
            android:layout_below="@id/textView6"
            android:layout_marginTop="40dp"
            android:text="Nature" />

    <TextView
            android:id="@+id/textView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/EditText04"
            android:layout_alignTop="@id/button3"
            android:text="      " />

    <EditText
            android:id="@+id/EditText06"
            android:layout_width="140dp"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/textViewE"
            android:layout_alignBottom="@id/textViewE"
            android:layout_alignLeft="@id/textView7"
            android:ems="10" />

</RelativeLayout>


Q:

Casting an interface

I have the following code
  var distributionUnits = _distributionUnitRepository.FindByCompanyId(userSession.CompanyId);

This returns 2 records. However when i tried the following cast. I have no records.
        var myentities = distributionUnits as List<IEntity>;

Is this kind of cast possible?
Further info.
 public interface IEntity
    {
        string Name { get; set; }
    }

public class DistributionUnit : IEntity
{

   public virtual string Name { get; set; }

}

A:

var myentities = distributionUnits.Cast<IEntity>().ToList();

assuming your distributionUnits are either IEntity or something that either inherits or implements IEntity.


Q:

mySql count all latest versions

In had a question up yesterday unfortunately I didn't explain myself well enough - one of them end of the day things.
Anyway I have a table called documents...
+----+--------------------------------------+-----------+---------+---------+
| id | document_guid                        | title     | version | payload |
+----+--------------------------------------+-----------+---------+---------+
| 1  | 0D2753BE-583B-42CE-B0DA-1FD0171D95C0 | animation | 1       | {}      |
| 2  | 0D2753BE-583B-42CE-B0DA-1FD0171D95C0 | animation | 2       | {}      |
| 3  | 1C2A1131-0261-4D58-81AA-EFAB5285B282 | formation | 1       | {}      |
| 4  | 1E17403F-C590-4CE4-9E79-E1B7C98F97F1 | session   | 1       | {}      |
| 4  | 1E17403F-C590-4CE4-9E79-E1B7C98F97F1 | session   | 2       | {}      |
+----+--------------------------------------+-----------+---------+---------+

As you can see we can have multiple versions of the same document (referenced by document_guid). What I need is a count of all documents in the table excluding obsolete version. i.e. If the document 1E17403F-C590-4CE4-9E79-E1B7C98F97F1 has two versions like it shows in the example above then it should only account for one document in the overall count.
I really hope this makes more sense then my last question.
The main problem I have is I need a similar query that returns all the latest versions rather than just the count too.

A:

A useful query would probably look like:
-- select the maximum version (and other information, per group)
-- can also add a 'count(1) as version_count' if required
select max(version) as latest_version, title, document_guid
from documents
-- from each group, as divided up by the same guid *see note 1
group by document_guid, title

This query returns the latest version number; there is always "one latest version" per document.

1 The title, which may be a break in normalization, needs to be part of the group for it to be included in the result columns; if not needed, it can be removed.
If the title is a required field that can change across versions then this needs to be written differently - first find the "latest version" and then join it back with the appropriate rows. An example:
select t.latest_version, d.title, d.document_guid
from documents d
join (
  select max(version) as latest_version, document_guid
  from documents
  group by document_guid
) t
on t.document_guid = d.document_guid and t.latest_version = d.version

And of course this assumes a key of (document_guid, version).


Q:

Onboarding with custom animation

If I want to create Onboarding Screen  with custom page interactive transitions without any library. What should I do ?
Should I use pageViewController or collectionViewController ?

A:

I would use a PageViewController with custom transitions/animations.
Take a look at this post on how you might want to structure and build it.
Click here.


Q:

Application running slow after adding GDB symbols - Side effect?

We have a application of size about 20MB in release mode. This application is meant to run on MIPS running Linux 2.6.12 The debug build of the same is about 42 MB, with optimization switched off and -g flag added. The additional 22 MB increase is only because of gdb debug symbols embedded into the application (no logs or print statements added).
Now will debug build run slower than the image compared to release mode, if yes why ?
Also AFAIK strip debug_image should give me release_image, but in my case I observe following.
debug_image = 42MB
strip debug_image = 24MB
release_image = 20MB

Why is there a difference between stripped debug_image and release_image ?
Are there any other side effects embedding gdb symbols into application ?

A:

Now will debug build run slower than the image compared to release
  mode, if yes why ?

Yes it will, if optimizations are off, which is true in your case.

Why is there a difference between stripped debug_image and
  release_image ?

Because of optimizations are on in release, the whole image size is optimized, reducing it. This results to less image size in release than in debug.

Are there any other side effects embedding gdb symbols into
  application ?

It will take longer time for gdb to load symbols and more memory will be required.


Q:

Connecting to clients using proxy server

I need to build some software infrastructure to manage computers which are connected to the internet using a 3G modem (about 30-40 clients).
The scenario that I came up with for project needs:

Client established internet connection (this is made on OS startup - no user action needed)
Client make connection to some server in internet (I named it "PROXY" - maybe there is a better name)
From now client is connected to PROXY server and it is listening for connections on some port (static or dynamic port?)

The same is true for all other machines.
What I need:

When I connect to PROXY server I want to see list of all connected clients to it (optionaly time of connection, client IP etc)
I can make connection to any clients but not P2P I want to connect using PROXY server (some kind of tunneling?)
Access to client should be impossible without PROXY server.

Example:

Client connect to internet using 3G modem - received IP: 149.10.20.30
Client connect to PROXY (79.10.11.12)
I connect to PROXY (terminal / VNC / putty / whatever). I can list connected clients (ex. using some command: $ show_connected_clients). And I see list: IP / MAC or other informations.
From my computer (or PROXY server if this is simpler) I can make connection to client (terminal / VNC / RDP whatever) using for this PROXY server.
$ connect_to 149.10.20.30 using 79.10.11.12

Is such a thing is to realize with the help of the built-in OS services? Or maybe I need to use some commercial software or write my own application?
Writing this from scratch is possible but I do not want to reinvent the wheel.
Some advice? Thanks in advance for any help.
PS. Clients OS (probably all) is Linux. PROXY server OS - I can make decision by my own.

A:

I've decide to use VPN. Perfect in its simplicity. If someone is interested.

Client connects to VPN. Gets IP from VPN network
VPN server on PROXY server
My machine connects to VPN
On PROXY server I can list connected clientes to VPN
Using (ex RDP) I can connect to any client by VPN network

I think I can configure client to deny connection from other network then VPN. If so, I have everything I need.
Simple :)


Q:

Convert a string to array of array

I need your help today to convert a string (I'll name it $data) like this one :
{"hours":{"2018-06-10 11:00":2,"2018-06-12 07:00":5,"2018-06-12 08:00":4,"2018-06-12 09:00":2,"2018-06-13 09:00":1,"2018-06-13 13:00":1,"2018-06-13 23:00":1,"2018-06-15 13:00":1,"2018-06-15 14:00":1,"2018-06-15 15:00":2,"2018-06-18 06:00":5,"2018-06-18 07:00":9,"2018-06-18 08:00":1,"2018-06-18 09:00":1,"2018-06-18 12:00":2,"2018-06-18 13:00":13},"days":{"2018-06-10 00:00":2,"2018-06-12 00:00":11,"2018-06-13 00:00":3,"2018-06-15 00:00":4,"2018-06-18 00:00":29,"2018-06-18 07:00":2},"weeks":{"2018-06-10 00:00":20,"2018-06-17 00:00":29,"2018-06-18 07:00":2}}

to something like this :

hours (Array)

2018-06-10 11:00 (key) : 2 (value as int)
2018-06-12 7:00 (key) : 5 (value as int)
etc...

days (Array)

2018-06-10 00:00 (key) : 2 (value as int)
etc...

weeks (Array)

2018-06-10 00:00 (key) : 20 (value as int)
etc...

I know there's some PHP functions like str_split or explode but I don't really know how to do.
I've tried to make something like :
explode('{', $data);

or things like that but I don't really know where to start, if I explode with the ":", it will take the ":" in the date too.
If I forgot to put something, just tell me I'll edit the question.
Thanks in advance

A:

Or you can to try this:
$data = '{"hours":{"2018-06-10 11:00":2,"2018-06-12 07:00":5,"2018-06-12 08:00":4,"2018-06-12 09:00":2,"2018-06-13 09:00":1,"2018-06-13 13:00":1,"2018-06-13 23:00":1,"2018-06-15 13:00":1,"2018-06-15 14:00":1,"2018-06-15 15:00":2,"2018-06-18 06:00":5,"2018-06-18 07:00":9,"2018-06-18 08:00":1,"2018-06-18 09:00":1,"2018-06-18 12:00":2,"2018-06-18 13:00":13},"days":{"2018-06-10 00:00":2,"2018-06-12 00:00":11,"2018-06-13 00:00":3,"2018-06-15 00:00":4,"2018-06-18 00:00":29,"2018-06-18 07:00":2},"weeks":{"2018-06-10 00:00":20,"2018-06-17 00:00":29,"2018-06-18 07:00":2}}
';

$dados =  json_decode( $data, true );
echo "<pre>";
print_r($dados);
echo "</pre>";


Q:

Does Epplus support set sheet data/cell value by office open xml?

My question :
If there is a sheet data format with office open xml like below :
        <sheetData>
            <row r="1" spans="1:3" x14ac:dyDescent="0.25">
                <c r="A1" t="s">
                    <v>0</v>
                </c>
                <c r="B1" t="s">
                    <v>1</v>
                </c>
                <c r="C1" t="s">
                    <v>2</v>
                </c>
            </row>
            <row r="2" spans="1:3" x14ac:dyDescent="0.25">
                <c r="A2">
                    <v>1</v>
                </c>
                <c r="B2">
                    <v>2</v>
                </c>
                <c r="C2">
                    <v>3</v>
                </c>
            </row>
            <row r="3" spans="1:3" x14ac:dyDescent="0.25">
                <c r="A3">
                    <v>4</v>
                </c>
                <c r="B3">
                    <v>5</v>
                </c>
                <c r="C3">
                    <v>6</v>
                </c>
            </row>
            <row r="4" spans="1:3" x14ac:dyDescent="0.25">
                <c r="A4">
                    <v>7</v>
                </c>
                <c r="B4">
                    <v>8</v>
                </c>
                <c r="C4">
                    <v>9</v>
                </c>
            </row>
        </sheetData>

how can I set this xml for epplus to change the cells value?
What I tried :
Searching epplus and only Cells[IndexName].Value = "xx" api.
What I expect for :
some epplus method like :
ws.SetSheetDataXml = xml;

A:

You can always get to and manipulate the XML for the Worksheet like this:
var fi = new FileInfo(@"c:\temp\SomeExcelFile.xlsx");

using (var pck = new ExcelPackage(fi))
{
    var workbook = pck.Workbook;
    var ws = workbook.Worksheets.Add("Sheet1");
    ws.Cells.LoadFromDataTable(datatable, true);
    var xdoc = ws.WorksheetXml;

    ...
}

Obviously, you will have to be careful what you do with it so Epplus does not get upset when you try to save it.  Generally, messing with the XML directly is a last resort for thing that Epplus cannot do.  Here are a few examples:
How can I turn background error checking off for the Excel app object in EPPlus?
How to stop other conditional formatting from disappearing when hackmodding databars into solid fills?
X-Axis label formatting issue while exporting Chart to Excel using EPPlus


Q:

Javascript alert if text is found on another page

Currently using this code to show a popup if the text is found on that page. However, I wanted to show that popup on other pages if the text exists on the original page.
Example
Text is on /invoice
I navigate to /payment
Pop up still runs
<script type="text/javascript">
  window.onload = function(){
    //If the body element of the page contains 'one hour turnaround' then trigger an alert
    if(document.body.innerHTML.toString().indexOf('one hour turnaround') > -1){
         alert("You have a ONE HOUR TURNAROUND order");
    }};
</script>

A:

For easy workaround, you can do this by saving the flag for this in the local storage and accessing on every page to check if that localstorage has value then show the popup otherwise not. after that 1hour time span should clear the localstorage. so now you dunction on the page wher you have that element is now
 window.onload = function(){
        //If the body element of the page contains 'one hour turnaround' then trigger an alert
        if(document.body.innerHTML.toString().indexOf('one hour turnaround') > -1){
              localStorage.setItem('oneHourTurnaround', "true");
               alert("You have a ONE HOUR TURNAROUND order")
               setTimeout(function(){ alert("You have a ONE HOUR TURNAROUND order"); }, 3000); // currenlty it's 3 sec
          }
        else{
            localStorage.setItem('oneHourTurnaround', "false");
        }
      }

and for all other page are
window.onload = function(){
    //If the body element of the page contains 'one hour turnaround' then trigger an alert
    if(localStorage.getItem('oneHourTurnaround')==true){
      alert("You have a ONE HOUR TURNAROUND order");
    }
 }


Q:

How can I get a summary of my cvs conflicts when doing a cvs update on the command line?

Is there an easy way to get a conflict summary after running a cvs update?
I work on a large project and after doing some work I need to do an update.  The list of changes coming back from the cvs update command is several pages long and I'd like to see only the list of conflicts (starts with 'C') repeated at the end of the cvs update command output.
The solution needs to work from the command line.
If my normal output is:
M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt

I want my new output to be:
M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt

Conflict Summary:
C src/file3.txt

I want this to be a single command (possibly a short script or alias) that outputs the normal cvs output as it happens followed by a summary of conflicts.

A:

Given the specification, it seems that you need a minor adaptation of Martin York's solution (because that only shows the conflicts and not the normal log information).  Something like this - which might be called 'cvsupd':
tmp=${TMPDIR:-/tmp}/cvsupd.$$
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15
cvs update "$@" | tee $tmp
if grep -s '^C' $tmp
then
    echo
    echo Conflict Summary:
    grep '^C' $tmp
fi
rm -f $tmp
trap 0
exit 0

The trap commands ensure that the log file is not left around.  It catches the normal signals - HUP, INT, QUIT, PIPE and TERM (respectively) and 0 traps any other exit from the shell.


Q:

MySQL join, order not correct

I have two tables:
tickets

ticket_id, int(11), NO, PRI, , auto_increment
order_num, varchar(45), NO, , ,
user_id, int(11), YES, , ,
event_id, int(11), YES, , ,
number_of_tickets, varchar(4), YES, , ,
order_placed, timestamp, NO, , CURRENT_TIMESTAMP,
payment_recd, enum('Yes','No'), YES, , No,
payment_time, timestamp, YES, , ,

events

event_id, int(11), NO, PRI, , auto_increment
venue_id, int(11), YES, , ,
event_date, date, YES, , ,
event_time, time, YES, , ,
event_price, decimal(4,2), YES, , ,
event_capacity, int(11), YES, , ,
dateadded, timestamp, NO, , CURRENT_TIMESTAMP,

I need to list tickets bought by a user and order by the event date but the following I'm trying is not doing the sort by correctly
select tickets.order_num as ordnum, tickets.event_id as tickid, tickets.number_of_tickets as numtix
   from tickets, events
where  ((tickets.user_id = '1') and (tickets.payment_recd = 'Yes'))
  group by tickets.order_num
order by events.event_date asc

Any ideas?

A:

you are not joining the tables, so it will list all rows from both tables, try:
select tickets.order_num as ordnum, tickets.event_id as tickid, tickets.number_of_tickets as numtix
from tickets
inner join events on tickets.event_id = events.event_id
where ((tickets.user_id = '1') && (tickets.payment_recd = 'Yes'))
group by tickets.order_num order by events.event_date asc


Q:

stop Listview from capturing mouse scroll inside ScrollViewer in XAML

Hello I'm making UWP app, where on one of the pages I want a website like experience, meaning a long scroll on the page.
I have a Listview inside a pivot on the page.
It looks something like this.
<ScrollViewer
        x:Name="scrollViewer"
        ManipulationMode="All"
        ScrollViewer.IsVerticalScrollChainingEnabled="True"
        VerticalScrollBarVisibility="Auto">
        <RelativePanel>
            <Image />
    <Pivot>
        <Listview />
    </Pivot>
    <Other stuff />
    </RelativePanel>

Now my problem is that, the mouse scroll works fine when im holding the mouse over any object except the listview, as soon as the mouse is over the listview the scroll dont work.
I have tried creating a custom ListView Style like this but that dont work.
<Style
            x:Key="NoScrollListViewStyle"
            TargetType="ListView">
            <Setter
                Property="IsTabStop"
                Value="False" />
            <Setter
                Property="TabNavigation"
                Value="Once" />
            <Setter
                Property="IsSwipeEnabled"
                Value="False" />
            <Setter
                Property="ScrollViewer.HorizontalScrollBarVisibility"
                Value="Disabled" />
            <Setter
                Property="ScrollViewer.VerticalScrollBarVisibility"
                Value="Disabled" />
            <Setter
                Property="ScrollViewer.HorizontalScrollMode"
                Value="Disabled" />
            <Setter
                Property="ScrollViewer.IsHorizontalRailEnabled"
                Value="False" />
            <Setter
                Property="ScrollViewer.VerticalScrollMode"
                Value="Disabled" />
            <Setter
                Property="ScrollViewer.IsVerticalRailEnabled"
                Value="False" />
            <Setter
                Property="ScrollViewer.ZoomMode"
                Value="Disabled" />
            <Setter
                Property="ScrollViewer.IsDeferredScrollingEnabled"
                Value="False" />
            <Setter
                Property="ScrollViewer.BringIntoViewOnFocusChange"
                Value="True" />
            <Setter
                Property="ItemContainerTransitions">
                <Setter.Value>
                    <TransitionCollection>
                        <AddDeleteThemeTransition />
                        <ContentThemeTransition />
                        <ReorderThemeTransition />
                        <EntranceThemeTransition
                            IsStaggeringEnabled="False" />
                    </TransitionCollection>
                </Setter.Value>
            </Setter>
            <Setter
                Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <ItemsStackPanel
                            Orientation="Vertical" />
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
            <Setter
                Property="Template">
                <Setter.Value>
                    <ControlTemplate
                        TargetType="ListView">
                        <Border
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}">
                            <ScrollViewer
                                x:Name="ScrollViewer"
                                AutomationProperties.AccessibilityView="Raw"
                                BringIntoViewOnFocusChange="{TemplateBinding ScrollViewer.BringIntoViewOnFocusChange}"
                                HorizontalScrollMode="Disabled"
                                HorizontalScrollBarVisibility="Hidden"
                                IsHorizontalRailEnabled="False"
                                IsHorizontalScrollChainingEnabled="False"
                                IsVerticalScrollChainingEnabled="False"
                                IsVerticalRailEnabled="False"
                                IsDeferredScrollingEnabled="False"
                                TabNavigation="{TemplateBinding TabNavigation}"
                                VerticalScrollBarVisibility="Disabled"
                                VerticalScrollMode="Disabled"
                                ZoomMode="Disabled">
                                <ItemsPresenter
                                    FooterTransitions="{TemplateBinding FooterTransitions}"
                                    FooterTemplate="{TemplateBinding FooterTemplate}"
                                    Footer="{TemplateBinding Footer}"
                                    HeaderTemplate="{TemplateBinding HeaderTemplate}"
                                    Header="{TemplateBinding Header}"
                                    HeaderTransitions="{TemplateBinding HeaderTransitions}"
                                    Padding="{TemplateBinding Padding}" />
                            </ScrollViewer>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

Any ideas?

A:

On solution that cross my mind is to capture PointerWheelChanged event and move ScrollView:
   private void ListView_PointerWheelChanged(object sender, PointerRoutedEventArgs e)
    {
     ScrollView.ScrollToVerticalOffset(ScrollView.VerticalOffset - e.GetCurrentPoint(ScrollView).Properties.MouseWheelDelta);
    }


Q:

How to plot graph where the indexes are strings

I'm running with python 3.7.6 and I have the following dataframe:
         col_1  col_2  col_3  col_4
GP           1      1      1      1
MIN          1      1      1      1
PTS          1      1      1      1
FGM          1      1      0      1
FGA          0      1      0      0
FG%          0      1      1      1
3P Made      0      1      1      0
AST          0      1      1      0
STL          0      1      0      0
BLK          0      1      1      0
TOV          0      0      1      0

I want to plot the dataframe as scatter plot or other (dot's plot) where:
X axis - dataframe indexes
Y axis - dataframe columns
points on the graph are according to the values from dataframe (1 - show on graph and 0 not)
How can I do it ?

A:

I'm not sure about scatter, but you can use imshow to display the binary values:
fig, ax = plt.subplots()
ax.imshow(df, cmap='gray')
ax.set_xticks(range(df.shape[1]))
ax.set_xticklabels(df.columns)

ax.set_yticks(range(df.shape[0]))
ax.set_yticklabels(df.index)
plt.show()

Output:

Update: scatter also possible:
plt.scatter(*np.where(df.T))
plt.xticks(range(df.shape[1]), df.columns)
plt.yticks(range(df.shape[0]), df.index)
plt.show()

Output:


Q:

Resolve using UI Router and pass to a component's controller

How do I resolve a variable with UI Router when I am using a component.
This is the route:
$stateProvider
  .state('route', {
    url: '/route',
    template: '<my-component user="user"></my-component>',
    resolve: {
      user: (Auth) => {
        return Auth.getCurrentUser().$promise;
      }
    }
  })

This is the component:
(function () {

   class BookingListComponent {
     constructor(user) {
        //I want to use the user here but getting the unknown provider error
     }

  }

  angular.module('app')
    .component('myComponent', {
      templateUrl: 'my-url.html',
      controller: MyComponent,
      bindings: {
      user: '<'
      }
    });

})();

Using Angular 1.5 and yeoman angular-fullstack

A:

You will need to do one of the following:

Create a controller for the state and bind the resolved value to the $scope.
Bind the reference of Auth.getCurrentUser() to the $rootScope for it to be available for each state.

Example for approach #1:
.state('route', {
    url: '/route',
    template: '<my-component user="user"></my-component>',
    controller: ($scope, user) => { $scope.user = user; },
    resolve: {
      user: (Auth) => {
        return Auth.getCurrentUser().$promise;
      }
    }
});

Example for approach #2:
.run(($rootScope, Auth) => {
 //This does NOT replace the resolve in your state definition but for this to work,
 //Auth.getCurrentUser() must NEVER return null.
 $rootScope.user = Auth.getCurrentUser();
});

Further explaination on approach #2:
Each $scope will inherit from $rootScope so as long $rootScope.user points to an actual object, child scopes will point to the same object.
The best practice if you choose to go with #2 is to bind the user object to a property of a defined object on the $rootScope to avoid any issues:
.run(($rootScope, Auth) => {
     $rootScope.data = {
      //Now user can be null.
      user: Auth.getCurrentUser()
      //Other shared data...
     }
});

But then you'll have to update your template to use data.user.
EDIT:
I've found this example in the docs, might shed a bit of light on the issue:
angular.module('myMod', ['ngRoute']);
.component('home', {
  template: '
Home

Hello, {{ $ctrl.user.name }} !
',
  bindings: {
    user: '<'
  }
})
.config(function($routeProvider) {
  $routeProvider.when('/', {
    //Notice $resolve?
    template: '<home user="$resolve.user"></home>',
    resolve: {
      user: function($http) { return $http.get('...'); }
    }
  });
});


Q:

How to make a large array usable within a function with good performance

I have a peace of precedural code which is executed in a loop. This peace of code requires one large array, but only for reading and not manipulating purposes. I generate this array once before the loop.
Now I would like to move this code into a function in order to use it again is some other script, but I don't know how to that in a clean way, but still having a good performance:

Generating this large array every time in the function itself would be bad, since it is always the same array and creates unnecessary overhead.
I dont want to use a global array, since this is bad practise
I guess therefore it would be the best to pass it as a paremeter every time I call the function.

I don't like that last option too much either, because it clutters the argument list and I am not sure about the overhead caused through this. As I understand it the array would be copied every time - would it be a good idea to pass it by reference therefore (by using the & operator)?

A:

One, who is really concerned in performance, should
avoid processing large arrays in a performance-critical code.
instead of playing tricks of speeding up an essentially slow process.
So, without knowing a REAL CASE (the purpose, processing and content of the array) the only answer could be:
Thus, turn your array into a database and select only necessary data.
This is a general answer to such a general question like this.