text:
Q: errors with updating halide function in all pixel I try to implement an optical flow algorithm in Halide. I have some problems with the update of u and v vectors. Here is my C++ version:
for(int i= 0; i<h; i++) {
for(int j= 0; j<bpl; j++) {
  float iix = Ix[i*bpl+j];
  float iiy = Iy[i*bpl+j];
  float iit = It[i*bpl+j];
  for(int k=0; k<40; k++) {
    float Uav     = (u[(i-1)*bpl+j] + u[(i+1)*bpl+j] + u[i*bpl+j-1] + u[i*bpl+j+1])/4;
    float Vav     = (v[(i-1)*bpl+j] + v[(i+1)*bpl+j] + v[i*bpl+j-1] + v[i*bpl+j+1])/4;
    float P       = iix*Uav + iiy*Vav + iit;
    float D       = iix*iix + iiy*iiy + lambda*lambda;
    float tmp     = P/D;
    float utmp    = Uav - iix*tmp;
    float vtmp    = Vav - iiy*tmp;
    u[i*bpl+j] = utmp;
    v[i*bpl+j] = vtmp;
  }
}

}
And this is my halide implementation:
Func u("u"), v("v");
Func Uav("Uav"), Vav("Vav"), P("P"), D("D"), tmp("tmp"), utmp("utmp"), vtmp("vtmp");
RDom r_0(0, input_1.width(), 0, input_1.height());
u(x, y, c) = 0;
v(x, y, c) = 0;
for(int k=0; k<40; k++) {
Uav (x, y, c) = (u(x, y-1, c) + u(x, y+1, c) + u(x-1, y, c) + u(x+1, y, c))/4;
Vav (x, y, c) = (v(x, y-1, c) + v(x, y+1, c) + v(x-1, y, c) + v(x+1, y, c))/4;
P (x, y, c) = Ix(x, y, c) * Uav(x, y, c) + Iy(x, y, c) * Vav(x, y, c) + It(x, y, c);
D (x, y, c) = Ix(x, y, c) * Ix(x, y, c) + Iy(x, y, c) * Iy(x, y, c) + lambda * lambda;
tmp (x, y, c) = P(x, y, c)/D(x, y, c);
utmp(x, y, c) = Uav(x, y, c) - Ix(x, y, c) * tmp(x, y, c);
vtmp(x, y, c) = Vav(x, y, c) - Iy(x, y, c) * tmp(x, y, c);
u(r_0.x, r_0.y, c) = utmp(x, y, c);
v(r_0.x, r_0.y, c) = vtmp(x, y, c);
}

When I run my program, I get the following runtime error:

Error:
  Func u cannot be given a new update definition, because it has already been realized or used in the definition of another Func.
  Aborted (core dumped)

Thanks for yours responses.
As say, AhiyaHiya, variables x, y, c are declared as:
Var x("x"), y("y"), c("c");
As you suggested, I use an extern c++ function to update my Halide functions. Here is my extern function:
extern "C" DLLEXPORT buffer_t compute_flow(buffer_t *Ix, buffer_t *Iy, buffer_t *It, buffer_t *u, buffer_t *v,
                                       const int32_t bpl, const int32_t h, const float lambda, const uint8_t IsU) {
    //about Ix
    const auto min0_ix = Ix->min[0];
    const auto internalX_ix = min0_ix;
    const auto min1_ix = Ix->min[1];
    const auto internalY_ix = min1_ix;
    const auto stride0_ix = Ix->stride[0];
    const auto stride1_ix = Ix->stride[1];
    const auto x_ix = bpl + internalX_ix;
    const auto y_ix = h + internalY_ix;
        //about Iy
    const auto min0_iy = Iy->min[0];
    const auto internalX_iy = min0_iy;
    const auto min1_iy = Iy->min[1];
    const auto internalY_iy = min1_iy;
    const auto stride0_iy = Iy->stride[0];
    const auto stride1_iy = Iy->stride[1];
    const auto x_iy = bpl + internalX_iy;
    const auto y_iy = h + internalY_iy;

    //about It
    const auto min0_it = It->min[0];
    const auto internalX_it = min0_it;
    const auto min1_it = It->min[1];
    const auto internalY_it = min1_it;
    const auto stride0_it = It->stride[0];
    const auto stride1_it = It->stride[1];
    const auto x_it = bpl + internalX_it;
    const auto y_it = h + internalY_it;

    const auto iix = *(Ix->host + (x_ix - min0_ix) * stride0_ix + (y_ix - min1_ix) * stride1_ix);
    const auto iiy = *(Iy->host + (x_iy - min0_iy) * stride0_iy + (y_iy - min1_iy) * stride1_iy);
    const auto iit = *(It->host + (x_it - min0_it) * stride0_it + (y_it - min1_it) * stride1_it);

    //about u
    const auto min0_u = u->min[0];
    const auto internalX_u = min0_u;
    const auto min1_u = u->min[1];
    const auto internalY_u = min1_u;
    const auto stride0_u = u->stride[0];
    const auto stride1_u = u->stride[1];
    const auto x_u = bpl + internalX_u;
    const auto y_u = h + internalY_u;
      //about v
    const auto min0_v = v->min[0];
    const auto internalX_v = min0_v;
    const auto min1_v = v->min[1];
    const auto internalY_v = min1_v;
    const auto stride0_v = v->stride[0];
    const auto stride1_v = v->stride[1];
    const auto x_v = bpl + internalX_v;
    const auto y_v = h + internalY_v;

    buffer_t *uResult, *vResult;

    for(int k=0; k<40; k++) {
      const auto u0 = *(u->host + (x_u - min0_u) * stride0_u + (y_u - 1 - min1_u) * stride1_u); //u[(i-1)*bpl+j]
      const auto u1 = *(u->host + (x_u - min0_u) * stride0_u + (y_u + 1 - min1_u) * stride1_u); //u[(i+1)*bpl+j]
      const auto u2 = *(u->host + (x_u - 1 - min0_u) * stride0_u + (y_u - min1_u) * stride1_u); //u[i*bpl+j-1]
      const auto u3 = *(u->host + (x_u + 1 - min0_u) * stride0_u + (y_u - min1_u) * stride1_u); //u[i*bpl+j+1]

      const auto v0 = *(v->host + (x_v - min0_v) * stride0_v + (y_v - 1 - min1_v) * stride1_v); //v[(i-1)*bpl+j]
      const auto v1 = *(v->host + (x_v - min0_v) * stride0_v + (y_v + 1 - min1_v) * stride1_v); //v[(i+1)*bpl+j]
      const auto v2 = *(v->host + (x_v - 1 - min0_v) * stride0_v + (y_v - min1_v) * stride1_v); //v[i*bpl+j-1]
      const auto v3 = *(v->host + (x_v + 1 - min0_v) * stride0_v + (y_v - min1_v) * stride1_v); //v[i*bpl+j+1]

      const auto Uav     = (u0 + u1 + u2 + u3)/4;
      const auto Vav     = (v0 + v1 + v2 + v3)/4;
      const auto P       = iix*Uav + iiy*Vav + iit;
      const auto D       = iix*iix + iiy*iiy + lambda*lambda;
      const auto tmp     = P/D;
      const auto utmp    = Uav - iix*tmp;
      const auto vtmp    = Vav - iiy*tmp;

      *(u->host + (x_u - min0_u) * stride0_u + (y_u - min1_u) * stride1_u) = utmp; //u[i*bpl+j]
      *(v->host + (x_v - min0_v) * stride0_v + (y_v - min1_v) * stride1_v) = vtmp; //v[i*bpl+j]

      if(IsU)
        *(uResult->host + (x_u - min0_u) * stride0_u + (y_u - min1_u) * stride1_u) = utmp;
      else
        *(vResult->host + (x_v - min0_v) * stride0_v + (y_v - min1_v) * stride1_v) = vtmp;
    }

    if(IsU) return *uResult;
    else return *vResult;

}
And in my main, I call it as follows:
    const float lambda = 0.05;

    Image<uint8_t> input_1 = load_image(argv[1]);
    Image<uint8_t> input_2 = load_image(argv[1]);

    Var x("x"); //image indice in x direction
    Var y("y"); //image indice in y direction
    Var c("c"); //image number of channel

    //clamp to edge
    Func clamped_1("clamped_1"), clamped_2("clamped_2");
    clamped_1 = BoundaryConditions::repeat_edge(input_1);
    clamped_2 = BoundaryConditions::repeat_edge(input_2);

    //convert rgb image to grayscale image
    Func f_1("f_1"), f_2("f_2");
    f_1(x,y,c) = min(0.299f * clamped_1(x,y,0) + 0.587f * clamped_1(x,y,1) + 0.114f * clamped_1(x,y,2), 255.0f);
    f_2(x,y,c) = min(0.299f * clamped_2(x,y,0) + 0.587f * clamped_2(x,y,1) + 0.114f * clamped_2(x,y,2), 255.0f);

    //gaussian bluring
    Image<float> kernel(5, 5);
    kernel(0, 1) = 0.000067; kernel(0, 1) = 0.001663; kernel(0, 2) = 0.004706; kernel(0, 3) = 0.001663; kernel(0, 4) = 0.000067;
    kernel(1, 0) = 0.001663; kernel(1, 1) = 0.041482; kernel(1, 2) = 0.117381; kernel(1, 3) = 0.041482; kernel(1, 4) = 0.001663;
    kernel(2, 0) = 0.004706; kernel(2, 1) = 0.117381; kernel(2, 2) = 0.332152; kernel(2, 3) = 0.117381; kernel(2, 4) = 0.004706;
    kernel(3, 0) = 0.001663; kernel(3, 1) = 0.041482; kernel(3, 2) = 0.117381; kernel(3, 3) = 0.041482; kernel(3, 4) = 0.001663;
    kernel(4, 0) = 0.000067; kernel(4, 1) = 0.001663; kernel(4, 2) = 0.004706; kernel(4, 3) = 0.001663; kernel(4, 4) = 0.000067;
    RDom r(kernel);
    Func I1("I1"), I2("I2");
    I1(x, y, c) = sum(f_1(x+r.x, y+r.y, c) * kernel(r.x, r.y));
    I2(x, y, c) = sum(f_2(x+r.x, y+r.y, c) * kernel(r.x, r.y));

    //inputs derivations
    Func Ix("Ix"), Iy("Iy"), It("It");
    Ix(x, y, c) = (-I1(x-1, y-1, c) + I1(x, y-1, c) - I1(x-1, y, c) + I1(x, y, c)) +
                  (-I2(x-1, y-1, c) + I2(x, y-1, c) - I2(x-1, y, c) + I2(x, y, c));
    Iy(x, y, c) = (-I1(x-1, y-1, c) - I1(x, y-1, c) + I1(x-1, y, c) + I1(x, y, c)) +
                  (-I2(x-1, y-1, c) - I2(x, y-1, c) + I2(x-1, y, c) + I2(x, y, c));
    It(x, y, c) = (-I1(x-1, y-1, c) - I1(x, y-1, c) - I1(x-1, y, c) - I1(x, y, c)) -
                  ( I2(x-1, y-1, c) + I2(x, y-1, c) + I2(x-1, y, c) + I2(x, y, c));

    Func u("u"), v("v");
    u(x, y, c) = 0; v(x, y, c) = 0;

    Func callU("callU"), callV("callV");
    vector<ExternFuncArgument> argsU(9);
    argsU[0] = Ix;                   argsU[1] = Iy;            argsU[2] = It;
    argsU[3] = u;                    argsU[4] = v;             argsU[5] = input_1.width();
    argsU[6] = input_1.height();     argsU[7] = lambda;        argsU[8] = 1;
    vector<ExternFuncArgument> argsV(9);
    argsV[0] = Ix;                   argsV[1] = Iy;            argsV[2] = It;
    argsV[3] = u;                    argsV[4] = v;             argsV[5] = input_1.width();
    argsV[6] = input_1.height();     argsV[7] = lambda;        argsV[8] = 0;
    vector<Type> types(9);
    types[0] = Ix.output_types()[0]; types[1] = Iy.output_types()[0]; types[2] = It.output_types()[0];
    types[3] = u.output_types()[0];  types[4] = v.output_types()[0];  types[5] = Int(32);
    types[6] = Int(32);              types[7] = Float(32);            types[8] = UInt(8);

    callU.define_extern("compute_flow", argsU, types, 1);
    callV.define_extern("compute_flow", argsV, types, 1);

    Func outputU("outputU"), outputV("outputV");
    outputU(x, y, c) = callU(x, y, c);
    outputV(x, y, c) = callV(x, y, c);

    Ix.compute_root();
    Iy.compute_root();
    It.compute_root();
    outputU.compile_jit();
    outputV.compile_jit();

    Image<uint8_t> out_u = outputU.realize(input_1.width(), input_1.height(), input_1.channels());
    Image<uint8_t> out_v = outputV.realize(input_1.width(), input_1.height(), input_1.channels());

When I don't schedule u and v, all compile well, but I get this runtime error:

Error: Func u cannot be scheduled to be computed inline, because it is used in the externally-computed function callU Aborted (core dumped)

But when I schedule both u and v as:
    u.compute_root();
    v.compute_root();

I get the following runtime error:

Internal error at /home/rokiatou/Documents/Thèse/halide/Halide-master/src/BoundsInference.cpp:283 Condition failed: b.empty() || b.size() == func_args.size() Aborted (core dumped)

I'm not sure if my external function compute_flow is well defined. I can not solve the scheduling problem.
Any help is welcome. Thank you.

A: I am assuming that the variables x,y,c are declared as Halide::Var; if that were the case, then the above listed error is actually accurate.
You can use a c++ for-loop to add update definitions to your Halide::Func, but you would need to use regular C or C++ style variables to do so, at least in one variable spot; the code you have above just references the same variables over and over.
Regarding access to the pixels you listed, "(x-1, y, c), (x+1, y, c), (x, y, c), (x, y-1, c)[...]" here is an example of accessing a value within a buffer_t* in an extern Halide func:
extern "C" void
auto get_something_done_in_c(buffer_t* my_buffer, const int32_t dx, const int32_t dy)
{
    const auto min0       = my_buffer->min[0];
    const auto internal_x = min0;

    const auto min1       = my_buffer->min[1];
    const auto internal_y = min1;

    const auto stride0 = my_buffer->stride[0];
    const auto stride1 = my_buffer->stride[1];

    const auto x1 = dx + internal_x;
    const auto y1 = dy + internal_y;

    const auto value =  *(my_buffer->host + (x1 - min0) * stride0 + (y1 - min1) * stride1);

    return value;
}
HalideExtern_3(int32_t, get_something_done_in_c, buffer_t, int32_t, int32_t);

To explain a little about how to get the 'value'... I use the my_buffer variable to get access to the data pointer, known as host. That host variable returns the pointer address for the data that you care about. Since this is a 1 dimensional buffer, you use the x and y coordinates, multiplied by stride0 and stride1 to get the address offset within the data pointer to get the value you care about.


text:
Q: What is the difference between photons in the E-Field and the H-Field? It is well established that the photon is the propagator for the electromagnetic force. How are the set of photons used in the H-field behaving differently than those in the E-field? Is it different when dealing with an electromagnet versus an intrinsic magnet?
In what way do the photons need to be emitted by a bar magnet to result in a magnetic interaction? How about a charged object to interact with a charged object?

A: The virtual photons that represent the static Coulomb potential, so the electric field, have time polarisation and those representing the static vector potential, so the magnetic field, have spatial polarisation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pandas to_gbq freezes trying to insert small dataframe I have a python script that grabs NBA game data from each day of the season. My script has a for loop which starts at day 1 and goes to current day. For each day, the script:

*

*Opens webpage with schedule for that day and gets all game info using Beautiful Soup

*stores it in a dataframe

*appends that data to a BigQuery table

The dataframe is never more than 15 rows and usually even smaller, yet the script will just randomly hang while trying to insert into BigQuery table using to_gbq function. It might happen on the first day, the 3rd day, or some other. But it hasn't even come close to running for every day before hanging.
This is the code that it gets stuck on:
game_df.to_gbq(
            "nba_data.games",
            if_exists="append",
            project_id="my_test_project",
            credentials=credentials
)

Any idea why this would happen?


text:
Q: Iterating through a directory in java Hi right now I have the following method I am using to read one file at a time in a the same directory as the class that has this method:
private byte[][] getDoubleByteArrayOfFile(String fileName, Region region)
    throws IOException
{
    BufferedImage image = ImageIO.read(getClass().getResource(fileName));
    byte[][] alphaInputData =
        new byte[region.getInputXAxisLength()][region.getInputYAxisLength()];
    for (int x = 0; x < alphaInputData.length; x++)
    {
        for (int y = 0; y < alphaInputData[x].length; y++)
        {
            int color = image.getRGB(x, y);
            alphaInputData[x][y] = (byte)(color >> 23);
        }
    }
    return alphaInputData;
}

I was wondering how I can make it so that instead of having "fileName" as a argument I can but a directory name as a argument and then iterate through all of the files within that directory and perform the same operation on it. Thanks!

A: If you are using Java 7, then you need to take a look at NIO.2.
Specifically, take a look at the Listing a Directory's Contents section.
Path dir = Paths.get("/directory/path");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for (Path file: stream) {
        getDoubleByteArrayOfFile(file.getFileName(), someRegion);
    }
} catch (IOException | DirectoryIteratorException x) {
    // IOException can never be thrown by the iteration.
    // In this snippet, it can only be thrown by newDirectoryStream.
    System.err.println(x);
}

A: Here is a quick example that may help:
private ArrayList<byte[][]> getDoubleByteArrayOfDirectory(String dirName,
    Region region) throws IOException {
       ArrayList<byte[][]> results = new ArrayList<byte[][]>();
       File directory = new File(dirName);
       if (!directory.isDirectory()) return null //or handle however you wish
       for (File file : directory.listFiles()) {
           results.add(getDoubleByteArrayOfFile(file.getName()), region);
       }
       return results;
}

Not exactly what you asked for since it's wrapping your old method rather than re-writing it, but I find it a bit cleaner this way, and leaves you with the option of still processing a single file.  Be sure to tweak the return type and how to handle the region based on your actual requirements (hard to tell from the question).

A: It is rather simple, using the File#listFiles() which returns a list of files in the specified File, which must be a directory. To make sure that the File is a directory, simply use File#isDirectory(). The problem occurs where you decide how to return the byte buffer. Since the method returns a 2d buffer, it is necessary to use a 3d byte buffer array, or in this case a List seems to me like the best choice since an unknown number of files will exist in the directory in question.

    private List getDoubleByteArrayOfDirectory(String directory, Region region) throws IOException {
      File directoryFile = new File(directory);

      if(!directoryFile.isDirectory()) {
        throw new IllegalArgumentException("path must be a directory");
      }

      List results = new ArrayList();

      for(File temp : directoryFile.listFiles()) {
        if(temp.isDirectory()) {
          results.addAll(getDoubleByteArrayOfDirectory(temp.getPath(), region));
        }else {
          results.add(getDoubleByteArrayOfFile(temp.getPath(), region));
        }
      }
      return results;
    }

A: You can, see the list and listFiles documentation for how to do this.

A: We can use recursion to process a directory with subdirectories also. Here I am deleting file one by one, you can call any other function to process it.
public static void recursiveProcess(File file) {
    //to end the recursive loop
    if (!file.exists())
        return;

    //if directory, go inside and call recursively
    if (file.isDirectory()) {
        for (File f : file.listFiles()) {
            //call recursively
            recursiveProcess(f);
        }
    }
    //call processing function, for example here I am deleting
    file.delete();
    System.out.println("Deleted (Processed) file/folder: "+file.getAbsolutePath());
}


text:
Q: Retrieve intraday data with BDH() using blpapiwrapper in Python I'm trying to get the stock price at a specific time using the blpapiwrapper (https://github.com/alex314159/blpapiwrapper) with inspiration from this (https://quant.stackexchange.com/questions/35126/price-at-specific-time-from-bloomberg):
=BDH("EURGBP Curncy","Last Price","7/13/2017 3:00:00 PM","7/13/2017 3:00:01 PM","BarTp=T,BarSz=1,Fill=P")

If I try to recreate it, I get the EOD price instead of the last price between 15:40:00 and 15:40:01. Using the same syntax in Excel with same SEDOL and dates gives the correct stock price at 15:40.
bloomberg = BLP()

startdate = datetime.datetime.strptime('2020-01-03 15:40:00', '%Y-%m-%d %H:%M:%S')
enddate = datetime.datetime.strptime('2020-01-03 15:40:01', '%Y-%m-%d %H:%M:%S')

bloomberg.bdh('/SEDOL1/B151P43 Equity', "Last price",startdate, enddate , "BarTp = T, BarSz = 1, Fill = P")

I've tried to modify the bdh() function in blpapiwrapper changing periodicity to 'INTRADAY' and including '%H:%M:%S' in the definition of 'startDate' and 'endDate' but without luck.
def bdh(self, strSecurity='SPX Index', strData='PX_LAST', startdate=datetime.date(2014, 1, 1),
        enddate=datetime.date(2014, 1, 9), adjustmentSplit=False, periodicity='DAILY'):
    request = self.refDataSvc.createRequest('HistoricalDataRequest')
    request.append('securities', strSecurity)
    if type(strData) == str:
        strData = [strData]

    for strD in strData:
        request.append('fields', strD)

    request.set('startDate', startdate.strftime('%Y%m%d'))
    request.set('endDate', enddate.strftime('%Y%m%d'))
    request.set('adjustmentSplit', 'TRUE' if adjustmentSplit else 'FALSE')
    request.set('periodicitySelection', periodicity)
    requestID = self.session.sendRequest(request)

Any suggestions for a solution using blpapiwrapper?


text:
Q: highmap : not able to display tooltip Can someone please guide me on below queries please:
1) How can i achieve tootltip onhover on state as per the json. I did tried and created a fiddle.
submissionDate:05/20/2017,
submissionResponseDate:06/20/2017,
stateResponse:Approved
2) I want to show color of state on basis of Json data (Approved/Approval Pending).
3) Do i need o pass json for all states for "hc-key" as allAreas proper is not showing all states
http://fiddle.jshell.net/a65yufqf/
US Map

A: Solution For each point
1>For tooltip  you have to use formatter
tooltip: {
  formatter: function() {
    return 'submissionDate: ' + this.point.submissionDate + '
' +
      'submissionResponseDate: ' + this.point.submissionResponseDate + '
' +
      'stateResponse: ' + this.point.stateResponse + '
'

  }
},

2>Prepare JSON data containing color
  var data = [{
    "hc-key": "us-ca",
    "submissionDate": "05/20/2017",
    "submissionResponseDate": "06/20/2017",
    "stateResponse": "Approved",
    "color": "#C40401",
  }, {
    "hc-key": "us-or",
    "submissionDate": "05/20/2017",
    "submissionResponseDate": "",
    "stateResponse": "Approval Pending",
    "color": "#0200D0"
  }];

3>As you show in sample image , you want default color which are not in JSON.So for this you have to use nullColor: 'grey', in series.
series: [{
allAreas: true,
  data: data,
  mapData: Highcharts.maps['countries/us/us-all'],
  joinBy: 'hc-key',
  //name: 'Random data',
  nullColor: 'grey', //add this to color default area
  states: {
    hover: {
      color: '#BADA55'
    }
  },
  dataLabels: {
    enabled: true,
    format: '{point.name}'
  }
}, {
  name: 'Separators',
  type: 'mapline',
  data: Highcharts.geojson(Highcharts.maps['countries/us/us-all-all'], 'mapline'),
  color: 'black',
  showInLegend: false,
  enableMouseTracking: false
}]

Fiddle demonstration

A: Item #1: the tooltip
To add a tooltip to your map that pulls in the JSON data values you've defined, you'll add the following:
tooltip: {
  formatter: function () {
    /* set value if the state hasn't yet responded */
    if (!this.point.submissionResponseDate) {
      this.point.submissionResponseDate = 'not applicable';
    }
    /* format the tooltip */
    return '' + this.point.name + '
' +
            'Submission date: ' + this.point.submissionDate +
            '
Submission response date: ' + this.point.submissionResponseDate +
            '
State response: ' + this.point.stateResponse;
  }
},

Your tooltip will then look like this:

Note the if statement I added for your response date ... rather than show an empty value (as you have for Oregon in your example), this will show a value more helpful to the user.
Item #2: state colors based on JSON data
You can parse through your JSON data and add a value attribute based on whether the state is approved or pending approval. The value will then take on the colors you defined in colorAxis:
  /* check the JSON data and add a value for approved
   or approval pending that will be picked up by your
   colorAxis formatting */
  for (d = 0; d < data.length; d++) {
    if (data[d].stateResponse == "Approved") {
      data[d].value = -1;       /* will color state red */
    } else {
      data[d].value = 1;        /* will color state blue */
    }
  }

You'll want to run this after you've defined or pulled in your data, but before you set the chart attributes.
Item #3: pulling in data for all states
No, you don't have to pull in hc-key data for all states; only the ones you need, as you've done in your example.

I've modified your fiddle with these answers: http://fiddle.jshell.net/brightmatrix/a65yufqf/4/
I hope this is helpful for you!


text:
Q: Python Gurobi: How can I implement a maximum value of a decision variable in the objective function? Hopefully someone can help me out. I am developing an optimization model where I minimize electricity costs over time (t) and over different transactions (s). (where: standard power(p)*costs of electricity (c) = electricity costs).
Now I am trying to implement a cost component in the objective function that is based on the maximum power consumption that occurred (some alike: max(P[s,t])). However, np.max() returns an error because P[s,t] is an unsupported class for np.max(). Also the Gurobi function gp.max_(P[s,t]) also gives an unsupported class error. Is there someone who has a solution?
Code:
obj = gp.quicksum(p[s, t] * Cost_elect[t]e for t in range(T) for s in range(S)) + gp.max_(p_batt_ch[s,t]*fixed_cost for t in range(T) for s in range(S))

A: You need to assign the max constraint to a new auxiliary variable and the put this variable into the objective instead of the actual constraint.
maxobj = model.addVar()
max_constr = model.addConstr(maxobj == gp.max_(p_batt_ch[s,t] * fixed_cost
                             for t in range(T) for s in range(S)))

obj = gp.quicksum(p[s,t] * Cost_elect[t] for t in range(T) for s in range(S)) + maxobj)

Gurobi documentation


text:
Q: KIVY python virtual keyboard how to make python KIVY onscreen keyboard numeric only? im using Config.set('kivy', 'keyboard_mode', 'systemandmulti') and its working but there is the whole keyboard, I just need numerics

A: I believe you'd need to create a keyboard JSON file like these, add it to the correct path (the default layout_path is <kivy_data_dir>/keyboards/), and set it onto the keyboard_layout value.
Config.setdefault('widgets', 'keyboard_layout', 'numeric')

Where your JSON template file is numeric.json.


text:
Q: What is the runtime type of my union function variable? Is it returning a Promise or an Observable? I have this abstract variable in my class:
abstract save(): Promise<boolean> | Observable<boolean>;

I have a function that runs this save function that the derived class implemented. How can I check if it is a promise or an observable?
executeSave(): void {
  if (///// is this a promise??? /////) {
    (<Promise<boolean>>this.save()).then(isSaved => { ... });
  } else {
    (<Observable<boolean>>this.save()).subscribe(isSaved => { ... });
  }
}

A: easiest way is to use rxjs inbuilt isObservable test:
import { isObservable } from "rxjs";

executeSave(): void {
  const toSave = this.save();
  if (isObservable(toSave)) { // checks if observable
    toSave.subscribe(isSaved => { ... });
  } else { // only 2 options so this is a promise
    toSave.then(isSaved => { ... });
  }
}

also don't need the forced typings anymore

A: That can be achieved using the handy instanceof operator. This also gives you the benefit that the type of your variable (in your case toSave) will be automatically inferred to the type of the right-hand side of your instanceof operation inside the if-block. So you won't need to typecast.
import { Observable } from "rxjs";

executeSave(): void {
    const toSave = this.save();
    if (toSave instanceof Observable) {
        // Since you used "instanceof" here, typescript knows that "toSave" is of type "Observable" inside this if
        toSave.subscribe(isSaved => { /* omitted */ });
    } else if (toSave instanceof Promise) { // else would be enough, since there are only two possible types for "toSave"
        // Same goes for the Promise
        toSave.then(isSaved => { /* omitted */ });
    }
}

Edit: As stated in comments, second typecheck is not needed. I adjusted the comment in code accordingly.


text:
Q: How to get the count of a substing in SQL Developer? I have a table with phone numbers in a column. I want to return the amount of times a certain area code appears using COUNT(*).
PHONE:
555-555-5565
323-595-8686
666-565-5232
323-599-0000

After Query:
ZIP:   FREQUENCY:
555    1
323    2
666    1

Non-working Query:
select distinct (substr(phone,0,3)) as "AREA_CODE", count(distinct substr(phone,0,3)) as "COUNT",
from address

I feel like I should be getting the substring of the phone number that is the area code as one result column, and then counting the frequency with the other, but I can't seem to get it to work. Help?

A: Where does the idea of using select distinct for this type of query come from?
The proper construct is group by.  Learn SQL!
select substr(phone, 1, 3)) as "AREA_CODE", count(*) as "COUNT"
from address
group by substr(phone, 1, 3)) as "AREA_CODE";

Notes:

*

*substr() starts counts from "1" not "0".

*count(distinct) is not appropriate.  It would only return 1 when referring to the group by key.

*In fact, distinct is very special purpose in SQL.  You generally want to avoid it.

A: You can create an temp table which store your zip :
create table #TempTable
(
    Zip Varchar(3)
)
INSERT INTO #TempTable (Zip )
SELECT substr(phone,0,3) from Address

Then you can query and count this result:
Select Zip , count(distinct Zip ) as FREQUENCY
from #TempTable
group by Zip


text:
Q: Microsoft Dynamics Nav2009 closed immediately when i try to run This is the Error details from the Event Viewer:
Type: System.Configuration.ConfigurationErrorsException
Message: The type 'Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior, Microsoft.VisualStudio.Diagnostics.ServiceModelSink, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' registered for extension 'Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior' could not be loaded. (C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Config\machine.config line 192)
BareMessage: The type 'Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior, Microsoft.VisualStudio.Diagnostics.ServiceModelSink, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' registered for extension 'Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior' could not be loaded.
Filename: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Config\machine.config
Line: 192
StackTrace:
at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult)
at System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey, Boolean getLkg, Boolean checkPermission)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.ServiceModel.Configuration.ConfigurationHelpers.UnsafeGetSectionFromConfigurationManager(String sectionPath)
at System.ServiceModel.Configuration.ConfigurationHelpers.UnsafeGetAssociatedSection(ContextInformation evalContext, String sectionPath)
at System.ServiceModel.Configuration.CommonBehaviorsSection.UnsafeGetSection()
at System.ServiceModel.Description.ConfigLoader.LookupCommonBehaviors(ContextInformation context)
at System.ServiceModel.Description.ConfigLoader.LoadCommonClientBehaviors(ServiceEndpoint serviceEndpoint)
at System.ServiceModel.ChannelFactory.ApplyConfiguration(String configurationName, Configuration configuration)
at System.ServiceModel.ChannelFactory.ApplyConfiguration(String configurationName)
at System.ServiceModel.ChannelFactory.InitializeEndpoint(Binding binding, EndpointAddress address)
at System.ServiceModel.DuplexChannelFactory1..ctor(Object callbackObject, Binding binding, EndpointAddress remoteAddress) at System.ServiceModel.DuplexChannelFactory1..ctor(InstanceContext callbackInstance, Binding binding, EndpointAddress remoteAddress)
at Microsoft.Dynamics.Nav.Client.ServiceConnection.Initialize()
at Microsoft.Dynamics.Nav.Client.ServiceConnection.OpenConnectionInternal(ConnectFailedEventArgs connectFailedArg)
at Microsoft.Dynamics.Nav.Client.ServiceConnection.OpenConnection()
at Microsoft.Dynamics.Nav.Client.FormBuilder.BuilderSession.Initialize()
at Microsoft.Dynamics.Framework.UI.UISession.Initialize()
at Microsoft.Dynamics.Framework.UI.Windows.ClientSessionBase.SetupUISession()
at Microsoft.Dynamics.Framework.UI.Windows.ClientSessionBase.Init()
at Microsoft.Dynamics.Nav.Client.Program.MainCore(String[] args)
at Microsoft.Dynamics.Nav.Client.Program.Main(String[] args)
Source: System.Configuration

A: It could be an error use by Windows Update. Try to restart the server if there was an update recently.

A: Option 1:
Install the latest version of .net and if possible update your Nav service account to the latest version available. sometimes is te service doesn't have the same version as the client, that happens. a downgrade of the version may work, depending of what you updated before the crash.
Option 2:
A table might be modified recently, so when you ran the client it didn't fount the right indexes. Open Nav in a classic mode, then go to objects and sort by date modified, you should see a recent modified object.


text:
Q: Calculate percentage difference of gauge value over 5 minutes I would like to compare the same gauge metrics with itself.
Lets say i have a metric items_count_exported gauge. Gauge is updated every 5 minutes
I want to create and alert which can spot the difference between gauge generated 5 minutes ago and the one generated now and if there is a difference lets say 10% then alert will be triggered. Is it possible ?

A: It is possible. You can use offset to get a value from X minutes ago and calculate the percentage difference that way. Since it's a gauge, it can go in any direction and it might even be negative. You should get the absolute value with abs() to make sure the percentage changed is a positive number.
Query that gives you the percentage you want
100 * abs(items_count_exported - items_count_exported offset 5m) / abs(items_count_exported offset 5m)

Then create an alert that checks if the output of the query above is > 10.
If you want to know the direction of change (10% increase vs 10% decrease), then this query needs to be adapted a bit.


text:
Q: Select table values to text field using SWT? I have Table (TableViewer) containing TableItems with values. I have another class TextField mapped according to table column name.
Now my question is: When I select any row in table, the values in that row should get reflected in Text field. In Text field I can edit these vales and save to to table. Please let me know how I can achieve this?

A: What ever "Baz" has said is the right thing to do. If editing is table data is requirement, then make the table columns as editable. But if you want to specifically edit table row separately in a control (like Text field), then get IStructuredSelection from TableViewer and get the data in control to edit. Then after you edit, get the data back from control and set it back to table. Hope it helps.


text:
Q: How does recursion work for the following code, since a Boolean OR operation is used in the return statement? I came across this code, but I couldn't understand how the recursion works for the following code, as there's a Boolean OR operator used within a return statement, which I have never seen before. How is it supposed to work?
bool match(char *first, char * second)
{
    if (*first == '\0' && *second == '\0')
        return true;

    if (*first == '*' && *(first+1) != '\0' && *second == '\0')
        return false;

    if (*first == '?' || *first == *second)
        return match(first+1, second+1);

    if (*first == '*')
        return match(first+1, second) || match(first, second+1); //How does it work?
    return false;
}

A: It works like all other disjunctions:
First the left-hand side, match(first+1, second) is evaluated.
If it is true, the result of the entire expression is true and nothing else is evaluated.
If it is false, the right-hand side, match(first, second+1) is evaluated and that becomes the result of the entire expression.

A: An important feature of the boolean operators || and && is short-circuit evaluation. That means in the case of || that if the first call match(first + 1, second) returns true, the second call will not be made, and true will be returned. Else the return value is the returned value of the second call.

A: It works mostly as if a variable were assigned the parameter of return, then that variable returned. The only difference is, the compiler might do return value optimization.


text:
Q: Insert Records in multiple table which are dependent on primary / foreign key using Linq-to-SQL I have 3 tables:

*

*master_upload (master upload has primary key with auto increment named master_upload_id)

*master_upload_files (this consist of 2 columns and refer master_upload_id from above table )

*master_upload_tags (same as second)
in 2nd and 3rd table there can be multiple rows for 1st table.
Now to insert in 2nd and 3rd table I need a master_upload_id which I only get after inserting. Hence I had to call db.SubmitChanges at least 3 times. If there are multiple values for 2nd and 3rd table I had to call db.SubmitChanges for each row in those two table. But some times the insertion in 2nd or 3rd table can fail due to some rule violation.
Hence I need to roll back in these cases. How can I do that?
I use to do these things via a SQL Server stored procedure, but now I need to do it in LINQ.
// Here is my code sample
using (dbDataContext db = new dbDataContext())
{
    db.master_uploads.InsertOnSubmit(mu);// toget mu.upload_id

    try
    {
        db.SubmitChanges();
        master_upload_file mf = new master_upload_file();
        mf.master_upload_id = mu.upload_id;
        mf.upload_file_id = uploadedfile.file_id;

        db.master_upload_files.InsertOnSubmit(mf);

        for (int i = 0; i < tags.Length; i++)
        {
            master_upload_tag mt = new master_upload_tag();
            mt.master_upload_id = mu.upload_id;
            mt.tag = tags[i];
            db.master_upload_tags.InsertOnSubmit(mt);
        }

        db.SubmitChanges();
        gtu.writetext("0",context);
    }
    catch (Exception)
    {
        gtu.writetext("1:File Upload Add Error", context);
    }
}

I am using SQL Server 2008.
Thanks

A: You're doing this way too complicated! Use the force, man!! :-)
Try this code:
// define your context
using (UploadContextDataContext ctx = new UploadContextDataContext())
{
    try
    {
        // create your new upload
        upload up = new upload();
        up.UploadName = "Some test name";

        // define two new upload files
        UploadFile file1 = new UploadFile { FileName = "TestFile1.zip" };
        UploadFile file2 = new UploadFile { FileName = "TestFile2.zip" };

        // *ADD* those two new upload files to the "Upload"
        up.UploadFiles.Add(file1);
        up.UploadFiles.Add(file2);

        // define three new upload tags
        UploadTag tag = new UploadTag { TagName = "Tag #1" };
        UploadTag tag2 = new UploadTag { TagName = "Tag #2" };
        UploadTag tag3 = new UploadTag { TagName = "Tag #3" };

        // *ADD* those three new upload tags to the "Upload"
        up.UploadTags.Add(tag);
        up.UploadTags.Add(tag2);
        up.UploadTags.Add(tag3);

        // add the "Upload" to the context - this *INCLUDES* the files and tags!
        ctx.uploads.InsertOnSubmit(up);

        // call SubmitChanges *just once* to store everything!
        ctx.SubmitChanges();
    }
    catch (Exception exc)
    {
        string msg = exc.GetType().Name + ": " + exc.Message;
    }

You basically set up an object graph - your basic Upload object - and you add your files and tags to that Upload object. You only need to add that Upload object to the data context - the other (added) subobjects are tagging along automatically!
And in this case, you only need to call SubmitChanges() a single time and this will insert all the new objects, set up all the necessary foreign key / primary key relationships and all for you. No fiddling around with primary keys, multiple calls to the database - just use the magic of Linq-to-SQL!


text:
Q: Why Is my data not being completely added to my array? I am trying to take the data from the CSV file output.csv using strtok and then print it out. However, when I print it out, it seems to split the last datapoints into 2 entries, with the second one being put in the next entry in the array.
time,identifier,x,y,z
2000.123,A123,2.849,0.34,-0.543
2001.456,A123,3.493,0.19,-0.987
2001.735,A123,5.403,1.587,0.579,-0.254

I'm reading the data and using a struct and an array to store it.
struct  Data {
double Time_Data;
char* ID;
double X_Data;
double Y_Data;
double Z_Data;

};
int main(int argc, char *argv[]){
char* field;
char line[50];
struct Data dataPoints[3567];
FILE * pointer;
fpointer = fopen("output.csv", "r");

if(fpointer == NULL){
    printf("Unable to open file \n");
    return 0;
}
int LineCount = 0;
while(fgets(line, 30, fpointer) != NULL){

    field = strtok(line, ",");
    dataPoints[LineCount].Time_Data = atof(field);

    field = strtok(NULL, ",");

    field = strtok(NULL, ",");
    dataPoints[LineCount].X_Data = atof(field);

    field = strtok(NULL, ",");
    dataPoints[LineCount].Y_Data = atof(field);
    field = strtok(NULL, ",");
    dataPoints[LineCount].Z_Data = atof(field);

    LineCount++;
}

fclose(fpointer);

printf("%lf    %lf    %lf    %lf\n", dataPoints[0].Time_Data,
dataPoints[0].X_Data,dataPoints[0].Y_Data, dataPoints[0].Z_Data);
printf("%lf    %lf    %lf    %lf\n", dataPoints[1].Time_Data,
dataPoints[1].X_Data,dataPoints[1].Y_Data, dataPoints[1].Z_Data);
printf("%lf    %lf    %lf    %lf\n", dataPoints[2].Time_Data,
dataPoints[2].X_Data,dataPoints[2].Y_Data, dataPoints[2].Z_Data);
printf("%lf    %lf    %lf    %lf\n", dataPoints[3].Time_Data,
dataPoints[3].X_Data,dataPoints[3].Y_Data, dataPoints[3].Z_Data);
printf("%lf    %lf    %lf    %lf\n", dataPoints[4].Time_Data,
dataPoints[4].X_Data,dataPoints[4].Y_Data, dataPoints[4].Z_Data);
printf("%lf    %lf    %lf    %lf\n", dataPoints[5].Time_Data,
dataPoints[5].X_Data,dataPoints[5].Y_Data, dataPoints[5].Z_Data);

return 0;

}

The problem is that for some reason the Z_Data is being split into 2 and moved to the next entry in the array. The output I get is
0.000000    0.000000    0.000000    0.000000
2000.123000    2.849000    0.340000    -0.500000
43.000000    0.000000    0.000000    0.000000
2001.456000    3.493000    0.190000    -0.900000
87.000000    0.000000    0.000000    0.000000
2001.735000    5.403000    1.587000    0.500000

Which I'm not really sure why it is happening.

A: The length of each lines of your CSV file are:
time,identifier,x,y,z                  : 21 chars
2000.123,A123,2.849,0.34,-0.543        : 31 chars
2001.456,A123,3.493,0.19,-0.987        : 31 chars
2001.735,A123,5.403,1.587,0.579,-0.254 : 38 chars

You specified 30 as the buffer size for fgets(). This value is insufficient for reading the data lines.
The value should be sizeof(line) because you allocated 50 chars for line and using magic numbers should be avoided.


text:
Q: How to delete records permanently in case of linked tables? Let's say I have these 2 tables QuesType and Ques:-
QuesType

QuestypeID|QuesType      |Active
------------------------------------
101       |QuesType1     |True
102       |QuesType2     |True
103       |XXInActiveXX  |False

Ques

QuesID|Ques|Answer|QUesTypeID|Active
------------------------------------
1     |Ques1|Ans1 |101     |True
2     |Ques2|Ans2 |102     |True
3     |Ques3|Ans3 |101     |True

In the QuesType Table:-
QuesTypeID is a Primary key
In the Ques Table:-
QuesID is a Primary key and QuesType ID is the Foreign Key that refernces QuesTypeID from QuesType Table
Now I am unable to delete records from QuesType Table, I can only make QuesType inactive by setting Active=False.
I am unable to delete QuesTypes permanently because of the Foreign key relation it has with Ques Table. So , I just set the
column Active=false and those Questypes then don't show on my grid when its bound.
What I want to do is be able to delete any QuesType permamnently. Now it can only be deleted if its not being used anywhere
in the Ques table, right?
So to delete any QuesType permanently I thought this is what I could do:-
In the grid that displays QuesTypes, I have this check box for Active and a button for delete.What I thought was, when a user
makes some QuesType inactive then OnCheckChanged() event will run and that will have the code to delete all the Questions
in Ques table that are using that QuesTypeID. Then on the QuesType grid, that QuesType would show as Deactivated and only
then can a user delete it permanently.
Am I thinking correctly?
Currently in my DeleteQuesType Stored Procedure what I am doing is:-
Setting the Active=false and
Setting QuesTye= some string like XXInactiveXX
Is there any other way?
edit
What if I want to implement that way only, like first get the user to deactivate the QuesType and only if it's deactivated that the user can delete it permanently. Is that correct logic?

A: I think what you need to do is put the
ON DELETE CASCADE

clause on your foreign key constraint. This will automatically delete rows from your Ques table when its corresponding QuesType row is deleted.

A: You can delete only the QuesTypes deactivated.
Before deleting a QuesType you'll have to query the database and see if QuesType.Active = false. If yes, you can delete all rows from the child table that reference that QuesType.Id (this is known as a cascade delete). You can also set a null value on QuesTypeID column in the child rows.
Read this book online to learn about the ON DELETE CASCADE | SET NULL clause. This clause will enable you to do what you want.


text:
Q: Using parameters for JMH benchmark methods I've written two methods whose performances I need to compare. Both methods take in parameters, so I've made two separate fields with the @Param annotation - one for each of the methods. The parameters are used independently (AKA each method only uses its respective field and don't make use of the @Param field that the other method uses). I've read that JMH runs tests using the permutations of the @Param fields, but I don't need EVERY permutation tested since each method just uses its own parameter. For each method, is there a way to have JMH run tests to measure performance while only cycling through the @Param field it uses?
What I'm doing right now is that I've separated the two @Param fields into two distinct State classes, and I have each method take in the corresponding state object as a parameter. This seems unnecessary to me though, since the only difference between the two State classes is the @Param field (the rest of the setup, etc. is the same for both classes). Is there a more concise way to go about this?
Thanks for the help!


text:
Q: tikz: transparent object (overlay) loses its transparency. Why? I'd like to draw a (transparent) disk with tikz on top of some text in the
middle of the page so that the text is still readable.  The following MWE
correctly shows this for a red disk if the first \blindtext command is not
there/commented out. However, if it is there (so if there is some text before
the tikz picture), then the disk loses its transparency. I wonder how this can
be prevented (in case it matters: this is on macOS 12.1, TeXLive 2020).
\documentclass{scrartcl}

\usepackage{tikz}
\usepackage{blindtext}

\begin{document}
%% Commenting the following line *out* correctly shows the disk in full transparency.
%% However, with the following line the disk is only transparent with respect to
%% the text thereafter.
\blindtext[3] % comment in/out to see the difference
\begin{tikzpicture}[remember picture, overlay, shift={(current page.center)}]
  \pgfdeclarelayer{ink}
  \pgfsetlayers{main,ink}
  \begin{pgfonlayer}{ink}
    \draw[fill, color = red!95] (0,0) circle (2cm);
  \end{pgfonlayer}
\end{tikzpicture}
\blindtext[4]
\end{document}

A: Thanks to Ulrike Fischer (always a pleasure to see her help here, incredible work), I could find the following solution. Note that it required updating to TeXLive 2021.
\documentclass{scrartcl}

\usepackage{tikz}
\usepackage{blindtext}

\begin{document}
\blindtext[3]
\AddToHook{shipout/background}{\put(0,0){
\begin{tikzpicture}[remember picture, overlay, shift={(current page.center)}]
  \pgfdeclarelayer{ink}
  \pgfsetlayers{main,ink}
  \begin{pgfonlayer}{ink}
    \draw[fill, color=red] (0,0) circle (2cm);
  \end{pgfonlayer}
\end{tikzpicture}
}}
\blindtext[4]
\end{document}

The above solution prints a picture on all pages. Here is a follow-up in case a picture should only appear on a single page, or in case it should appear on several (but not all pages).


text:
Q: Android Studio blank CoordinatorLayout designer I just started an Android Studio project and on the center of the Design of the MainActivity the is written "android...CoordinatorLayout".

A: To use Coordination layout
Add this dependency
compile 'com.android.support:design:24.0.0' to gradle (module)
(According to your android studio version and sdk. You can check any video to watch how to add dependcy) and then sync it
If you already did this then the problem is present in you xml code. Please put the text xml code in this post.


text:
Q: Scraping dynamically generated data with scrapy (and selenium?) I'm struggling with getting scrapy (with or without selenium) to extract dynamically generated content from a web page. The site lists performance for different universities, and allows you to select each Study Area offered by that uni. As an example, from the page listed in the code below, I'd like to be able to extract university name ("Bond University") and the value for 'Overall quality of experience' (91.3%).
However, when I use 'view source', curl or scrapy, the actual values aren't shown. E.g. where I'd expect to see Uni name, it shows:

But if I use firebug or chrome to inspect element, it shows the

Bond University

On further inspection, on the 'Net' tab in firebug, I can see that there's an AJAX (?) call being made that returns the relevant information, but I haven't been able to mimic this in scrapy or even curl (yes, I did search and spend an embarrassingly long time trying I'm afraid).
Request headers
POST /Websilk/DataServices/SurveyData.asmx/FetchInstitutionStudyAreaData HTTP/1.1
Host: www.qilt.edu.au
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:39.0) Gecko/20100101 Firefox/39.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://www.qilt.edu.au/institutions/institution/bond-university/business-management
Content-Length: 36
Cookie: _ga=GA1.3.69062787.1442441726; ASP.NET_SessionId=lueff4ysg3yvd2csv5ixsc1f; _gat=1
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

POST Parameters passed with the request
{"InstitutionId":20,"StudyAreaId":0}

As a second option, I tried using Selenium with scrapy, since I thought it might 'see' the real values, like the browser does, but to no avail. My main attempt thus far is below:
import scrapy
import time  #used for the sleep() function

from selenium import webdriver

class QiltSpider(scrapy.Spider):
    name = "qilt"

    allowed_domains = ["qilt.edu.au"]
    start_urls = [
        "http://www.qilt.edu.au/institutions/institution/rmit-university/architecture-building/"
    ]

    def __init__(self):
        self.driver = webdriver.Firefox()
        self.driver.get('http://www.qilt.edu.au/institutions/institution/rmit-university/architecture-building/')
        time.sleep(5) # tried pausing, in case problem was delayed loading - didn't work

    def parse(self, response):
        # parse the response to find the uni name and show in console (using xpath code from firebug). This find the relevant section, but it shows as empty
        title = response.xpath('//*[@id="bd"]/div[2]/div/div/div[1]/div/div[2]/h1').extract()
        print title
        # dumping the whole response to a file so I can check whether dynamic values were captured
        with open("extract.html", 'wb') as f:
            f.write(response.body)
            self.driver.close()

Can anyone tell me how I can achieve this?
Many thanks!
EDIT: Thanks for the suggestions so far, but any thoughts on how to specifically mimic the AJAX call with parameters of InstitutionID and StudyAreaID? My code to test this was as below, but it seems to still hit an error page.
import scrapy
from scrapy.http import FormRequest

class HeaderTestSpider(scrapy.Spider):
    name = "headerTest"

    allowed_domains = ["qilt.edu.au"]
    start_urls = [
        "http://www.qilt.edu.au/institutions/institution/rmit-university/architecture-building/"
    ]

    def parse(self, response):
        return [FormRequest(url="http://www.qilt.edu.au/Websilk/DataServices/SurveyData.asmx/FetchInstitutionData",
                            method='POST',
                            formdata={'InstitutionId':'20', 'StudyAreaId': '0'},
                            callback=self.parser2)]

A: QILT page uses AJAX to retrieve the data from server. This AJAX request is sent using a javascript code which is fired using the even document.ready(jQuery)/window.onload(Javascript) (If you are not familiar with javascript, this method is fired as soon as the web page finished loading on the browser window). Since you are using a software to stimulate the page requests, this event is not fired at all.
For the AJAX request you are trying to simulate, The request body is of type Application/JSON.
please add the following header to the request.
Content-Type: application/json


text:
Q: How to solve probability questions? Jack and Jill were both sent to the blue room for not completing their probability assignment on time.  When they reported to the blue room, they were each given an envelope with either a green or red card in it.  Jack was told that he can look into Jill's envelope and Jill was told that she can look into Jack's envelope.  Neither of the students was allowed to look into their own envelope and they are not allowed to communicate what they saw in the envelope.  Jack and Jill were then told to guess the colour of their own card and write their guess on their own envelope.  They were informed that both will escape detention as long as at least one of them guess their own colour correctly.  Otherwise, they will serve detention for the rest of the term.
Discuss the probability that Jack and Jill will escape detention.

A: With the right strategy, the probability they escape is 1.
Jack should guess that their two colors are the same, and Jill should guess that their two colors are different. Exactly one of them will be correct.


text:
Q: Errors in installing keras using pip? I am trying to install Keras library using pip in windows 10. I have all the requirements installed, python>=3.8, pip>=20.0.0, NumPy, pandas, matplotlib, virtualenv. But I'm getting the following error.
(keras) C:\Users\namba>pip install keras
Collecting keras
  Using cached Keras-2.4.3-py2.py3-none-any.whl (36 kB)
Collecting h5py
  Using cached h5py-3.1.0.tar.gz (371 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Installing backend dependencies ... done
    Preparing wheel metadata ... done
Requirement already satisfied: numpy>=1.9.1 in c:\users\namba\keras\lib\site-packages (from keras) (1.19.4)
Collecting pyyaml
  Using cached PyYAML-5.3.1-cp38-cp38-win32.whl (199 kB)
Requirement already satisfied: scipy>=0.14 in c:\users\namba\keras\lib\site-packages (from keras) (1.5.4)
Building wheels for collected packages: h5py
  Building wheel for h5py (PEP 517) ... error
  ERROR: Command errored out with exit status 1:
   command: 'c:\users\namba\keras\scripts\python.exe' 'c:\users\namba\keras\lib\site-packages\pip\_vendor\pep517\_in_process.py' build_wheel 'C:\Users\namba\AppData\Local\Temp\tmp0_p1fdyc'
       cwd: C:\Users\namba\AppData\Local\Temp\pip-install-k9e6wdb4\h5py
  Complete output (70 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win32-3.8
  creating build\lib.win32-3.8\h5py
  copying h5py\h5py_warnings.py -> build\lib.win32-3.8\h5py
  copying h5py\ipy_completer.py -> build\lib.win32-3.8\h5py
  copying h5py\version.py -> build\lib.win32-3.8\h5py
  copying h5py\__init__.py -> build\lib.win32-3.8\h5py
  creating build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\attrs.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\base.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\compat.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\dataset.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\datatype.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\dims.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\files.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\filters.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\group.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\selections.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\selections2.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\vds.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\__init__.py -> build\lib.win32-3.8\h5py\_hl
  creating build\lib.win32-3.8\h5py\tests
  copying h5py\tests\common.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\conftest.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_attribute_create.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_attrs.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_attrs_data.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_base.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_big_endian_file.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_completions.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_dataset.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_dataset_getitem.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_dataset_swmr.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_datatype.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_dimension_scales.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_dims_dimensionproxy.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_dtype.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_errors.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_file.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_file2.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_file_image.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_filters.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_group.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_h5.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_h5d_direct_chunk.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_h5f.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_h5p.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_h5pl.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_h5t.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_objects.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_selections.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_slicing.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\__init__.py -> build\lib.win32-3.8\h5py\tests
  creating build\lib.win32-3.8\h5py\tests\data_files
  copying h5py\tests\data_files\__init__.py -> build\lib.win32-3.8\h5py\tests\data_files
  creating build\lib.win32-3.8\h5py\tests\test_vds
  copying h5py\tests\test_vds\test_highlevel_vds.py -> build\lib.win32-3.8\h5py\tests\test_vds
  copying h5py\tests\test_vds\test_lowlevel_vds.py -> build\lib.win32-3.8\h5py\tests\test_vds
  copying h5py\tests\test_vds\test_virtual_source.py -> build\lib.win32-3.8\h5py\tests\test_vds
  copying h5py\tests\test_vds\__init__.py -> build\lib.win32-3.8\h5py\tests\test_vds
  copying h5py\tests\data_files\vlen_string_dset.h5 -> build\lib.win32-3.8\h5py\tests\data_files
  copying h5py\tests\data_files\vlen_string_dset_utc.h5 -> build\lib.win32-3.8\h5py\tests\data_files
  copying h5py\tests\data_files\vlen_string_s390x.h5 -> build\lib.win32-3.8\h5py\tests\data_files
  running build_ext
  Loading library to get version: hdf5.dll
  error: Unable to load dependency HDF5, make sure HDF5 is installed properly
  error: Could not find module 'hdf5.dll' (or one of its dependencies). Try using the full path with constructor syntax.
  ----------------------------------------
  ERROR: Failed building wheel for h5py
Failed to build h5py
ERROR: Could not build wheels for h5py which use PEP 517 and cannot be installed directly

I thought this error was caused due to improper installation of h5py & hdf5. I tried installing them using pip install h5py but then I encountered the following error:
(keras) C:\Users\namba>pip install h5py
Collecting h5py
  Using cached h5py-3.1.0.tar.gz (371 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Installing backend dependencies ... done
    Preparing wheel metadata ... done
Requirement already satisfied: numpy>=1.17.5; python_version == "3.8" in c:\users\namba\keras\lib\site-packages (from h5py) (1.19.4)
Building wheels for collected packages: h5py
  Building wheel for h5py (PEP 517) ... error
  ERROR: Command errored out with exit status 1:
   command: 'c:\users\namba\keras\scripts\python.exe' 'c:\users\namba\keras\lib\site-packages\pip\_vendor\pep517\_in_process.py' build_wheel 'C:\Users\namba\AppData\Local\Temp\tmpid2mdza_'
       cwd: C:\Users\namba\AppData\Local\Temp\pip-install-yppxk_bm\h5py
  Complete output (70 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win32-3.8
  creating build\lib.win32-3.8\h5py
  copying h5py\h5py_warnings.py -> build\lib.win32-3.8\h5py
  copying h5py\ipy_completer.py -> build\lib.win32-3.8\h5py
  copying h5py\version.py -> build\lib.win32-3.8\h5py
  copying h5py\__init__.py -> build\lib.win32-3.8\h5py
  creating build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\attrs.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\base.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\compat.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\dataset.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\datatype.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\dims.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\files.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\filters.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\group.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\selections.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\selections2.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\vds.py -> build\lib.win32-3.8\h5py\_hl
  copying h5py\_hl\__init__.py -> build\lib.win32-3.8\h5py\_hl
  creating build\lib.win32-3.8\h5py\tests
  copying h5py\tests\common.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\conftest.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_attribute_create.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_attrs.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_attrs_data.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_base.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_big_endian_file.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_completions.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_dataset.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_dataset_getitem.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_dataset_swmr.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_datatype.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_dimension_scales.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_dims_dimensionproxy.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_dtype.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_errors.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_file.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_file2.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_file_image.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_filters.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_group.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_h5.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_h5d_direct_chunk.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_h5f.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_h5p.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_h5pl.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_h5t.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_objects.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_selections.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\test_slicing.py -> build\lib.win32-3.8\h5py\tests
  copying h5py\tests\__init__.py -> build\lib.win32-3.8\h5py\tests
  creating build\lib.win32-3.8\h5py\tests\data_files
  copying h5py\tests\data_files\__init__.py -> build\lib.win32-3.8\h5py\tests\data_files
  creating build\lib.win32-3.8\h5py\tests\test_vds
  copying h5py\tests\test_vds\test_highlevel_vds.py -> build\lib.win32-3.8\h5py\tests\test_vds
  copying h5py\tests\test_vds\test_lowlevel_vds.py -> build\lib.win32-3.8\h5py\tests\test_vds
  copying h5py\tests\test_vds\test_virtual_source.py -> build\lib.win32-3.8\h5py\tests\test_vds
  copying h5py\tests\test_vds\__init__.py -> build\lib.win32-3.8\h5py\tests\test_vds
  copying h5py\tests\data_files\vlen_string_dset.h5 -> build\lib.win32-3.8\h5py\tests\data_files
  copying h5py\tests\data_files\vlen_string_dset_utc.h5 -> build\lib.win32-3.8\h5py\tests\data_files
  copying h5py\tests\data_files\vlen_string_s390x.h5 -> build\lib.win32-3.8\h5py\tests\data_files
  running build_ext
  Loading library to get version: hdf5.dll
  error: Unable to load dependency HDF5, make sure HDF5 is installed properly
  error: Could not find module 'hdf5.dll' (or one of its dependencies). Try using the full path with constructor syntax.
  ----------------------------------------
  ERROR: Failed building wheel for h5py
Failed to build h5py
ERROR: Could not build wheels for h5py which use PEP 517 and cannot be installed directly

Please suggest any solutions to overcome these errors?

A: It is preferred to use a 64bit python3(<3.9), to work with deep learning libraries(Keras, TensorFlow), because testings on 32bit were not yet performed and released. So, Make sure you check whether it is 64 bit or 32 bit. Thanks to Tasnuva for helping!

A: Sometimes it happens due to old version of pip
upgrade pip:
pip3 install --upgrade pip

then try again:
pip install h5py

Note: make sure your python3.8 is 64bit

A: The following is the procedure I followed to fix the problem.
First, to check which version you're using:

*

*look at the bottom left corner of Visual Studio Code in case you're using this IDE (you'll find something like Python v.v.v 32-bit)

*execute python -VV from the terminal
Then download and install the 64-bit version of python from here (don't forget to check Add Python v.v to PATH before installing)
Delete the existing virtual environment (if you already have one) and create a new venv with the latest version of Python that you downloaded.


text:
Q: skew UIView without giving perspective and keeping heigh and width
Hi,
I am trying to achieve a transformation like in the image but I only have got a similar transformation but with perspective (which I don't want) using CGATransform3D. How could I achieve this using objective-c? The transformed image should have the same heigh and width than the original but with the base tilted by a given angle.
Thanks in advance for your help.

A: This is a "shear" or "skew" transformation. Luckily for you, shear transformations are affine transformations, and iOS supports affine transformations at both the UIView and CALayer levels. However, it has no convenience functions to construct shear transforms, so let's write one:
static CGAffineTransform affineTransformMakeShear(CGFloat xShear, CGFloat yShear) {
    return CGAffineTransformMake(1, yShear, xShear, 1, 0, 0);
}

It's not obvious exactly what xShear and yShear mean. xShear is the tangent of the angle by which the y-axis is skewed, and yShear is the tangent of the angle by which the x-axis is skewed. This may seem backwards, but it has the visual effect you expect: a non-zero xShear tilts the figure left or right, and a non-zero yShear tilts the figure up or down.
Since tan π/4 = 1 (or, if you prefer, tan 45° = 1), the transform returned by affineTransformMakeShear(1, 0) turns a rectangle into a parallelogram whose left and right edges are at π/4 radians (or 45°).
Demo:

Note that shearing on both axes can be identical to the combination of a rotation and a scale.
Here's my demo code:
#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UIView *shearedView;
@property (strong, nonatomic) IBOutlet UISlider *verticalShearSlider;
@property (strong, nonatomic) IBOutlet UISlider *horizontalShearSlider;
@property (strong, nonatomic) IBOutlet UILabel *verticalShearLabel;
@property (strong, nonatomic) IBOutlet UILabel *horizontalShearLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self updateAppearance:nil];
}

static CGAffineTransform affineTransformMakeShear(CGFloat xShear, CGFloat yShear) {
    return CGAffineTransformMake(1, yShear, xShear, 1, 0, 0);
}

- (IBAction)updateAppearance:(id)sender {
    CGFloat xShear = self.horizontalShearSlider.value;
    CGFloat yShear = self.verticalShearSlider.value;
    self.shearedView.transform = affineTransformMakeShear(xShear, yShear);
    self.horizontalShearLabel.text = [NSString stringWithFormat:@"%.2f", xShear];
    self.verticalShearLabel.text = [NSString stringWithFormat:@"%.2f", yShear];
}

@end

A: @Fattie.
Quick Swift version of Rob's demo:
class AffineTester: UIViewController
{
    @IBOutlet weak var shearedView: UIView!
    @IBOutlet weak var verticalShearSlider: UISlider!
    @IBOutlet weak var horizontalShearSlider: UISlider!
    @IBOutlet weak var verticalShearLabel: UILabel!
    @IBOutlet weak var horizontalShearLabel: UILabel!

    override func viewDidLoad()
    {
        super.viewDidLoad()
        updateAppearance(self)
    }

    @IBAction func updateAppearance(_ sender: Any)
    {
        let xShear = CGFloat(horizontalShearSlider.value)
        let yShear = CGFloat(verticalShearSlider.value)
        shearedView.transform = CGAffineTransform(1, yShear, xShear, 1, 0, 0)
        horizontalShearLabel.text = String(format: "%.2f", xShear)
        verticalShearLabel.text = String(format: "%.2f", yShear)
    }
}


text:
Q: Corda network parameter change with Network Map Service I have run network map service of corda on my VM. When I changed whitelist file, network map service rebuild network map and also network parameter.
If the network-parameters file is changed and no longer matches what the network map service is advertising then the node will automatically shutdown.
In my case all nodes gets shut down which was expected. On start up got message "Node is using parameters with hash: X but network map is advertising: Y". After deleting network-parameter it starts properly.
As per docs mentioned here, to manually accept updated network parameters and to send back parameters approval to the zone operator, the RPC method fun acceptNewNetworkParameters(parametersHash: SecureHash) has to be called with parametersHash from the update.
I have called above mentioned function from corda shell as below:
run acceptNewNetworkParameters parametersHash: "ba19fc1b9e9c1c7cbea712efda5f78b53ae4e5d123c89d02c9da44ec50e9c17d"

I have got error "RPC failed: java.lang.IllegalArgumentException: argument type mismatch".
I need to figure out how corda nodes accept updated network parameters from Network Map service and how can I prevent corda nodes to be shut down after getting new parameter.
Note: Using Network Map service with below config changes:
cache-timeout : 2 Sec
param-update-delay : 10 Sec
network-map-delay : 1 Sec
08:35:13.664 [vert.x-eventloop-thread-3] ERROR i.c.n.s.NetworkMapServiceProcessor - failed during processParamUpdate
io.vertx.core.file.FileSystemException: java.nio.file.NoSuchFileException: /data/corda-workspace/network-map-service-v0.3.0/network-map/parameters-update/next-params-update
        at io.vertx.core.file.impl.FileSystemImpl$10.perform(FileSystemImpl.java:638)
        at io.vertx.core.file.impl.FileSystemImpl$10.perform(FileSystemImpl.java:615)
        at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:275)
        at io.vertx.core.impl.TaskQueue.run(TaskQueue.java:76)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.nio.file.NoSuchFileException: /data/corda-workspace/network-map-service-v0.3.0/network-map/parameters-update/next-params-update
        at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
        at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
        at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
        at sun.nio.fs.UnixFileAttributeViews$Basic.readAttributes(UnixFileAttributeViews.java:55)
        at sun.nio.fs.UnixFileSystemProvider.readAttributes(UnixFileSystemProvider.java:144)
        at sun.nio.fs.LinuxFileSystemProvider.readAttributes(LinuxFileSystemProvider.java:99)
        at java.nio.file.Files.readAttributes(Files.java:1737)
        at java.nio.file.FileTreeWalker.getAttributes(FileTreeWalker.java:219)
        at java.nio.file.FileTreeWalker.visit(FileTreeWalker.java:276)
        at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:322)
        at java.nio.file.Files.walkFileTree(Files.java:2662)
        at java.nio.file.Files.walkFileTree(Files.java:2742)
        at io.vertx.core.file.impl.FileSystemImpl$10.perform(FileSystemImpl.java:620)
        ... 7 common frames omitted

I have tried multiple time network parameter change along with NMS, few times gets network-parameter-updated files in nodes and few times got below issues:
Couldn't find parameters update for the hash: <Hash>

Refused to accept parameters with hash <Hash> because network map advertises update with hash <Hash>. Please check newest version

A: Corda 3.2/3.3 has a bug whereby the shell cannot deserialise strings into SecureHash objects. The fix is here: https://github.com/corda/corda/pull/3248. It will be available in Corda 4.
In the meantime, you should use an RPC client to accept the new network parameters instead. For example:
public class AcceptNetworkParams {
    public static void main(String[] args) {
        // Create an RPC connection to the node.
        if (args.length != 4)
            throw new IllegalArgumentException("Usage: Client <node address> <rpc username> <rpc password> <network params hash");
        final NetworkHostAndPort nodeAddress = parse(args[0]);
        final String rpcUsername = args[1];
        final String rpcPassword = args[2];
        final CordaRPCClient client = new CordaRPCClient(nodeAddress);
        final CordaRPCOps proxy = client.start(rpcUsername, rpcPassword).getProxy();

        // Accept the new network parameters.
        final String networkParamsHashString = args[3];
        final SecureHash networkParamsHash = SecureHash.parse(networkParamsHashString);
        proxy.acceptNewNetworkParameters(networkParamsHash);
    }
}


text:
Q: how to switch connection string using switch case and session my application is like one application with multiple database[all databse are with same schema] i need to switch the connection on dropdown select.i am now managing the all connection string with switch case but now i need to transfer the all connection string to class[.cs] file for globally use in hole app how to do this if session is correct then how to pass string using session to class file and how to retrieve it in hole project
now my cs file is:-
public class connectionstr {    static string mulcon = "";
static SqlConnection myconnection = null;
public connectionstr()
{
    //      // TODO: Add constructor logic here         //
}
public static SqlConnection getconnection(string opt)
{
    if(opt=="RV001")
    {
        mulcon = ConfigurationManager.ConnectionStrings["DUM01ConnectionString"].ConnectionString;
    }
    else if(opt=="SV001")
    {
        mulcon = ConfigurationManager.ConnectionStrings["CompMasterConnectionString"].ConnectionString;
    }
    if(myconnection==null)
    {
        myconnection = new SqlConnection(mulcon);
        myconnection.Open();

    }
    return myconnection;

}

}

but i need to add this in one webform which have dropdown the we shift the connection on dropdown selection and also which connection is selected that that connection is applied with all project webforms

A: What you essentially need is a single repository for the entire application. You have few options -

*

*Singleton pattern - More details here - Basically you have to implement a singleton class which acts as a store for the connection string. Keep a dictionary in the singleton class. The key in the dictionary will be the user id, and the value will be the selected connectionstring. When the user selects the connectionstring, insert into the dictionary against the user. Wherever he needs a connection, use the connectionstring from the store.

*You can do the same by storing the connectionstring in a session variable. As long the user session is valid, you can retrieve it and use it.


text:
Q: Smooth approximation identities Let $G$ be a Lie group. Let $\mathcal U$ be a neighbourhood base at $1$ of G. Does there exist $\{\psi_U:U\in\mathcal U\}$ with the following properties support of $\psi_U$ is compact and contained in $U,$ $\psi_U\geq 0,$ $\psi_U(x^{-1})=\psi_U(x)$, $\int_G\psi_U(x)dx=1$ and $\psi_U$ is smooth?

A: It seems so. Start with any bump function $\phi_U \geq 0$ around $1$ whose compact support is contained in $U$. Then let $\varphi_U(x) \doteq \phi_U(x)\phi_U(x^{-1})$. This is smooth, also has compact support contained in $U$, and the property $\varphi_U(x^{-1}) = \varphi_U(x)$ holds by construction. Then set $$\psi_U(x) = \frac{1}{\int_G \varphi_U(x)\,{\rm d}x} \varphi_U(x).$$


text:
Q: Evitar que el header me tape el texto Estoy creando un navbar con enlaces que te trasladan a los textos lorem (segun corresponda), lo que ocurre es lo siguiente:
el navbar esta en una posicion fixed y estoy tratando de evitar que el header me tape el texto cuando preciono alguno de los link ("home", "contact", "about") lo pueden ver en la imagen:

hasta ahi todo bien pero en el momento que preciono "Home", (o alguno) me tapa el texto y aparece asi como el la siguiente imagen:

les paso el htlm y el estilo que estoy usando

.navbar {
    position: fixed;
    top: 0;
    color: #FFF;
    border: 1px solid #ccc;
    background: blue;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-content: center;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    z-index: 100;
}

.nav-title {
      text-transform: uppercase;
      width: 50px;
      margin-left: 50px;
    }

 .nav-box {
      width: 300px;
      list-style:none;
      margin-right: 50px;
}

li {
        display: flex;
        justify-content: space-between;
      }

      li a {
        color: #fff !important;
          text-decoration: none;
      }

      .text {
        margin-top: 100px
      }

title

      Home
      Contact
      About

1 Lorem.

  Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque quasi provident
  officia mollitia nam! Facilis eius, debitis quo minima magni quas culpa esse
  libero assumenda maiores, iste, quaerat illo sed sequi tempore. Autem
  distinctio ipsa incidunt, veniam modi facilis consectetur suscipit error sunt,
  et rerum enim qui beatae possimus! Veritatis.

2 Lorem.

  Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque quasi provident
  officia mollitia nam! Facilis eius, debitis quo minima magni quas culpa esse
  libero assumenda maiores, iste, quaerat illo sed sequi tempore. Autem
  distinctio ipsa incidunt, veniam modi facilis consectetur suscipit error sunt,
  et rerum enim qui beatae possimus! Veritatis.

3 Lorem.

  Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque quasi provident
  officia mollitia nam! Facilis eius, debitis quo minima magni quas culpa esse
  libero assumenda maiores, iste, quaerat illo sed sequi tempore. Autem
  distinctio ipsa incidunt, veniam modi facilis consectetur suscipit error sunt,
  et rerum enim qui beatae possimus! Veritatis.

4 Lorem.

  Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque quasi provident
  officia mollitia nam! Facilis eius, debitis quo minima magni quas culpa esse
  libero assumenda maiores, iste, quaerat illo sed sequi tempore. Autem
  distinctio ipsa incidunt, veniam modi facilis consectetur suscipit error sunt,
  et rerum enim qui beatae possimus! Veritatis.

5 Lorem.

  Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque quasi provident
  officia mollitia nam! Facilis eius, debitis quo minima magni quas culpa esse
  libero assumenda maiores, iste, quaerat illo sed sequi tempore. Autem
  distinctio ipsa incidunt, veniam modi facilis consectetur suscipit error sunt,
  et rerum enim qui beatae possimus! Veritatis.

6 Lorem.

  Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque quasi provident
  officia mollitia nam! Facilis eius, debitis quo minima magni quas culpa esse
  libero assumenda maiores, iste, quaerat illo sed sequi tempore. Autem
  distinctio ipsa incidunt, veniam modi facilis consectetur suscipit error sunt,
  et rerum enim qui beatae possimus! Veritatis.

7 Lorem.

  Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque quasi provident
  officia mollitia nam! Facilis eius, debitis quo minima magni quas culpa esse
  libero assumenda maiores, iste, quaerat illo sed sequi tempore. Autem
  distinctio ipsa incidunt, veniam modi facilis consectetur suscipit error sunt,
  et rerum enim qui beatae possimus! Veritatis.

8 Lorem.

  Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque quasi provident
  officia mollitia nam! Facilis eius, debitis quo minima magni quas culpa esse
  libero assumenda maiores, iste, quaerat illo sed sequi tempore. Autem
  distinctio ipsa incidunt, veniam modi facilis consectetur suscipit error sunt,
  et rerum enim qui beatae possimus! Veritatis.

9 Lorem.

  Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque quasi provident
  officia mollitia nam! Facilis eius, debitis quo minima magni quas culpa esse
  libero assumenda maiores, iste, quaerat illo sed sequi tempore. Autem
  distinctio ipsa incidunt, veniam modi facilis consectetur suscipit error sunt,
  et rerum enim qui beatae possimus! Veritatis.

10 Lorem.

  Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque quasi provident
  officia mollitia nam! Facilis eius, debitis quo minima magni quas culpa esse
  libero assumenda maiores, iste, quaerat illo sed sequi tempore. Autem
  distinctio ipsa incidunt, veniam modi facilis consectetur suscipit error sunt,
  et rerum enim qui beatae possimus! Veritatis.

les agradezco si me dan una mano c:

A: Mejor sería que uses jQuery. Sólo modifica a tu gusto la altura en "padding-top":"50px" y la velocidad 700.
$(document).ready(function() {
 // función de los enlaces que contengan #
 $('a[href^="#"]').on("click", function() {
  var destino = $(this.hash);
 if(destino.length == 0) {
  destino= $('a[name="' + this.hash.substr(1) + '"]');
 }
 if(destino.length == 0) {
  destino= $('html');
 }
$("html,body").animate({
 scrollTop: destino.offset().top,
 // ajuste de espacio entre el top
 "padding-top":"50px",
}, 700); // ajuste de velocidad
return false;
});
});


text:
Q: regular expression except pattern Lets say I have multiple css files.
bear.css
cat.css
styles.css
colors.css
... multiptle different css files

I would like to select all the files except the bear.css and cat.css
Look around operation might be work but I could not make it work
Condition is like if((pattern != bear.css && pattern != cat.css) && .css))
I need to add the regex to   test: /.css$/, which is webpack css loader config

A: Try this regex:
^(?!bear|cat).*\.css$

Click for Demo
Explanation:

*

*^ - asserts the start of the line

*(?!bear|cat) - negative lookahead to make sure that whatever follows the current position should neither be bear nor cat

*.* - once the above condition is satisfied, we match 0+ occurrences of any character except the newline character

*\.css - matches .css

*$ - asserts the end of the line


text:
Q: LINQ Having Clause with inner select How would the following be converted to LINQ-EF
select Name
from TableA as TableAOuter
group by TableAOuter.Name, TableAOuter.Id
having(
    select count(TableAInner.Id)
    from TableA as TableAInner
    where TAbleAInner.Reference=TableAOuter.Id) = 0
);

A: To me, that looks like:
var query = from row in tableOuter
            group row by new { row.Name, row.Id } into g
            where !tableInner.Any(inner => inner.Reference == g.Key.Id)
            select g.Key.Name;

Although I'd be tempted to perform the filtering before the grouping - at which point you can just group the row name:
var query = from row in tableOuter
            where !tableInner.Any(row => inner.Reference == row.Id)
            group row.Name by new { row.Name, row.Id };

I think that should do the same thing, right?


text:
Q: VSCODE no longer detecting python virtual environment On Windows.
Normally, when I run
python -m venv myvenv

In the bottom right corner, VSCODE will detect this virtual environment and prompt me to set it as default interpreter.
In fact, this was working up to about 30 minutes ago.
However, I was having errors with path in Git Bash and followed instructions here to change my default terminal back to the CMD.
After doing so, VSCODE no longer recognizes any virtual environment I create automatically. Doing CTRL SHIFT P and trying to set it manually doesn't work either, as it cannot seem to find it.
However, if I do
source myvenv/Scripts/activate

It does indeed open the virtual environment. However, this only lasts for that one terminal session.
How can I fix this problem?

A: Try the solution from the below link and do let me know in the comments if that works for you
Even though I have referred to the exact section of the page required for your resolution, as suggested by @Ch3steR, I am putting the required details below :-
From within VS Code, select a Python 3 interpreter by opening the Command Palette (⇧⌘P), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too):
No interpreter selected
The command presents a list of available interpreters that VS Code can find automatically, including virtual environments. If you don't see the desired interpreter, configure your Python environment.
for setting python environment, please follow below instructions: -

To select a specific environment, use the Python: Select Interpreter command from the Command Palette (⇧⌘P).
Python: Select Interpreter command
You can switch environments at any time; switching environments helps you test different parts of your project with different interpreters or library versions as needed.
The Python: Select Interpreter command displays a list of available global environments, conda environments, and virtual environments.

Note: When using an Anaconda distribution, the correct interpreter should have the suffix ('base':conda), for example Python 3.7.3 64-bit ('base':conda).
Selecting an interpreter sets the python.pythonPath value in your workspace settings to the path of the interpreter. To see the setting, select File > Preferences > Settings (Code > Preferences > Settings on macOS), then select the Workspace Settings tab.
Reference :-
https://code.visualstudio.com/docs/python/python-tutorial#_select-a-python-interpreter
https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment
Thanks

A: The crisp of VS code Environment setting as per there site:
From within VS Code, select a Python 3 interpreter by opening the Command Palette (Ctrl+Shift+P), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too)
The command presents a list of available interpreters that VS Code can find automatically, including virtual environments. If you don't see the desired interpreter, see https://code.visualstudio.com/docs/python/environments
Note: When using an Anaconda distribution, the correct interpreter should have the suffix ('base':conda), for example Python 3.7.3 64-bit ('base':conda).
Selecting an interpreter sets the python.pythonPath value in your workspace settings to the path of the interpreter. To see the setting, select File > Preferences > Settings (Code > Preferences > Settings on macOS), then select the Workspace Settings tab.
Note: If you select an interpreter without a workspace folder open, VS Code sets python.pythonPath in your user settings instead, which sets the default interpreter for VS Code in general. The user setting makes sure you always have a default interpreter for Python projects. The workspace settings let you override the user setting.
Above Paragraph is taken from: https://code.visualstudio.com/docs/python/python-tutorial#_select-a-python-interpreter


text:
Q: Preset amount of degree an image rotates per scroll Is it possbile to set a preset amount an image rotates per scroll?
I created a rotate function with js, which rotates an image (gears in my case) by scrolling up and down the website. In my opinion it needs to rotate more degrees per scroll and Im trying to increase the degrees the image is rotating
JS
function rotate(e) {
  e.preventDefault();

  rot += e.deltaY * 0.5;
  leftGear.style.transform = `rotate(${rot}deg)`;
  rightGear.style.transform = `rotate(${rot}deg)`;
}

let rot = 0;
const leftGear = document.querySelector(".leftGear");
document.body.onwheel = leftGear.onwheel = rotate;
const rightGear = document.querySelector(".rightGear");
document.body.onwheel = rightGear.onwheel = rotate;

html

I tried changing '0.5' as factor but somehow it doesnt change anything, or maybe its a false thought of mine

A: it's because your rotate the whole div which width is 100% of your browser.
Add a width to your div, it will solve your problem
.rightGear{
  width:100px;
}


text:
Q: how can I make the active tab highlighted until I change the tab for another? I created a simple vue app with router. I managed to get the tab highlighted upon hovering on it but I want it to stay coloured until the user changes for another.
Here is relevant code:

<router-link to="/contact">Contact</router-link>

<router-link to="/blog">Blog</router-link>

<router-link to="/ceremonies">Ceremonies</router-link>

<router-link to="/pregnancy">Pregnancy Yoga</router-link>

<router-link to="/about">About</router-link>

<router-link to="/">Home</router-link>

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color:#F1D0E5
}

li {
  float: right;
}

li a {
  font-size: 20px;
  display: block;
  color: #89a864;
  font-weight:900;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  background-color:#985277;
}
li a:active {
    background-color:#985277;

}

it does not stay higlighted as soon as I remove the cursor

A: vue-router automatically adds two classes to the active <router-link> component.
.router-link-active and .router-link-exact-active
You can use those classes to style your links.
This is a comprehensive answer that covers how/when these classes are applied.


text:
Q: Script tags seem to automatically be loaded async on mobile this is a weird one.
I have several <script>...</script> tags with inline code in my page that were used to logically separate pieces of code. For instance: <script id='prepareA'>...</script> <script id='docReadyStuff'>...</script>.
Now, what is happening is that sometimes a function declared in a script tag is not visible in another one, even though the function script tag comes before in code.
To better explain this, consider this piece of code:
<script>

function DoSomething() {
    alert("something");
}

</script>

<script id=blockA>

function Foo() {

$("#btn").on("click", function() {

    alert("calling DoSomething");
    DoSomething();

});

}

</script>

<script>
$(function() {

    // Calling Foo() from within
    // ready, so any access to DOM from Foo
    // *should* be safe!
    Foo();

});
</script>

Now, on every desktop browser, this works fine. However, on mobile chrome and safari for iPhone, when the button btn is pressed, it says DoSomething is undefined. On Android it works fine.
I have no idea why this happens since DoSomething is clearly defined before the button event handler is event attached. Now, if I move DoSomething to the line before Foo is defined, then it works.
Can anybody explain this behavior?
*iPhone 5s, iOs 9.3.5; Mobile Chrome 55.0.2883.79;


text:
Q: $P(\max\{ X,Y \} \leq aX)$. Is it correct? Let $X,Y$ be independent random variables which have exponential distributions of parameters $\lambda, \nu$ respectively, and $a \geq 1$. Calculate $$P(\max\{ X,Y \} \leq aX)$$
My work is this:
$$P(\max\{ X,Y \} \leq aX) = P(X\leq aX; Y \leq aX)=P(X\leq aX)\cdot P(Y\leq aX)$$
We know that $P(X\leq aX) =1$ since $a\geq 1$ so we only have to calculate $P(Y\leq aX)$
$$P(Y\leq aX)=\int_{x=0}^{\infty}\int_0^{ax}f_{X}(x)f_Y(y)\:dy\: dx =
\int_{x=0}^{\infty}\int_0^{ax} \lambda e^{-\lambda x}\nu e^{-\nu y} \: dy \: dx = \frac{a\nu}{a\nu + \lambda}$$
However I am not sure if this is correct because I got a solution from a teacher and it was this:
$$\frac{\nu}{\nu + \lambda} + \frac{\lambda}{1+\nu a - \nu}$$
Could someone tell me if I messed up and where please?

A: The answer you have calculated, $ \frac{a\nu}{a\nu+\lambda}$ is indeed correct. The answer given by your teacher seems to be wrong. Here is a small check. For, $a \to \infty$ the probability should tend to 1.