Q: Is it possible to initialize a property in a category before any category method is called? Is it possible to initialize a property in a category?
For example, if I have a mutable array property called nameList in a class.  Is it possible to have a category created for this class to add an object to the array property before any of the category method is called?

A: If I understand you correctly, and others are interpreting your question differently, what you have is:

*

*A class with a property

*A category on that class

And you want to call a particular method automatically before any category method is called on a given instance, that method would "initialise" the category methods by modifying the property.
In other words you want the equivalent of a subclass with its init method, but using a category.
If my understanding is correct then the answer is no, there is no such thing as a category initializer. So redesign your model not to require it, which may be to just use a subclass - as that provides the behaviour you are after.
The long answer is you could have all the category methods perform a check, say by examining the property you intend to change to see if you have.  If examining the property won't determine if an object has been "category initialized" then you might use an associated object (look in Apple's runtime documentation), or some other method, to record that fact.
HTH
Addendum: An even longer/more complex solution...
GCC & Clang both support a function (not method) attribute constructor which marks a function to be called at load time, the function takes no parameters and returns nothing. So for example, assume you have a class Something and a category More, then in the category implementation file, typically called Something+More.m, you can write:
__attribute__((constructor)) static void initializeSomethingMore(void)
{
   // do stuff
}

(The static stops the symbol initializeSomethingMore being globally visible, you neither want to pollute the global name space or have accidental calls to this function - so you hide it.)
This function will be called automatically, much like a the standard class + (void) initialize method. What you can then do using the Objective-C runtime functions is replace the designated initializer instance methods of the class Something with your own implementations. These should first call the original implementation and then an initialize your category before returning the object. In outline you define a method like:
- (id) categoryVersionOfInit
{
    self = [self categoryVersionOfInit]; // NOT a mistake, see text!
    if (self)
    {
       // init category
    }
    return self;
}

and then in initializeSomethingMore switch the implementations of init and categoryVersionOfInit - so any call of init on an instance of Something actually calls categoryVersionOfInit. Now you see the reason for the apparently self-recursive call in categoryVersionOfInit - by the time it is called the implementations have been switched so the call invokes the original implementation of init... (If you're crosseyed at this point just draw a picture!)
Using this technique you can "inject" category initialization code into a class. Note that the exact point at which your initializeSomethingMore function is called is not defined, so for example you cannot assume it will be called before or after any methods your target class uses for initialization (+ initialize, + load or its own constructor functions).

A: Sure, it possible through objc/runtime and objc_getAssociatedObject/objc_setAssociatedObject
check this answer

A: No it's not possible in objective c.Category is the way to add only method to an existing class you can not add properties in to this.
Read this
Why can't I @synthesize accessors in a category?


Q: Regular expression alphanumeric with dash and underscore and space, but not at the beginning or at the end of the string This regex lets me have a string with alphanumeric, dash, underscore, and space chars in my string:
^[a-zA-Z0-9-_ ]+$

However, I need it to prevent string starting and ending by space. How can I do it?


Q: Can @SuppressWarnings("deprecation") apply to the use of a deprecated interface without applying to the whole class? I have some legacy code that implements a deprecated interface. This particular component will soon be deprecated and removed itself so it does not make sense to refactor to address the root cause of the compiler warning. Instead I'd like to suppress it. However, I do NOT want the scope of the suppression to be for the entire class.
The code was originally:
public class Foo
  extends
    Bar
  implements
    DeprecatedBaz,
    Qux { ... }

DeprecatedBaz is an interface which has been marked as @Deprecated and is a third party framework meaning I am unable to remove the @Deprecated. I'd like to suppress the warning but not deprecations for the whole class. Essentially I'd like to write:
public class Foo
  extends
    Bar
  implements
    @SuppressWarnings("deprecation")
    DeprecatedBaz,
    Qux { ... }

However this is invalid syntax and does not parse. So next I had hoped I might be able to do it at the import but this SO post seems to imply it must be done at a class level.
Alternatively I thought potentially applying it to all of the methods that interface dictates must be implemented might address the issue but that did not work either.
So it seems I'm forced to apply the annotation at the class level:
@SuppressWarnings("deprecation")
public class Foo
  extends
    Bar
  implements
    DeprecatedBaz,
    Qux { ... }

I don't like this because if someone edits this class and introduces new code which refers to deprecated code the warning will be swallowed.
Is there a way to limit the scope in this case?

A: The @SuppressWarnings annotation can only be used at the point of a declaration. Even with the Java 8 annotation enhancements that allow annotations to occur in other syntactic locations, the @SuppressWarnings annotation can't be used where you need it in this case, that is, at the point where a deprecated interface occurs in the implements clause.
You're right to want to avoid putting @SuppressWarnings on the class declaration, since that will suppress possibly unrelated warnings throughout the entire class.
One possibility for dealing with this is to create an intermediate interface that extends the deprecated one, and suppress the warnings on it. Then, change the uses of the deprecated interface to the sub-interface:
@SuppressWarnings("deprecation")
interface SubBaz extends DeprecatedBaz { }

public class Foo ... implements SubBaz ...

This works to avoid the warnings because class annotations (in this case, @Deprecated) are not inherited.

A: The purpose of the @Deprecated annotation is to trigger the warning.
If you don't want to trigger the warning, don't use the annotation.


Q: Play with numbers problem from hackerearth ....i'm getting time limit exceed problem You are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R.
Input:
First line contains two integers N and Q denoting number of array elements and number of queries.
Next line contains N space seperated integers denoting array elements.
Next Q lines contain two integers L and R(indices of the array).
Output:
print a single integer denoting the answer.
Constraints:
1<= N ,Q,L,R <= 10^6
1<= Array elements <= 10^9
import java.util.Scanner;

public class PlayWithNumbers {
    public static void main(String[] args) {
        Scanner obj=new Scanner(System.in);
        long n=obj.nextLong();
        long qry=obj.nextLong();
        long arr[]=new long[(int) n];
        for (int i = 0; i <n ; i++) {
            arr[i]=obj.nextInt();
        }
            for (int j = 0; j <qry ; j++) {
                long sum=0;
                double ans=0;
                int L=obj.nextInt();
                int R=obj.nextInt();
                sum=(L+R)/2;
                ans=Math.floor(sum);
                System.out.println((int) ans);
            }
    }
}

A: First: your solution is wrong. The question clearly is stating that L and R are the indexes of the subarray (not the value), and you are using as value to find the mean value.
Second: Scanner class is very easy, need less typing but not recommended as it is very slow. Instead, use BufferReader.
Here is my solution:
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PlayWithNumbers {
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(
                              new InputStreamReader(System.in));

        StringTokenizer st = new StringTokenizer(br.readLine());
        long n=Integer.parseInt(st.nextToken());
        long qry=Integer.parseInt(st.nextToken());
        long arr[]=new long[(int) n];
        st = new StringTokenizer(br.readLine());

        // read every number, adding with previous all numbers and store in the array index
        arr[0] = Integer.parseInt(st.nextToken());
        for (int i = 1; i <n ; i++) {
            arr[i]=arr[i-1]+Integer.parseInt(st.nextToken());
        }

        for (int j = 0; j <qry ; j++) {
            long sum=0;
            double ans=0;
            st = new StringTokenizer(br.readLine());
            int L=Integer.parseInt(st.nextToken());
            int R=Integer.parseInt(st.nextToken());

            // check if the value 1 then don't subtract left value (as in that case there won't be any left value
            // otherwise subtract just left most value from the array
            if (L == 1) {
                sum=arr[R-1]/(R-L+1);
            } else {
                sum=(arr[R-1] - arr[L-2])/(R-L+1);
            }
            ans=Math.floor(sum);
            System.out.println((int) ans);
        }
    }
}

Let me know if you need any clarification.


Q: Why composer runs as root even though it's setuid has been changed to another user I am using official docker php image as base image and installed composer on it. Some snippets from my dockerfile has given below.
RUN  set ex \
  # Install Composer
  && curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin -- --filename=composer \
  && chown www-data:www-data /usr/local/bin/composer \
  && chmod u+s /usr/local/bin/composer

Docker main process runs as root and worker process runs as www-data. When I run composer install on my container the vendor dir and composer.lock etc owned by root as the container's main process runs as root. So I had changed owner of the /usr/local/bin/composer to www-data and set u+s setuid on it. You can see it below.
/var/www/test # ls -al /usr/local/bin/composer
-rwsr-sr-x    1 www-data www-data   1875611 Oct 21 00:56 /usr/local/bin/composer

But when I run composer install still the vendor dir etc created with root owner. What is wrong I am doing ?
-rwxr-x---    1 1000     www-data      2299 Oct 19 06:36 composer.json
-rw-r--r--    1 root     root        276423 Oct 21 01:02 composer.lock
drwxr-x---    4 1000     www-data      4096 Oct 19 06:36 drush
-rwxr-x---    1 1000     www-data       414 Oct 19 06:36 load.environment.php
-rwxr-x---    1 1000     www-data       481 Oct 19 06:36 phpunit.xml.dist
drwxr-x---    3 1000     www-data      4096 Oct 19 06:36 scripts
drwxr-xr-x   50 root     root          4096 Oct 21 01:08 vendor
drwxr-x---    7 1000     nginx         4096 Oct 21 01:02 web

Update-1
The dir where composer keeps vendor directory is bind mounted named volume. My docker-compose file like below:
version: "3.3"

services:

  nginx:
    container_name: ${PROJECT_NAME}.nginx
    build: ./docker/nginx
    image: witbix/nginx
    restart: always
    volumes:
      - drupal:/var/www/${PROJECT_NAME}:cached
    working_dir: /var/www/${PROJECT_NAME}
    environment:
      PROJECT_NAME: ${PROJECT_NAME}
      DOMAIN_NAME: ${DOMAIN_NAME}
      DRUPAL_VERSION: ${DRUPAL_VERSION}
      MYSQL_HOSTNAME: ${PROJECT_NAME}.mariadb
      MYSQL_DATABASE: ${MYSQL_DATABASE}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}
      MYSQL_PORT: ${MYSQL_PORT}
      HOST_USER: ${USER}
    labels:
      - "traefik.frontend.rule=Host:${DOMAIN_NAME}"
    networks:
      - drupal

  php:
    container_name: ${PROJECT_NAME}
#    build: ./docker/php
    image: witbix/php
    restart: always
    volumes:
      - drupal:/var/www/${PROJECT_NAME}:cached
    working_dir: /var/www/${PROJECT_NAME}
    environment:
      GITHUB_TOKEN: ${GITHUB_TOKEN}
    networks:
      - drupal

  mariadb:
    container_name: ${PROJECT_NAME}.mariadb
#    build: ./docker/mariadb
    image: witbix/mariadb
    restart: always
    volumes:
      - database:/var/lib/mysql
    environment:
       MYSQL_USER: ${MYSQL_USER}
       MYSQL_PASSWORD: ${MYSQL_PASSWORD}
       MYSQL_DATABASE: ${MYSQL_DATABASE}
       MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
    networks:
      - drupal

volumes:
  drupal:
    driver: local
    driver_opts:
      type: bind
      device: $PWD/code/drupal
      o: bind
  database:
    driver: local

networks:
  drupal:
    external:
     name: ${NETWORK_NAME}

So when I execute mount command on my nginx container It gives me below output.
/var/www/test # mount
    overlay on / type overlay (rw,relatime,lowerdir=/var/lib/docker/overlay2/l/CYKNPHGSOXMLOUVNEOJ6QITFA2:/var/lib/docker/overlay2/l/OOOELOMQBXBBMCRFGVOTTOXUTQ:/var/lib/docker/overlay2/l/SLGSDLE7HYX7AY4JCOWPJIKD73:/var/lib/docker/overlay2/l/RMB5364TWTFBFY6HFZWJVTROKW:/var/lib/docker/overlay2/l/JGNFDDFSDHLKE4E63LME3E7QM3:/var/lib/docker/overlay2/l/STSQQ4PZE25ZTSNMTHBBD6AELJ:/var/lib/docker/overlay2/l/XJLZ5WXZZF55YINJ7TMCDMIL6G:/var/lib/docker/overlay2/l/W3DF5PJFB4H57RBOZ44CLWKGEP:/var/lib/docker/overlay2/l/NKVID7PASLZXXMDWZW6AHFPGOE:/var/lib/docker/overlay2/l/TQQRV5LAYELBLUBS5D6FPHRI3S,upperdir=/var/lib/docker/overlay2/0865874042b7848d173e19593df0f3397f466450f5f3b8f3d33fc79a33c3f336/diff,workdir=/var/lib/docker/overlay2/0865874042b7848d173e19593df0f3397f466450f5f3b8f3d33fc79a33c3f336/work)
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
tmpfs on /dev type tmpfs (rw,nosuid,size=65536k,mode=755)
devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=666)
sysfs on /sys type sysfs (ro,nosuid,nodev,noexec,relatime)
tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,relatime,mode=755)
cgroup on /sys/fs/cgroup/systemd type cgroup (ro,nosuid,nodev,noexec,relatime,xattr,name=systemd)
cgroup on /sys/fs/cgroup/pids type cgroup (ro,nosuid,nodev,noexec,relatime,pids)
cgroup on /sys/fs/cgroup/memory type cgroup (ro,nosuid,nodev,noexec,relatime,memory)
cgroup on /sys/fs/cgroup/net_cls,net_prio type cgroup (ro,nosuid,nodev,noexec,relatime,net_cls,net_prio)
cgroup on /sys/fs/cgroup/devices type cgroup (ro,nosuid,nodev,noexec,relatime,devices)
cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (ro,nosuid,nodev,noexec,relatime,cpu,cpuacct)
cgroup on /sys/fs/cgroup/blkio type cgroup (ro,nosuid,nodev,noexec,relatime,blkio)
cgroup on /sys/fs/cgroup/hugetlb type cgroup (ro,nosuid,nodev,noexec,relatime,hugetlb)
cgroup on /sys/fs/cgroup/cpuset type cgroup (ro,nosuid,nodev,noexec,relatime,cpuset)
cgroup on /sys/fs/cgroup/rdma type cgroup (ro,nosuid,nodev,noexec,relatime,rdma)
cgroup on /sys/fs/cgroup/freezer type cgroup (ro,nosuid,nodev,noexec,relatime,freezer)
cgroup on /sys/fs/cgroup/perf_event type cgroup (ro,nosuid,nodev,noexec,relatime,perf_event)
mqueue on /dev/mqueue type mqueue (rw,nosuid,nodev,noexec,relatime)
/dev/vda1 on /etc/resolv.conf type ext4 (rw,relatime,data=ordered)
/dev/vda1 on /etc/hostname type ext4 (rw,relatime,data=ordered)
/dev/vda1 on /etc/hosts type ext4 (rw,relatime,data=ordered)
shm on /dev/shm type tmpfs (rw,nosuid,nodev,noexec,relatime,size=65536k)
/dev/vda1 on /var/www/test type ext4 (rw,relatime,data=ordered)
proc on /proc/bus type proc (ro,relatime)
proc on /proc/fs type proc (ro,relatime)
proc on /proc/irq type proc (ro,relatime)
proc on /proc/sys type proc (ro,relatime)
proc on /proc/sysrq-trigger type proc (ro,relatime)
tmpfs on /proc/acpi type tmpfs (ro,relatime)
tmpfs on /proc/kcore type tmpfs (rw,nosuid,size=65536k,mode=755)
tmpfs on /proc/keys type tmpfs (rw,nosuid,size=65536k,mode=755)
tmpfs on /proc/timer_list type tmpfs (rw,nosuid,size=65536k,mode=755)
tmpfs on /proc/sched_debug type tmpfs (rw,nosuid,size=65536k,mode=755)
tmpfs on /proc/scsi type tmpfs (ro,relatime)
tmpfs on /sys/firmware type tmpfs (ro,relatime)

But executing mount command on my php container doesn't provide any output. It may as I am mounted the local files with nginx and then using that nginx volume with php.

A: The composer program is a ascii text file, and as such the setuid bit has no effect on it.  Since you are kicking off the process as root, you can do something like su www-data -c "composer ...."


Q: Can other words replace "consideration" in "with all due consideration"? The following is a multiple choice question in an English test:

The employers prepared, with all due _______, for a conference with the Trade Union.
A. caution
B. concern
C. certainty
D. consideration

I feel A ("with all due caution") is ok, but I am not sure.

A: The answer is caution. Why? Because I can find the phrase on the internet in a context completely unrelated to multiple-choice questions.

*

*Caution (n.) great care which you take in order to avoid possible danger. E.g. the employers prepared, with all due caution, for a conference with the Trade Unions.

Having found the "answer" by cheating, let me say further that I see no reason why "consideration" isn't an equally good answer.
Whoever prepared this test was _____.
A. incompetent
B. lazy
C. rushed
D. sadistic

A: *

*'C' is almost certainly not the correct answer. It is only acceptable if the intended emphasis is on the employers' correctness in being sure that the meeting will occur.

*'A' is possible, but it ought to be used when there is an actually anticipated danger of some kind.

At first glance 'B' and 'D' are nearly equally acceptable as an answer.  But 'B', concern,  is closer in meaning to 'A', caution, than 'D', consideration, is to 'A'.  So that makes 'B' less appropriate than 'D' in almost all situations.  However it should be noted that this same condition makes 'B' a valid answer when 'A' is valid.
Yes, all the answers are potentially correct, though 'C' is least probable and 'D' is most probable.
I would hope this is not too confusing--I take the first two items (marked by bullet points) as fundamental assumptions.  From there I weight the relative likelihood of each of answers ultimately corresponding to the answer the test writer(s) had in mind.
To put it another way, I start by essentially ruling out C then A.  I conclude that of the remaining answers B is less appropriate than D.

A: In fact, I chose "caution" instead of "consideration" because I feel the phrase  "with..." should be able to be used where "with all due..." is used, though their meanings are not completely the same. They are of basically the same structure and the only difference is that some extra meaning is added in the latter.
Now compare:
1.They prepared for the conference with caution.
2.They prepared for the conference with consideration(concern).
Aparently, there is nothing wrong with sentence 1. However, something seems to be lacking in sentence 2 and one may wonder: with consideration to what? or with concern for what?
Am I right? Looking forward to your comments.

A: AutoIncrement is correct in saying that options A and B are very similar in meaning and option C is almost certainly wrong.
In my view, this information is enough to deduce that the correct answer is D. Of course, the correct word depends largely on the intended meaning, of which we cannot be certain. However, assuming that this multiple-choice test has exactly one correct answer for each question, we can deduce the following about the correct answer to the test:
Since options A and B are so similar in meaning, it would not be reasonable to award a mark for option A but not for option B, and vice versa. Hence, neither A nor B is correct. Then, since certainty is not a choice and therefore cannot be expected from the employers, to say that they prepared with all 'due' certainty seems absurd to me. We can therefore rule out option C and conclude that D must be the answer the examiner is looking for.


Q: Como agrupar por fecha o número del mes en el mismo campo en sql server Tengo un procedimiento sencillo que recibe 3 parametros (@desde as date, @hasta as date, @agrupa as int) necesito que si @agrupa=0 agrupe el resultado por dias y si @agrupa=1 agrupe el resultado por mes.
SELECT case when @agrupa =0 then DOC_CFECHA
    else MONTH(DOC_CFECHA) end as fecha
    ,total= sum(cantidad)
FROM documentos
WHERE DOC_CFECHA between @desde and @hasta
group by case when @agrupa=0 then DOC_CFECHA else MONTH(DOC_CFECHA) end

Si mando @agrupa en 0 no hay ningún problema, el procedimiento funciona, pero si le envío el 1 para agrupar por mes el resultado de la columna se convierte a formato de fecha así: 1900-01-02 00:00:00.000 en lugar de mostrar el numero del mes.
Intento no usar IF para escribir 2 sentencias ni menos escribir 2 procedimientos separados.
Alguna idea como hacerlo en la misma sentencia?

A: Para poder devolver una sentencia con los mismos datos agrupados, debes devolver la columna con el mismo tipo de dato.
Create table dbo.documentos (Doc_CFecha datetime, cantidad int);

go
insert into dbo.documentos (Doc_CFecha, cantidad)
values
('20201001',2),
('20201101',4),
('20201101',5),
('20201102',6),
('20201001',3),
('20201003',4),
('20201001',1),
('20201101',2),
('20201001',2);
go

Por ejemplo, como varchar
Declare @AGRUPA int = 0;
declare @DESDE datetime = '19000101';
declare @HASTA datetime = '21000101';

SELECT case
            when @AGRUPA = 0 then Convert(varchar(30), doc_cfecha, 120)
            else cast(MONTH(DOC_CFECHA) as varchar(30))
       end as fecha
     , sum(cantidad) as Total
       FROM dbo.documentos
       WHERE DOC_CFECHA between @DESDE and @HASTA
       group by case
                     when @AGRUPA = 0 then Convert(varchar(30), doc_cfecha, 120)
                     else cast(MONTH(DOC_CFECHA) as varchar(30))
                end;

Declare @AGRUPA int = 1;
declare @DESDE datetime = '19000101';
declare @HASTA datetime = '21000101';

SELECT case
            when @AGRUPA = 0 then Convert(varchar(30), doc_cfecha, 120)
            else cast(MONTH(DOC_CFECHA) as varchar(30))
       end as fecha
     , sum(cantidad) as Total
       FROM dbo.documentos
       WHERE DOC_CFECHA between @DESDE and @HASTA
       group by case
                     when @AGRUPA = 0 then Convert(varchar(30), doc_cfecha, 120)
                     else cast(MONTH(DOC_CFECHA) as varchar(30))
                end;


Q: Unable to start Sphinx searchd daemon due to already running searchd process, and it restarts just after killing it When I try to start searchd, it gives the following error.
bind() failed on 0.0.0.0, retrying...
FATAL: bind() failed on 0.0.0.0: Illegal seek

I can find a searchd process running
root     14863  0.1  0.0  73884  3960 ?        Ssl  23:21   0:00 /usr/bin/searchd --nodetach
Now, when i kill it or try to stop it (searchd --stop), it instantly restarts.
root     15841  0.5  0.0  73884  3960 ?        Ssl  23:33   0:00 /usr/bin/searchd --nodetach

I am guessing there is some setting by which it automatically starts when the process is not running. How can I stop this from happening?

A: By default, it seems like the debian package will start Sphinx with an additional keepalive process. I was able to stop it successfully with this;

sudo service sphinxsearch stop

A: the 'init: ... main process ended, respawning' suggests there is something in the init script that sets a watchdog to make sure sphinx doesnt die.
Perhaps you need to shutdown sphinx via the init script itself
/etc/init.d/sphinxsearch stop

A: To my knowledge, Upstart is responsible for respawning searchd after you attempt to stop/kill it.
Since we know that this process is being managed by upstart, we can terminate the daemon using "stop sphinxsearch" and then start it again with "start sphinxsearch".
If you want to kill it normally like any other process, then you can remove the "--nodetach" argument in the config file /etc/sphinxsearch/sphinx.conf. However, by doing this, you can no longer stop the process using "stop sphinxsearch".

A: No, there are no any sphinx option to restart Sphinx.
Probably some monitoring tool like monit installed for Sphinx.


Q: MongoDB aggreagate query to get list of each element and its count for each record In my mongodb, i have few collections, i want to create a new collection by comparing the collection 1 and collection 2 using pymongo.
    Collection 1 :
    Object id       timestamp                          Prof_Name   subjects1
    abc67478898k  ISODate("2018-01-03T09:26:37.541Z")   ABDC      "sub1, sub2, sub3"
    jjjjjjjjjj    ISODate("2018-01-03T09:26:37.541Z")   XYZ       "sub2, sub4, sub8"

    Collection 2 :
    Object id   timestamp               UUID   subjects2            rating score
    3333333    ISODate("2018-01-03TZ")  7897  "sub1,sub4, sub7"     7      10
    444444     ISODate("2018-01-03TZ")  4532   "sub2"               4      6
    777777     ISODate("2018-01-03TZ")  7876  "sub1,sub2,sub3"      8      8
    1111111    ISODate("2018-01-03TZ")   654   "sub1,sub3"          7      8

I'm getting my 3 collection, for each subject by Prof_name find matching subjects in collection2 and the UUID and UUID_count between a certain timestamp and my mongo query is as below:
    db.data1.aggregate([
      {"$lookup":{
        "from":"data2",
        "let":{"subject":{"$split":["$SUBJECT",", "]}},
        "pipeline":[
          {"$match": {"expr":{"$and":[{"$eq":[{"$year":"$timestamp"}, 2016]}, {"$eq":[{"$month":"$timestamp"}, 1]}]}}},
          {"$addFields":{"SUBJECT_ID":{"$split":["$SUBJECT_ID",", "]},"SUBJECT":"$$subject"}},
          {"$unwind":"$SUBJECT"},
          {"$match":{"$expr":{"$in":["$SUBJECT","$SUBJECT_ID"]}}},
          {"$facet":{
            "UUID":[{"$group":{"_id":{"id":"$_id","UUID":"$UUID"}}},{"$count":"UUID_Count"}],
            "REST":[
              {"$group":{"_id":null,"subjects_list":{"$addToSet":"$SUBJECT"},"UUID_distinct_list":{"$addToSet":"$UUID"}}},
              {"$addFields":{"subject_count":{"$size":"$subjects_list"},"UUID_distinct_count":{"$size":"$UUID_distinct_list"}}},
              {"$project":{"_id":0}}
             ]
          }},
          {"$replaceRoot":{"newRoot":{"$mergeObjects":[{"$arrayElemAt":["$UUID",0]},{"$arrayElemAt":["$REST",0]}]}}}
        ],
        "as":"ref_data"
      }},
      {"$unwind":{"path":"$ref_data","preserveNullAndEmptyArrays":true}},
      {"$addFields":{"ref_data.Prof_Name":"$Prof_Name"}},
      {"$replaceRoot":{"newRoot":"$ref_data"}},
      {"$out":"data3"}
    ])

Above query gives me below collection.
    Collection 3 :

     objectid  Prof_name subjects_list  UUID_list           UUID-count subject_count
        12       ABDC      sub1,sub2,sub3 7897,4532,7876,654  4            3
        34       XYZ       sub2,sub4,sub8 7897,4532,7876      2            3

Now i want to get another column for my collection 3 which says list of count for each subject and UUID associated with each subject, something like this
        Collection 3 :
     objectid  Prof_name subjects_list  UUID_list           UUID-count subject_count each_sub_count             UUID-assocaited_sub
        12       ABDC      sub1,sub2,sub3 7897,4532,7876,654  4           3         sub1:3,sub2:2,sub3:2    [sub1:7897,7876,654, sub2:4532,7876, sub3:7876]
        34       XYZ       sub2,sub4,sub8 7897,4532,7876      2           3         sub2:2,sub4:1,sub8:0    [sub2:4532,7876, sub4:7897,sub8:0]

Last 2 column is what i need, how do i achieve this, possible to modify above query and get it or what is the new query to get these columns.

A: Include another pipeline in $facet.
{"$facet":{
  "UUID":[{"$group":{"_id":{"id":"$_id","UUID":"$UUID"}}},{"$count":"UUID_Count"}],
  "COUNT":[
     {"$group":{"_id":null,"subjects_list":{"$addToSet":"$SUBJECT"},"UUID_distinct_list":{"$addToSet":"$UUID"}}},
     {"$addFields":{"subject_count":{"$size":"$subjects_list"},"UUID_distinct_count":{"$size":"$UUID_distinct_list"}}},
     {"$project":{"_id":0}}
  ],
  "SUB":[
     {"$group":{"_id":"$SUBJECT","count":{"$sum":1}," UUID_list":{"$push":"$UUID"}}},
     {"$group":{"_id":null,"each_sub_count":{"$push":{"sub":"$_id", "count":"$count"}},"UUID-assocaited_sub":{"$push":{"sub":"$_id", uuids:"$UUID_list"}}}},
     {"$project":{"_id":0}}
  ]
}},
{"$replaceRoot":{"newRoot":{"$mergeObjects":[{"$arrayElemAt":["$UUID",0]},{"$arrayElemAt":["$COUNT",0]}, {"$arrayElemAt":["$SUB",0]}]}}}


Q: Настройка версии интерпретатора Python в PyCharm PyCharm использует системный Python 2.7, хотя у меня выбран Python 3.9. В настройках интерпретатора Python 2.7 удален.
Но почему то PyCharm все равно используется Python 2.7.
Как просто переключиться на установленный Python 3.9, без создания venv?

Настройка интерпретатора


Q: Facebook Graph API - PHP - Can't post to certain pages Question:  Why is it giving this error and how do I resolve it?
I am using the Facebook Graph API to post a reply/comment to specific posts that I have already created in specific Facebook groups.  I am a currently a member of the group and can reply/comment manually to my post.
The app is not currently "live" in the developer interface.
39 of the 80 some odd posts give this error:
Array ( [error] => Array ( [message] => (#200) Permissions error [type] => OAuthException [code] => 200 ) )
Access Token Code
//Gets Facebook Token ID for use in facebook-poster.php

session_start();
   $app_id = "...";
   $app_secret = "....";
   $my_url = "......";  // redirect url

    $code = $_REQUEST["code"];

   if(empty($code)) {
     // Redirect to Login Dialog
     $_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
     $dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
       . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
       . $_SESSION['state'] . "&scope=publish_stream,publish_actions,read_friendlists,email";

     echo("");
   }
if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) {
     $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;

     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);
     $longtoken=$params['access_token'];
}

echo $longtoken;

?>

Comment Posting Snippet
            $accessToken = "abc";
            $fbId = array ( '1893939', '919191');

            echo "

            ";

            foreach ($fbId as $ID) {

                    $i++; //Increment counter for sleep timer.

                    $attachment =  array(
                            'access_token'  => $accessToken,
                            'message'       => "Message",
                    );

                    // set the target url

                    $url = 'https://graph.facebook.com/v2.2/' . $ID . '/comments';

                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    $go = curl_exec($ch);
                    echo "Facebook ID:  ". $ID ." >> Status:  ". $go ."
";
                    curl_close ($ch);

                    $go = json_decode($go, TRUE);

                    echo "JSON Decode 1:
";
                    print_r($go);

                    if( isset($go['id']) ) {
                        $url = "https://graph.facebook.com/v2.2/{$go['id']}/comments";

                        $attachment =  array(
                                'access_token'  => $accessToken,
                                'message'       => "Bump". rand(0,5000) ."...",
                        );

                        // set the target url
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, $url);
                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
                        curl_setopt($ch, CURLOPT_POST, true);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
                        curl_setopt($ch, CURLOPT_HEADER, 0);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        $comment = curl_exec($ch);
                        curl_close ($ch);
                        $comment = json_decode($comment, TRUE);
                        print_r($comment);
                        echo "

";
                     }

                     if ($i % 20 == 0) { echo "
Sleep

"; sleep(20);  }
            }

        foreach ($fbId as $ID) {
              echo "". $ID ."    |   ";
              if ($i % 10 == 0) { echo "
"; }
            }
}


Q: Conditional probability, 3 variables, lots of unknowns The question is:

Given $P(B|A) = 0.3, P(A) = 0.6, P(B) = 0.4, P(C|B) = 0.4$ find:

*

*$P(A~\text{and}~B)$

*$P(B~\text{and}~C)$

*$P(A~\text{or}~B)$

I am happy with working out the first 2 answers, but I am struggling with the third, the answer has been provided (0.82), but I don't understand how to get there.
I have tried using a tree to help me better understand it, but all I have is:
probability tree

A: $$P\left(A\cup B\right)=P\left(A\right)+P\left(B\right)-P\left(A\cap B\right)=P\left(A\right)+P\left(B\right)-P\left(B\mid A\right)P\left(A\right)$$


Q: Is there a way to get the dual problem of a primal problem in pyomo? I am currently working on robust optimization and here I use the dual problem to make the optimizationn tractable. As I want to start to create larger problems, I don't want to have two optimization programs all the time. Therefore, I was wondering if it is possible to create the dual problem from the primal problem in pyomo, which I can then adjust (add uncertainty set) and optimize.
Until now, I have just found solutions which give you the dual values AFTER optimization. But I am looking for the whole dual problem before optimization.


Q: Is the difference between the addresses of a function's parameters always 4 bytes? I've been doing some pointers testing in C, and I was just curious if the addresses of a function's parameters are always in a difference of 4 bytes from one another.
I've tries to run the following code:
#include <stdio.h>

void func(long a, long b);

int main(void)
{
    func(1, 2);

    getchar();
    return 0;
}

void func(long a, long b)
{
    printf("%d\n", (int)&b - (int)&a);
}

This code seems to always print 4, no matter what is the type of func's parameters.
I was just wondering if it's ALWAYS 4, because if so it can be useful for something I'm trying to do (but if it isn't necessarily 4 I guess I could just use va_list for my function or something).
So: Is it necessarily 4 bytes?

A: Absolutely not, in so many ways that it would be hard to count them all.
First and foremost, the memory layout of arguments is simply not specified by the C language.  Full stop.  It is not specified.  Thus the answer is "no" immediately.
va_list exists because there was a need to be able to navigate a list of varadic arguments because it wasn't specified other than that.  va_list is intentionally very limited, so that it works on platforms where the shape of the stack does not match your intuition.
Other reasons it can't always be 4:

*

*What if you pass an object of length 8?

*What if the compiler optimizes a reference to actually point at the object in another frame?

*What if the compiler adds padding, perhaps to align a 64-bit number on a 64-bit boundary?

*What if the stack is built in the opposite direction (such that the difference would be -4 instead of +4)

The list goes on and on.  C does not specify the relative addresses between arguments.

A: As the other answers correctly say:
No.
Furthermore, even trying to determine whether the addresses differ by 4 bytes, depending on how you do it, probably has undefined behavior, which means the C standard says nothing about what your program does.
void func(long a, long b)
{
    printf("%d\n", (int)&b - (int)&a);
}

&a and &b are expression of type long*. Converting a pointer to int is legal, but the result is implementation-defined, and "If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type."
It's very likely that pointers are 64 bits and int is 32 bits, so the conversions could lose information.
Most likely the conversions will give you values of type int, but they don't necessarily have any meaning, nor does their difference.
Now you can subtract pointer values directly, with a result of the signed integer type ptrdiff_t (which, unlike int, is probably big enough to hold the result).
printf("%td\n", &b - &a);

But "When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements."  Pointers to distinct object cannot be meaningfully compared or subtracted.
Having said all that, it's likely that the implementation you're using has a memory model that's reasonably straightforward, and that pointer values are in effect represented as indices into a monolithic memory space.  Comparing &b vs. &a is not permitted by the C language, but examining the values can provide some insight about what's going on behind the curtain -- which can be especially useful if you're tracking down a bug.
Here's something you can do portably to examine the addresses:
printf("&a = %p\n", (void*)&a);
printf("&b = %p\n", (void*)&b);

The result you're seeing for the subtraction (4) suggests that type long is probably 4 bytes (32 bits) on your system. I'd guess you're on Windows. It also suggests something about the way function parameters are allocated -- something that you as a programmer should almost never have to care about, but is worth understanding anyway.

A:
[...] I was just curious if the addresses of a function's parameters are always in a difference of 4 bytes from one another."

The greatest error in your reasoning is to think that the parameters exist in memory at all.
I am running this program on x86-64:
#include <stdio.h>
#include <stdint.h>

void func(long a, long b)
{
    printf("%d\n", (int)((intptr_t)&b - (intptr_t)&a));
}

int main(void)
{
    func(1, 2);
}

and compile it with gcc -O3 it prints 8, proving that your guess is absolutely wrong. Except... when I compile it without optimization it prints out -8.
X86-64 SYSV calling convention says that the arguments are passed in registers instead of being passed in memory. a and b do not have an address until you take their address with & - then the compiler is caught with its pants down from cheating the as-if rule and it quickly pulls up its pants and stuffs them into some memory location so that they can have their address taken, but it is in no way consistent in where they're stored.


Q: vscode How to change `package scripts` to` launch debug`?
package.json

  "scripts": {
    "start": "node -r dotenv/config index.js dotenv_config_path=.env",

.vscode\launch.json

{
    //  https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "debug",
            "skipFiles": ["<node_internals>/**"],
            "program": "${workspaceFolder}\\index.js",
            "args": ["-r dotenv/config index.js dotenv_config_path=.env"]
        }
    ]
}

I want to debug, but he can't work, How do I configure launch.json?

A: Please check Add Configuration button on lower right corner of launch.json.
Sample npm task configuration generated from same:
{
    "type": "node",
    "request": "launch",
    "name": "Launch via NPM",
    "runtimeExecutable": "npm",
    "runtimeArgs": [
        "run-script",
        "debug"
    ],
    "port": 9229
}

Screenshot:

Adding additional configuration:


Q: solving assignment error in typescript: «Module parse failed» I'm trying to assign a object to initialState variable, the selectedActivity type is Activity | undefined and after Nullish Coalescing operator (??) the emptyActivity is of type Activity.
but when this line execute, it throws an error that says: Module parse failed: Unexpected token You may need an appropriate loader to handle this file type.
Code:
interface Props {
    selectedActivity: Activity | undefined
    closeForm: () => void
}
export default function ActivityForm({ selectedActivity, closeForm }: Props) {
    const emptyActivity: Activity = {
        id: '',
        title: '',
        date: '',
        description: '',
        category: '',
        city: '',
        venue: '',
    }
const initialState = selectedActivity ?? emptyActivity;

and this is Activity interface:
export interface Activity {
    id: string
    title: string
    date: string
    description: string
    category: string
    city: string
    venue: string
}

I'm coding a react project and I want to solve the assignment error.

A: As the error said that your loader can't handle this syntax, maybe it is old, and you need to update it, but as a temporary solution you can convert this syntax to ternary operator syntax and it should work.
const initialState = selectedActivity ? selectedActivity : emptyActivity;


Q: string.c_str() outputs gibberish - but only sometimes I'm writing a short OpenGL-program, and need to import the shader source, which I use the following code for (OpenGL wants the shader source as a c-string):
    std::ifstream t("GLshader.vert");
    if (!t.is_open()) {
        std::cerr << "vertex shader open failed" << std::endl;
    }
    std::stringstream buffer;
    buffer << t.rdbuf();

    const char* source = buffer.str().c_str();
    std::string s = buffer.str().c_str();
    std::cerr << "vs string :" << std::endl << s << std::endl;
    std::cerr << "vs source:" << std::endl << source << std::endl;

What has me really stumped is the fact that sometimes everything is fine, and the last two lines of code output the same text. Sometimes however, for some reason, the output is instead this:
vs string:
/* actual shader code*/
#version 330 core

layout(location=0) in vec3 position;

out vec3 pos;
out vec2 texcoord;

void main(){
  pos = position;
  texcoord = (position.xy +1.f) / 2.f;
  gl_Position = vec4(position, 1.0f);
}

vs source:
@ð4

The printouts, as well as the string, is there because I kept getting shader compilation errors (again, sometimes), and thought it might be some weird concurrency issue with reading the file. Obviously that works fine, but for some reason the c-string creation sometimes fails.
The function is called in a .dll, and I'm using visual studio. (I've run the .exe outside of VS, and the problem occurs there as well)
I'm really out of ideas here, anyone have an answer?


Q: Convince macOS Catalina that there is Internet command-line There are several ways to provide your MacBook Pro with Internet via some obscure socket, typically using OpenVPN, complemented by stubby for dns-over-tls. This works in Terminal
However, other GUI apps refuse to recognize that Internet is available because of how macOS detects connectivity. No custom network service can convince macOS that there is Internet. Only real network services like Ethernet, Bluetooth and Wi-Fi can do this, giving a green dot and “Connected” status in Network Preferences
How can I configure Catalina or issue a command on the command-line that convinces macOS GUI that Internet and dns are available?

scutil --dns | head -8 # displays the dns server used for general queries
# general queries are a vanilla request for any interface
# scoped queries are directed to particular interface
# dns servers comes from networkservices

# network services are evaluated in particular order
networksetup -listnetworkserviceorder

# each network service is associated with a hardware port
networksetup -listallhardwareports
# hardware ports have a magic state of being connected
# if a hardware port is not connected, its dns configuration is ignored

# if you don't have a hardware port, which in this case you do not
# you are not going to have any hardware port that is connected
# therefore there are no dns servers
# therefore no dns queries are executed by macOS

# the trick at the moment is to connect bluetooth to any device
# which means there is hardware port that is connected
# therefore, dns queries are executed
# executed queries are picked up by stubby: success!

# the question here is to compel macOS to execute dns queries anyway
# without a real hardware port
# without such trickery, dns will only work in Terminal that does not use that part of macOS

A:
How can I configure Catalina or issue a command on the command-line that convinces macOS GUI that Internet and dns are available?

macOS (every OS for that matter) doesn’t care about the Internet.  The Internet, to your computer, is nothing special.  It is to you can me, but to your computer, it’s just another network.
As far as DNS goes, it’s not required for Internet access.  As long as you can route packets from one IP addresses to another on the public network called the Internet, you’re connected.  DNS is required for convenience so you can associate a name with an IP.  It makes using the Internet easier.  However, it’s no different than how your local network works - you don’t need a DNS resolver (mDNS), but it sure makes it easier to remember the names of your computers than it is to remember each individual IP.
macOS or your apps (including the GUI) isn’t “aware” of the Internet.  Your GUI has nothing, actually, to do with the network or the Internet.  The GUI will still function whether or not it is connected.  The GUI, however, will make things convenient for you; ;it tells you that you have Internet by (macOS) sending out a simple IGMP packet (like a ping) to a known server and if a response comes back, it tells you that it’s connected to the Internet.  That “little green dot” in Network Preferences is nothing special.  It’s just an indicator for you that you have Network Connectivity (not Internet) and that your Network is working as it should.
The error message in your browser, “ERR NAME NOT RESOLVED” means whatever you typed, DNS was not able to find.  That doesn’t mean your Internet is not working nor are there special or obscure sockets incorrectly configured.   There are any number of reasons that you’ve received that error message from not being connected to the network, to the Internet being down, to having stale DNS entries requiring a flush, etc.  When you run into issues like this, the quickest way to resolve is to simply reboot.


Q: ms-access 2003: form does not open! help! i have an access db with forms, one of the forms is not opening. i double clicked on it, i tried to open in design mode. nothing happens. there's no error message, but nothing happens.
has anyone had this issue before?
i am sorry i actually am getting an error now:
The error said that there wasn't enough memory to open it or something to that effect.

A: Here's the bible for Access corruption issues.
http://www.granite.ab.ca/access/corruptmdbs.htm
First things first: try to decompile and recompile (check the help files on how to do that).  Next, try creating a second database and importing your form from the corrupt one.  Lastly, use SaveAsText and LoadFromText to export and reimport the form.

A: The lack of an error message makes this extra challenging.  OTOH, without an error message, how do you know the form hasn't opened?  Could it be open but hidden?
Try these two commands in the Immediate Window:
DoCmd.OpenForm "YourForm", acNormal,,,,acWindowNormal

? Forms("YourForm").Name

Do you you get any error messages then?  If so, tell us what error messages and at which step they occur.


Q: Error 404 after install gitlab I've installed gitlab on centos 7. I've followed the instructions gitlab instructions ,  I 've set the external url as 192.168.0.6/gitlab but I got a 404 error when I browse this url. I've never installed Gitlab before but on apache document root there is no Gitlab folder. What can be wrong? Did I missed something?


Q: How to separate Arabic with alphabetical? If you try this link https://jsfiddle.net/u4bxz74c/10/. Later the result will be like this
PART 1

This is a samplasde textssss

فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ

PART 2

This is a samplasde textssss فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ

Question PART 1 : If you see the code below, all paragraphs or
 are class="ENGLISH".
How to make it into a paragraph or
 class="ENGLISH" to be class="ARAB", if the writing in a paragraph is Arabic? But if the writing is not Arabic, so the paragraph of class="ENGLISH"
PART 1

This is a samplasde textssss

فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ

*****     I WANT TO BE LIKE THIS     *******

This is a samplasde textssss

فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ

Question PART 2 : But if the Arabic joins with plain writing or regular fonts. So paragraph or
 remain class="ENGLISH"
Like this

 This is a sa   لْيُسْرَى ثُم تَشَهدْ

  لْيُسْرَى ثُم تَشَهدْ This is a sa

 This is a sa  ا لْيُسْرَى ثُم تَشَهدْ This is a sa

  لْيُسْرَى ثُم تَشَهدْ This is a sa   لْيُسْرَى ثُم تَشَهدْ

Note: I've tried this code, but it seems, this code encapsulates the entire contents of the textarea
if (pattern.test(newText)) {
    str = newText.replace($format_search[i], $arab_format_replace[i]);
} else {
    str = newText.replace($format_search[i], $format_replace[i]);
}

A: You can create a RegExp pattern from string "abcdefghijklmnopqrstuvwxyz " with RegExp() constructor with case insensitive flag i; iterate elements using a loop; if .textContent of element begins with one of the characters of string cast to RegExp  or every character of element .textContent is one of the characters within RegExp, set element .className to "ENGLISH", else set element .className to "ARAB".
Note that id of element in document should be unique. Also,
 is not a valid child element of
 element.
Substituted class="posttextareadisplay" for id="posttextareadisplay" at parent
 element and  for child
 element.

const en = "abcdefghijklmnopqrstuvwxyz ";

for (let el of document.querySelectorAll(".ENGLISH")) {
  if (new RegExp(`^[${en.slice(0, en.length -1)}]`, "i").test(el.textContent)
     || [...el.textContent].every(char =>
          new RegExp(`${char}`, "i").test(en))) {
    el.className = "ENGLISH"
  } else {
    el.className = "ARAB"
  }
}
PART 1

    This is a samplasde textssss
    فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ

PART 2

    This is a samplasde textssss فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ


Q: 2D SVD and Kabsch algorithm I'm implementing Kabsch algorithm in 2D. Result of algo is: translation, rotation, scale. Combaining them and applying on 1st set of points should "align" them to 2nd set of points.
So far my implementation (work-in-progress):
    // maps points 'A' onto points 'B'
    public static (Vector2,Matrix2x2,float) Compute( List< Vector2 > pointsA, List< Vector2 > pointsB )
    {
        // scale : ratio of sums of "some" distances, e.g. to "neighbour" or to centroid...

        var dsumA = 0f;
        var dsumB = 0f;

        for( var i = num; i --> 1; )
        {
            dsumA += ( pointsA[ i ] - pointsA[ i-1 ] ).sqrMagnitude;
            dsumB += ( pointsB[ i ] - pointsB[ i-1 ] ).sqrMagnitude;
        }

        if( dsumA == 0f || dsumB == 0f )
            return (Vector2.zero,Matrix2x2.IDENTITY,1f);

        var scale = MathF32.Sqrt( dsumB / dsumA );

        // rotation : based on singular-value-decomposition of cross-covariance matrix of given point-sets...

        var centroidA = Vector2.zero;
        var centroidB = Vector2.zero;

        for( int i = num; i --> 0; ) // centroids
        {
            centroidA += pointsA[ i ];
            centroidB += pointsB[ i ];
        }

        var invNum = 1f / num;

        centroidA *= invNum;
        centroidB *= invNum;

        var cc = new Matrix2x2();

        for( var i = num; i --> 0; ) // cross-covariance matrix : transposed( move-to-origin( A ) ) * move-to-origin( B )
        {
            var a = pointsA[ i ] - centroidA;
            var b = pointsB[ i ] - centroidB;

            cc.m00 += a.x * b.x;   cc.m01 += a.x * b.y;
            cc.m10 += a.y * b.x;   cc.m11 += a.y * b.y;
        }

        (var u, _, var v) = cc.SingularValueDecomposition();

        u.Transpose();

        if( cc.GetDeterminant() < 0f ) // handling special "reflection" case
        {
            v.m01 *= -1f;
            v.m11 *= -1f;
        }

        var rotation = v * u;

        // transition : difference of centroids...

        var translation = centroidB - rotation * ( centroidA * scale );

        // result...

        return (translation,rotation,scale);
    }

To compute rotation matrix you need to compute SVD (singular value decomposition) of covariance matrix. I'm not "fluent" in math at all :( so I tried few SVD implementations (svd(A) = U * S * V^T) meantioned here.
I compared results of "borrowed" implementations with few online SVD calculators. Matrix S is alright but almost all entries in U and V have different signs. I tried 2 or 3 different implementations so I assume
that problem is somewhere else - probably in construction of covariance matrix :(, but I can't spot the bug.

*

*Any notes for implementation of Kabsh itself ?

*Or how can I fix SVD (those wrong signs in U and V) ?

I noticed that determinant of my covariance matrix is negative. Could it be this?
Many thanks for any advice.
UPDATE #1
For SVD I'm using following implementation (with others I got small errors - few degrees in final rotation).
    public (Matrix2x2,Matrix2x2,Matrix2x2) SingularValueDecomposition()
    {
        Matrix2x2 u;
        Matrix2x2 s;
        Matrix2x2 v;

        s.m00 = ( MathF32.Hypot( m00 - m11, m01 + m10 ) +
                  MathF32.Hypot( m00 + m11, m01 - m10 ) ) * 0.5f;
        s.m01 = 0f;
        s.m10 = 0f;
        s.m11 = MathF32.Abs( s.m00 - MathF32.Hypot( m00 - m11, m10 + m01 ));

        v.m10 = ( s.m00 > s.m11 ) ? MathF32.Sin(( MathF32.ATan2( 2f * ( m00 * m01 + m10 * m11 ), m00 * m00 - m01 * m01 + m10 * m10 - m11 * m11 )) / 2f ) : 0f;
        v.m00 = MathF32.Sqrt( 1f - v.m10 * v.m10 );
        v.m01 = -v.m10;
        v.m11 = +v.m00;

        u.m00 = s.m00 != 0f ? ( m00 * v.m00 + m01 * v.m10 ) / s.m00 :     1f;
        u.m10 = s.m00 != 0f ? ( m10 * v.m00 + m11 * v.m10 ) / s.m00 :     0f;
        u.m01 = s.m11 != 0f ? ( m00 * v.m01 + m01 * v.m11 ) / s.m11 : -u.m10;
        u.m11 = s.m11 != 0f ? ( m10 * v.m01 + m11 * v.m11 ) / s.m11 : +u.m00;

        return (u,s,v);
    }

Yet still those signs in U and V are different from decompositions I got from few online SVD calculators.
UPDATE #2
I'm able to fixup rotation (rotation angle) to align points properly but "fixup" differs based on input point-sets.
Sometimes helps 180-angle. Sometimes 360-angle... and even 180+angle for some poit-sets :(. Mentioned / corrected angle is extracted from computed 'rotation' matrix.
This "correction" is needed for all implementations of SVD I tried so far (3 or 4) so I'm "starting" to think that problem lies somewhere else...
Translation and scale seams to work properly. With "fixed" rotation I'm able to align 'A' to 'B' properly.
UPDATE #3
I tested if SVD works by checking if U * S * Vt gets me original covariance-matrix and it does.
I found one problem in setupping covariance-matrix (fixed, code above updated) but still getting wrong rotation :(.
Also I fixed translation.
Ahhhh... so simple algorithm yet I can't beat it :)
UPDATE #4... FINAL ONE
Sorry everyone, I finally found the problem :). At some point (in my test app) order of points in one of input set changed. I corrected it and it "magically" started to work. I updated / polished the code above for future generations :).


Q: Write csv data to directly to azure blob in node js I want to create a CSV file using csv-writer , and upload that csv to azure blob, I am able to create the csv, store it on local system, and then read from local and upload to blob using azure-storage npm. But I dont want to create/store the CSV on local filesystem (because of some issues that I am running into on Prod), is there any way to create the CSV and directly feed to azure blob storage, without writing the csv to local file system.
Some code for reference
const csvWriter = createCsvWriter({
        path: `__dirname/${blobName}`,
        header: [
          { id: "id", title: "name" },
        ],
      });

      await csvWriter
        .writeRecords(csvData)
        .then(() => console.log("file successfully written"));

And once this csv is created on local, read it from there using fs module, and upload to blob using "blobService.createBlockBlobFromStream" function.
Can you please suggest how can I directly give path of azure blob storage to csvWriter? or is there any other way to achieve this?

A: Please try the code below.
const {BlobServiceClient, StorageSharedKeyCredential} = require('@azure/storage-blob');
const createCsvStringifier = require('csv-writer').createObjectCsvStringifier;
const accountName = 'account-name';
const accountKey = 'account-key';
const container = 'container-name';
const blobName = 'text.csv';

const csvStringifier = createCsvStringifier({
    header: [
        {id: 'name', title: 'NAME'},
        {id: 'lang', title: 'LANGUAGE'}
    ]
});
const records = [
    {name: 'Bob',  lang: 'French, English'},
    {name: 'Mary', lang: 'English'}
];
const headers = csvStringifier.getHeaderString();
const data = csvStringifier.stringifyRecords(records);
const blobData = `${headers}${data}`;
const credentials = new StorageSharedKeyCredential(accountName, accountKey);
const blobServiceClient = new BlobServiceClient(`https://${accountName}.blob.core.windows.net`, credentials);
const containerClient = blobServiceClient.getContainerClient(container);
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const options = {
    blobHTTPHeaders: {
        blobContentType: 'text/csv'
    }
};
blockBlobClient.uploadData(Buffer.from(blobData), options)
.then((result) => {
    console.log('blob uploaded successfully!');
    console.log(result);
})
.catch((error) => {
    console.log('failed to upload blob');
    console.log(error);
});

Two things essentially in this code:

*

*Use createObjectCsvStringifier if you don't want to write the data to disk.

*Use @azure/storage-blob node package instead of azure-storage package as former is the newer one and the latter is being deprecated.

Update
Here's the code using azure-storage package.
const azure = require('azure-storage');
const createCsvStringifier = require('csv-writer').createObjectCsvStringifier;
const accountName = 'account-name';
const accountKey = 'account-key';
const container = 'container-name';
const blobName = 'text.csv';

const csvStringifier = createCsvStringifier({
    header: [
        {id: 'name', title: 'NAME'},
        {id: 'lang', title: 'LANGUAGE'}
    ]
});
const records = [
    {name: 'Bob',  lang: 'French, English'},
    {name: 'Mary', lang: 'English'}
];
const headers = csvStringifier.getHeaderString();
const data = csvStringifier.stringifyRecords(records);
const blobData = `${headers}${data}`;

const blobService = azure.createBlobService(accountName, accountKey);
const options = {
    contentSettings: {
        contentType: 'text/csv'
    }
}
blobService.createBlockBlobFromText(container, blobName, blobData, options, (error, response, result) => {
    if (error) {
        console.log('failed to upload blob');
        console.log(error);
    } else {
        console.log('blob uploaded successfully!');
        console.log(result);
    }
});


Q: Optimizing the product of two integers How to efficiently solve the following optimization problem?

Find $a$ and $b$ which minimize $ c = a * b $ under the constraints $ c \geq C $, $ a \leq A $, $ b \leq B $, where $a, b, A, B, C$ are positive integers.

Obviously the problem is challenging only if $ A < C $ and $ B < C $.
I cannot think of a solution which does not involve going through many $a$ and finding the best $b$ for each $a$. But the problem does sound very simple (it's just product!) so I'm wondering if there is a faster way.

A: I have drawn a graph showing the feasible region (the points marked on the graph) for a particular example:

The curve is $y=\frac Cx$. It crosses the line $y=B$ at $(\frac CB, B)$ and it crosses the line $x=A$ at $(A, \frac CA)$
I would suggest the following algorithm to suggest which of the red points minimises $xy$. It should be obvious that we do not need to consider any of the blue points above a red point.
Leftmost red point is found by calculating $x_0=\left \lfloor \frac CB \right \rfloor$ and $y_0=B$. Gives us our best (so far!) value of $C_{min}=x_0y_0$. Let $x_{best}=x_0$ and let $y_{best}=y_0$
Let $x_1=x_0+1$. Calculate $y_1=\left \lfloor \frac C{x_1} \right \rfloor$. Compare $C_1=x_1y_1$ with $C_{min}$. If $C_1<C_{min}$ then let $x_{best}=x_1$ and let $y_{best}=y_1$.
Continue like this with $x_{n}=x_{n-1}+1$ until $x_n=A$.
To make this more efficient you should set $A<B$ - that way you will have fewer values to test.


Q: choose stepper in odeint through if statement I want to choose integration scheme through a if statement like this:
//stepper_type steppr; ??
if (integration_scheme == "euler") {
    [auto] stepper = euler<state_type>{};
}
else
{
    [auto] stepper = runge_kutta4<state_type>{};
}

but stepper is only valid inside the curly bracket.
What is the type of stepper to be defined before the if statement?
another way is to pass the integration scheme (or even stepper) as an argument to a function.

A: In C++17 and over, for this purpose we can apply std::variant as follows:
#include <variant>

class state_type {};

template<class T>
class euler {};

template<class T>
class runge_kutta4 {};

template<class T>
using stepper_t = std::variant<euler<T>, runge_kutta4<T>>;

Then you can do like this:
DEMO
stepper_t<state_type> stepper;

if (integration_scheme == "euler") {
    stepper = euler<state_type>{};
}
else{
    stepper = runge_kutta4<state_type>{};
}

std::cout << stepper.index(); // prints 0.

But although I don't know the whole code of your project, I think the subsequent code would not be simple one in the above way.
If I were you, I will define the base calss stepperBase and euler and runge_kutta4 as the inheritances of stepperBase.


Q: Python - Datetime's Time is always zero Strange little problem I'm facing with Datetime. Here's what I'm doing:
>>> from datetime import datetime, date
>>> t = date.timetuple(datetime.now())
>>> t
time.struct_time(tm_year=2011, tm_mon=6, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=165, tm_isdst=-1)

tm_hour, tm_min and tm_sec are all zero. Why is this?

A: Well t is a date, so of course it doesn't contain any time data. You have to use datetime.timetuple(datetime.now()) to have those fields populated.

A: I have tried this in my console and get the following results:
from datetime import datetime, date

date.timetuple(datetime.now())
>>> time.struct_time(tm_year=2011, tm_mon=6, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=165, tm_isdst=-1)
datetime.timetuple(datetime.now())
>>> time.struct_time(tm_year=2011, tm_mon=6, tm_mday=14, tm_hour=13, tm_min=23, tm_sec=34, tm_wday=1, tm_yday=165, tm_isdst=-1)

A: >>> from datetime import datetime
>>> datetime.timetuple(datetime.now())
time.struct_time(tm_year=2011, tm_mon=6, tm_mday=14, tm_hour=18, tm_min=25, tm_sec=20,  tm_wday=1, tm_yday=165, tm_isdst=-1)
>>> from datetime import date
>>> date.timetuple(datetime.now())
time.struct_time(tm_year=2011, tm_mon=6, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=165, tm_isdst=-1)

this is my result.

A: this should work:
t = datetime.timetuple(datetime.now())


Q: Getting the Date in stencil bigcommerce I'm setting up a minimum and maximum number of days a customer can return a product. But my problem is that how can I get the current Date on stencil bigcommerce? I tried using the
{{moment "now" "MM/DD/YYYY"}}

It works great but the problem is that when I change the current date of my computer the output of the code changes also. That is why I wanted to get like the "Server Date", just to be sure I will always getting the correct current date.


Q: Deformation invariance of rational connectedness in positive/mixed characteristic Let $f:X \to S$ be a smooth morphism and $S$ the spectrum of a discrete valuation ring. If the generic fiber of $f$ is rationally (chain) connected then is the special fiber of $f$ also rationally (chain) connected? We know this to be true if $S$ is over a field of characteristic zero, due to Kollar, Miyaoka and Mori. If not true in general, is there any known special cases when this holds true? Any hint/reference will be most welcome.

A: In characteristic $ p>0 $, RCC and SRC (separable rational connectedness) do differ (see Janos Kollar's (Rational curves) book: V.5.19, I know that Janos Kollar refers to this even though I do not have the book.).  In Higher Dimensional Varieties and Rational Points pg. 41 and pg. 43, Carolina Araujo and Janos Kollar show that SRC is deformation invariant.
Namely they refer to Kollar IV.3.11 and Kollar, Miyaoka and Mori to show that the existence of a very free curve is an open condition (condition 6) and the existence of a chain of rational curves connecting any two points (condition 1+) is a closed condition.  I do not have access to these sources, so you will have to check that the proof that condition 6 is an open condition does not use properties that only hold for varieties over a field of characteristic zero.
Assuming that there are no problems with condition 6 being an open condition, then since $ \operatorname{Spec}(R) $ is connected, if $ \mathcal{X} $ is a scheme over $ \operatorname{Spec}(R) $ and the general fibre of $ \mathcal{X} $ is SRC, then the special fibre is also SRC.
I don't know about whether RC is deformation invariant in positive characteristic, so I cannot answer that part of the question per se.


Q: How to vectorize this code below in Python without joining two dataframes I have two dataframes with multiple columns like below
head(df
    SCHEDULING_DC_NBR       COMMODITY_CODE          Unload_Start_Time   DOW     Dlry
0   6042.0                    SCGR                      15:15           SUN      5
1   6042.0                    SCGR                      15:30           SUN      6
2   6042.0                    SCGR                      15:45           SUN      7
3   6042.0                    SCGR                      16:15           SUN      8
4   6042.0                    SCGR                      18:30           SUN      9

head(config_df)
Node      Window               APPLICABLE_DAYS   COMMODITY_CODE  Window_start_time  config_ID
7023.0  03:15 AM to 03:16 AM            MON         SCPR                03:15        123
7023.0  03:15 AM to 03:16 AM            THUR        SCPR                03:15        123
7023.0  03:15 AM to 03:16 AM            FRI         SCPR                03:15        123
6042.0  06:00 PM to 06:05 PM            SUN         SCPR                18:00        111
6042.0  03:00 PM to 03:05 PM            SUN         SCGR                15:00        222

I want to apply row-wise operation on dataframe df to find the appropriate capacity_config_id from config_df using some logic like below using apply function.
def config_map(row):
    row = row.copy()
    return config_df.loc[(config_df['Node'] == row['SCHEDULING_DC_NBR']) & (config_df['COMMODITY_CODE'] == row['COMMODITY_CODE'])
                          &  (config_df['APPLICABLE_DAYS'].str.contains(row['DOW'],case=False))
                          & (live_config['Window_start_time'] == row['Unload_Start_Time']),"capacity_config_id"].values[0]

Even though, the above code works it takes a lot of time to run.
I don't want to join or merge both the dataframes, as i will be doing multiple other checks in apply function above. I am looking for a way to vectorize this function for faster computation.

A: You may consider using Pandas apply method, https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html
Using this you can vectorize the operation


Q: WPF adorned elements flickering I have built a custom timer control that is basically a user control, this control has TextBox controls the have values which counts down while it is working.
This control is added as a child to a Canvas, and when start dragging the control it is placed in an AdornerLayer.
while dragging this control, the working TextBoxes flickers and if you stopped moving (but don't Mouse Up!!) the TextBoxes disappear!!!
I have search for a solution, and in one of them it said to set the adorned element and the AdornerLayer IsHitTestVisible to false but it didn't do the trick
Any help would be appreciated


Q: Render props method without nesting dom element In essence I have the following inside a react functional component:

    <MyFilter1 data={data}>
        {(filter1Data) => {
            return <MyFilter2 data={filter1Data}>
                {(finalData) => {
                    return
{finalData}

                }}
            </MyFilter2>
        }}
    </MyFilter1>

I am using multiple filters with the render children paradigm to get the final data. But for (admittedly frustrating) styling reasons, I would like to render the final data in a div outside of the filters location (inside the 'filtered' div in this case). How can I do this? Is my approach wrong? Is the 'filter with render children' the wrong approach?
I have tried:
React portal with createRef(), in essence the problem ends up being that the ref is not available yet when the 'finalData' function is called.
Edit:
The filter components themselves are very complicated but I can give a couple examples. The data I'm filtering is a simple object with 12ish properties. One of the filters is implemented as a series of checkboxes determining which properties of the data I want to display (necessary as a separate component because of the number of fields). One of the properties on the data is a price, and another filter is a price range 'dialer', that specifies the price range to display ( aka exclude data points outside the range).


Q: Terraform parsing error in Visual Studio Code I am new to Terraform and I'm trying to deploy a resource group using the example from the documentation found here, in Visual Studio Code. I receive a json parsing error when trying to use terraform apply or terraform plan. The commandsterraform init, terraform fmt and terraform validate all work fine. Connecting to azure using az login also works.
Information about code, versioning and setup can be seen below.
Error
╷
│ Error: building AzureRM Client: please ensure you have installed Azure CLI version 2.0.79 or newer. Error parsing json result from the Azure CLI: unmarshaling the result of Azure CLI: invalid character 'C' looking for beginning of value.
│
│   with provider["registry.terraform.io/hashicorp/azurerm"],
│   on main.tf line 10, in provider "azurerm":
│   10: provider "azurerm" {
│
╵

Code in main.tf
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "3.28.0"
    }
  }
}

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "example" {
  name     = "example-resourcegroup"
  location = "eu-west"
}

az --version output
azure-cli                         2.41.0

core                              2.41.0
telemetry                          1.0.8

Dependencies:
msal                            1.20.0b1
azure-mgmt-resource             21.1.0b1

terraform --version output
Terraform v1.2.5
on windows_amd64
+ provider registry.terraform.io/hashicorp/azurerm v3.28.0

A: I tried to reproduce the same issue in my environment and got the below results
For installing the terraform in visual studio refer this link
We have to install the developer cli use this link to download and install
I have installed the visual studio code and install the terraform
Please find the versions which I have used

I have created terraform file
vi main.tf

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "3.28.0"
    }
  }
}

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "example23" {
  name     = "example-resourcegroup23"
  location = "eastus"
}

I have followed some commands to run the file
  Terraform init

terraform plan

terraform apply

When I open the portal  I am able to see newly created resource group

Note:
1).In order to use the azure CLI, terraform should be able to do the azure cli authentication for that we have to add the token.
2).Both terraform and Azure cli should be on same path
az account get-access-token { "accessToken": token_id", "expiresOn": <Date_with_time>, "subscription": "subscription_id", "tenant": "", "tokenType": "token_type" }***

3). you can also refer this link here  for know abt the issue


Q: keyboard event should fire after filling text box I am working on keyboard events using j query. I have two text boxes one accepting first name and second one accepting last name. I want to alert first and the last name after filling the text box. I am using a(ascii code 65) key to fire event.
The problem here is event is firing when i am filling the text box. I don't want the interruption while entering name into the text box and i need to call the event after entering the text box. I am using ajax that connects c# in web forms.
Please help me with this.
This is my html code:

                First Name:

                <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>

                Last Name:

                <asp:TextBox ID="txtLastName" runat="server" onkeyup="JqueryAjaxCall();" AutoPostBack="true"></asp:TextBox>

This is my Script:

This is my C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
  {

  }
[WebMethod]
public static string jqueryAjaxCall(string firstName, string lastName)
  {
    //Do coding staff.
    return firstName + " " + lastName;
  }
}

A: Instead of onkeyup, use onchange event.
onchange event will fire only on blur of the text box.
<asp:TextBox ID="txtLastName" runat="server" onchange="JqueryAjaxCall();" AutoPostBack="true"></asp:TextBox>


Q: Line Order Probability I am struggling to conceptualize conditional probability in this problem.
Four people A,B,C,D form a line in a random order.
a) Find the conditional probability that A is the first in line given that B is the last.
I believe this is $1/3$ because options A,C,D are the only choices for position 1 under the aforementioned scenario.
b) Find the conditional probability that A is the first given that A is not the last.
I believe this is $1/3$ because again there will only be $3$ choices for the first place given the condition set.
c) Find the conditional probability that A is first given that B is not the last.
d) Find the conditional probability that A is the first given that B is (not necessarily immediately) after A.
e) Find the conditional probability that A is standing in line before B given that A is before C.

A: Your answers on a) and b) are correct. To write them down (and get a better oversight on what you are doing) you need proper notation. You can choose for random variables $A,B,C,D$ that take values in $\{1,2,3,4\}$ and where e.g. $\{A=3\}$ stands for the event that person A takes the third position. Then to be found are the conditional probabilities:

*

*a) $P(A=1\mid B=4)$

*b) $P(A=1\mid A\neq4)$

*c) $P(A=1\mid B\neq4)$

*d) $P(A=1\mid B>1)$

*e) $P(A<B\mid A<C)$

When it comes to conditional probabilities then the following rule is essential:$$P(E\mid F)P(F)=P(E\cap F)$$
Solution of c): $$P(A=1\mid B\neq4)P(B\neq4)=P(A=1\wedge B\neq 4)=P(A=1\wedge B=2)+P(A=1\wedge B=3)$$
where $P(B\neq4)=\frac34$ and $P(A=1\wedge B=2)=P(B=2\mid A=1)P(A=1)=\frac13\frac14$.
Can you take it from here?

A: Hint: use total probability theorem. For example, given $B$ is not the last, $B$ can be 1st, 2nd or 3rd, equally likely. Find the probability of $A$ being the 1st for each scenario and find the total probability of $A$ being the 1st.

A: The way to think of it is that knowing that (e.g.) B is last reduces the set of possible configurations from $24$ to $6$. Each configuration is equally likely, so all that matters is: of those $6$, how many have A first? There are $2$ configurations that have A first and B last (ACDB, ADCB), out of $6$ total that have B last, so the answer is $2/6=1/3$.
Similarly for c), say, there are $18$ configurations where B is not last ($24-6$, since there are $6$ where B is last). Of those, $4$ have A first: ABCD, ABDC, ACBD, ADBC. So the answer is $4/18=2/9.$


Q: echo works twice just for one id but doesn't for the other one There are 2 entries on the table. But it echos 3 entries but it echos twice one of them. If i change it to ASC from DESC, then it echos the other one twice. If i use "where id <> 5" then it just echos id 6 just once. But it is a dynamic site so... And i use the same exact code on another page and it works. Here is the full code:
<?php
$cek = mysql_query('select id,isim,aciklama,tarih from galeri where dil = '.$dbDil.' order by id desc');
while($kaynak = mysql_fetch_assoc($cek)){
    $cekG = mysql_query('select resim_url from galeriresim where galeriID = '.$kaynak['id'].' order by id desc');
    $galeri .= '
'.$kaynak['tarih'].' '.$kaynak['isim'].'
';
    $galeri .= '
'.$kaynak['aciklama'].'
';
    $galeri .= '
';
    $galeri .= '
';
    $galeri .= '
';
    while($kaynakG = mysql_fetch_assoc($cekG)){
           $galeri .= '

';
    }
    $galeri .= '

';
    $galeri .='';
    echo $galeri;
}
?>

A: You're doing your final echo INSIDE the main while() loop:
while(..) {
   while(..) { .. }
   echo ..
}

It should be
while(..) {
   while(..) { .. }
}
echo ..

Since you're echoing INSIDE the main loop, you'll be running that echo multiple times, spitting out $galeri as it's being built.

A: Try this:
i have added mysq_free_result and echo must be outside the while !
<?php
    $cek = mysql_query('select id,isim,aciklama,tarih from galeri where dil = '.$dbDil.' order by id desc');
    while($kaynak = mysql_fetch_assoc($cek)){
        $cekG = mysql_query('select resim_url from galeriresim where galeriID = '.$kaynak['id'].' order by id desc');
        $galeri .= '
'.$kaynak['tarih'].' '.$kaynak['isim'].'
';
        $galeri .= '
'.$kaynak['aciklama'].'
';
        $galeri .= '
';
        $galeri .= '
';
        $galeri .= '
';
        while($kaynakG = mysql_fetch_assoc($cekG)){
               $galeri .= '

';
        }
        mysql_free_result($cekG);
        $cekG ="";
        $galeri .= '

';
        $galeri .='';

    }
     echo $galeri;
    ?>

A: Use a JOINed query then you wouldn't need a double while loop. you shouldnt be using mysql anyway. Use mysqli or pdo
'select g.id,g.isim,g.aciklama,g.tarih, gr.resim_url
  from galeri g
  JOIN galeriresim gr on gr.galeriID = g.id
  where g.dil = '.$dbDil.' order by id desc'


Q: SQL - create SQL to join lists I have the following table:
CREATE temp TABLE "t_table" (
  usr_id bigint,
  address varchar[],
  msg_cnt bigint,
  usr_cnt bigint,
  source varchar[],
  last_update timestamp
);

Add Data:
INSERT INTO "t_table"(usr_id, address, msg_cnt, usr_cnt, source, last_update) VALUES (1, '{44.154.48.125,81.134.82.111,95.155.38.120,94.134.88.136}', 10, 3, '{src1,src2}', '2019-10-16 22:16:22.163000');
INSERT INTO "t_table"(usr_id, address, msg_cnt, usr_cnt, source, last_update) VALUES (2, '{44.154.48.125}', 10, 3, '{src1,src3}', '2019-10-16 22:16:22.163000');
INSERT INTO "t_table"(usr_id, address, msg_cnt, usr_cnt, source, last_update) VALUES (3, '{94.134.88.136}', 10, 3, '{src1,src4}', '2019-10-16 22:16:22.163000');
INSERT INTO "t_table"(usr_id, address, msg_cnt, usr_cnt, source, last_update) VALUES (4, '{127.0.0.1}', 10, 3, '{src1,src5}', '2019-10-16 22:16:22.163000');
INSERT INTO "t_table"(usr_id, address, msg_cnt, usr_cnt, source, last_update) VALUES (5, '{127.0.0.1,5.5.5.5}', 10, 3, '{src1,src3}', '2019-10-16 22:16:22.163000');
INSERT INTO "t_table"(usr_id, address, msg_cnt, usr_cnt, source, last_update) VALUES (6, '{1.1.0.9}', 10, 3, '{src1,src2}', '2019-10-16 22:16:22.163000');

Find users who share addresses.
Expected Results:
|      users                      |  address                                                    | sum_msg_cnt  |  sum_usr_cnt     | max_last_date                  | source                      |
|---------------------------------|-------------------------------------------------------------|--------------|------------------|--------------------------------|-----------------------------|
|    {1,2,3}                      |  {44.154.48.125,81.134.82.111,95.155.38.120,94.134.88.136}  | 30           |         9        |  "2019-10-16 22:16:22.163000"  |    {src4,src1,src2,src3}    |
|    {4,5}                        |  {127.0.0.1,5.5.5.5}                                        | 20           |         6        |  "2019-10-16 22:16:22.163000"  |    {src1,src5,src3}         |
|    {6}                          |  {1.1.0.9}                                                  | 10           |         3        |  "2019-10-16 22:16:22.163000"  |    {src1,src2}              |

Question:
How do I formulate a SQL query to obtain the expected result?
Much appreciated.
More info:
PostgreSQL 9.5.19

A: I don't know if this is the most efficient method, but I can't come up with something better right now.
I assume this will have a terrible performance on a larger table.
with userlist as (
  select array_agg(t.usr_id) as users,
         a.address
  from t_table t
    left join unnest(t.address) as a(address) on true
  group by a.address
), shared_users as (
  select u.address,
         array(select distinct ul.uid
               from userlist u2, unnest(u2.users) as ul(uid)
               where u.users && u2.users
               order by ul.uid) as users
  from userlist u
)
select users, array_agg(distinct address)
from shared_users
group by users;

What does it do?
The first CTE  collects all users that share at least one address. The output of the userlist CTE is:
users | address
------+--------------
{1}   | 95.155.38.120
{1,3} | 94.134.88.136
{1,2} | 44.154.48.125
{6}   | 1.1.0.9
{4,5} | 127.0.0.1
{1}   | 81.134.82.111
{5}   | 5.5.5.5

Now this can be used to aggregate those user lists that share at least one address. The output of the shared_users CTE is:
address       | users
--------------+--------
95.155.38.120 | {1,2,3}
94.134.88.136 | {1,2,3}
44.154.48.125 | {1,2,3}
1.1.0.9       | {6}
127.0.0.1     | {4,5}
81.134.82.111 | {1,2,3}
5.5.5.5       | {4,5}

As you can see we now have groups with the same list of usr_ids. In the final step we can group by those and aggregate the addresses, which will then return:
users   | array_agg
--------+----------------------------------------------------------
{1,2,3} | {44.154.48.125,81.134.82.111,94.134.88.136,95.155.38.120}
{4,5}   | {127.0.0.1,5.5.5.5}
{6}     | {1.1.0.9}

Online example

A: Group the addresses using "group by" operator


Q: Firebase admin: Cannot read property 'cert' of undefined I'm trying to set up firebase in in my node.js server. In deploy.js I am setting up up like this:
const admin = require('firebase-admin/app');
const serviceAccount = require('../serviceAccountKey.json')

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://projectName.firebaseio.com"
});
...

I am getting the error:
 credential: admin.credential.cert(serviceAccount),
                               ^
TypeError: Cannot read property 'cert' of undefined
    at Object.<anonymous> (C:\Users\Uporabnik\hello-world\scripts\deploy.js:9:32)
    at Module._compile (internal/modules/cjs/loader.js:1068:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:933:32)
    at Function.Module._load (internal/modules/cjs/loader.js:774:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

My package.json:
{
  "name": "hardhat-project",
  "devDependencies": {
    "@nomiclabs/hardhat-ethers": "^2.0.6",
    "ethers": "^5.6.9",
    "hardhat": "^2.9.9"
  },
  "version": "1.0.0",
  "description": "hello world smart contract",
  "main": "hardhat.config.js",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "firebase-admin": "^11.0.0"
  },
  "scripts": {
    "test": "mocha"
  },
  "author": "",
  "license": "ISC"
}

What could be causing it?

A: This is the solution:
Replace
const admin = require('firebase-admin/app');

with
const admin = require('firebase-admin');

You would use /app if you’re going to use modular approach


Q: Smoother Keypressed event for paddle object in pong I'm trying to make my paddle movements smoother in my pong game. My player_paddle1 has smooth movements and will stop whenever I let go of the key. However, my other player_paddle2, which incorporates the same keypress algorithm has the other paddle, does not do so. It will keep on going even if I release the key.
        if game_option == "Two Player":
            if event.type == KEYDOWN:
                if event.key == K_UP:
                    player_paddle1.direction = -1
                elif event.key == K_DOWN:
                    player_paddle1.direction = 1

                if event.key == K_w:
                    player_paddle2.direction = -1
                elif event.key == K_s:
                    player_paddle2.direction = 1

            if event.type == KEYUP:
                if event.key == K_UP and player_paddle1.direction == -1:
                    player_paddle1.direction = 0
                elif event.key == K_DOWN and player_paddle1.direction == 1:
                    player_paddle1.direction = 0

                if event.key == K_UP and player_paddle2.direction == -1:
                    print("The key is now up!")
                    player_paddle2.direction = 0
                elif event.key == K_UP and player_paddle2.direction == 1:
                    player_paddle2.direction = 0

Also, while the up and down keys are extremely responsive, the W and S keys are not too responsive, which means, a keypressed will not immedieatly result in paddle motion. How can I fix this?

A: You check K_UP for second player in KEYUP but it has to be K_w and K_s.
Besides you don't have to check player_paddle2.direction
        if event.type == KEYUP:
            if event.key == K_UP:
                player_paddle1.direction = 0
            elif event.key == K_DOWN:
                player_paddle1.direction = 0

            elif event.key == K_w: # <-- there was K_UP
                print("The key is now up!")
                player_paddle2.direction = 0
            elif event.key == K_s: # <-- there was K_UP
                player_paddle2.direction = 0

it can be shorter
        elif event.type == KEYUP:
            if event.key in (K_UP, K_DOWN)
                player_paddle1.direction = 0

            elif event.key in (K_w, K_s):
                player_paddle2.direction = 0

BTW: you can use elif in some places.


Q: Using RestSharp, how to include a fieldname like "$fieldname" in RestRequest.AddJsonBody()? Using RestSharp, I need to POST a body containing a json string that looks like this:
{
    "$a": "b",
    "c": "d"
}

In the past I've created RestSharp requests using code like this:
var request = new RestRequest("someApiEndPoint", RestSharp.Method.POST);
request.AddJsonBody(new
{
    a = "b",
    c = "d"
});

What's the best way to add a "$" to the "a" property in this case?

A: Since you are using an anonymous type, you could just as easily switch to using a dictionary:
var root = new Dictionary<string, object>
{
    {"$a", "b" },
    {"c", "d" },
};
var request = new RestRequest("someApiEndPoint", RestSharp.Method.POST)
    .AddJsonBody(root);

If you were using an explicit type, you could check RestSharp serialization to JSON, object is not using SerializeAs attribute as expected for options.


Q: Pass through `IHttpHandler` response on error So, IIS is pissing me off. It keeps on screwing with my error handling. I have a number of IHttpHandlers registered, and they're doing a good job. When I connect locally, I get the response I expect. But when I connect remotely, IIS's CustomErrorModule starts interfering. I've played with system.webServer/httpErrors and ssytem.web/customErrors to no avail. The only thing that works is system.webServer/modules/remove@name=CustomErrorModule, but that requires setting lockItem="false" for CustomErrorModule in the system's applicationHost.config file. Which is not a solution I like.
Is there some way to entirely disable CustomErrorModule without messing with any system files? I.e. without having admin privileges?

A: Aha! In <system.webServer>:
<httpErrors existingResponse="PassThrough" />
This does exactly what I want.


Q: Synaptics-Touchpad (xorg-xserver) tap sensitivity too high I have a Lenovo x1 carbon 7th gen. I just recently installed the xserver-xorg-input-synaptics to fix the disabled click buttons after suspension.
Since I have installed the synaptics driver, the tap functionality of the touchpad itself is extremely high. Everytime I type on the keyboard, I activate a click on the touchpad, and when I click on the "activity" Icon in gnome it often registers two clicks.
From what I found out so far, I should change the options in synclient to alter this behaviour. But I cannot figure out which options need to be altered to fix this behaviour.
I am using the latest Pop OS version, which basically is Ubuntu 18.10

A: I believe this answers your question.

*

*Run xinput.

*Get the id number of the touchpad.

*Then run this command: xinput list-props X (where X is the id number you just obtained).

*Then you can change your synaptic finger values by following this guide.


Q: onLoad() jQuery not working correctly because of Uncaught TypeError: Cannot read property 'hps' of undefined My onLoad jQuery function is not working. The HTML starts with a "loading" gif, and the jQuery should fade in the featured-photo while fading out image-loader.
The loadImage function is called in the html, and causes an error because window.app is undefined in the HTML.  Like this:
html

      <img src="<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>" class="lazy-image" onload="window.app.hps.loadImage(this, '.featured-photo')"/>

application.js
    loadImage: function(img, attachment_class)
    {
            var backgroundImage = $(img).attr('src');
                console.log("Lazy load image: "+backgroundImage);

                $('.image-loader').fadeOut();
                $('.post-loaders').fadeIn();
                $(attachment_class).css("opacity", 0).css('background-image', 'url(' + backgroundImage + ')').css("opacity", 1);
    }

The error I get is Uncaught TypeError: Cannot read property 'hps' of undefined, which I understand means window.app is undefined in the html page.  My question is how do I properly define window.app within the html so the function will work?
The function is defined in application.js like this:
$(document).ready(function() {
    window.app = new Application({ el: $("body") });
    if ( $('body').hasClass("page-id-142") ) { revenew(); }
});

But I'm not sure how to define it in the HTML properly.


Q: Cast ConstantDataArray to i8* in LLVM Simple question: "I have a ConstantDataArray of type [7 x i8], how can I cast it to have the i8* type?"
EDIT
More Context:
The ConstantDataArray is created as follows:
ConstantDataArray::getString(Fn->getContext(), "Hello", true);
And I have created a LLVM:Function that has an argument with the type coming from Type::getInt8PtrTy(getGlobalContext()) and I want to cast the array to this type, so I can pass it as an argument.
I'm developing a pass

A: You can use IRBuilder's CreateGlobalStringPtr which is a convenience wrapper for creating a global string constant and returning an i8* pointing to its first character.


Q: Options for a file system based Sql database for a multiuser web application that can perform and scale What are my options for a file based sql database (not NoSql) which scales well, performs well, and is designed for handling many hundreds of multiple users (and plays nice with .net)?
My requirements
I'm accustomed to working with SqlServer, and for this application my needs are simpler (I still need sql though, although other parts of the application will use NoSql).
I want something which is embedded mainly because it's just simple and easy to set up, without any major overheads or services or configurations. I'd like to keep it filesystem for as long as I can.
However, when the time comes, ideally I'd like a solution which allows me to change the "context"of the database so maybe it is server based. I'd like that option to grow.
I'd also like it to be free (at least for small application, or non-commercial applications (although it will become commercial in the future...?)).
Does such a database solution exist?
Update
Sorry guys, I used the wrong terminology and ugh ink we misunderstood each other. Forget I said embedded, I meant file base, like lucene or raven, but relational.

A: You ever heard of SQL Server? Like SQL Server EMBEDDED? No install ;)

A: You have contradictory requirements.
Small and embedded (no server) usually means SQL Server compact or SQLLite. But these are neither multi-user not network aware in practice.  Especially whan you say "hundreds of multiple users"
So you have to decide what you want to do. A proper, scalable, web based app with correct architecture? Or a a cheap kludgely unworkable unmaintainable mess?
SQL Server Compact will scale up of course in future to normal SQL Server with minimum fuss. But I'd start with SQL Server properly now

A: You can use FireBird, it can be embedded and scales well and deployment is really easy - an ADO.NET provider is available... see for more information http://www.firebirdsql.org/en/net-provider/


Q: What caused review to cease for this item? Apparently this review item was created by a possible duplicate flag, as there is only one close vote on the corresponding question, and a single review with a vote to close.
Sounds good so far, except that the item is no longer reviewable. Why is that? There were never any Leave Open votes, and there's only one vote to close. It seems to me it should still be going to gather either four more close votes or three Leave Open votes.
Is this some sort of bug with flags being handled by the review queue that causes review to complete prematurely?

A: This is fixed now. Here's what happened:
The post was enqueued in the Close Votes queue via a single close flag. When Toon cast his close vote, the close flag was automatically dismissed as "helpful". Since the queue only includes posts with close flags/votes cast more than 15 minutes ago, it was no longer considered reviewable since Toon's vote replaced the flag, and was cast within the past 15 minutes.
Edit: I re-enabled the review item in question.