text:
Q: Use cases for categories in Machine Learning I started learning the concepts of machine learning.
I would like to know some of the use case scenarios for below

*

*Classification

*Regression

*Clustering

*Anomaly detection

*Dimension reduction

And I would even like to know under which category the above mentioned list falls?(Is it in supervised or unsupervised or reinforcement )

A: General note
You should not think about types of tasks in ML as something that has assigned label "supervised/unsupervised/...". This is not how it works. You can say that usually given task is solved using supervised/unsupervised learning, but this is just this. You can generate approach which has any label with any task in practise.
Actual answer
These parts of ML were originally well defined, but with progress in the field many of them merged, and now we have much more types of problems (like semi-supervised learning, weakly supervised classification, representation learning), so I stress that I refer to the original meaning of each

Classification

Defined as a problem of looking for a mapping from objects to a finite set of classes. Usually each object has just one class (but there are generalizations to multiple ones).
Real life examples:

*

*Face recognition (we are given a face and answer who is it)

*Drug discovery (we are given a compound and we answer if it is a drug or not)

Type of learning: usually supervised

Regression

We are looking for a mapping to a infinite number values, with valid ordering, for example real numbers.
Real life examples:

*

*Predicting for much money a user will spend in our shop based on his characteristic

*Predicting power consumption in the next month

*Predicting stock prices

Type of learning: usually supervised

Clustering

Usually defined as finding a structure in data, without access to any sample of such structure (later on with many modifications such as constrained clustering, weakly supervised clustering)
Real life examples:

*

*Given set of images of stars, do they form some distinguishable types of stars?

*Given users activity on our website - are there distinguishable usage scenarios that we can find?

Type of learning: usually unsupervised

Anomaly detection

Given a set of "normal" observations build amodel to answer "is new observation normal, or is it an anomaly?"
Real life examples:

*

*We have record of a valid engine parameters and need a method to alarm as that it starts to behave "weird" (even though we do not know from the past what kind of "weird" we are looking for)

*We have recordings from camera of usual people behaviour, we want method to alarm as that "something unusual is happening" (without specifing what)

Type of learning: usually unsupervised

Dimension reduction

This is just a preprocessing step. Given high dimensional data we seek for a lower-dimensional representation which is usable in other tasks.
Real life examples:

*

*We have set of high-dimensional data (like patients records) and want to visualize it (draw on a plane)

*We have a problem of classification and our methods fail - we need to reduce dimensionality to increase scores

Type of learning: usually unsupervised
Reinforcment
None of the above is reinforcment learning. Reinforcment learning can be applied to any of the above, if we simply have some 'environment' saying that our method is doing 'good' or 'bad' (so instead of saying 'I want this image to be classified as cat' it only says 'I see that you classified this image as a plane, well.. it is not!').
In other words - we do any  task, but we do have humans who judge is our method good or bad, but they do not give as correct answers.

A: classification -> dividing the data in categories where output classes are known.  -> supervised task
regression -> output data is continous -> supervised task.
clustering -> divide the data in some groups -> unsupervised task
Anomaly detection -> find out some out of the place data point from input data -> output classes labels are not required  -> unsupervised task.
Dimension reduction -> map a higher dimension input to a lower dimension input -> output classes labels are not required -> unsupervised task

A: Here is a somewhat atypical use case where classification was used to analyze performance data in a microservice architecture and identified two issues, an environmental issue and a software bug that made the microservice more inefficient than was necessary.


text:
Q: Getting the item under mouse cursor in a listview control? Basically I am trying to implement a feature where if the user presses a key, I want to find out the item under the mouse cursor.
So I don't use Mouse events but Keyboard events which doesn't give me a ListViewItem of course.
I just don't know in what space I need to get the mouse position and convert it into the control's space.
Any ideas?

A: If you know which ListView control you are interested in, the following method will do the trick:
private ListViewItem GetItemFromPoint(ListView listView, Point mousePosition)
{
    // translate the mouse position from screen coordinates to
    // client coordinates within the given ListView
    Point localPoint = listView.PointToClient(mousePosition);
    return listView.GetItemAt(localPoint.X, localPoint.Y);
}

// call it like this:
ListViewItem item = GetItemFromPoint(myListView, Cursor.Position);

A: A keyboard action that depends on the mouse position sounds a little unorthodox. Keyboard actions should normally effect some item that is highlighted/focused/selected on the screen, either selected by previous keyboard actions or by a previous mouse click on that item.
Just something to bear in mind, or you'll wind up with a "unique" (confusing) user interaction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: nginx: [emerg] host not found in upstream "api:5000" in /etc/nginx/conf.d/default.conf I have searched for hours but I cannot find the root problem cause.This is my docker-compose.yml file you can see below:
version: "3"
services:
   postgres:
     image: "postgres:latest"
     environment:
      - POSTGRES_PASSWORD=postgres_password
   redis:
     image: "redis:latest"
   nginx:
     restart: always
     build:
      dockerfile: Dockerfile
      context: ./nginx
     ports:
      - '3666:80'
     depends_on:
      - api
      - client
   api:
     build:
      dockerfile: Dockerfile.dev
      context: ./server
     volumes:
      - /app/node_modules
      - ./server:/app
     environment:
      - REDIS_HOST=redis
      - REDIS_PORT=6379
      - PGUSER=postgres
      - PGHOST=postgres
      - PGDATABASE=postgres
      - PGPASSWORD=postgres_password
      - PGPORT=5432
   client:
     stdin_open: true
     build:
      dockerfile: Dockerfile.dev
      context: ./client
     volumes:
      - /app/node_modules
      - ./client:/app
   worker:
     build:
      dockerfile: Dockerfile.dev
      context: ./worker
     volumes:
      - /app/node_modules
      - ./worker:/app

This is my nginx/default.conf
upstream client {
        server client:3000;
}

upstream api {
        server api:5000;
}

server {
        listen 80;

        location / {
                proxy_pass http://client;
        }

        location /api {
                rewrite /api/(.*) /$1 break;
                proxy_pass http://api
        }
}

When I try :
#docker-compose up --build
This error occured in the process:
nginx_1     | nginx: [emerg] host not found in upstream "api:5000" in /etc/nginx/conf.d/default.conf:6

A: please check your docker-compose file, you must set api under services

A: Probably there is an error in the API container when it's trying to run, so it crashes and closes down. This results in Nginx failing to connect. Open the logs of the given container, to see what's causing the issue.


text:
Q: SSRS Leap Year Determination with DateAdd I have a report that compares year over year changes for any date range within a year.  Thus, in my Reporting Services report, I have two parameters @StartDate and @EndDate that the user supplies.  I also have two hidden parameters (@PriorStartDate, @PriorEndDate) for the previous year with default values that are programatically determined using an expression such as this.
=DateAdd(DateInterval.Year,-1,Parameters!StartDate.Value)

I recently ran into a problem when 2/1/17-2/28/17 generated previous dates of 2/1/16-2/28/16.  Unfortunately there was a record on 2/29/16 that did not get picked up due to the leap year.  What's the most concise way to set my previous date while determining if a day should be added based upon leap year?

A: We use parameters in the data set that utilize this function.
Example
select @lastYearBegin =  dbo.ithc_DateAdd('YEAR', -1, @relativeFromDate)
select @lastYearEnd = dbo.ithc_DateAdd('YEAR', -1, @relativeToDate)

Function
ALTER FUNCTION [dbo].[ithc_DateAdd]
    (
      @datePart VARCHAR(5) ,
      @changValue INT ,
      @baseDate DATETIME
    )
RETURNS DATETIME
AS
    BEGIN
        DECLARE @returnDate DATETIME

        SELECT  @returnDate = CASE WHEN ( @baseDate = DATEADD(MM,
                                                              DATEDIFF(MM, -1,
                                                              @baseDate), 0)
                                          - 1
                                          AND( @datePart = 'YY' OR @datePart = 'YEAR')
                                        )
                                   THEN DATEADD(MM,
                                                DATEDIFF(mm, -1,
                                                         DATEADD(yy,
                                                              @changValue,
                                                              @baseDate)), 0)
                                        - 1
                                   WHEN @datePart = 'DD' OR @datePart = 'DAY'
                                   THEN DATEADD(DD, @changValue, @baseDate)
                                   WHEN @datePart = 'MM' OR @datePart = 'MONTH'
                                   THEN DATEADD(MM, @changValue, @baseDate)
                                   WHEN @datePart = 'YY' OR @datePart = 'YEAR'
                                   THEN DATEADD(YY, @changValue, @baseDate)
                              END

        RETURN @returnDate

    END

A: You can check if the year is leap before calculate the previous year date. So for @StartDate it would be.
=IIF(
(((Parameters!StartDate.Value.Year - 1) Mod 4 = 0 and
(Parameters!StartDate.Value.Year - 1) Mod 100 <> 0) or
(Parameters!StartDate.Value.Year - 1) Mod 400 = 0) and
 Parameters!StartDate.Value.Month = 2 and Parameters!StartDate.Value.Day = 28,
Parameters!StartDate.Value.AddYears(-1).AddDays(1),
Parameters!StartDate.Value.AddYears(-1)
)

Replique the same solution for @EndDate.
Hope it helps.


text:
Q: Resolve promise when all images are loaded I was preloading images with the following code:
    function preLoad() {
        var deferred = $q.defer();
        var imageArray = [];
        for (var i = 0; i < $scope.abbreviations.length; i++) {
            imageArray[i] = new Image();
            imageArray[i].src = $scope.abbreviations[i].imgPath;
        }
        imageArray.forEach.onload = function () {
            deferred.resolve();
            console.log('Resolved');
        }
        imageArray.forEach.onerror = function () {
            deferred.reject();
            console.log('Rejected')
        }
        return deferred.promise;
    }
    preLoad();

I thought images were all loading correctly because I could see the 'Resolved' log.
Later somebody pointed out that the code above doesn't guarantee that all images are loaded before resolving the promise. In fact, only the first promise is resolved.
I was advised to use $q.all applied to an array of promises instead.
This is the resulting code:
    function preLoad() {
        var imageArray = [];
        var promises;
        for (var i = 0; i < $scope.abbreviations.length; i++) {
            imageArray[i] = new Image();
            imageArray[i].src = $scope.abbreviations[i].imgPath;
        };

        function resolvePromises(n) {
            return $q.when(n);
        }
        promises = imageArray.map(resolvePromises);
        $q.all(promises).then(function (results) {
            console.log('array promises resolved with', results);
        });
    }
    preLoad();

This works, but I want to understand:

*

*what's happening in each function;

*why I need $q.all to make sure all images are loaded before resolving the promises.

The relevant docs are somewhat cryptic.

A: Check out this plunkr.
Your function:
function preLoad() {

    var promises = [];

    function loadImage(src) {
        return $q(function(resolve,reject) {
            var image = new Image();
            image.src = src;
            image.onload = function() {
              console.log("loaded image: "+src);
              resolve(image);
            };
            image.onerror = function(e) {
              reject(e);
            };
        })
    }

    $scope.images.forEach(function(src) {
      promises.push(loadImage(src));
    })

    return $q.all(promises).then(function(results) {
        console.log('promises array all resolved');
        $scope.results = results;
        return results;
    });
}

The idea is very similar to Henrique's answer, but the onload handler is used to resolve each promise, and onerror is used to reject each promise.
To answer your questions:
1) Promise factory
$q(function(resolve,reject) { ... })

constructs a Promise. Whatever is passed to the resolve function will be used in the then function. For example:
$q(function(resolve,reject) {
     if (Math.floor(Math.random() * 10) > 4) {
         resolve("success")
     }
     else {
         reject("failure")
     }
}.then(function wasResolved(result) {
    console.log(result) // "success"
}, function wasRejected(error) {
    console.log(error) // "failure"
})

2) $q.all is passed an array of promises, then takes a function which is passed an array with the resolutions of all the original promises.

A: I'm not used to angular promise library, but the idea is as follows:
function getImagePromise(imgData) {
    var imgEl = new Image();
    imgEl.src = imgData.imgPath;

    return $q(function(resolve, reject){
        imgEl.addEventListener('load', function(){
            if ((
                   'naturalHeight' in this
                    && this.naturalHeight + this.naturalWidth === 0
                )
                || (this.width + this.height == 0)) {
                reject(new Error('Image not loaded:' + this.src));
            } else {
                resolve(this);
            }
        });

        imgEl.addEventListener('error', function(){
            reject(new Error('Image not loaded:' + this.src));
        });
    })
}

function preLoad() {
    return $q.all($scope.abbreviations.map(getImagePromise));
}

// using
preLoad().then(function(data){
    console.log("Loaded successfully");
    data.map(console.log, console);
}, function(reason){
    console.error("Error loading: " + reason);
});


text:
Q: Spreadsheet hide formula result I have the following formula in cell D255.
=$C$3+(D255*$C$2)
I wish to copy this down to D1000, but do not want to show the result until data is entered into the cells between D255 and D1000 inclusive.

A: Try this:
=IF(D255>0,$c$3+(D255*$c$2),"-")
You can replace "-" with whatever you want to appear when the field is blank. However, as fixer1234 pointed out in the comments, if you put that formula in cell D255, you will have a circular reference, and Excel isn't fond of those. If you put this formula in cell E255, and the values you want to calculate in D255, all will be good.

A: So if no data is in D255 you wish to show an empty cell.  Calculating on the same cell that you wish to show data in isn't possible since it would be circular referencing.  To avoid circular logic you simply put the data you wish to calculate with in a column next to the other column.  This formula would be in D255 and the data that it would check against would be next to the formula in E255.  Of  course you can hide the column if the data can't be shown.

=if (E255="","",$C$3+(E255*$C$2)

Now D255 will not show anything unless data is put into it.  I'm assuming of course c2 and c3 have been set.  And again if you didn't want the data to show in E255 you can always hide the column.  Another way of handling this might be to put the data you are calculating against on another sheet.


text:
Q: Can the portworx "internal" kvdb coexist with etcd? I have a tiny (three worker node, one controlplane) kubernetes cluster running and I want to configure portworx for storage. All my hosts are kvm virtual machines running Ubuntu 20.4.3 LTS with 5.4.0-73-generic kernel. I used https://central.portworx.com/specGen/wizard to generate a portworx 2.8.1.2-c9b840b (OCI) spec file and applied it to my cluster. I chose to not configure a dedicated kvdb drive on these hosts although each host does have a sdb intended as the portworx drive. (These sdb drives are not mounted.)
When I run pxctl status I see:

NODE    NodeStartFailure        3a5bce08-b8ed-4fca-93a2-435a8d6e512b    ALARM           1       Jan 9 18:31:45 UTC 2022 Jan 9 18:31:45 UTC 2022        > Could not find any available storage disks on this node. Node cannot act as a kvdb node as no storage device found. Waiting for other nodes to start kvdb. > If this is a storage node please add disks and restart Portworx.

NODE    InternalKvdbSetupFailed 907d5a2c-297d-4587-87f8-31d539cff440    ALARM           1       Jan 9 18:31:10 UTC 2022 Jan 9 18:31:10 UTC 2022        failed to setup internal kvdb: failed to provision internal kvdb: timeout waiting for other kvdb nodes to start: Could not find any available storage disks on this node. Node cannot act as a kvdb node as no storage device found. Waiting for other nodes to start kvdb. If this is a storage node please add disks and restart Portworx.

I would rather use etcd instead of kvdb. Does anyone care to comment? Also, is the portworx operator intended for kubernetes?
oops. I just noticed this on the portworx website:
PX-Essentials support only built-in KVDB.
External ETCD is accessible in PX-Enterprise

Thanks.

A: PX-Essentials supports only built-in KVDB.
External ETCD is accessible in PX-Enterprise


text:
Q: Flutter Items inside ExpansionTile inside ListView are not scrollable I am trying to place a ExpansionTile inside a nested ListView Builder. Unfortunately despite all attempts I am unable to make the ListView items inside the ExpansionTile scrollable.
Kind of attempted to use ClampPhysics and NeverClampPhysics but dont seem to work.
Any ideas how I can get that done? Any pointers? Am I doing anything wrong?
Here is the code.
body: SingleChildScrollView(
      child: Column (
          children: <Widget>[
            ListTile(
              title: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  Card(
                    child: Text(' Sunrise : '+DateFormat.jms().format(DateTime.fromMillisecondsSinceEpoch(yamistart))),
                  ),
                  Card(
                    child: Text(' Sunset : '+DateFormat.jms().format(DateTime.fromMillisecondsSinceEpoch(yamiset))),
                  ),
                ],
              ),
            ),
            Card(
              child: ListView.builder(
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: paksList == null ? 0 : paksList.length,
                itemBuilder: (BuildContext context, int index){
                 /* Custom Code Here */
                  return Card(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(15),
                    ),
                    elevation: 8.0,
                    margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
                    child: Container(
                      decoration: BoxDecoration(color: (yfrom >= valnow || valnow >= yto) ? Color.fromRGBO(40, 75, 50, .9) : Color.fromRGBO(9, 72, 135, .9), border: Border.all(color: (yfrom >= valnow || valnow >= yto) ? Colors.redAccent : Colors.lightBlue)),
                      child: (yfrom >= valnow || valnow >= yto) ? ListTile(
                        contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
                        title: Column(
                            children: <Widget>[

                                    Text(
                                "Current Rhythm",
                                style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
                              ),
                            ]),
                        trailing: (yfrom >= valnow || valnow >= yto) ? null : Icon(Icons.keyboard_arrow_down_rounded) ,
                      ) : ExpansionTile(
                        tilePadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),

                        title: SingleChildScrollView(
                  child: Column(
                            children: <Widget>[

                                    Text(
                                "Current Rhythm",
                                style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
                              ),
                            ])),
                      children: [
                        ListView.builder(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: TestList == null ? 0 : TestList.length,
                            itemBuilder: (BuildContext context, int index){
                          /* Custom Code */
                              if (color == "Red"){
                                myColor = Colors.red;
                              }
                              else if (color == "Green"){
                                myColor = Colors.lightGreenAccent;
                              }
                              else {
                                myColor = Colors.yellow;
                              }

                              if (index ==0){
                                yfroms = yfrom;

                                ytos = yfroms+ duration*60*1000;
                              }

                              else{
                                yfroms = ytos;

                                ytos = ytos+duration*60*1000;
                              }

                              return Card(
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(15),
                                ),
                                elevation: 8.0,
                                margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
                                child: Container(
                                  decoration: BoxDecoration(color: myColor, border: Border.all(color: Colors.lightBlue)),
                                  child: ListTile(
                                    contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
                                    title: Container(
                              child: Column(
                                        children: <Widget>[
                                            Text(
                                "Current Rhythm : Silence ",
                                style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
                              ),
                                        ]),

                                  ),
                                ),
                              ));
                            },)
                      ],
                      //  trailing: (yfrom >= valnow || valnow >= yto) ? null : Icon(Icons.keyboard_arrow_down_rounded) ,
                      ),

                    ),
                  );
                },
              ),
            )])),
);

A: You should use ExpandableListView widget for scrolling your listView.
Below link will helpful to you for creating that widget.
Create enpandable listview


text:
Q: How do you Swim? Playing Fallout 4 on Xbox One, some of the quests require you to swim.
For example, in Thicket Excavations, you need to swim underwater to repair pipes. Unfortunately, the pipes are quite a bit underwater, and the water is irradiated. Sully Mathis suggests you look for the bubbles, at the surface, to identify where the leaks are. However, I still die before I fix the pipes, in part due to difficulty with the swimming controls.
What are the swimming controls?

A: To swim, simply look in the direction you wish to move, and move forward.
It might also be benefitial to pick up issue 7 of the Wasteland Survival Guide, found in Old Gullet Sinkhole, as this will reward you with a perk that increases swimming speed by 25%
I believe the issue you are having lies elsewhere, in regards to this quest.

The first thing you want to be doing is bolstering your radiation resistance. I watched a level 20 friend complete this, and the first thing he did was use some Rad-X. It significantly decreased the amount of radiation he absorbed. You could also go for more permanent protection, such as lead armor, or a reinforced Vault 111 jumpsuit. It might be handy to carry a Rad Away on you, just in case, and have it mapped to the d-pad.
You will notice an elevator of sorts, further down past Sully. If you press the button, the elevator will rise up, although it takes a little. Inside this elevator is a lock box with a Novice lock, holding a Rad X.

The second thing you want to be doing is paying attention to those bubbles. By identifying the bubbles forming at the top, you can identify where the leaks are, before having to dive in. Furthermore, the bubbles emit directly from the leaks, allowing you to dive down and fix them quite quickly.
The valves are yellow-coloured, and stand out from the pipes. If you follow the pipe directly down, they are impossible to miss. You simply have to use them, there is no hold down or turn animation to wait through. The second I hit the valve, I am moving on to the next, or surfacing for air.

A: The swimming controls are not different from the regular moving controls.
On XBox One, you'll use the two sticks to move, and that's it. Look in the direction you want to move, and go forward, backward, left, or right. If you want to swim upward, look up and press forward on the movement stick. If you want to swim down, look down and press forward on the movement stick.
There's no separate control for diving or surfacing.
Note that you sink in Power Armor, and can't swim. You can walk on the bottom, and don't run out of air, though.
I've done the quest you're referring to without too much trouble, and I've had to swim for other reasons, including retrieving equipment off a raider that fell into the river when he died. Find your objective, aim directly at it, and press forward. The bubbles really do indicate where the pipes that need fixed are.
When you're near the surface, you can jump to help get yourself back on dry land.

A: To answer the question directly stated, you swim with the same controls as walking, simply orienting your view in the direction you want to move.
To answer the question of why you're dying before you can fix the pipes:
As a quick and easy workaround, you could wear a Hazmat suit. This will pretty nearly prevent all radiation damage.
I know of three Hazmat suits:

*

*One is located in the locker room of the Cambridge Polymer Labs (south of Cambridge Police Station). This is available very early in the game.

*Two are located around the Beryllium Agitator chamber, in a late-game quest.

Please note that this will not stop damage from lack of air - despite the apparent air-tanks on the back of the suit.

Alternatively, you can find and consume some Rad-X, which will increase your radiation resistance by +25. This will prevent some radiation damage - possibly enough to allow you to complete your task, and should last several minutes. This will also be more effective if you have perks.

Alternatively, you could get the first level of the perk Aquaboy (/Aquagirl), which provides the following benefits:

Water is your ally. You no longer take radiation damage from swimming, and can breathe underwater

This will require 5 Endurance, and a spare perk point.

A: Don't use armour suit, make sure to use rad remove.


text:
Q: Python number print formatting using %.*g I found this python example online and I'd like to understand exactly how the number formatting works:
print "%.*g\t%.*g" % (xprecision, a, yprecision, b)

I can see by experimentation that this prints a (with precision xprecision), a tab and then b (with precision yprecision).  So, as a simple example, if I run
print "%.*g\t%.*g" % (5, 2.23523523, 3, 12.353262)

then I get
2.2352  12.4

I understand how %g usually works.  I also understand how the % generally works.  What is confusing me in this example is the construct %.*g.  How does the * work here?   I can see that it is somehow taking the desired precision value and substituting it into the print expression, but why is that happening?  Why does the precision number appear before the number being formatted in (xprecision, a...)?
Can someone break this down and explain it to me?

A: * is a size placeholder. It tells the formatting operation to take the next value from the right-hand-side tuple and use that as the precision instead.
In your example, the 'next' value is 5 for the first slot, so you could read this as %.5g, which is used to format 2.23523523. The second slot uses 3 for the width, so becomes %.3g to format 12.353262.
See the String Formatting Operations documenation:

A conversion specifier contains two or more characters and has the following components, which must occur in this order:
(...)

*Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.

*Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.

So both the minimum width and the precision can be made variable with *, and the documenation explicitly states that the value to convert comes after the width and precision.

A: In format specifications, there are field widths with each item.  Most of the time it is a constant:
 The value is %.16g

But field widths/precisions can also be variables.  The * means replace the splat with the next integer in the format list.
 The value is %.*g

will do the same thing if there is a 16 before the value to format:
 "The value is %.*g" % (16, 14.372492384472)


text:
Q: Consuming an Array returned from a Method from my function below, I am returning an array. In C# how would I consume that array?
 public Array arrayFucntion()
 {
// do something

 foreach (var Objs in items)
            {

                list.Add(Objs.value1);

            }

            string[] myArray = list.ToArray();
            MessageBox.Show(myArray.ToString());
            return myArray;
}

Now how would I use it in a function like below
void consumeFunction()
        {

            var x = arrayFucntion();

       // what do do to see values of the array

        }

A: Return a string[],  then you can do the for loop through the string array.
public string[]arrayFucntion()

void consumeFunction()
{
  var x = arrayFucntion();
  for (int i=0; i<x.Lenght; i++)
  {
    x[i]...
  }
}

A: Make the return type string[] instead of Array.

A: You can iterate through the members:
foreach (string sArrayMember in x)
{
   // Do something with s
}

You can also access any of the properties or members listed in the MSDN documentation, including Copy, Find, and Sort.

A: x is now an array object...
you can do foreach on it, or use linq.....or using direct addressing x[0]


text:
Q: Unable to properly manipulate this differential equation Before the start of a memory test a student has to memorize a set of $60$ facts. According to psychologists the rate at which a person memorizes a set of facts is proportional to the number of facts remaining to be memorized. So if a student memorizes $x$ facts in $t$ minutes, taking $x$ and $t$ as continuous variables, this situation can be modeled by the differential equation $dx/dt = k(60-x)$, where $k$ is a positive constant and $x$ is greater than or equal to $60$ for all $t$ that are greater than or equal to $0$.
a) By solving the differential equation and assuming that initially no facts are memorized, show that $x = 60(1-e^-kt)$
Okay so I don't actually need to do this question, seeing as the equation for the next question is already given here, however I want to be able to recreate what's happening to better understand.
1): $dx/dt = k(60-x)$ (divide both sides by $60-x$)
2): $1/(60-x) dx/dt = k$ (multiply both sides by $dt$)
3): $1/(60-x) dx = k dt$ (integrate both sides)
4): $1/60 ln|-x| = kt + c$ (take exponent from both sides)
5): $1/60-x = e^kt + c$ (multiply both sides by $60$ and rearrange to make $x $ the subject)
$x = 60(-c - e^-kt)$
Where am I going wrong? I assume the arbitrary constant is the $1$ in the given equation, however I get this as a minus integer instead of a positive. Also not sure on how this can be calculated as $1$.
b) Given that the student memorizes fifteen facts in the first twenty minutes, show that $20k = ln3/4$
So going from what was given in a)
$x = 60(1-e^-kt)$, the equation under the given parameters would be
1): $15 = 60(1-e^-20k)$ (take $60$ from both sides)
2): $15/60 = 1-e^-20k$ (take exponential from both sides)
3): $ln15/60 = ln1-(-20k)$ ($ln1 = 0$ and $20k$ becomes positive)
This still leaves $20k = ln1/4$, which again is not the same answer given. If someone could tell me where i'm going wrong so I can properly solve these and any similar questions in the future, I would appreciate it.

A: For part a, in equation 2, you missed some parentheses. It's not $1/60 -x$ but $1/(60-x)$

A: There are some mistakes but you were close to the solution
(Line 4 is wrong ... and so is line 5 and 6)
$$dx/dt = k(60-x)$$
$$\frac {dx}{(60-x)}=kdt$$
$$\frac {dx}{(x-60)}=-kdt$$
Integrate both side :
$$\ln{(x-60)}=-kt+C$$
$$(x-60)=e^{-kt+C}=Ce^{-kt}$$
$$\boxed{x=Ce^{-kt}+60}$$


text:
Q: Http request works in PostMan but not in JS I have http patch request with Bearer Token Authorization. But the Http Request get a Unauthorized error from the Server, when making the exact same Request(console.log(url + token) and then copy it from the console) in Postman, it works.
What could be the Problem ?
this.getToken().subscribe((data: FormData) => {
      const httpOptions = {
        headers: new HttpHeaders({
          'Authorization': ('Bearer ' + data['access_token'])
        })
      }
      console.log("URL with " + httpOptions.headers.get("Authorization"));
      this.http.patch("URL",httpOptions).subscribe((articledata: Article)=>
{
        console.log(articledata);
      })
    });

So this should work, since copying the output and using it in Postman works, but i get a 401 Unauthorized.

A: For Anyone that needs it, i used http.patch wrong, the headers are the 3rd parameter after url and body.


text:
Q: Unable to install 20.04 LTS on Intel NUC 10i3FNH I am unable to boot using Live CD (USB) install for 20.04 LTS.
System Configuration:
Intel NUC10i3FNH
Gigabyte m.2 2280 SSD 256GB
1 x 16GB HyperX SODIMM 2666MHz
Screenshot below
Bootscreen
Any ideas what to do?
/Uffe

A: I finally got my NUC10i7FNH operational with Ubuntu 20.04. I disabled lots of stuff in the BIOS (Bluetooth/Wi-Fi, HDMI TV controls), but the big one that finally worked was turning off Intel Turbo Boost Technology on the Performance → Processor page.
I went back later and started enabling all the items I had recently disabled. The boot failed, so there is a combination of settings that worked. My changes were all on the Advanced tab in the BIOS, and the one checkbox on the Processor page.

A: I strongly suspect your USB hardware — the flash drive or any hubs you may be using — to be the culprit. I have successfully installed Ubuntu 20.04 LTS (server version) with no issue on an Intel NUC10i3FNH with an m.2 SSD (Western Digital in my case). Those USB errors indicate that something isn't communicating properly between the OS and the USB hardware; I've seen them before on NUC 7's, and it's indicative of a failing USB device or port.

*

*Make sure you're plugging the USB drive directly into the NUC's built-in USB ports — no hubs, cables, et cetera; this includes Type C-to-A adapters (or vice versa)

*I've noticed that USB ports on the NUCs tend to be very snug, so make sure your drive is inserted fully (turn off the NUC, remove the drive, reinsert firmly, try again)

*Try the USB drive in another port. The NUC10s have three USB type A and two type C ports, so you definitely have a choice no matter what sort of drive you're using (please tell me you're not using the SD card slot? LOL)

*Try a different flash drive. Even if you only have one fast flash drive and the rest are slow, try a slow one just to see if it works successfully. Also, if your flash drive is USB 2.0, try a USB 3.0 drive if possible, and vice versa.

The company I work for has deployed literally thousands of NUC 7 devices across the United States and India, and we are working on upgrading to NUC 10s... so I've had lots of hands-on experience with this hardware and all its quirks and foibles (much to Intel's dismay, because I harass them about it ).

A: It looks like the actual solution to this problem is to switch from RST to AHCI in the BIOS Storage settings.
I found this out by attempting to install Ubuntu 21.04 Desktop edition. The graphical installer popped a warning and directed me to this page that explains the issue.
Once I made that BIOS change, the 20.04 LTS Server installer worked as expected.
FWIW, I have a NUC10i7FNHJA and previously upgraded the BIOS and firmware.

A: I also had a lot of problems running Ubuntu 20.04 TLS, I bought NUC10FNK, the problems I had was related to the disk, type M2, I installed several times, with different USBs and different files, each time different errors, mainly had a read-only filesystem error...
This is the configuration in which it worked for me in the end:
Changes I made to the BIOS:
I turned off all the features I did not need such as - Bluetooth, HDMI CEC ...
In STORAGE I turned off the SMART SELF TEST and after installing the OS, I changed the SATA MODE from AHCI to RAID ...
In the process of installing the UBUNTU:
I chose a minimal installation, deleted the disk, and did the installation without internet connections...
Now it seems to be working...


text:
Q: Want to open a dialog box to open file in web browser based application Am using JSF and primefaces to develop web application.I want to open existing files on client machines using dialog box which prompts the user to select a path and the corresponding file. Please suggest a component which can be used.

A: While I doubt the feasibility of your intentions; accessing content directly on a client's machine (some security implications there), a combination of <p:media/> and <p:lightBox/> will work for you. There are file type restrictions imposed  by primefaces though (multimedia files and pdf only) The <p:media/> can be embedded in the <p:lightBox/> like so :
    <p:lightBox>
          <p:media value="{yourBean.filePath}" width="100%" height="300px">
    </p:lightBox>

Like I said, I doubt the feasibility of directly streaming content from a client's local filesystem. How do you intend to use the path c:\Users\john doe\my documents\my books\book.pdf on a user's local system within your own web application, without first uploading the file to your own webserver? With image files, you might have some success loading the file into memory and streaming the file directly from RAM using <p:dynaImage/>...consider the scalability of this option too for a high traffic application


text:
Q: Trying to make the search bar functionality filter the names of the contacts which are coming from a json object into an array of strings Want to convert my json object into an array of just names so I can use the search bar to search for different names and filter it.
    "data2": {
    "id": 1,
    "contacts": [
        {
            "name": "Molly",
            "pictureUrl": "molly"
        },
        {
            "name": "Cathy",
            "pictureUrl": "molly"
        },

        {
            "name": "Bob",
            "pictureUrl": "bob"
        },
        {
            "name": "Nick",
            "pictureUrl": "clothes"
        }
    ],

},
"error": 0,
"message": "Success"

This is the json file with the object:
var contact = [IndividualContact]()

init?(data2: Data) {
    do {
        if let json2 = try JSONSerialization.jsonObject(with: data2) as? [String: Any], let body = json2["data2"] as? [String: Any] {

            if let contacts = body["contacts"] as? [[String: Any]] {
                self.contact = ( contacts.map { IndividualContact(json2: $0) } )

                //Expected: ["Molly", "Bob", "Cathy"]

            }

 }


text:
Q: ListPlot and Filling: overlapped vertical lines I was plotting multiple discrete series on the same figure. Filling is needed to highlight trajectory of the series. However, if I use Filling->All, filling lines are overlapped.
One of the solution is to apply filling to only highlight most complicated parts of these series. I tried but failed to achieve this. I was wondering if there is a better solution.
The code I was using is
c = 0.002/12; b0 = 0; b1 = 0.1 c; b2 = 0.2 c; b3 = 0.3 c; b4 = 0.4 c; b5 = 0.5 c; b6 = 0.6 c; \[Omega] = 300; \[Nu] = 30000;
m[t_, s_] := \!\(\*UnderoverscriptBox[\(\[Sum]\), \(j = 0\), \(t - s\)]\*FractionBox[\(\[Omega] \*SuperscriptBox[\((\(-b\))\), \(j\)]\), \(\((\[Nu] + \((t - j)\) \[Omega])\) \*SuperscriptBox[\((2 \((c - b)\))\), \(j + 1\)]\)]\);
m0[t_, s_] := \[Omega]/((\[Nu] + t \[Omega]) (2 c));xticks = {10, 20, 30, 40, 50};
yticks = {10, 20, 30, 40};
age = 48; points = Range[48];
data1 = Transpose[{points, Table[m[age, s] /. b -> b6, {s, points}]}];
data2 = Transpose[{points, Table[m[age, s] /. b -> b4, {s, points}]}];
data3 = Transpose[{points, Table[m[age, s] /. b -> b2, {s, points}]}];
data4 = Transpose[{points, Table[m0[age, s], {s, points}]}];
Figurems = ListPlot[{data1, data2, data3, data4}, PlotRange -> All, Frame -> True, FrameLabel -> {"s", "\!\(\*SubscriptBox[\(m\), \(t, s\)]\)"}, BaseStyle -> {FontFamily -> "Arial", 8},PlotLegends -> Placed[PointLegend[{"b=0.6c", "b=0.4c", "b=0.2c", "b=0"}, LegendLayout -> "Row"], {0.5, 0}], FrameTicks -> {{yticks, {#, ""} & /@ yticks}, {xticks, {#, ""} & /@ xticks}}, PlotRange -> {{1, 100}, {10, 50}}, PlotMarkers -> {{\[FilledSquare], 6}, {\[FilledUpTriangle], 6}, {\[FivePointedStar], 6}, {\[FilledCircle], 4}}, Filling -> Axis]

My current figure is

A: Here are two solutions:
The first is as you've said: only fill the second curve. The second is a bit more complicated: make the point move a bit and make the line distinct~ I'll use sample data like the following to get a maximized variety:
data = {Table[N@10 Sin[i], {i, 10}],
Table[{i, N@10 Sin[i] + 1}, {i, 1, 10, 1/2}],
Table[{i - .2, N@10 Sin[i] - 1}, {i, 1, 10, 1/2}]};

The original graph is like this:
 (*Original Plot*)
 ListPlot[data, Filling -> Axis, PlotLabel -> "ORIG",
 PlotLegends -> {1, 2, 3}]

We can make some small adjustments to fill only the second curve:
(*Only Fill 2*)
ListPlot[data, Filling -> {2 -> Axis}, PlotLabel -> "FILL 2", PlotLegends -> {1, 2, 3}]

And the result looks like:

But I suppose the following code is the best in appearance:
(*Make Overlap disappear*)

Module[{dat =
SortBy[GatherBy[
Flatten[MapIndexed[Thread[{First@#2, #1}] &, proc /@ data],
1], #[[2, 1]] &], #[[1, 2, 1]] &]},
ListPlot[
GatherBy[
Flatten[MapThread[{#[[1]], {#[[2, 1]] + #2, #[[2, 2]]}} &, {#,
     Min[Rest@# - Most@# &@
         dat[[;; , 1, 2, 1]]]/(3 Max[Length /@ dat]) Range[0,
       Length@# - 1]}] & /@ dat, 1], First][[;; , ;; , 2]],
Filling -> Axis, PlotLabel -> "NO OVERLAP",
PlotLegends -> {1, 2, 3}]]

I suppose this is just what you need?

It successfully make overlapping disappear while preserved all the filling lines~
Will this help?

A: My suggestion would be to use include the Joined->True directive.  This has the effect of changing the filling style from vertical line segments to uniform coloring:

Also, since nothing much happens for the first half of the data, you may consider plotting only the second half:

A: you can define your own customized plotting function for that.
bar[col_, thickness_,  opc_, marker_, size_, data_] := {col, Opacity[opc],
   Thickness[thickness], Line[{{#[[1]], 0}, #}], Opacity[1],
   Text[Style[marker, size], #]} & /@ data

Now you can plot lines with different thickness and opacity to make all of them visible.
Graphics[{
  bar[Blue, 0.01, \[FilledSquare], 10, 0.5, data1],
  bar[Green, 0.007, \[FilledUpTriangle], 10, 0.5, data2],
  bar[Red, 0.005, \[FilledCircle], 10, 0.5, data3]},
Frame -> True, FrameLabel -> {"s", "mts"},
FrameTicks -> {{yticks, {#, ""} & /@ yticks}, {xticks, {#, ""} & /@
xticks}}, PlotRange -> All, AspectRatio -> 1/2]


text:
Q: Are there Graph Polynomials? Knots can be represented by polynomials like the Jones polynomial. Is there a comparable representation for graphs? How does it work for subclasses like planar, k-regular...?
Google doesn't really help here...
Thanks

A: There are polynomial invariants for graphs. One of them is the characteristic polynomial of the adjacency matrix. This has been studied extensively, for example in connection with the graph isomorphism problem.

A: Also check out the Tutte polynomial.  It is actually a generalization of many polynomials in graph theory, including the chromatic polynomial and the Jones polynomial.  It's not a "representation" of the graph, per se, but is extensively used.


text:
Q: Correct approach to avoid rendering view in Action I currently use an ajax post back to an action to create a new database object and then return the rendered html for a view of that object. I then inject that html into the page.
I was wondering, since MVC does easily allow you to render views to HTML from within controllers, if there was a better (or more correct) approach to the problem.
(I currently use this code to render the view as html in the action).
Any and all ideas appreciated.

A: As a matter of fact there is. Just return a partial view.
public ActionResult AjaxStuff()
{
    // do whatever
    var model = ...;
    return PartialView(model);
}

A: It's true you can render it using PartialView or doing it custom via JSON (PartialView is just so much easier!).
It really depends on your implementation and choices regarding graceful degradation.
What I usually do is:
[HttpGet]
public ActionResult SignIn()
{
    //Check if it is an AJAX request
    if (Request.IsAjaxRequest())
        return PartialView();
    else
         return View();
}

So it is possible to get your cake and eat it too.
Truth be told there are various ways to get this view from the server. You could use the asp.net mvc ajax js library, use .getJSON or .ajax, or even do it via JQuery using .load: http://api.jquery.com/load/

A: You can render a PartialView as the other answer suggested or return JsonResult and populate your HTML from the JSON data.  Your call.


text:
Q: create a list of matrices where columns are permutations based on a list I have two lists, list1 and list2. The former is composed of cluster values and the latter of cluster pvalues. The elements in each list are strictly related, for example list1[[1]] has 13 numbers and list2[[1]] has 13 pvalues corresponding to each value in list1. Then, I have another list, list3, with a certain number of pvalues (in my real case there are at least 100) classified according to numbers in list1, i.e, list3['1'] will have all pvalues from list2 that corresponds to a value of 1. Here are some examples of the objects in order to clarify the question.
list1
# $cluster.1
# [1] 1 2 12 58 31 41 44 24
#
# $cluster.2
# [1] 6  56  46  44
#
# $cluster.3
# [1]   1  63  74   4 12
#
# $cluster.4
# [1]  49 112   9  34   4  76  48  18  20  64
#
# $cluster.5
# [1]  14  22  63  47  36   6  40   7   2   4  90  16  20  15  14 18  76  35
#
# $cluster.6
# [1]    1    9    1    8    2    2   51   36    3  212   33   12   88 23

list2
# $cluster.1
# [1] 0.6591487 0.8994453 0.1538042 0.6964092 0.8401874 0.3814041 0.4633218
# [8] 0.7244993
#
# $cluster.2
# [1] 0.8497138 0.5865632 0.1077595 0.6833493
#
# $cluster.3
# [1] 0.3361554 0.6120117 0.0981049 0.5463973 0.3299392
#
# $cluster.4
# [1] 0.66537320 0.92404972 0.03616409 0.20704537 0.40120409 0.68727494
# [7] 0.60326315 0.08871090 0.71780273 0.09714994
#
# $cluster.5
# [1] 0.5926167 0.4155177 0.5230090 0.3620749 0.8698867 0.2490805 0.2775648
# [8] 0.1876079 0.5346257 0.6736455 0.3626760 0.8941776 0.4278336 0.7944475
# [15] 0.6687182 0.0171974 0.2931373 0.3987727
#
# $cluster.6
# [1] 0.3222530 0.1097813 0.3014139 0.9999900 0.5232969 0.4544731 0.4342567
# [8] 0.9999900 0.5435826 0.1937477 0.1713069 0.7474790 0.1683223 0.8814443

list3[1:2]
# $`1`
# [1] 0.2977049 0.3080035 0.3445133 0.2938342 0.3630210 0.3037416 0.2841442
# [8] 0.2777617 0.3366143 0.3121525 0.2460582 0.3229141 0.3283752 0.4038269
# [15] 0.3220467 0.3059212 0.2960296 0.3747395 0.3228451 0.2894994 0.3609505
# [22] 0.3447814 0.2993272 0.3088115 0.3255970
#
# $`2`
# [1] 0.21775479 0.98620413 0.25035841 0.31131319 0.48057769 0.98633571
# [7] 0.20208590 0.39117415 0.55579118 0.23737710 0.37548844 0.20139280
# [13] 0.49689904 0.34500830 0.19796570 0.45113871 0.20210998 0.51241253
# [19] 0.49254870 0.50922946 0.20125218 0.21230656 0.23612062 0.13508699
# [25] 0.48944306

The list3 is based on the two previous lists, i.e, the first element of list1 is the number associated with the pvalue of first element of list2. Therefore, the list3 includes all the pvalues corresponding to the same number, for example all the pvalues for number 2. Until now, I was interested in building a list of matrices where the elements of list1 were substituted by sampling of elements from list3 with the same number. My command to do it was:
list4 <- lapply(list1, function(x) sapply(x, function(i, l)
  sample(l[[as.character(i)]], 10, replace=T), l=list3))

And this command gave me this kind of output
list4[[2]]
#           [,1]       [,2]      [,3]      [,4]
# [1,] 0.7983852 0.29404183 0.2416229 0.3018420
# [2,] 0.7398054 0.41266109 0.9253389 0.3249007
# [3,] 0.1150981 0.24138907 0.4040050 0.8335943
# [4,] 0.4564887 0.28336511 0.2520307 0.5460348
# [5,] 0.2810911 0.92870457 0.6865136 0.4851188
# [6,] 0.6396584 0.68957506 0.8336891 0.1355544
# [7,] 0.3365557 0.01609222 0.2504679 0.1974983
# [8,] 0.2307067 0.99999000 0.8328432 0.6538944
# [9,] 0.9999900 0.84980684 0.5590235 0.2566799
# [10,] 0.5791690 0.27672559 0.3584696 0.8335943

However, now I want to build the permutations for each cluster but avoiding to sample the pvalues of that cluster in list3. Thus, and as an example, for list1['cluster.1] I'd like to remove from list3 the pvalues from list2['cluster.1'] and the same for the rest of clusters in list1.
Any help would be very appreciated.
Many thanks
UPDATE,
Following comments I will update the process to get these lists and the final desire output. These lists come from a data.frame with ~17,000 rows and 3 columns, and example looks like this:
 head(pvals)
#    gene        pval mac
#1   A1CF 0.896076585  26
#2  ABCC2 0.376808322 571
#3   ABI1 0.048601644  27
#4 ABLIM1 0.729589080  63
#5 ACADSB 0.001609905  50
#6  ACBD5 0.446628090  11

The list3 comes from the split of column mac in the pvals data.frame:
split.mac = split(pvals, pvals[,3])
mac.pval = lapply(split.mac, '[[', 2)
pvals.order <- pvals[order(pvals$mac),]

Then, I generate a list containing each element at least 100 genes
l3 <- list()
ll1 <- length(mac.pval)
length(l3) <- ll1
set.seed(4)
for (i in 1:ll1) {
  vec1 <- mac.pval[[i]]
  jl <- 1; jr <- 1;
  while (length(vec1) < 100) {
    if(i==1 || i-jl==0) {
      vec1 <- c(vec1, mac.pval[[i+jr]])
      jr <- jr+1
    } else if (i==ll1 || jr+i==ll1 ) {
      vec1 <- c(vec1, mac.pval[[i-jl]])
      jl <- jl+1
    } else {
      vec1 <- c(vec1, mac.pval[[i-jl]], mac.pval[[i+jr]])
      jl <- jl+1
      jr <- jr+1
    }
  }
  l3[[i]] <- vec1
}

names(l3) <- names(mac.pval)
list3 <- l3

clusters <- strsplit(readLines("clusters.txt"), "\t") # the output is a list with gene names

Then, the list1 and the 'list2are generated matching thepvalues` data.frame
list2 <- lapply(clusters, function(x) {
  pvals[match(as.character(unlist(x)), as.character(pvals[[1]])), 2]
}) # the output is a list with the `mac` column of `pvals`

list1 <- lapply(clusters, function(x) {
  pvals[match(as.character(unlist(x)), as.character(pvals[[1]])), 3]
}) # the output is a list with the `pval` column of `pvals`

Finally, using the list3 and the list1 I obtain a list (list4) with number of permutations being rows and columns the number of elements in that cluster. So far, I was interested in sampling in the whole group of genes with the same mac, but now I would like to remove from each of the samplings the pvalues corresponding at the cluster for that sampling.
The function I've used for permutation is this:
list4 <- lapply(list1, function(x) sapply(x, function(i, l) {
  sample(l[[as.character(i)]], 10, replace=T)
}, l=list3))

Hope this update help to get an answer,
Thanks a lot

A: What you want is maybe not that difficult - what is difficult is wading through your long and confusing explanation. Would this work?
list4 <- lapply(list1,
  function(x) sapply(x, function(i) {
    sample_from <- setdiff(list3[[as.character(i)]], list1[[as.character(i)]])
    sample(sample_from, 10, replace=T)
}))

In general, you are probably going about this the wrong way. For example, why bother generating lists 1 and 2? You already have the data in your data frame, so work there.
I think what you aim to do is sample from list3 for each unique value of list1. And list3 is a bunch of pvals. So my guess is you want to do something much simpler like:
list4 <- list()
for (mac in unique(pvals$mac)) {
    list4[[mac]] <- sample(pvals$pval[pvals$mac==m], 100, replace=FALSE)
}


text:
Q: C# await & Task.Run      private void button1_Click_1(object sender, EventArgs e)
     {
         webBrowser1.Navigate("http://www.naver.com");
     }

     private void button2_Click_1(object sender, EventArgs e)
     {
         HtmlWindow wf = webBrowser1.Document.Window.Frames[0];
         string s = wf.Document.Body.OuterHtml;
         MessageBox.Show(s);
     }

.. this does work... but i need to click two buttons.
i want to make thoes together. and i wrote below codes...
the error comes out on second line(nullReferenceException). it seems that await doesn`t work
can anybody help??
     private async void button2_Click_1(object sender, EventArgs e)
     {
         await Task.Run(() => webBrowser1.Navigate("http://www.naver.com"));
         HtmlWindow wf = webBrowser1.Document.Window.Frames[0];
         string s = wf.Document.Body.OuterHtml;
         MessageBox.Show(s);
     }

A: Navigate starts the downloading. It returns before the downloading is completed. You'll have to wait for event WebBrowser.DocumentCompleted
By the way, because Navigate does not wait until loaded it is fast, there is no need to call it asynchronously, otherwise Microsoft would have made an async version like in the WebClient task.
private void button2_Click_1(object sender, EventArgs e)
{
    webBrowser1.Navigate("http://www.naver.com");
}

private void OnDocumentCompleted(object sender, ...)
{
    HtmlWindow wf = webBrowser1.Document.Window.Frames[0];
    string s = wf.Document.Body.OuterHtml;
    MessageBox.Show(s);
}

A: If you want the button2 to perform automatically on button1 event, then you can use the Button.PerformClick Method
So, your code goes this way:
 private void button1_Click_1(object sender, EventArgs e)
 {
     webBrowser1.Navigate("http://www.naver.com");
     button2.PerformClick();
 }

 private void button2_Click_1(object sender, EventArgs e)
 {
     HtmlWindow wf = webBrowser1.Document.Window.Frames[0];
     string s = wf.Document.Body.OuterHtml;
     MessageBox.Show(s);
 }

If you want to make work together, then you can set those button click events on Form Load using the Load event
public Form1()
    {
        InitializeComponent();
        Load += button1_Click;
        Load += button2_Click;;
    }


text:
Q: Return all properties of an object in Objective-C Is it possible to return a list of all the properties implemented by an object in Objective-C?
I understand the properties are just getters and setters so I'm not sure how it would work. If this cannot be done, then is it possible to return all the selectors that an object will respond to? I'm looking for something similiar to the "methods" method in Ruby.

A: // Get properties list
objc_property_t* class_copyPropertyList(Class cls, unsigned int *outCount);
// Get methods list
Method* class_copyMethodList(Class cls, unsigned int *outCount);

The following code will output all methods implemented in UIImage class to console:
unsigned int count;
Method* methods = class_copyMethodList([UIImage class], &count);
for (size_t i = 0; i < count; ++i)
   NSLog([NSString stringWithCString:sel_getName(method_getName(methods[i]))]);
free(methods);

A: I was actually trying out this yesterday and it is possible, however you cannot get everything from UIView.
 Take a look at the Objective-C Runtime Reference


text:
Q: W/System.err: org.json.JSONException: Value http of type java.lang.String cannot be converted to JSONArray A script on my server returns an array of SQL rows. An appropriate curl returns string which is correct:
[{"ID":"1","DATETIME":"2021-05-30 21:29:27","SETPOINT":"45.22","LUMIN":"65.98","DIRECTION":"LOG"},{"ID":"1","DATETIME":"2021-05-30 15:55:34","REVS":"2.11934","ROTATION":"1","DIRECTION":"LOG","POSITION":"12"}]

However, while parsing it in my Android application, I am getting an error org.json.JSONException: Value http of type java.lang.String cannot be converted to JSONArray. Closer investigation (Toast printing) to what is passed indicated that the application is receiving the remote script's address http://<ip>/readLatest.php, and not the array, as seen with the curl query.
What seems to be a problem? Other answers as to similar questions were not helpful
Async task:
public class DataGetter extends AsyncTask<String, Void, String[]> {

    Context context;
    private GetListener GetListener;
    public String jsonString;
    public boolean passed_successfully;

    DataGetter(Context ctx, GetListener listener) {
        this.context = ctx;
        this.GetListener = listener;
        this.passed_successfully = false;
    }

    @Override
    protected String[] doInBackground(String... params) {
        String ip = params[0];
        String scriptname = params[1];
        String db = params[2];
        String urladress = "http://" + ip + "/"+ scriptname +".php";

        try {
            URL url = new URL(urladress);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);

            OutputStream os = connection.getOutputStream();
            OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");

            String data = URLEncoder.encode("database", "UTF-8") + "=" + URLEncoder.encode(db, "UTF-8");

            writer.write(data);
            writer.flush();
            writer.close();

            BufferedReader reader = new BufferedReader(new
                    InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                break;
            }
            connection.disconnect();

            return new String[] {sb.toString(), scriptname};
        } catch (Exception e) {
            return new String[] {e.getMessage()};
        }
    }

    @Override
    protected void onPostExecute(String... result) {
        GetListener.passJSONGet(result);
    }
}

Part of appropriate Activity:
@Override
    public void passJSONGet(String... result) {
        String jsonstring = result[0];
        try {
            showToast(jsonstring);
            this.jsonArray = new JSONArray(jsonstring);
            this.printControls(jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void printControls(JSONArray jsonArray) throws JSONException {
        String lumin = jsonArray.getJSONObject(1).getString("LUMIN");
        this.luminval.setText(String.format("%s", lumin));
        int position = Integer.parseInt(jsonArray.getJSONObject(0).getString("POSITION"));
        this.positionval.setText(String.format("%s", position));
    }


text:
Q: Pass the same value in structs in c I have this code which is basically some logical gates and I want the user to give the input values and just the program to print the output.The problem is I wnat two gates to have the same inputs and so I want to give the same values to funcs_ptr[3]->in2 and
funcs_ptr[4]->in1.
#include <stdio.h>
#include <stdlib.h>

typedef int (*CallBack)(int, int);
int myand (int a, int b);
int myor(int a, int b);
int mynand (int a, int b);
int mynor(int a, int b);
int myxor(int a, int b);
typedef struct gate
{
    CallBack f;
    struct gate * in1 ;
    struct gate * in2 ;
} Gate;

int getinput()
{
    int x;
    scanf("%d", &x);
    return x;
}

Gate * creategate(CallBack f)
{
    Gate * temp ;
    temp = malloc(sizeof (Gate));
    temp->f = f;
    temp->in1 = NULL;
    temp->in2 = NULL;
    return temp;
}

int eval(Gate *x)
{
    int a, b;
    if (x->in1 != NULL)
        a = eval(x->in1);
    if (x->in2 != NULL)
        b = eval(x->in2);
    if (x->in1==NULL && x->in2 == NULL)
        return (x->f)(0,0);
    else
        return (x->f)(a,b);
}
int main( )
{
    int i;
    CallBack funcs[] = {mynor, myand, myor, mynand, myxor};
    Gate * funcs_ptr[6  ], * inputs_ptr[6];
    for(i=0;i<5;i++)
        funcs_ptr[i] = creategate(funcs[i]);
    for(i=0;i<6;i++)
        inputs_ptr[i] = creategate(getinput);
    for(i=0;i<3;i++)
    {
        funcs_ptr[i]->in1 = inputs_ptr[i];
        funcs_ptr[i]->in2 = inputs_ptr[i+1];
    }

    funcs_ptr[3] = creategate(funcs[3]);
    funcs_ptr[3]->in1 = funcs_ptr[0];
    /*--*/funcs_ptr[3]->in2 = funcs_ptr[1];

    funcs_ptr[4] = creategate(funcs[4]);
    /*--*/funcs_ptr[4]->in1 = funcs_ptr[1];
    funcs_ptr[4]->in2 = funcs_ptr[2];

    funcs_ptr[5] = creategate(funcs[3]);
    funcs_ptr[5]->in1 = funcs_ptr[3];
    funcs_ptr[5]->in2 = funcs_ptr[4];

    printf(">>>%d\n", eval(funcs_ptr[5]));
    return 0;
}

int myand (int a, int b)
{
    return a * b;
}

int myor(int a, int b)
{
    return a+b>0;
}

int mynand (int a, int b)
{
    return myand(a,b)==0;
}

int mynor(int a, int b)
{
    return myor(a,b)==0;
}

int myxor(int a, int b)
{
    if(a!=b) return 1;
    return 0;
}

But when I run  the code the eval function calls getinput() two times instead of just passing the same value.
How can I pass the same value to both structs?


text:
Q: Why does my code delete everything in the folder? I wrote code to detect all the .exe files in a directory but instead it deletes everything in the folder. How can I change the code to make it delete only the .exe files?
import os
import shutil

dir_name = "/Users/plapl/Downloads/"
source = os.listdir("/Users/plapl/Downloads/")

for files in source:
    if files.endswith(".exe"):
        shutil.rmtree(dir_name, files)

A: You can only delete directories with shutil.rmtree but not files (See https://docs.python.org/3/library/shutil.html#shutil.rmtree).
You should use pathlib or os instead.
os.remove(f'{dir_name}/{files}')

pathlib.Path(f'{dir_name}/{files}').unlink()

A: shutil.rmtree removes the entire directory specified by its first argument. The second argument to shutil.rmtree is ignore_errors, telling the function whether to ignore errors that occur. It is not a file to remove.
shutil.rmtree is a completely inappropriate tool for the job you want to do. You need something like os.remove.


text:
Q: supermarket dataclasses from dataclasses import dataclass
from typing import Union

@dataclass
class OtherStock:
    name:str  = "gold"
    units:int = 7
    price_per_unit : float = 150000

@dataclass
class FoodStock:
    name:str = "bread"
    units:int = 2
    price_per_unit: float = 700
    expiration_date: str = "2021-02-16"

stock = Union[OtherStock,FoodStock]

def is_expired(inventory:stock,date:str)->bool:
    if type(inventory) == OtherStock:
        return False
    if date == inventory.expiration_date:
        return True
    else:
        return False

print(is_expired("bread","2021-02-16"))
print(is_expired("gold","2021-02-16"))

The code should compare both attributes in date and expiration_date and should return True if the product is expired. OtherStock can't expire so it returns false every time. If I try to run it I get an AttributeError: 'str' object has no attribute 'expiration_date'.

A: Your code passes strings to is_expired, not objects. "bread" is a string.
Maybe you want print(is_expired(FoodStock(), "2021-02-16"))?

A: Like you said, the problem is with inventory.expiration_date, and like the error says, inventory is a str. And the first arguments you pass ("bread" and "gold") are indeed strings.
You'll need to create your stock objects first. Python won't do it for you. However, according to documentation, Python automatically creates initialisers for us. That's the FoodStock(...) and OtherStock(...) calls you see below.
today = "2021-02-16"
print(is_expired(FoodStock(name="bread", expiration_date="2021-02-12"), today))
print(is_expired(OtherStock(name="gold"), today))

Here, we used keyword arguments to specify individual fields.
You may also want to consider checking date >= inventory.expiration_date instead of ==.


text:
Q: Start with a tooltip displayed and area highlighted? Great plugin with awesome documentation.
I want to know if there is a way to have the map load with an area already highlighted, and a tool-tip for that area already displayed.
Here's my fiddle:
 See My Fiddle Code
If it could start with the key northwest highlighted (not selected) and a tooltip that would be great.
has been messing with it for a bit but can't figure this out.
Thanks in advance!

A: It works in this ImageMapster demo when I add this:
SEE FIDDLE
    $(function(){

         $('area[state="OR"]').mapster('set',true);

    });

For your Fiddle I could also do it. Like this

.mapster('set', true, 'northwest');

Your fiddle

A: You can try using the .ready() function in to fire events as soon as the page finishes loading.
$(document).ready(function() {
  // Handler for .ready() called.
});

Inside this you can call the function which is called when your mouseover event is triggered. You can just specify the northwest item to be selected.


text:
Q: UIView animation with multiple animation I wrote this a series of code that move the UIIMAGE from CENTER to LEFT position then will appear two textfields afterward too. The animation worked fine however that UIIMAGE will move back to the original (CENTER) location after I tapped on either one textfield. Please advise.
Here my code:
-(void)moveLogoLeft{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationDelay:0.0];
img_CPLLogo.frame = CGRectMake(130.0f, 230.0f, img_Logo.frame.size.width, img_Logo.frame.size.height);
[UIView commitAnimations];

}
and making a `UIButton' to trigger the action
-(IBAction)doShowTextfield:(id)sender{
[UIView animateWithDuration:0 animations:^{
[btm_welcome setAlpha:0];
img_Logo.frame = CGRectMake(100.0f, 230.0f, img_Logo.frame.size.width, img_Logo.frame.size.height);

}completion:^(BOOL completed){
    [self showTextfield];
}];
}
}

What's wrong with this?

A: Use UITextField's delegate method for your requirement:
 - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
 {
   [UIView animateWithDuration:0 animations:^{
   [
      //do your requirement here
   }completion:^(BOOL completed){
      //do anything more here
   }];
   }
 }


text:
Q: Do phrasal verbs depend on understanding English? I was wondering if phrasal verbs depend on understanding English.
Do native speakers just memorize phrasal verbs they've been hearing over their lives, or they can create new phrasal verbs while talking because they understand English well?

A: Phrasal verbs are associated with idiomatic expressions. They are the "verb" part of a "phrase", and that phrase is usually an idiomatic expression. An idiom, by definition, takes on a meaning different from the words making up the idiom. So, no, we don't make up new idioms on the spot. The listener would not understand what's meant. The phrase (the idiom) needs to simply be learned.
For example, when a car "breaks down," it is not literally moving "down" and it did not visibly split into pieces (break). That phrase is an idiom meaning that the car no longer functions as a car should. It's no longer able to travel. The "break down" might be due to a flat tire, or might be due to the cylinder head gasket. Either way, the car doesn't run; it can't travel.


text:
Q: Add Hyperlink as Label to UserForm I have UserForm and want to add a Label as a HyperLink.
If the user clicks on the label the link www.stackoverflow.com should be opened.
The web-address is stored in Cell A1 in Sheet1.
Sub UserForm_Activate()
Label1.Caption = Sheet1.Range("A1").Value
End Sub

So far I used the VBA above. It displays the link from the cell as Label.
However, I cannot click it and use it as Hyperlink.
How do I need to modify it to make it work?
Is it also possible to give the Label a separate description instead of the web-address (similar to what the HYERPLINK formula in Excel does)?

A: You can try either the Click or DblClick event, set the caption to your "separate description" then put the below code in your userform
Private Sub Label1_Click()
    ThisWorkbook.FollowHyperlink Sheet1.Range("A1").Value
End Sub

Or
Private Sub Label1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    ThisWorkbook.FollowHyperlink Sheet1.Range("A1").Value
End Sub


text:
Q: I used openMP directive on matmul function it does not work I am trying to use openMP in a matmul function, but it does not work...
In this part I tried everything, but it takes over 60 min to complete and it does not reduce any time.
What am I supposed to do?
int matmul( int l, int m, int n, float *A, float *B, float *C )
{
    int i, j, k;
    omp_set_dynamic(0);
    #pragma omp parallel for shared(A,B,C) private(i, k, j) num_threads(4)
    for( i=0; i<l; i++ )                // Loop over the rows of A and C.
      for( k=0; k<n; k++ )              // Loop over the columns of B and C
      {
        // Initialize the output element for the inner
        // product of row i of A with column j of B
        C[i*n+k] = 0;
        for( j=0; j<m; j++ )                // Loop over the columns of A and C
        {
          C[i*n+k] += A[i*m+j] * B[j*n+k];  // Compute the inner product
        }
      }
    }
}   // Added by edit!

Can anyone help me with this?

A:
What am I supposed to do?

Use an optimized matmul from a BLAS library, rather than trying to write your own.
Optimizing matrix multiplication is non-trivial (you haven't considered vectorization or tiling yet, and both are needed to get high performance).
If you are on an Intel processor, Intel Math Kernel Library is now free for anyone for any use and is highly optimized, or there are other implementations freely available.
I realize that reading a manual is less fun than writing code, but in this case it's also much more effective!
(In case it matters to anyone, I work for Intel, but this advice is entirely general :-))


text:
Q: Insert data from text delimiter | file into SQL Server table in python script I have a delimited file like this:
    name1|9|111|replace|12|sds22|dsd|GDS-sw-E|1|1|0|No|21|43|No|0.1
    name1|9|222|replace|33|dfs|SWR|RRR-ddd@-S1|1|1|0|No|33|4|None|0.9

I want to import this data into SQL Server using Python code.
This is my code:
import pyodbc

def sql_conn():
    conn = pyodbc.connect('Driver={SQL Server};'
                          'Server=servername\\dbname,1433;'
                          'Database=dbname;'
                          'UID=uname;'
                          'PWD=pass;'
                          'Trusted_Connection=no;')
    cursor = conn.cursor()
    SQLCommand = (
        "INSERT INTO dbname.schema.table VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
    print(SQLCommand)
    Values = ['name1', '9', '1111', 'replace', '12', 'sds22', 'dsd', 'GDS-sw-E',
               '1', '1', '0', 'No', '21', '43', 'None', '0.1']

    print(Values)
    # Processing Query
    cursor.execute(SQLCommand, Values)

    conn.commit()
    print("Data Successfully Inserted")
    conn.close()

if __name__ == "__main__":
    sql_conn()

Currently I have to manually put values in variable, I am looking to automate this to read the data from the delimited file and insert it into the SQL Serve database.

A: Assuming your lines are composed of strings like this:
line = "name1|9|111|replace|12|sds22|dsd|GDS-sw-E|1|1|0|No|21|43|No|0.1"

Since the delimiter is fixed, you can get the values directly by splitting:
Values = line.split("|")

gives Values as
['name1', '9', '111', 'replace', '12', 'sds22', 'dsd', 'GDS-sw-E', '1', '1', '0', 'No', '21', '43', 'No', '0.1']

Basically, just loop over the lines and split them around the delimiter and then pass in your SQL insert statement. Something like:
cursor = conn.cursor()
SQLCommand = (
    "INSERT INTO dbname.schema.table VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
)
lines = f.readlines() # assuming you opened your file with 'f = open("file.txt", "r")'
for line in lines:
    Values = line.split("|")
    cursor.execute(SQLCommand, Values)
    conn.commit()
    print("Data Successfully Inserted")
conn.close()


text:
Q: Rails Tutorial 3.3.4 - "mv: foobar: No such file or directory" I am following Hartl's Tutorial and am confused as to why I am getting this error. I am trying to eliminate duplication in my code by embedding ruby in my layouts. To do this, I follow the tutorial's instructions and I enter the command:
$ mv foobar app/views/layouts/application.html.erb

and in return, I see:
mv: foobar: No such file or directory

My questions are:
1) What does "foobar" mean?
2) How do I fix/get past this error?
Please let me know if this requires more context and/or code. Thanks.

A: foobar is a generic name. It is most likely used as a placeholder.
mv is a command that moves a file from a source to a destination
mv <source> <destination>

This means that tutorial tells you to move the file foobar to app/views/layouts/application.html.erb.
Obviously you don't have a file named foobar. Either you have to create it or it stands for another file that you already have.


text:
Q: React Hooks: Too many re-renders on switch mode I'm trying to improve my switch theme code but I have the following error:

Error: Too many re-renders. React limits the number of renders to
  prevent an infinite loop.

My code:
export default function App() {
  const theme = useTheme();

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <button
          css={css`
            background: red;
            width: 100px;
            height: 50px;
            border-radius: 10px;
          `}
          onClick={theme.setTheme(
            theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
          )}
        >
          a
        </button>
      </div>
    </ThemeProvider>
  );
}

My hook:
   export default function useTheme(defaultTheme = lightTheme) {
  const [theme, _setTheme] = useState(getInitialTheme);

  function getInitialTheme() {
    const savedTheme = localStorage.getItem('theme');
    return savedTheme === 'dark' ? darkTheme : defaultTheme;
  }
  useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(theme.type));
  }, [theme]);

  return {
    ...theme,
    setTheme: ({ setTheme, ...theme }) => {
      if (theme.type === 'dark') {
        return _setTheme(darkTheme);
      } else {
        return _setTheme(lightTheme);
      }
    },
  };
}

I would also like to know how I could get what was sent on my setTheme.

A: Change
onClick={theme.setTheme(
        theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
      )}

To
onClick={() => theme.setTheme(theme.type === 'dark' ? { type: 'light' } : { type: 'dark' })}

In your code, you are immediately executing setTheme during render and it is causing  another render and recursively endless rendering, which is stopped by react. onClick prop expects a function as the value, that function will be executed during click.


text:
Q: Module 'Tabula' not found in python spyder I tried to run this code:
from tabula import read_pdf
df = read_pdf("../pdf/Documentacao.pdf")
print(df)

And got this:
runfile('C:/Users/Henri/git/Git/PDS1/dev/lib/planilhas01.py', wdir='C:/Users/Henri/git/Git/PDS1/dev/lib')
Traceback (most recent call last):

File "<ipython-input-4-e12a8a26bbfa>", line 1, in <module>
runfile('C:/Users/Henri/git/Git/PDS1/dev/lib/planilhas01.py', wdir='C:/Users/Henri/git/Git/PDS1/dev/lib')

File "C:\Users\Henri\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)

File "C:\Users\Henri\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/Henri/git/Git/PDS1/dev/lib/planilhas01.py", line 1, in <module>
from tabula import read_pdf

ModuleNotFoundError: No module named 'tabula'

This is what my anaconda says:
(base) C:\Users\Henri>pip install tabula-py
Requirement already satisfied: tabula-py in c:\users\henri\miniconda3\lib\site-packages (1.4.1)
Requirement already satisfied: pandas in c:\users\henri\miniconda3\lib\site-packages (from tabula-py) (0.25.1)
Requirement already satisfied: distro in c:\users\henri\miniconda3\lib\site-packages (from tabula-py) (1.4.0)
Requirement already satisfied: numpy in c:\users\henri\miniconda3\lib\site-packages (from tabula-py) (1.17.2)
Requirement already satisfied: python-dateutil>=2.6.1 in c:\users\henri\miniconda3\lib\site-packages (from pandas->tabula-py) (2.8.0)
Requirement already satisfied: pytz>=2017.2 in c:\users\henri\miniconda3\lib\site-packages (from pandas->tabula-py) (2019.3)
Requirement already satisfied: six>=1.5 in c:\users\henri\miniconda3\lib\site-packages (from python-dateutil>=2.6.1->pandas->tabula-py) (1.12.0)

I think is something about directories, but what ??

A: (base) C:\Users\Henri>pip install tabula-py
Requirement already satisfied: tabula-py in c:\users\henri\miniconda3\lib\site-packages (1.4.1)
I think is installed, just you need to make sure which Python environment yre installing it because maybe is installed in python3 directory, not python2.


text:
Q: OrientDB slow Edge ETL creation I'm new to OrientDB, having had a little experience with Neo4J, and I'm having performance issues when trying to load and create Edges using the OETL.BAT tool. I need to create ~4.4million edges between nodes (roughly 42million, not all are used in this stage of etl). The "Customer" nodes are already loaded, and the edge list I'm loading is very simple (as below) and simply has a source & destination ID for each edge, its intention is to model payments between customers.
At the moment I'm getting a throughput of ~23-30 per second, according to the etl tool. I've resorted to using a CSV file, rather than a JDBC connection to my RDBMS, and I'm in "plocal" mode as well.
Is there any faster way of doing this?  or am I perhaps taking the wrong approach?
Customer - Vertex
CISNumber, Name
PAID - Edge
SourceCISNumber,DestCISNumber, Amount, TransactionCount
{
 "source": { "file": { "path": "/datafiles/PersonalCustomers/Edges.csv" } },
  "extractor": { "row": {} },
 "transformers": [
    {"csv": {} },
    {"merge": {"joinFieldName": "SourceCISNumber", "lookup": "Customer.CISNumber"} },
    {"vertex": {"class": "Customer", "skipDuplicates": true} },
    { "edge":
        {
            "class": "PAID",
            "joinFieldName": "DestCISNumber",
            "lookup": "Customer.CISNumber",
            "unresolvedLinkAction": "SKIP",
            "edgeFields":
                {
                    "Volume": "${input.Transactioncount}",
                    "Value": "${input.Amount}"
                }
        }
    },
    {"field": {"fieldNames": ["SourceCISNumber", "DestCISNumber", "Transactioncount", "Amount"], "operation": "remove" } }
  ],
   "loader": {
    "orientdb": {
       "dbURL": "plocal:/orientdb/databases/Customers",
       "dbType": "graph",
       "batchCommit": 500,
       "useLightweightEdges" : true,
       "classes": [
         {"name": "PAID", "extends": "E"},
       ]
    },
    "indexes": [
         {"class":"Customer", "fields":["CISNumber:long"] }
       ]
  }
}

A: You should put "batchCommit": 1000 in the "loader".
Also "parallel": true in the "config"


text:
Q: Combining if statements and multiple sql queries into one query I have a server where it limits the amount of sql queries you can make per hour, so I'm trying to find a way to combine all 3 of my if statements and sql queries into one sql query, and am wondering if that's possible? Please take a look at my code:
$text1 = "one";
$text2 = "two";
$text3 = "three";

$data = SELECT text FROM tableName WHERE
text LIKE '%$text1%' AND
text LIKE '%$text2%' AND
text LIKE '%$text3%' order by rand() limit 1;

if ($data == null) {
$data = SELECT text FROM tableName WHERE
text LIKE '%$text1%' AND
text LIKE '%$text2%' order by rand() limit 1;
}

if ($data == null) {
$data = SELECT text FROM tableName WHERE
text LIKE '%$text1%' order by rand() limit 1;
}

A: SELECT text,
((text LIKE '%$text1%') + (text LIKE '%$text2%') + (text LIKE '%$text3%')) as `matches`
FROM tableName
HAVING `matches` > 0
ORDER BY `matches` DESC, rand() LIMIT 1

This should sort the values by the number of matches as each expression will be treated as integer 1 on a match or 0 otherwise.


text:
Q: MySQL break out group clause from subquery Here is my query
SELECT
    COALESCE(js.name,'Lead saknas'),
    count(j.id)
FROM
    jobs j
LEFT JOIN
    job_sources js
    ON j.job_source=js.id
LEFT JOIN
    (SELECT
        *
    FROM
        quotes
    GROUP BY
        job_id) q
    ON j.id=q.job_id
GROUP BY
    j.job_source

The problem is that it's allowed for each job to have more than one quote. Because of that i group the quotes by job_id. Now sure, this works. But i don't like the solution with a subquery. How can i break out the group clause from the subquery to the main query? I have tried to add q.job_id to the main group clause, both before and after the existing one but don't get the same results.

A: The GROUP BY in the subquery limits all results from quotes to 1 for a given job_id (MySQL will only return 1 result for each distinct grouping if you just do 'SELECT *', even if there are multiple rows that has that grouping), so you're joining jobs onto job_sources onto a table with only 1 row from quotes for each job_id.
What would happen when the GROUP BY is in the main query, is that it will join the 3 tables, then select 1 of them for each job_id.
Since MySQL can return any 1 of multiple rows, obviously you cannot expect the results to be the same in every case.
If you were to use group functions it should return the same results (try something like SELECT COUNT(*), GROUP_CONCAT(quote_id) FROM quotes).
MS SQL doesn't allow you just to do a 'SELECT *' when doing a GROUP BY (unless you GROUP BY all the fields, which is kind of pointless), since it can return different results for different queries. Being allowed to do this in MySQL means you should know what you're doing.
More specifically MS SQL does not allow you to select fields which you did not group on, unless you use grouping functions on them.

A: You are looking for a simple group by, I think:
SELECT COALESCE(js.name,'Lead saknas'), count(j.id)
FROM jobs j LEFT JOIN
     job_sources js
     ON j.job_source=js.id
GROUP BY COALESCE(js.name,'Lead saknas')


text:
Q: Is there any way to downgrade Xcode project from 8 to 7? I developed task using Xcode v8. But now I need to be able to open it in Xcode v7.
I have needed version of Xcode. But I cannot open Files and perform build.

A: You can use Xcode 7 but you will need to change all the syntax manually. There is no converter available for downgrading.
If your code is completely in Obj-C then it will not be a problem for you, but for swift you will end up with a lot of changes.
If you want to test your functionality you can download lower version simulators and add device with that OS.


text:
Q: Adding a date every few days I have some code that generates fixtures, I am looking to add a fixture date to the code.
$totalRounds = $teams - 1;
    $matchesPerRound = $teams / 2;
    $rounds = array();
    for ($i = 0; $i < $totalRounds; $i++) {
        $rounds[$i] = array();
    }

    for ($round = 0; $round < $totalRounds; $round++) {
        for ($match = 0; $match < $matchesPerRound; $match++) {
            $home = ($round + $match) % ($teams - 1);
            $away = ($teams - 1 - $match + $round) % ($teams - 1);
            // Last team stays in the same place while the others
            // rotate around it.
            if ($match == 0) {
                $away = $teams - 1;
            }

            $rounds[$round][$match] = "$user[$home]~$team[$home]@$user[$away]~$team[$away]";
        }
    }

$team is the amount of teams in the league.
I want to add a variable for every 4 days, and for every round of fixtures generated, I want to add 4 days onto the previous round.
For example, if today is 3rd may, i want 3rd may for first fixture, 7th may for second fixture, 11th may for third fixture.
By fixture i mean round which includes a set of fixtures!
How do I add 4 days to a strotime variable everytime the rounds increase?

A: Have you looked into strtotime? It allows syntax like the following:
$future_date = strtotime('+4 days');
$even_further_in_the_future = strtotime('+4 days', $future_date);
$arbitrary_start_date = strtotime('+4 days', strtotime('May 25th, 2010'));

A: If I understand your question correctly, you just want each round to have an associated date.  You've got an array of $rounds, so could you not just create a correspondingly-keyed array to hold the round dates?
...
$rounds = array();
$roundDates = array();
$curTime = time();
for ($i = 0; $i < $totalRounds; $i++) {
    $rounds[$i] = array();
    $numDays = $i * 4;
    $roundDates[$i] = strtotime("+".$numDays." days",$curTime);
}

foreach($roundDates as $time) echo date("Y-m-d",$time)."\n";
//gives
//2010-05-03
//2010-05-07
//2010-05-11
//etc


text:
Q: Unable to set PHP variables as values for input field in form I have a PHP file which SELECT's all from the row found  based on an SQL query. When I put the echo in a div, I get all information, but when I try to echo it into an input box in a form, it does not shows.
What am I doing wrong?
Please also note that I am aware that I am (most likely) making a lot of mistakes when it comes to security practices or programming standards, but this whole thing (PHPDesktop > https://github.com/cztomczak/phpdesktop) will get packed into an EXE file which will run locally only (no need for an online connection as the SQLite3 DB gets packed in with the EXE), and I am still figuring out how to program this in the first place, so efficient and tidy coding are not high on my list yet ;-)
DO_CUSTEDIT.PHP
$custName = $_POST['custName'];

$query = "SELECT * FROM `CustDB` WHERE CustName LIKE '%$custName%'";

$result = $db->query($query);

while ($row = $result->fetchArray()) {
      $custID = $row['CustID'];
      ......;
}

if (!$result) {
   echo $db->lastErrorMsg();
   $db->close();
   exit;
} else {
   echo $custID;
   echo ......;
   $db->close();
   exit;
}

EDITCUST.PHP / Javascipt

EDITCUST.PHP / HTML
      <form id="editcustform" name="editcustform" action="" method="post">

                  Customer ID

                    <input type="text" name="custID" value="<?php echo (isset($custID)) ? $custID: ''; ?>" readonly/>

            <button id="subeditcust" type="submit" class="mainbtn">Create</button>

            <button id="reseteditcust" type="reset" class="mainbtn">Reset</button>

    </form>

A: <input type="text" name="custID" value="<?php echo (isset($custID) ? $custID: ''); ?>" readonly/>

Replace this line with yours it will work. IA

A: It seems you have two different files, right? DO_CUSTEDIT.PHP and EDITCUST.PHP
The variables are being created on DO_CUSTEDIT.PHP and the when you are creating the HTML code those variables ($custID) are not setted.
Is one file including or requiring the other?

A: EDITCUST.PHP is your first page from you are submitting form to DO_CUSTEDIT.PHP

*

*When you land on EDITCUST.PHP variable $custID is not created

*When the form is submitted through ajax, the ajax returns the data inform of object or array depending on how you are echoing the data from DO_CUSTEDIT.PHP
I would recommend to use json_encode() php function to return inform of array

*To debug the value by logging the data in console (though function console.log())

*After returning the value from ajax, you have to populate the value in form through jquery something like $(input[name="custID"]).val( data.custID )

A: I managed to figure it out!
DO_CUSTEDIT.php / PHP
$results = array($custID, $custName);
echo json_encode($results, JSON_PRETTY_PRINT);

EDITCUST.php / HTML
<input type="text" id="custID" name="custID" value="" readonly/>
<input type="text" id="custName" name="custName" value="" readonly/>

EDITCUST.php / JS


text:
Q: Microsoft teams meeting invitation (push notification) in Spring I read this discussion about Outlook emails:
How to send mail via outlook using spring boot?
And I have similar question. In Outlook it is possible to push notification (calendar meetings, this is not an email).
I can't find any information about managing such push-notifications in Spring.
Can anybody please help me with it?
UPD: sorry I confused the thing that I need is called "teams meeting invitation", it appears in Outlook on the right side, below calendar

A: Copying answer from comments for better understanding
There may not be (I doubt there is) a bespoke spring project for Outlook calendar meeting push notifications.
Please check this doc


text:
Q: Getting 500 Internal Server Error from request Long story short i'm making script for parsing sankakucomplex in search of pictures and downloading them. And everything until this function goes fine
def download_image_from_link(link, auth, number):
    url = f"https:{link}"
    bruh = requests.get(url)
    with open(f"images/{auth}/image{number}.png", "wb") as im:
        im.write(bruh.content)

{link} is something like //v.sankakucomplex.com/data/sample/a5/dc/sample-a5dcd9f21fc80b6bfe5acfa74c3bd936.jpg?e=1648321131&expires=1648321131&m=JqNaW8AUSE-G-jyihn0uiQ&token=hLsB-lYp7bQhgUbkLsZScpch1DBX6JQoFh4T-CglAKA
{auth} and {number} is not important
It just downloads all the puctires from array that i received from other inconsiderable in this situation functions.
And half of links to images starts with http://s. and other half is http://v.
So the thing is when it downloads http://v. files everything is fine, but in when it downloads http://s. it receives
b'\r\n<title>500 Internal Server Error</title>\r\n\r\n
500 Internal Server Error
\r\n
nginx\r\n\r\n\r\n'

Here is the safest links that i could find if you need to check:
for //s. link
https://chan.sankakucomplex.com/ru/post/show/30856755
for //v. link (requests for //beta. doesnt work too)
https://beta.sankakucomplex.com/ru/post/show/30856755


text:
Q: redirect to other page once click close the current page in asp.net I am new to JavaScript Programming. What I want to do is the following:
I am opening popup window for the user to print something. once he finishes, he will close the page. I want the portal to open another page once he closes this page. I tried the following:
<body onbeforeunload="window.open('BondData.aspx');">

but it does not work. Can you please guide me to an idea where I can get this working?
Thanks in advance

A: try this:
Add this code on page on which you going to close
<script >
window.onbeforeunload =

  function ()
    {

    window.open('NewPage.aspx');
    };
</script >


text:
Q: Ionic/AngularJS dependency injection - factory with return functions I would like to inject all factories to my controllers using one name...so in order to do that, I did this:
.factory('Injection', ['ActionSheetFactory', 'ResourceFactory', 'ModalFactory', 'ResponseFactory',
        function (ActionSheetFactory, ResourceFactory, ModalFactory, ResponseFactory) {
            return {
                ActionSheetFactory: ActionSheetFactory,
                ResourceFactory: ResourceFactory,
                ModalFactory: ModalFactory,
                ResponseFactory: ResponseFactory
            }
        }])

And then in controller:
angular.module('app.controllers', ['app.services'])

.controller('categoriesCtrl', ['Injection', function (Injection, $ionicActionSheet, $state) {

    Injection.ActionSheetFactory.action($ionicActionSheet, $state);
    ...

}])

Problem:
My factories look like this:
 .factory('ActionSheetFactory', function () {
        return {
            action: function ($ionicActionSheet, $state) { ... }
            action2: function(){}
               }
         })

So I have several functions inside each defined factory. And once I try to get to it, I get error Cannot read property 'action' of undefined. How can I fix that?


text:
Q: Restart with PM2 API, restarts also the script self, when running in PM2 I want to make a script in Javascript which controlls PM2 via the PM2 API, and also runs in PM2.
pm2.js
var pm2 = require('pm2');

setTimeout(() => {
  restartProcess('client');
}, 2000); //After 2 seconds restart the 'client' process

function restartProcess(name) {

  pm2.connect(function(err) {
    if (err) {
      console.error(err);
      process.exit(2);
    }
    console.log ("restarting ",name)
    pm2.restart(name);

  pm2.disconnect;
  })

}

When I run pm2.js only in the terminal, this works okay.
But when I run pm2.js inside PM2, the script keeps looping.
I checked the uptime of the processes, it seems that not only client restarts but also pm2.js itself restarts, and after 2 seconds again, and again, and again...
If I'm lookings at pm2 logs pm2 I see there in de stdout the pm2 list table. Which I don't see if I run pm2.js from the terminal.
I don't understand why this happens, and is there a workarround to fix this?

A: Why would you want to do that?

PM2 is a daemon process manager that will help you manage and keep your application online 24/7

Please check the official document first. PM2 was designed to manage long-running tasks, somethings like a web server. If the web server crashes or exits by any reasons, pm2 will interfere and wake it up again. That's the default behavior.
Your pm2.js just run in a short time (2 seconds) then exit. So if you start it with PM2, it will be started again and again...
There is no reason to run that script inside PM2. If you still want, then run it with --no-autorestart flag.

A: You can send SIGKILL to your service, then PM2 will start it again.
pm2.connect((err) => {
    pm2.sendSignalToProcessName('SIGKILL', name, (e, p) => {
        pm2.disconnect();
    });
});


text:
Q: genexus 9 submit I'm new here. I've got a trouble using Genexus 9.
Is there any way to disable a submit on Genexus 9 (Java + web). Im using CKEditor and I have to save the text in a variable before getting submit and saved on DB, but first at all Im getting submit and then the textarea is empty and I lose what I have write.
Thanks for your help!! Have a nice day

A: I did not understand the question that you lose the value of the variable, or the moment it is lost.
I give you solutions to common web problems in genexus 9:
1 - The values of web variables are lost if they are not on the page. You have to put them in the form and hide them in a table / div.
2 - Use the WebSession data type to save values. Through events then load or save them.


text:
Q: english-greek language in tccv document class I am using tccv document class in order to create my cv in Greek. For this reason I mainly have two questions: (1) is it possible to print my name in Greek but leave "curriculum vitae" in English; (2) how can I change the fonts?
Here is MWE:
\documentclass[fontsize=10pt]{tccv}
\usepackage[english,greek]{babel}

\begin{document}

\part{\selectlanguage{greek} Nicola Fontana}

\section{Work experience}

\begin{eventlist}

\end{eventlist}
\end{dpcument}

Thanks in advance!
PS: I here you can find the document class

A: I have taken one of the examples in the ZIP file, changing just the name to one of a hero of Greek independence. I left the rest unchanged, for lack of knowledge of Greek.
You can change font, provided you use one that supports Greek, I used GFS Artemisia.
I also changed the nonsensical Zapf Chancery for "Curriculum Vitae".
\documentclass[fontsize=10pt]{tccv}
\usepackage[utf8]{inputenc}
\usepackage[greek]{babel}
\usepackage{gfsartemisia}
\usepackage{xpatch}

% Why on earth using Zapf Chancery? Whoever receives the
% CV will laugh at it.
\xpatchcmd{\part}{\fontfamily{pzc}\selectfont}{}{}{}

\begin{document}

\part[\textlatin{Curriculum Vitae}]{Θεόδωρος Κολοκοτρώνης}

\section{Work experience}

\begin{eventlist}

\item{July 2007 -- Present}
     {eNTiDi software, Travagliato}
     {Management and development}

...