问:
Get only unique data from array of objects in JavaScript
So I have the following structure:

```<code>[{
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Monday",
    "periods": [{
        "openDay": "Monday",
        "openTime": "12:00",
        "closeDay": "Monday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Monday",
        "openTime": "19:00",
        "closeDay": "Monday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Monday",
        "openTime": "23:00",
        "closeDay": "Monday",
        "closeTime": "23:30"
      }
    ]
  },
  {
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Tuesday",
    "periods": [{
        "openDay": "Tuesday",
        "openTime": "12:00",
        "closeDay": "Tuesday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Tuesday",
        "openTime": "19:00",
        "closeDay": "Tuesday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Tuesday",
        "openTime": "23:00",
        "closeDay": "Tuesday",
        "closeTime": "23:30"
      }
    ]
  }
]
</code>```

What I want to do, is if all periods for a given day are the same as any other day(matching by their openTime and closeTime) in the array to merge them (or just delete the second occurrence). If the periods are of a different length no action will occur. Also if just one of the openTime or closeTime is different, again no action will occur.
So far I have tried looping through all days and comparing one with the following after it. Got stuck in comparing the periods. Tried following the explanation here - https://gomakethings.com/check-if-two-arrays-or-objects-are-equal-with-javascript/, but again got lost.
The desired output will be:

```<code>[{
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Monday, Tuesday",
    "periods": [{
        "openDay": "Monday",
        "openTime": "12:00",
        "closeDay": "Monday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Monday",
        "openTime": "19:00",
        "closeDay": "Monday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Monday",
        "openTime": "23:00",
        "closeDay": "Monday",
        "closeTime": "23:30"
      }
    ]
  },
</code>```

As I don't care about changing the openDay/closeDay in the periods. I want to do this check for all days in the array.

答:
I understand what you are trying to do. And I also noticed that your output might be a little bit confusing, since you are reducing the duplicates from the outer level of the array (by joining the humanDay names) but keeping the inner (openDay closeDay) tags.

I have re-written how the output should be like, and also, joined weekday names in an array for more convenience.

let timings = [{
    isOpen: 1,
    weekday: 1,
    humanDay: "Monday",
    periods: [{
        openDay: "Monday",
        openTime: "12:00",
        closeDay: "Monday",
        closeTime: "14:30",
      },
      {
        openDay: "Monday",
        openTime: "19:00",
        closeDay: "Monday",
        closeTime: "22:30",
      },
      {
        openDay: "Monday",
        openTime: "23:00",
        closeDay: "Monday",
        closeTime: "23:30",
      },
    ],
  },
  {
    isOpen: 1,
    weekday: 1,
    humanDay: "Tuesday",
    periods: [{
        openDay: "Tuesday",
        openTime: "12:00",
        closeDay: "Tuesday",
        closeTime: "14:30",
      },
      {
        openDay: "Tuesday",
        openTime: "19:00",
        closeDay: "Tuesday",
        closeTime: "22:30",
      },
      {
        openDay: "Tuesday",
        openTime: "23:00",
        closeDay: "Tuesday",
        closeTime: "23:30",
      },
    ],
  },
];

// create an empty object
const weekdays = {};

timings.forEach((timing) => {
  timing.periods.forEach((period) => {
    // check if the object has a key matching
    // the openTime to CloseTime string
    // (this can be any key, but we want to capture all
    // .. days that have the same open and close times)

    if (!weekdays[`${period.openTime}-${period.closeTime}`]) {
      // the key does not exist, so lets create an new sub-object for
      // that given key, and prepare its array of days:
      weekdays[`${period.openTime}-${period.closeTime}`] = {
        days: [],
      };
    }

    // now, add the current day to the pre-defined sub-array:
    weekdays[`${period.openTime}-${period.closeTime}`].days.push(
      timing.humanDay
    );

    // also, store the openTime and closeTime as sub-properties, for convenience
    // i know they are stored in the key but the whole purpose of the key
    // is to reduce duplicates by taking advantage of javascript built in
    // funcationalities.

    weekdays[`${period.openTime}-${period.closeTime}`]["openTime"] =
      period.openTime;

    weekdays[`${period.openTime}-${period.closeTime}`]["closeTime"] =
      period.closeTime;
  });
});

console.log(weekdays);```

Body:
So I have the following structure:

[{
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Monday",
    "periods": [{
        "openDay": "Monday",
        "openTime": "12:00",
        "closeDay": "Monday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Monday",
        "openTime": "19:00",
        "closeDay": "Monday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Monday",
        "openTime": "23:00",
        "closeDay": "Monday",
        "closeTime": "23:30"
      }
    ]
  },
  {
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Tuesday",
    "periods": [{
        "openDay": "Tuesday",
        "openTime": "12:00",
        "closeDay": "Tuesday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Tuesday",
        "openTime": "19:00",
        "closeDay": "Tuesday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Tuesday",
        "openTime": "23:00",
        "closeDay": "Tuesday",
        "closeTime": "23:30"
      }
    ]
  }
]

What I want to do, is if all periods for a given day are the same as any other day(matching by their openTime and closeTime) in the array to merge them (or just delete the second occurrence). If the periods are of a different length no action will occur. Also if just one of the openTime or closeTime is different, again no action will occur.
So far I have tried looping through all days and comparing one with the following after it. Got stuck in comparing the periods. Tried following the explanation here - https://gomakethings.com/check-if-two-arrays-or-objects-are-equal-with-javascript/, but again got lost.
The desired output will be:

[{
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Monday, Tuesday",
    "periods": [{
        "openDay": "Monday",
        "openTime": "12:00",
        "closeDay": "Monday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Monday",
        "openTime": "19:00",
        "closeDay": "Monday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Monday",
        "openTime": "23:00",
        "closeDay": "Monday",
        "closeTime": "23:30"
      }
    ]
  },

As I don't care about changing the openDay/closeDay in the periods. I want to do this check for all days in the array.


来源: stackexchange

问:
jQuery get textarea text
Recently I have started playing with jQuery, and have been following a couple of tutorials. Now I feel slightly competent with using it (it's pretty easy), and I thought it would be cool if I were able to make a 'console' on my webpage (as in, you press the ` key like you do in FPS games, etc.), and then have it Ajax itself back to the server in-order to do stuff.

I originally thought the best way would be to just get the text inside the textarea, and then split it, or should I use the keyup event, convert the keycode returned to an ASCII character, append the character to a string and send the string to the server (then empty the string).

I couldn't find any information on getting text from a textarea, all I got was keyup information. Also, how can I convert the keycode returned to an ASCII character?

答:
you can get textarea data by name and id</p>

```<code>// by name
<textarea name="comment"></textarea>
let text_area_data = $('textarea[name="comment"]').val();

// by id
<textarea id="comment" name="comment"></textarea>
let text_area_data = $('textarea#comment').val();
</code>```

OwnerDisplayName: RodgerB

ContentLicense: CC BY-SA 3.0

Title: jQuery get textarea text

Body:
you can get textarea data by name and id

// by name
<textarea name="comment"></textarea>
let text_area_data = $('textarea[name="comment"]').val();

// by id
<textarea id="comment" name="comment"></textarea>
let text_area_data = $('textarea#comment').val();

ContentLicense: CC BY-SA 4.0


问:
Convert recursive MySQL query to PostgreSQL
I want to convert a working MySQL query to PostgreSQL.
I'm a newbee for PostgreSQL

Working MySQL query:

```<code>select  id,
        user_name,
        reported_to
from    (select * from user_master
         order by reported_to) orrdered,
        (select @pv := 'prathap Achuthan') initialisation
where   find_in_set(reported_to, @pv)
and     length(@pv := concat(@pv, ',', user_name))
</code>```

http://sqlfiddle.com/#!9/bb94707/2

答:
In PostgreSQL you can use a recursive CTE to implement this query:

```<code>WITH RECURSIVE CTE AS (
  SELECT id, user_name, reported_to
  FROM user_master
  WHERE reported_to = 'prathap Achuthan'
  UNION ALL
  SELECT um.*
  FROM user_master um
  JOIN CTE c ON c.user_name = um.reported_to
)
SELECT *
FROM CTE
</code>```

Output:

```<code>id  user_name               reported_to
7   Sriram Gopalakrishnan   prathap Achuthan
15  Shalini Jagdish         Sriram Gopalakrishnan
</code>```

Demo on SQLFiddle

Body:
I want to convert a working MySQL query to PostgreSQL.
I'm a newbee for PostgreSQL

Working MySQL query:

select  id,
        user_name,
        reported_to
from    (select * from user_master
         order by reported_to) orrdered,
        (select @pv := 'prathap Achuthan') initialisation
where   find_in_set(reported_to, @pv)
and     length(@pv := concat(@pv, ',', user_name))

http://sqlfiddle.com/#!9/bb94707/2

Body:
In PostgreSQL you can use a recursive CTE to implement this query:

WITH RECURSIVE CTE AS (
  SELECT id, user_name, reported_to
  FROM user_master
  WHERE reported_to = 'prathap Achuthan'
  UNION ALL
  SELECT um.*
  FROM user_master um
  JOIN CTE c ON c.user_name = um.reported_to
)
SELECT *
FROM CTE

Output:

id  user_name               reported_to
7   Sriram Gopalakrishnan   prathap Achuthan
15  Shalini Jagdish         Sriram Gopalakrishnan

Demo on SQLFiddle


问:
Calling a C++ function from python, using cython, with cythonize
I'm trying to learn Cython, and I want to call a simple C++ function from python

When building, I either have a uio.obj : error LNK2001: unresolved external symbol _just_a_func, or when I tried different combinations of cython prototypes, my just_a_func() function does not land in my module.

Here is all the code, setup.py, test.py, .pxd, .pyx and .h

```<code>########################
### uio.h
########################
#include <string>
using namespace std;
struct uio{
    int i;
    uio():i(2){}
    float f;
    string s;
    // float fun(int a);
    float fun(int a){return float(a+i);}

};

// int just_a_func(string s);
int just_a_func(string s){return s.length();}

########################
### uio.pxd
########################
from libcpp.string cimport string

cdef extern from "uio.h":
    cdef extern int just_a_func(string s)

########################
### uio.pyx
########################
# distutils: language = c++

from uio cimport just_a_func
cdef extern int just_a_func(s):
    return just_a_func(s)

########################
### setup.py
########################
# python .\setup.py build_ext --inplace --compiler=msvc

from setuptools import setup

from Cython.Build import cythonize

setup(ext_modules=cythonize("uio.pyx"))

########################
### test2.py
########################
import uio
print(dir(uio))
print("just_a_func", uio.just_a_func("fdsfds"))
</code>```

答:
Found a solution on https://dmtn-013.lsst.io/

This is the working solution

```<code>########################
### uio.h
########################
#include <string>
using namespace std;

int just_a_func(string s){return s.length();}

########################
### uio.pxd
########################
from libcpp.string cimport string
cdef extern from "uio.h":
    int just_a_func(string s)

########################
### uio.pyx
########################
# distutils: language = c++
# note the "as", this is a trick to avoid name clash, to allow the same function name
from uio cimport just_a_func as cjust_a_func

def just_a_func(s):
    return cjust_a_func(s)

########################
### setup.py
########################
# python .\setup.py build_ext --inplace --compiler=msvc

from setuptools import setup

from Cython.Build import cythonize

setup(ext_modules=cythonize("uio.pyx"))

########################
### test2.py
########################
import uio
from sys import argv
print(dir(uio))
print("just_a_func", uio.just_a_func((argv[1].encode())))
</code>```

Body:
I'm trying to learn Cython, and I want to call a simple C++ function from python

When building, I either have a uio.obj : error LNK2001: unresolved external symbol _just_a_func, or when I tried different combinations of cython prototypes, my just_a_func() function does not land in my module.

Here is all the code, setup.py, test.py, .pxd, .pyx and .h

########################
### uio.h
########################
#include <string>
using namespace std;
struct uio{
    int i;
    uio():i(2){}
    float f;
    string s;
    // float fun(int a);
    float fun(int a){return float(a+i);}

};

// int just_a_func(string s);
int just_a_func(string s){return s.length();}

########################
### uio.pxd
########################
from libcpp.string cimport string

cdef extern from "uio.h":
    cdef extern int just_a_func(string s)

########################
### uio.pyx
########################
# distutils: language = c++

from uio cimport just_a_func
cdef extern int just_a_func(s):
    return just_a_func(s)

########################
### setup.py
########################
# python .\setup.py build_ext --inplace --compiler=msvc

from setuptools import setup

from Cython.Build import cythonize

setup(ext_modules=cythonize("uio.pyx"))

########################
### test2.py
########################
import uio
print(dir(uio))
print("just_a_func", uio.just_a_func("fdsfds"))

Body:
Found a solution on https://dmtn-013.lsst.io/

This is the working solution

########################
### uio.h
########################
#include <string>
using namespace std;

int just_a_func(string s){return s.length();}

########################
### uio.pxd
########################
from libcpp.string cimport string
cdef extern from "uio.h":
    int just_a_func(string s)

########################
### uio.pyx
########################
# distutils: language = c++
# note the "as", this is a trick to avoid name clash, to allow the same function name
from uio cimport just_a_func as cjust_a_func

def just_a_func(s):
    return cjust_a_func(s)

########################
### setup.py
########################
# python .\setup.py build_ext --inplace --compiler=msvc

from setuptools import setup

from Cython.Build import cythonize

setup(ext_modules=cythonize("uio.pyx"))

########################
### test2.py
########################
import uio
from sys import argv
print(dir(uio))
print("just_a_func", uio.just_a_func((argv[1].encode())))


问:
Refresh or update the button action
```<code>-(IBAction)button:(id)sender
{
    button = [UIButton buttonWithType:UIBarButtonSystemItemRefresh];
    NSLog(@"Value of txtfrequency in button fuinction :%@",txtfrequency.text);
    int z = [txtfrequency.text  intValue];
    NSLog(@"Value of z is :%d",z);
    int y = 10;
    //create a new dynamic button
    for (int j=0; j<z; j++)
    {
        CGRect frame = CGRectMake(20, y , 50, 30);
        button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTag:j];
        button.frame = frame;
        CGRect frame1 = CGRectMake(100, y , 50, 30);

    textFieldRounded = [[UITextField alloc] initWithFrame:frame1];
    textFieldRounded.borderStyle =UIButtonTypeInfoDark;   //UITextBorderStyleNone;
    textFieldRounded.textColor = [UIColor blackColor]; //text color
    textFieldRounded.font = [UIFont systemFontOfSize:17.0];  //font size
    textFieldRounded.backgroundColor = [UIColor whiteColor]; //background color
    textFieldRounded.autocorrectionType = UITextAutocorrectionTypeNo;   // no auto correction support

    textFieldRounded.keyboardType = UIKeyboardTypeDefault;  // type of the keyboard
    textFieldRounded.returnKeyType = UIReturnKeyDone;  // type of the return key
    textFieldRounded.clearButtonMode = UITextFieldViewModeWhileEditing; // has a clear 'x' button to the right
    textFieldRounded.delegate = self;
    [textFieldRounded setTag:j];

    //[[scroll viewWithTag:j] removeFromSuperview];
    [button reloadInputViews];
    [textFieldRounded removeFromSuperview];

    //[scroll

    [scroll addSubview:button];
    scroll.contentSize= CGSizeMake(100, 1400);
    [scroll addSubview:textFieldRounded];
    y= y+50;

}
}
</code>```

Hii..

Above code generates no of buttons dynamically whenever user give input for buttons. But there is problem in this event.. e.g. User have given the input to generate 4 buttons ..then on view we get 4 buttons but now if user wantto have only 2 buttons then there is still 4 buttons on view. I am not able to refersh or update the action of button.

Anyone know how can I do this.

Please help me.

Thanks alot.

答:
Try remove all subviews from scrollview. just create a enumeration loop before adding buttons to scrollview like

```<code> for(UIView *v in scroll){
     [v removeFromSuperView];
  }
</code>```

put the above code before your loop.

Title: Refresh or update the button action

Body:
-(IBAction)button:(id)sender
{
    button = [UIButton buttonWithType:UIBarButtonSystemItemRefresh];
    NSLog(@"Value of txtfrequency in button fuinction :%@",txtfrequency.text);
    int z = [txtfrequency.text  intValue];
    NSLog(@"Value of z is :%d",z);
    int y = 10;
    //create a new dynamic button
    for (int j=0; j<z; j++)
    {
        CGRect frame = CGRectMake(20, y , 50, 30);
        button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTag:j];
        button.frame = frame;
        CGRect frame1 = CGRectMake(100, y , 50, 30);

    textFieldRounded = [[UITextField alloc] initWithFrame:frame1];
    textFieldRounded.borderStyle =UIButtonTypeInfoDark;   //UITextBorderStyleNone;
    textFieldRounded.textColor = [UIColor blackColor]; //text color
    textFieldRounded.font = [UIFont systemFontOfSize:17.0];  //font size
    textFieldRounded.backgroundColor = [UIColor whiteColor]; //background color
    textFieldRounded.autocorrectionType = UITextAutocorrectionTypeNo;   // no auto correction support

    textFieldRounded.keyboardType = UIKeyboardTypeDefault;  // type of the keyboard
    textFieldRounded.returnKeyType = UIReturnKeyDone;  // type of the return key
    textFieldRounded.clearButtonMode = UITextFieldViewModeWhileEditing; // has a clear 'x' button to the right
    textFieldRounded.delegate = self;
    [textFieldRounded setTag:j];

    //[[scroll viewWithTag:j] removeFromSuperview];
    [button reloadInputViews];
    [textFieldRounded removeFromSuperview];

    //[scroll

    [scroll addSubview:button];
    scroll.contentSize= CGSizeMake(100, 1400);
    [scroll addSubview:textFieldRounded];
    y= y+50;

}
}

Hii..

Above code generates no of buttons dynamically whenever user give input for buttons. But there is problem in this event.. e.g. User have given the input to generate 4 buttons ..then on view we get 4 buttons but now if user wantto have only 2 buttons then there is still 4 buttons on view. I am not able to refersh or update the action of button.

Anyone know how can I do this.

Please help me.

Thanks alot.

Body:
Try remove all subviews from scrollview. just create a enumeration loop before adding buttons to scrollview like

 for(UIView *v in scroll){
     [v removeFromSuperView];
  }

put the above code before your loop.


问:
Laravel `has` relationship count using parent column value
I want to grab records whose relation count is less than the value of a parent column.

I have a model called Dealer, which has an attribute called daily_assign_limit.

In the Dealer model, I have this relationship:

```<code>public function assigns()
{
    return $this->hasMany(Assign::class);
}

public function assigns_today()
{
    return $this->assigns()->whereDate('created_at', today());
}
</code>```

I have tried to query the dealers who haven't reached their daily_assign_limit using this method:

```<code>    return Dealer::query()
        ->has('assigns_today', '<', 'daily_assign_limit')
        ->first();
</code>```

It looks like has wants an integer instead of a column name. So how would I accomplish this using the parent column rather than a hard coded integer?

答:
I figured out how to do it by grabbing the results and looping through them, but I would still prefer if it was done via the query builder.

Here is my solution:

```<code>$dealers = Dealer::query()
    ->withCount('assigns_today')
    ->get();

foreach ($dealers as $dealer) {
    if ($dealer->assigns_today_count < $dealer->daily_assign_limit) {
        return $dealer;
    }
}

return null;
</code>```

If someone can show me how to do this without the foreach loop I would be grateful.

Body:
I want to grab records whose relation count is less than the value of a parent column.

I have a model called Dealer, which has an attribute called daily_assign_limit.

In the Dealer model, I have this relationship:

public function assigns()
{
    return $this->hasMany(Assign::class);
}

public function assigns_today()
{
    return $this->assigns()->whereDate('created_at', today());
}

I have tried to query the dealers who haven't reached their daily_assign_limit using this method:

    return Dealer::query()
        ->has('assigns_today', '<', 'daily_assign_limit')
        ->first();

It looks like has wants an integer instead of a column name. So how would I accomplish this using the parent column rather than a hard coded integer?

Body:
I figured out how to do it by grabbing the results and looping through them, but I would still prefer if it was done via the query builder.

Here is my solution:

$dealers = Dealer::query()
    ->withCount('assigns_today')
    ->get();

foreach ($dealers as $dealer) {
    if ($dealer->assigns_today_count < $dealer->daily_assign_limit) {
        return $dealer;
    }
}

return null;

If someone can show me how to do this without the foreach loop I would be grateful.


问:
error installing pytorch using pip on windows 10
I am trying to install pytorch with pip using

```<code>pip install torch
</code>```

or

```<code>pip3 install torch===1.3.1 torchvision===0.4.2 -f https://download.pytorch.org/whl/torch_stable.html
</code>```

with python 3.7.4

and with python 3.8 (latest stable release)

both on 32 and 64 bit.

and getting

```<code>Collecting torch   Using cached
https://files.pythonhosted.org/packages/f8/02/880b468bd382dc79896eaecbeb8ce95e9c4b99a24902874a2cef0b562cea/torch-0.1.2.post2.tar.gz
Collecting pyyaml (from torch)   Downloading
https://files.pythonhosted.org/packages/bc/3f/4f733cd0b1b675f34beb290d465a65e0f06b492c00b111d1b75125062de1/PyYAML-5.1.2-cp37-cp37m-win_amd64.whl
(215kB)
    100% |████████████████████████████████| 225kB 1.2MB/s Installing collected packages: pyyaml, torch   Running setup.py install for torch
... error
    Complete output from command C:\Noam\Code\threadart\stav-rl\venv\Scripts\python.exe -u -c "import
setuptools,
tokenize;__file__='C:\\Users\\noams\\AppData\\Local\\Temp\\pip-install-djc6s2t8\\torch\\setup.py';f=getattr(tokenize,
'open', open)(__file__);code=f.read( ).replace('\r\n',
'\n');f.close();exec(compile(code, __file__, 'exec'))" install
--record C:\Users\noams\AppData\Local\Temp\pip-record-zohv2zo7\install-record.txt
--single-version-externally-managed --compile --install-headers C:\Noam\Code\threadart\stav-rl\venv\inclu de\site\python3.7\torch:
    running install
    running build_deps
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\noams\AppData\Local\Temp\pip-install-djc6s2t8\torch\setup.py",
line 265, in <module>
        description="Tensors and Dynamic neural networks in Python with strong GPU acceleration",
      File "C:\Noam\Code\threadart\stav-rl\venv\lib\site-packages\setuptools-40.8.0-py3.7.egg\setuptools\__init__.py",
line 145, in setup
      File "C:\Python37_x64\lib\distutils\core.py", line 148, in setup
        dist.run_commands()
      File "C:\Python37_x64\lib\distutils\dist.py", line 966, in run_commands
        self.run_command(cmd)
      File "C:\Python37_x64\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "C:\Users\noams\AppData\Local\Temp\pip-install-djc6s2t8\torch\setup.py",
line 99, in run
        self.run_command('build_deps')
      File "C:\Python37_x64\lib\distutils\cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "C:\Python37_x64\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "C:\Users\noams\AppData\Local\Temp\pip-install-djc6s2t8\torch\setup.py",
line 51, in run
        from tools.nnwrap import generate_wrappers as generate_nn_wrappers
    ModuleNotFoundError: No module named 'tools.nnwrap'

    ---------------------------------------- Command "C:\Noam\Code\threadart\stav-rl\venv\Scripts\python.exe -u -c "import
setuptools,
tokenize;__file__='C:\\Users\\noams\\AppData\\Local\\Temp\\pip-install-djc6s2t8\\torch\\setup.py';f=getattr(tokenize,
'open', open)(__file__);code=f.read().replace('\r\n', '\n');
f.close();exec(compile(code, __file__, 'exec'))" install --record
C:\Users\noams\AppData\Local\Temp\pip-record-zohv2zo7\install-record.txt
--single-version-externally-managed --compile --install-headers C:\Noam\Code\threadart\stav-rl\venv\include\site\python3.7\torch"
failed with error code 1 in
C:\Users\noams\AppData\Local\Temp\pip-install-djc6s2t8\torch\
</code>```

clearly, I am doing something wrong.

Please help!

答:
I had the same problem. Now the problem is fixed. (2020-05-31)

Visited the site pytorch.org

and find "QUICK START LOCALLY" on homepage of pytorch.org. ( it' can find by scroll down little )

Checking the environment form of your system
(ex: Windows, pip, python, ,,)
then, you can see the install command.
"pip install torch===.... "

Copy the install command

and Execute the command at your system.

Good Luck !!

Body:
I am trying to install pytorch with pip using

pip install torch

or

pip3 install torch===1.3.1 torchvision===0.4.2 -f https://download.pytorch.org/whl/torch_stable.html

with python 3.7.4

and with python 3.8 (latest stable release)

both on 32 and 64 bit.

and getting

Collecting torch   Using cached
https://files.pythonhosted.org/packages/f8/02/880b468bd382dc79896eaecbeb8ce95e9c4b99a24902874a2cef0b562cea/torch-0.1.2.post2.tar.gz
Collecting pyyaml (from torch)   Downloading
https://files.pythonhosted.org/packages/bc/3f/4f733cd0b1b675f34beb290d465a65e0f06b492c00b111d1b75125062de1/PyYAML-5.1.2-cp37-cp37m-win_amd64.whl
(215kB)
    100% |████████████████████████████████| 225kB 1.2MB/s Installing collected packages: pyyaml, torch   Running setup.py install for torch
... error
    Complete output from command C:\Noam\Code\threadart\stav-rl\venv\Scripts\python.exe -u -c "import
setuptools,
tokenize;__file__='C:\\Users\\noams\\AppData\\Local\\Temp\\pip-install-djc6s2t8\\torch\\setup.py';f=getattr(tokenize,
'open', open)(__file__);code=f.read( ).replace('\r\n',
'\n');f.close();exec(compile(code, __file__, 'exec'))" install
--record C:\Users\noams\AppData\Local\Temp\pip-record-zohv2zo7\install-record.txt
--single-version-externally-managed --compile --install-headers C:\Noam\Code\threadart\stav-rl\venv\inclu de\site\python3.7\torch:
    running install
    running build_deps
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\noams\AppData\Local\Temp\pip-install-djc6s2t8\torch\setup.py",
line 265, in <module>
        description="Tensors and Dynamic neural networks in Python with strong GPU acceleration",
      File "C:\Noam\Code\threadart\stav-rl\venv\lib\site-packages\setuptools-40.8.0-py3.7.egg\setuptools\__init__.py",
line 145, in setup
      File "C:\Python37_x64\lib\distutils\core.py", line 148, in setup
        dist.run_commands()
      File "C:\Python37_x64\lib\distutils\dist.py", line 966, in run_commands
        self.run_command(cmd)
      File "C:\Python37_x64\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "C:\Users\noams\AppData\Local\Temp\pip-install-djc6s2t8\torch\setup.py",
line 99, in run
        self.run_command('build_deps')
      File "C:\Python37_x64\lib\distutils\cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "C:\Python37_x64\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "C:\Users\noams\AppData\Local\Temp\pip-install-djc6s2t8\torch\setup.py",
line 51, in run
        from tools.nnwrap import generate_wrappers as generate_nn_wrappers
    ModuleNotFoundError: No module named 'tools.nnwrap'

    ---------------------------------------- Command "C:\Noam\Code\threadart\stav-rl\venv\Scripts\python.exe -u -c "import
setuptools,
tokenize;__file__='C:\\Users\\noams\\AppData\\Local\\Temp\\pip-install-djc6s2t8\\torch\\setup.py';f=getattr(tokenize,
'open', open)(__file__);code=f.read().replace('\r\n', '\n');
f.close();exec(compile(code, __file__, 'exec'))" install --record
C:\Users\noams\AppData\Local\Temp\pip-record-zohv2zo7\install-record.txt
--single-version-externally-managed --compile --install-headers C:\Noam\Code\threadart\stav-rl\venv\include\site\python3.7\torch"
failed with error code 1 in
C:\Users\noams\AppData\Local\Temp\pip-install-djc6s2t8\torch\

clearly, I am doing something wrong.

Please help!


问:
Keras: change learning rate
I'm trying to change the learning rate of my model after it has been trained with a different learning rate.

I read here, here, here and some other places i can't even find anymore.

I tried:

```<code>model.optimizer.learning_rate.set_value(0.1)
model.optimizer.lr = 0.1
model.optimizer.learning_rate = 0.1
K.set_value(model.optimizer.learning_rate, 0.1)
K.set_value(model.optimizer.lr, 0.1)
model.optimizer.lr.assign(0.1)
</code>```

... but none of them worked!
I don't understand how there could be such confusion around such a simple thing. Am I missing something?

EDIT: Working example

Here is a working example of what I'd like to do:

```<code>from keras.models import Sequential
from keras.layers import Dense
import keras
import numpy as np

model = Sequential()

model.add(Dense(1, input_shape=(10,)))

optimizer = keras.optimizers.Adam(lr=0.01)
model.compile(loss='mse',
              optimizer=optimizer)

model.fit(np.random.randn(50,10), np.random.randn(50), epochs=50)

# Change learning rate to 0.001 and train for 50 more epochs

model.fit(np.random.randn(50,10), np.random.randn(50), initial_epoch=50, epochs=50)
</code>```

答:
You can change the learning rate as follows:

```<code>from keras import backend as K
K.set_value(model.optimizer.learning_rate, 0.001)
</code>```

Included into your complete example it looks as follows:

```<code>from keras.models import Sequential
from keras.layers import Dense
from keras import backend as K
import keras
import numpy as np

model = Sequential()

model.add(Dense(1, input_shape=(10,)))

optimizer = keras.optimizers.Adam(lr=0.01)
model.compile(loss='mse', optimizer=optimizer)

print("Learning rate before first fit:", model.optimizer.learning_rate.numpy())

model.fit(np.random.randn(50,10), np.random.randn(50), epochs=50, verbose=0)

# Change learning rate to 0.001 and train for 50 more epochs
K.set_value(model.optimizer.learning_rate, 0.001)
print("Learning rate before second fit:", model.optimizer.learning_rate.numpy())

model.fit(np.random.randn(50,10),
          np.random.randn(50),
          initial_epoch=50,
          epochs=50,
          verbose=0)
</code>```

I've just tested this with keras 2.3.1. Not sure why the approach didn't seem to work for you.

Title: Keras: change learning rate

Body:
I'm trying to change the learning rate of my model after it has been trained with a different learning rate.

I read here, here, here and some other places i can't even find anymore.

I tried:

model.optimizer.learning_rate.set_value(0.1)
model.optimizer.lr = 0.1
model.optimizer.learning_rate = 0.1
K.set_value(model.optimizer.learning_rate, 0.1)
K.set_value(model.optimizer.lr, 0.1)
model.optimizer.lr.assign(0.1)

... but none of them worked!
I don't understand how there could be such confusion around such a simple thing. Am I missing something?

EDIT: Working example

Here is a working example of what I'd like to do:

from keras.models import Sequential
from keras.layers import Dense
import keras
import numpy as np

model = Sequential()

model.add(Dense(1, input_shape=(10,)))

optimizer = keras.optimizers.Adam(lr=0.01)
model.compile(loss='mse',
              optimizer=optimizer)

model.fit(np.random.randn(50,10), np.random.randn(50), epochs=50)

# Change learning rate to 0.001 and train for 50 more epochs

model.fit(np.random.randn(50,10), np.random.randn(50), initial_epoch=50, epochs=50)

Body:
You can change the learning rate as follows:

from keras import backend as K
K.set_value(model.optimizer.learning_rate, 0.001)

Included into your complete example it looks as follows:

from keras.models import Sequential
from keras.layers import Dense
from keras import backend as K
import keras
import numpy as np

model = Sequential()

model.add(Dense(1, input_shape=(10,)))

optimizer = keras.optimizers.Adam(lr=0.01)
model.compile(loss='mse', optimizer=optimizer)

print("Learning rate before first fit:", model.optimizer.learning_rate.numpy())

model.fit(np.random.randn(50,10), np.random.randn(50), epochs=50, verbose=0)

# Change learning rate to 0.001 and train for 50 more epochs
K.set_value(model.optimizer.learning_rate, 0.001)
print("Learning rate before second fit:", model.optimizer.learning_rate.numpy())

model.fit(np.random.randn(50,10),
          np.random.randn(50),
          initial_epoch=50,
          epochs=50,
          verbose=0)

I've just tested this with keras 2.3.1. Not sure why the approach didn't seem to work for you.


问:
Scraping links with selenium
I was working to scrape links to articles on a website. But normally when site was loaded it list only 5 articles then it requires to click load more button to display more articles list.
Html source has only links to first five articles.

I used selenium python to automate clicking load more button to completely load webpage with all article listings.

Question is now how can i extract links to all those articles.

After loading site completely with selenium i tried to get html source with driver.page_source and printed it but still it has only link to first 5 articles.

I want to get links to all those articles that were loaded in webpage after clicking load more button.

Please someone help to provide solution.

答:
Maybe the links take some time to show up and your code is doing driver.source_code before the source code is updated. You can select the links with Selenium after an explicit wait so that you can make sure that the links that are dinamically added to the web page are fully loaded. It is difficult to boil down exactly what you need without a link to your source, but (in Python) it should be something similar to:

from selenium.webdriver.support.ui import WebDriverWait

def condition(driver):
    """If the selector defined in the function retrieves 10 or more results, return the results.
    Else, return None.
    """
    selector = 'a.my_class' # Selects all  tags with the class "my_class"
    els = driver.find_elements_by_css_selector(selector)
    if len(els) >= 10:
        return els

# Making an assignment only when the condition returns a truthy value when called (waiting until 2 min):
links_elements = WebDriverWait(driver, timeout=120).until(condition)
# Getting the href attribute of the links
links_href = [link.get_attribute('href') for link in links_elements]
```

In this code, you are:

Constantly looking for the elements you want until there are 10 or more of them. You can do this by CSS Selector (as in the example), XPath or other method. This gives you a list of Selenium objects as soon as the wait condition returns an object with a True value, until a certain timeout. See more on explicit waits in the documentation. You should make the appropriate condition for your case - maybe expecting a certain number of links is not good if you are not sure of how many links there will be in the end.

Extracting what you want from the Selenium object. For that, use the appropriate method over the elements in the list you got from the step above.

Title: Scraping links with selenium

Body:
Maybe the links take some time to show up and your code is doing driver.source_code before the source code is updated. You can select the links with Selenium after an explicit wait so that you can make sure that the links that are dinamically added to the web page are fully loaded. It is difficult to boil down exactly what you need without a link to your source, but (in Python) it should be something similar to:

from selenium.webdriver.support.ui import WebDriverWait

def condition(driver):
    """If the selector defined in the function retrieves 10 or more results, return the results.
    Else, return None.
    """
    selector = 'a.my_class' # Selects all <a> tags with the class "my_class"
    els = driver.find_elements_by_css_selector(selector)
    if len(els) >= 10:
        return els

# Making an assignment only when the condition returns a truthy value when called (waiting until 2 min):
links_elements = WebDriverWait(driver, timeout=120).until(condition)
# Getting the href attribute of the links
links_href = [link.get_attribute('href') for link in links_elements]

In this code, you are:

Constantly looking for the elements you want until there are 10 or more of them. You can do this by CSS Selector (as in the example), XPath or other method. This gives you a list of Selenium objects as soon as the wait condition returns an object with a True value, until a certain timeout. See more on explicit waits in the documentation. You should make the appropriate condition for your case - maybe expecting a certain number of links is not good if you are not sure of how many links there will be in the end.

Extracting what you want from the Selenium object. For that, use the appropriate method over the elements in the list you got from the step above.


问:
How can i set state value after destructing in React Hooks?
I tried to destructure and set the value in state using React Hooks,but their it shows a syntax error.Since i am new on react JS,please help me for the solution.

Following below is my code:

I set the state as following:

```<code>const [Datasets, setDatasets] = useState({
  labels: [],
  datasets: [{
      label: 'Total Cases',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(100,19,12,1)',
      borderColor: 'green',
      borderWidth: 2,
      data: []
    },
    {
      label: 'Total Recovered',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(75,192,192,1)',
      borderColor: 'rgba(0,0,0,1)',
      borderWidth: 2,
      data: []
    },
    {
      label: 'Total Deaths',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(75,192,192,1)',
      borderColor: 'rgba(0,0,0,1)',
      borderWidth: 2,
      data: []
    }
  ]
})
</code>```

I used useEffect to fetch data from API and set state.Following are my codes on useEffect:

```<code>useEffect(() => {
  axios.get('https://data.nepalcorona.info/api/v1/covid/timeline')
    .then(res => {
      setTimelinedata(res.data)
      setDatasets({ ...Datasets, labels: res.data.map((item) => item.date) })
      setDatasets([Datasets.datasets[0].data: res.data.map((item) => item.totalCases)])
        .catch(err => {
          console.log("error>>", err);
        })
    })
</code>```

when i try to run the code the  error is shown in the following code:

```<code>setDatasets([Datasets.datasets[0].data: res.data.map((item) => item.totalCases)])
</code>```

following error is shown:

following are the data i have fetched from the API:

Please help me for the solution.

答:
Please useEffect with below one. Moreover, you should use empty dependency array [] as an second parameter in useEffect to run api once. Moreover, you missed to put }) before catch

```<code>useEffect(() => {
        axios.get('https://data.nepalcorona.info/api/v1/covid/timeline')
            .then(res => {
                setTimelinedata(res.data);
                setDatasets({...Datasets, labels: res.data.map((item) => item.date)});
                let newDatasets = {...Datasets};
                newDatasets.datasets[0].data = res.data.map((item) => item.totalCases);
                newDatasets.datasets[1].data = res.data.map((item) => item.newRecoveries);
                newDatasets.datasets[2].data = res.data.map((item) => item.totalDeaths);
                setDatasets({...Datasets, ...newDatasets});

                console.log(Datasets, 'datasets');
            })
            .catch(err => {
                console.log("error>>", err);
            })
    }, []);
</code>```

Body:
I tried to destructure and set the value in state using React Hooks,but their it shows a syntax error.Since i am new on react JS,please help me for the solution.

Following below is my code:

I set the state as following:

const [Datasets, setDatasets] = useState({
  labels: [],
  datasets: [{
      label: 'Total Cases',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(100,19,12,1)',
      borderColor: 'green',
      borderWidth: 2,
      data: []
    },
    {
      label: 'Total Recovered',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(75,192,192,1)',
      borderColor: 'rgba(0,0,0,1)',
      borderWidth: 2,
      data: []
    },
    {
      label: 'Total Deaths',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(75,192,192,1)',
      borderColor: 'rgba(0,0,0,1)',
      borderWidth: 2,
      data: []
    }
  ]
})

I used useEffect to fetch data from API and set state.Following are my codes on useEffect:

useEffect(() => {
  axios.get('https://data.nepalcorona.info/api/v1/covid/timeline')
    .then(res => {
      setTimelinedata(res.data)
      setDatasets({ ...Datasets, labels: res.data.map((item) => item.date) })
      setDatasets([Datasets.datasets[0].data: res.data.map((item) => item.totalCases)])
        .catch(err => {
          console.log("error>>", err);
        })
    })

when i try to run the code the  error is shown in the following code:

setDatasets([Datasets.datasets[0].data: res.data.map((item) => item.totalCases)])

following error is shown:

following are the data i have fetched from the API:

Please help me for the solution.

Body:
Please useEffect with below one. Moreover, you should use empty dependency array [] as an second parameter in useEffect to run api once. Moreover, you missed to put }) before catch

useEffect(() => {
        axios.get('https://data.nepalcorona.info/api/v1/covid/timeline')
            .then(res => {
                setTimelinedata(res.data);
                setDatasets({...Datasets, labels: res.data.map((item) => item.date)});
                let newDatasets = {...Datasets};
                newDatasets.datasets[0].data = res.data.map((item) => item.totalCases);
                newDatasets.datasets[1].data = res.data.map((item) => item.newRecoveries);
                newDatasets.datasets[2].data = res.data.map((item) => item.totalDeaths);
                setDatasets({...Datasets, ...newDatasets});

                console.log(Datasets, 'datasets');
            })
            .catch(err => {
                console.log("error>>", err);
            })
    }, []);


问:
How to access the current IWorld Instance of the Overworld from a seperate class
I'm currently trying to modify a Specific Block's BlockState (at a known position) from a seperate thread which is watching and waiting for external events to occur (not Minecraft related). To do this I would be required to get the overworld World Instance and call the setBlockState method of the IWorld class. Since this seperate thread isn't passed any Server or World parameters, I need to somehow get the instance manually (possibly from a public static variable or a getter method)

Is there a simple way to get an IWorld instance of the current Overworld from a class (An alternative to the unavailable MinecraftServer.getServer() method)?

答:
By following the usages, implementations, and hierarchies of the MinecraftServer parameter, I discovered the ServerLifecycleHooks class with the following declaration private static MinecraftServer currentServer which contains a reference to the current running MinecraftServer instance. This variable has a getter method which can be called through ServerLifecycleHooks.getCurrentServer().

You can then store the server instance or immediately call the getWorld(DimensionType dimension) method on it to get a reference of any of the Worlds. This function returns a MinecraftServer type which extends the IWorld type and can be used as you needed. An example implementation would be as follows to get the Overworld, Nether and End worlds respectively:

```<code>MinecraftServer currentServer = ServerLifecycleHooks.getCurrentServer();

IWorld currentOverworld = currentServer.getWorld(DimensionType.OVERWORLD);
IWorld currentNether = currentServer.getWorld(DimensionType.THE_NETHER);
IWorld currentEnd = currentServer.getWorld(DimensionType.THE_END);
</code>```

Body:
By following the usages, implementations, and hierarchies of the MinecraftServer parameter, I discovered the ServerLifecycleHooks class with the following declaration private static MinecraftServer currentServer which contains a reference to the current running MinecraftServer instance. This variable has a getter method which can be called through ServerLifecycleHooks.getCurrentServer().

You can then store the server instance or immediately call the getWorld(DimensionType dimension) method on it to get a reference of any of the Worlds. This function returns a MinecraftServer type which extends the IWorld type and can be used as you needed. An example implementation would be as follows to get the Overworld, Nether and End worlds respectively:

MinecraftServer currentServer = ServerLifecycleHooks.getCurrentServer();

IWorld currentOverworld = currentServer.getWorld(DimensionType.OVERWORLD);
IWorld currentNether = currentServer.getWorld(DimensionType.THE_NETHER);
IWorld currentEnd = currentServer.getWorld(DimensionType.THE_END);


问:
Cannot assign to read only property on deep copied object
I am using angular 9 and ngrx 9

I have a selector that do like this :

```<code>    this.store$
      .pipe(select(SettingsStoreSelectors.selectNavigationSettings), take(1))
      .subscribe((settings: SettingsStoreModels.INavigationSettings) => {
        let copy = JSON.parse(JSON.stringify(settings));
        this.settings = copy.vrMapSettings;
      });
</code>```

This is the only place settings is assigned in this component

In the component I then have a checkbox that edit a setting property

```<code>      <mat-checkbox
        class="setting-input"
        *ngIf="viewer"
        (click)="$event.stopPropagation()"
        (change)="onSettingChange(settings, true)"
        [(ngModel)]="settings.depthTestAgainstTerrain"
      >
        {{ "MAP.SETTINGS.DEPTH_TEST_AGAINST_TERRAIN" | translate }}
      </mat-checkbox>
</code>```

This keeps triggering

core.js:4117 ERROR TypeError: Cannot assign to read only property 'depthTestAgainstTerrain' of object '[object Object]'

But I don't understand anymore what to do. I deep cloned my store property, I want to edit to resubmit an action but it's not possible. why...

EDIT : actually I found out the reason why but I do not understand how to use it correctly then.

I deep clone the object like above from my selector

When a setting change, I dispatch an action to change the setting object in the store : this action setting object reference the same object that is used by the component.

```<code>this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({ settings: { vrMapSettings: settings } }));
</code>```

Which call this reducer :

```<code>const SET_NAVIGATION_SETTINGS = (state: State, action: featureAction.SetNavigationSettings) => {
  return {
    ...state,
    navigation: {
      ...state.navigation,
      ...action.payload.settings,
    },
  };
};
</code>```

But then, if I edit again, since the store reference directly the setting object of the component, it trigger the error....

If I deep clone here too

```<code>this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({ settings: { vrMapSettings: JSON.parse(JSON.stringify(settings))} }));
</code>```

The it works...

But if I have to create small action for EVERY property of settings, or deep clone for EVERY dispatch/selection of the store, there is going to be a HUGE flaw in the performance...

am I using it correctly ?

if need more information please comment I will provide.

答:
You're right, a state should be mutated only via actions. In you case, if the settings object has a lot of properties, it might be inconvenient to create a different action for each of the properties. A copying of the settings looks like a solution but deep object copying complexity depends on the object size.

I can suggest you use immer to create copies of the settings. Instead of copying the whole object it reuses all its unchanged parts that works much faster.

...
<mat-checkbox
  class="setting-input"
  *ngIf="viewer"
  (click)="$event.stopPropagation()"
  (change)="onDepthTestAgainstTerrainChange($event)"
  [checked]="settings.depthTestAgainstTerrain">
  {{ "MAP.SETTINGS.DEPTH_TEST_AGAINST_TERRAIN" | translate }}
</mat-checkbox>
...
```

<pre class="lang-js prettyprint-override"><code>@Component(...)
export class MyComponent {
  ...
  onDepthTestAgainstTerrainChange(change: MatCheckboxChange) {
    const patchedSettings = produce(settings, draft => {
      // draft remembers all the changes you've made and produces
      // new immutable state based on these mutations, but takes all
      // unchanged parts of the original object
      draft.depthTestAgainstTerrain = change.checked;
    });

    this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({
      settings: { vrMapSettings: patchedSettings}
    }));
  }
}
</code>```

Or you can create an action which accepts a patch function, like:

  onDepthTestAgainstTerrainChange(change: MatCheckboxChange) {
    this.store$.dispatch(new SettingsStoreAction.PatchNavigationSettings(sttingsDraft => {
      sttingsDraft.depthTestAgainstTerrain = change.checked;
    }));
  }
```

Body:
I am using angular 9 and ngrx 9

I have a selector that do like this :

    this.store$
      .pipe(select(SettingsStoreSelectors.selectNavigationSettings), take(1))
      .subscribe((settings: SettingsStoreModels.INavigationSettings) => {
        let copy = JSON.parse(JSON.stringify(settings));
        this.settings = copy.vrMapSettings;
      });

This is the only place settings is assigned in this component

In the component I then have a checkbox that edit a setting property

      <mat-checkbox
        class="setting-input"
        *ngIf="viewer"
        (click)="$event.stopPropagation()"
        (change)="onSettingChange(settings, true)"
        [(ngModel)]="settings.depthTestAgainstTerrain"
      >
        {{ "MAP.SETTINGS.DEPTH_TEST_AGAINST_TERRAIN" | translate }}
      </mat-checkbox>

This keeps triggering

core.js:4117 ERROR TypeError: Cannot assign to read only property 'depthTestAgainstTerrain' of object '[object Object]'

But I don't understand anymore what to do. I deep cloned my store property, I want to edit to resubmit an action but it's not possible. why...

EDIT : actually I found out the reason why but I do not understand how to use it correctly then.

I deep clone the object like above from my selector

When a setting change, I dispatch an action to change the setting object in the store : this action setting object reference the same object that is used by the component.

this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({ settings: { vrMapSettings: settings } }));

Which call this reducer :

const SET_NAVIGATION_SETTINGS = (state: State, action: featureAction.SetNavigationSettings) => {
  return {
    ...state,
    navigation: {
      ...state.navigation,
      ...action.payload.settings,
    },
  };
};

But then, if I edit again, since the store reference directly the setting object of the component, it trigger the error....

If I deep clone here too

this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({ settings: { vrMapSettings: JSON.parse(JSON.stringify(settings))} }));

The it works...

But if I have to create small action for EVERY property of settings, or deep clone for EVERY dispatch/selection of the store, there is going to be a HUGE flaw in the performance...

am I using it correctly ?

if need more information please comment I will provide.

Body:
You're right, a state should be mutated only via actions. In you case, if the settings object has a lot of properties, it might be inconvenient to create a different action for each of the properties. A copying of the settings looks like a solution but deep object copying complexity depends on the object size.

I can suggest you use immer to create copies of the settings. Instead of copying the whole object it reuses all its unchanged parts that works much faster.

...
<mat-checkbox
  class="setting-input"
  *ngIf="viewer"
  (click)="$event.stopPropagation()"
  (change)="onDepthTestAgainstTerrainChange($event)"
  [checked]="settings.depthTestAgainstTerrain">
  {{ "MAP.SETTINGS.DEPTH_TEST_AGAINST_TERRAIN" | translate }}
</mat-checkbox>
...

@Component(...)
export class MyComponent {
  ...
  onDepthTestAgainstTerrainChange(change: MatCheckboxChange) {
    const patchedSettings = produce(settings, draft => {
      // draft remembers all the changes you've made and produces
      // new immutable state based on these mutations, but takes all
      // unchanged parts of the original object
      draft.depthTestAgainstTerrain = change.checked;
    });

    this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({
      settings: { vrMapSettings: patchedSettings}
    }));
  }
}

Or you can create an action which accepts a patch function, like:

  onDepthTestAgainstTerrainChange(change: MatCheckboxChange) {
    this.store$.dispatch(new SettingsStoreAction.PatchNavigationSettings(sttingsDraft => {
      sttingsDraft.depthTestAgainstTerrain = change.checked;
    }));
  }


问:
Shadow MQTT - reg
I am using aws-iot-ask-python to communicate with the AWS IOT on the cloud. I have created a shadow to the "thing". I want to perform "update" operation.

I am publishing to the $aws/things/thingName/shadow/update from the AWS IOT test. On the device side I want to subscribe to $aws/things/thingName/shadow/update/accepted and $aws/things/thingName/shadow/update/rejected.

The problem is the function provided by the SDK is shadowUpdate(jsonPacket, CallbackFunction, timeout) but this function performs both the publish and subscribe operations at the same time. According to my requirement I don't want to perform publish from device. Can u guys suggest me a solution to this problem.

答:
The device can subscribe for shadow updates by using shadowRegisterDeltaCallback(). Alternatively it can get the current state using shadowGet().

See https://s3.amazonaws.com/aws-iot-device-sdk-python-docs/html/index.html#AWSIoTPythonSDK.core.shadow.deviceShadow.deviceShadow.shadowRegisterDeltaCallback and https://s3.amazonaws.com/aws-iot-device-sdk-python-docs/html/index.html#AWSIoTPythonSDK.core.shadow.deviceShadow.deviceShadow.shadowGet

Title: Shadow MQTT - reg


问:
Converting LME4 model result to latex (with longtable support)
It seems that the getSummary function for LME4 objects no longer plays well with the memisc package, and outputting LME4 model results to latex no longer works. The only alternative for exporting objects through stargazer however does not allow longtables. Has anyone come up with either a fix for the mtable format, or an alternative way to output these results into a longtable?

Edit:

Here is a reproducible example.

```<code>library(lme4)
library(memisc)

fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
mtable(fm1)
</code>```

This used to work, but I believe that lme4 now produces a new object that is no longer recognized by the mtable/getsummary command.

答:
Try this package stargazer

```<code>library(stargazer)

fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
stargazer(fm1, title="Results", align=TRUE)
</code>```

Body:
It seems that the getSummary function for LME4 objects no longer plays well with the memisc package, and outputting LME4 model results to latex no longer works. The only alternative for exporting objects through stargazer however does not allow longtables. Has anyone come up with either a fix for the mtable format, or an alternative way to output these results into a longtable?

Edit:

Here is a reproducible example.

library(lme4)
library(memisc)

fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
mtable(fm1)

This used to work, but I believe that lme4 now produces a new object that is no longer recognized by the mtable/getsummary command.

Body:
Try this package stargazer

library(stargazer)

fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
stargazer(fm1, title="Results", align=TRUE)


问:
JavaScript - Loop between two dates. Start and end date
I'm trying to console.log all the dates between two dates.

Here is the code i have so far:

```<code>    var dString = "18.04.2018";
    var dParts = dString.split('.');
    var in30Days = new Date(dParts[2] + '/' +
                            dParts[1] + '/' +
                            (+dParts[0] + 10)
                   );
    var endDate =  in30Days.getDate() + "." + (in30Days.getMonth()+1) + "." +in30Days.getFullYear();
    console.log("Now:" + dString + " EndDate: " + endDate);

    for (var d = dString; d <= endDate; d.setDate(d.getDate() + 1)) {
        var loopDay = new Date(d);
        console.log("Day:" + loopDay);
    }
</code>```

The end date is the start date plus 10 days.

Here is the console log output i receive:

```<code>Now:18.04.2018 EndDate: 28.4.2018
Day:Invalid Date
</code>```

Why the date is invalid. Where is my mistake ?

答:
Here is a code which displays the result between two different dates in an array:

 $('#button').on('click',function(){
    var end = $('#end').val()
    var start = $('#start').val()
    var tableau = testdiff(new Date(start),new Date(end));
    console.log(tableau);
  })

  function testdiff(from,to){
    var resultat=[];
    while (from <= to) {
        var dd = from.getDate();
        var mm = from.getMonth()+1;
        var yyyy = from.getFullYear();
        if(dd<10) {dd='0'+dd;}
        if(mm<10){mm='0'+mm;}
        var vDate = yyyy+'-'+mm+'-'+dd;
        resultat.push(vDate);
        from = new Date(from.setDate(from.getDate() + 1));
    }
    return resultat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<div class="my-2 mx-2">
        <div class="col-sm-4">
            <label for="">Start date</label>
            <input type="date" name="start" id="start" class="form-control form-control-sm">
        </div>
        <div class="col-sm-4">
            <label for=""> End date</label>
            <input type="date" name="end" id="end" class="form-control form-control-sm">
        </div>
        <div class="col-sm-4 my-3">
            <button type="button" id="button" class="btn btn-primary form-control">clic</button>
        </div>

    </div>
    <script
  src="https://code.jquery.com/jquery-3.5.1.js"
  integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
  crossorigin="anonymous"></script></code>```

Body:
I'm trying to console.log all the dates between two dates.

Here is the code i have so far:

    var dString = "18.04.2018";
    var dParts = dString.split('.');
    var in30Days = new Date(dParts[2] + '/' +
                            dParts[1] + '/' +
                            (+dParts[0] + 10)
                   );
    var endDate =  in30Days.getDate() + "." + (in30Days.getMonth()+1) + "." +in30Days.getFullYear();
    console.log("Now:" + dString + " EndDate: " + endDate);

    for (var d = dString; d <= endDate; d.setDate(d.getDate() + 1)) {
        var loopDay = new Date(d);
        console.log("Day:" + loopDay);
    }

The end date is the start date plus 10 days.

Here is the console log output i receive:

Now:18.04.2018 EndDate: 28.4.2018
Day:Invalid Date

Why the date is invalid. Where is my mistake ?

Body:
Here is a code which displays the result between two different dates in an array:

 $('#button').on('click',function(){
    var end = $('#end').val()
    var start = $('#start').val()
    var tableau = testdiff(new Date(start),new Date(end));
    console.log(tableau);
  })

  function testdiff(from,to){
    var resultat=[];
    while (from <= to) {
        var dd = from.getDate();
        var mm = from.getMonth()+1;
        var yyyy = from.getFullYear();
        if(dd<10) {dd='0'+dd;}
        if(mm<10){mm='0'+mm;}
        var vDate = yyyy+'-'+mm+'-'+dd;
        resultat.push(vDate);
        from = new Date(from.setDate(from.getDate() + 1));
    }
    return resultat;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<div class="my-2 mx-2">
        <div class="col-sm-4">
            <label for="">Start date</label>
            <input type="date" name="start" id="start" class="form-control form-control-sm">
        </div>
        <div class="col-sm-4">
            <label for=""> End date</label>
            <input type="date" name="end" id="end" class="form-control form-control-sm">
        </div>
        <div class="col-sm-4 my-3">
            <button type="button" id="button" class="btn btn-primary form-control">clic</button>
        </div>

    </div>
    <script
  src="https://code.jquery.com/jquery-3.5.1.js"
  integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
  crossorigin="anonymous"></script>


问:
Unable to push to navigation controller
```<code> override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 1: try loading the "Detail" view controller and typecasting it to be DetailViewController
    if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
        // 2: success! Set its selectedImage property
        vc.selectedImage = pictures[indexPath.row]

        // 3: now push it onto the navigation controller
        navigationController?.pushViewController(vc, animated: true)
    }
}
</code>```

I am facing issue -
1.Cast from 'UIViewController?' to unrelated type 'DetailViewController' always fails
2.Cannot convert value of type 'DetailViewController' to expected argument type 'UIViewController'

答:
Seems the DetailViewController isn't a subclass of UIViewController. You could simply fix this issue by modifying the DetailViewController definition as follows:

class DetailViewController: UIViewController {
...
}
```

Title: Unable to push to navigation controller

Body:
 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 1: try loading the "Detail" view controller and typecasting it to be DetailViewController
    if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
        // 2: success! Set its selectedImage property
        vc.selectedImage = pictures[indexPath.row]

        // 3: now push it onto the navigation controller
        navigationController?.pushViewController(vc, animated: true)
    }
}

I am facing issue -
1.Cast from 'UIViewController?' to unrelated type 'DetailViewController' always fails
2.Cannot convert value of type 'DetailViewController' to expected argument type 'UIViewController'


问:
Using shadow with borderRadius on a react native component
I'm trying to set a shadow on a custom card component in React Native with a borderRadius property of 10.

Here is the code:

```<code>borderBottomLeftRadius: 10,
borderBottomRightRadius: 10,
shadowOffset: {
  width: 0,
  height: 3,
},
elevation: 3,
</code>```

How can I apply rounded corners to the shadow?

答:
You can use the shadowRadius property to shape the rounded corners. But this will only work for iOS since Android only takes the elevation property to create shadows. You can read more about this in the official documentation here. https://reactnative.dev/docs/shadow-props

You can have styles like this example below applied to the container view of your custom card.

```<code> const shadowsStyling = {
    width: 100,
    height: 100,
    shadowColor: "#000000",
    shadowOpacity: 0.8,
    shadowRadius: 2,
    shadowOffset: {
      height: 1,
      width: 0
    }
}
</code>```

Body:
I'm trying to set a shadow on a custom card component in React Native with a borderRadius property of 10.

Here is the code:

borderBottomLeftRadius: 10,
borderBottomRightRadius: 10,
shadowOffset: {
  width: 0,
  height: 3,
},
elevation: 3,

How can I apply rounded corners to the shadow?

Body:
You can use the shadowRadius property to shape the rounded corners. But this will only work for iOS since Android only takes the elevation property to create shadows. You can read more about this in the official documentation here. https://reactnative.dev/docs/shadow-props

You can have styles like this example below applied to the container view of your custom card.

 const shadowsStyling = {
    width: 100,
    height: 100,
    shadowColor: "#000000",
    shadowOpacity: 0.8,
    shadowRadius: 2,
    shadowOffset: {
      height: 1,
      width: 0
    }
}


问:
How to create shadow or elevation on TabBar?

I tried different options but unable to add the shadow like in the image:

```<code>TabBar(
        indicatorColor: Colors.transparent,
        indicatorSize: TabBarIndicatorSize.tab,
        unselectedLabelColor: inActiveColor,
        // Using BoxDecoration there is PADDING issue in Tabs
         indicator: BoxDecoration(
           borderRadius: BorderRadius.circular(50),
           color: hexToColor(primaryColorDark),
           boxShadow: [
             BoxShadow(
               color: Colors.grey.withOpacity(0.5),
               spreadRadius: 10,
               blurRadius: 10,
               offset: Offset(0, 10), // changes position of shadow
             ),
           ],
         ),
        tabs: <Tab>[
          Tab(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.create,
                  size: 20,
                ),
                Text('   ' + 'Form'),
              ],
            ),
          ),
          Tab(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.remove_red_eye,
                  size: 20,
                ),
                Text('   ' + 'Preview'),
              ],
            ),
          ),
        ],
      ),
</code>```

答:
The best and easy solution, Just wrap the TabBar with Container with fix height like:

```<code>         Container(
            height: 35,
            child: TabBar(
              indicatorColor: Colors.transparent,
              indicatorSize: TabBarIndicatorSize.tab,
              unselectedLabelColor: inActiveColor,

              indicator: BoxDecoration(
                borderRadius: BorderRadius.circular(50),
                color: Colors.blueAccent,
                boxShadow: [
                  BoxShadow(
                    color: Colors.blueAccent.withOpacity(0.3),
                    blurRadius: 25,
                    offset: Offset(0, 20), // changes position of shadow
                  ),
                ],
              ),
              tabs: <Tab>[
                Tab(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(
                        Icons.create,
                        size: 20,
                      ),
                      Text('   ' + 'Form'),
                    ],
                  ),
                ),
                Tab(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(
                        Icons.remove_red_eye,
                        size: 20,
                      ),
                      Text('   ' + 'Preview'),
                    ],
                  ),
                ),
              ],
            ),
          )
</code>```

Body:
I tried different options but unable to add the shadow like in the image:

TabBar(
        indicatorColor: Colors.transparent,
        indicatorSize: TabBarIndicatorSize.tab,
        unselectedLabelColor: inActiveColor,
        // Using BoxDecoration there is PADDING issue in Tabs
         indicator: BoxDecoration(
           borderRadius: BorderRadius.circular(50),
           color: hexToColor(primaryColorDark),
           boxShadow: [
             BoxShadow(
               color: Colors.grey.withOpacity(0.5),
               spreadRadius: 10,
               blurRadius: 10,
               offset: Offset(0, 10), // changes position of shadow
             ),
           ],
         ),
        tabs: <Tab>[
          Tab(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.create,
                  size: 20,
                ),
                Text('   ' + 'Form'),
              ],
            ),
          ),
          Tab(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.remove_red_eye,
                  size: 20,
                ),
                Text('   ' + 'Preview'),
              ],
            ),
          ),
        ],
      ),

Body:
The best and easy solution, Just wrap the TabBar with Container with fix height like:

         Container(
            height: 35,
            child: TabBar(
              indicatorColor: Colors.transparent,
              indicatorSize: TabBarIndicatorSize.tab,
              unselectedLabelColor: inActiveColor,

              indicator: BoxDecoration(
                borderRadius: BorderRadius.circular(50),
                color: Colors.blueAccent,
                boxShadow: [
                  BoxShadow(
                    color: Colors.blueAccent.withOpacity(0.3),
                    blurRadius: 25,
                    offset: Offset(0, 20), // changes position of shadow
                  ),
                ],
              ),
              tabs: <Tab>[
                Tab(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(
                        Icons.create,
                        size: 20,
                      ),
                      Text('   ' + 'Form'),
                    ],
                  ),
                ),
                Tab(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(
                        Icons.remove_red_eye,
                        size: 20,
                      ),
                      Text('   ' + 'Preview'),
                    ],
                  ),
                ),
              ],
            ),
          )


问:
Error Message: No JIRA site configured | Using JiraCloud
I have setup Jira & Jenkins Integration. I'm using the typical Jira Cloud <orgname>.atlassian.net. So far jiraSendBuildInfo, jiraSendDeploymentInfo are working.

However when I tried using jiraTransitionIssue I received error No JIRA site configured with <org>.atlassian.net name.

I tried adding Jira Site in Jira Steps configuration, however I was unable to select credentials. I added atlassian API token in the credentials but for some reason it's not showing on the list.

PS: I'm using JIRA API Token because atlassian Username & Password is now deprecated.

JIRA STEPS Plugin Version: 1.6.0

答: email as a username & API Token from https://id.atlassian.com/manage-profile/security/api-tokens as a password works.


问:
What is the original meaning of P and V operations in a context of a semaphore?
Does anybody know why semaphore operations are called P and V? Every time I read a chapter on semaphores it says something like the following:

In order for the thread to obtain a resource it executes a P operation. And in order for the thread to release a resource it executes a V operation.

What does P and V stand for? Why they are not called wait and signal?

答:
@Kris answer is just partially right.

V stands for 'Verhoog' and P stands for 'Prolaag', not 'Probeer' as cited here.

Verhoog can be translated as 'increasing'. Decreasing would be 'Verlaag', but for better distinction between the letters Dijkstra invented the word 'Prolaag'.

See the naming in the original paper.


答:
I guess you will have to use withCount() + map() to achieve what you want.</p>

```<code>return Dealer::query()
    ->withCount('assigns_today')
    ->get()
    ->map(function ($q) {
        if ($q->assigns_today_count < $q->daily_assign_limit) {
            return $q;
        }
    })->filter(); // filter to remove null values
</code>```

Title: Laravel `has` relationship count using parent column value

Body:
I want to grab records whose relation count is less than the value of a parent column.

I have a model called Dealer, which has an attribute called daily_assign_limit.

In the Dealer model, I have this relationship:

public function assigns()
{
    return $this->hasMany(Assign::class);
}

public function assigns_today()
{
    return $this->assigns()->whereDate('created_at', today());
}

I have tried to query the dealers who haven't reached their daily_assign_limit using this method:

    return Dealer::query()
        ->has('assigns_today', '<', 'daily_assign_limit')
        ->first();

It looks like has wants an integer instead of a column name. So how would I accomplish this using the parent column rather than a hard coded integer?

Body:
I guess you will have to use withCount() + map() to achieve what you want.

return Dealer::query()
    ->withCount('assigns_today')
    ->get()
    ->map(function ($q) {
        if ($q->assigns_today_count < $q->daily_assign_limit) {
            return $q;
        }
    })->filter(); // filter to remove null values


问:
Docker Wordpress not connecting with docker Mysql Compose
I am trying to set up multiple WordPress sites being hosting on the same server using docker using nginx reverse proxy server. I have a network setup with the nginx proxy listening on port 80 called nginx-proxy. I confirmed they are all on the same docker network. However, I am still getting WordPress is unable to communicate with the database. I can confirm that the credentials are correct and that MySQL is running on the other docker container.

With my testing, the forwarding proxy is working if I update the virtual host and open it in the web browser it does open the error message on that page. I can ping both the containers from within their shell. I am not sure what I am doing wrong I am newer to dockers networking within version 3. I don't believe docker has differenced between platforms, but in case it does I am running it on Mac OS.

I know there are other posts similar to this using Link and version 2 however, I was not able to find a version 3 with information that fixed my issue.

```<code>version: "3.3"

    services:
       db_node_domain:
         image: mysql:5.7
         volumes:
           - db_data:/var/lib/mysql
         restart: always
         environment:
           MYSQL_ROOT_PASSWORD: PASSWORD
           MYSQL_DATABASE: wordpress
           MYSQL_USER: wordpress
           MYSQL_PASSWORD: PASSWORD
         container_name: wordpress_db

       wordpress:
         depends_on:
           - db_node_domain
         image: wordpress:latest
         expose:
           - 80
         restart: always
         environment:
           VIRTUAL_HOST: domain.com
           WORDPRESS_DB_HOST: db_node_domain:3306
           WORDPRESS_DB_USER: wordpress
           WORDPRESS_DB_PASSWORD: PASSWORD
         container_name: wordpress
    volumes:
        db_data: {}

    networks:
      default:
        external:
          name: nginx-proxy
</code>```

Please let me know if any more information is required. Thank you for any assistance you might be able to provide.

答:
I don't see any problem with your docker-compose file, also it's working on my local machine which is macOS.

One thing, 'wordpress' container will fail to bring up several times with MySQL Connection Error: (2002) Connection refused on the first bootup due to MySQL initialization. It should connect to 'wordpress_db' after a few retrials.

If it doesn't connect even after retrials, can you attach logs of 'wordpress' container?

Body:
I am trying to set up multiple WordPress sites being hosting on the same server using docker using nginx reverse proxy server. I have a network setup with the nginx proxy listening on port 80 called nginx-proxy. I confirmed they are all on the same docker network. However, I am still getting WordPress is unable to communicate with the database. I can confirm that the credentials are correct and that MySQL is running on the other docker container.

With my testing, the forwarding proxy is working if I update the virtual host and open it in the web browser it does open the error message on that page. I can ping both the containers from within their shell. I am not sure what I am doing wrong I am newer to dockers networking within version 3. I don't believe docker has differenced between platforms, but in case it does I am running it on Mac OS.

I know there are other posts similar to this using Link and version 2 however, I was not able to find a version 3 with information that fixed my issue.

version: "3.3"

    services:
       db_node_domain:
         image: mysql:5.7
         volumes:
           - db_data:/var/lib/mysql
         restart: always
         environment:
           MYSQL_ROOT_PASSWORD: PASSWORD
           MYSQL_DATABASE: wordpress
           MYSQL_USER: wordpress
           MYSQL_PASSWORD: PASSWORD
         container_name: wordpress_db

       wordpress:
         depends_on:
           - db_node_domain
         image: wordpress:latest
         expose:
           - 80
         restart: always
         environment:
           VIRTUAL_HOST: domain.com
           WORDPRESS_DB_HOST: db_node_domain:3306
           WORDPRESS_DB_USER: wordpress
           WORDPRESS_DB_PASSWORD: PASSWORD
         container_name: wordpress
    volumes:
        db_data: {}

    networks:
      default:
        external:
          name: nginx-proxy

Please let me know if any more information is required. Thank you for any assistance you might be able to provide.


问:
Extraction of sub string from the text using R
I have a string data as follows:

```<code>a<-  "\n    Update Your Profile to Dissolve This Message\nSocial Media Learning and behaviour\n        Uploaded on May 3, 2020 at 10:56 in Research\n            View Forum\n        \n"
</code>```

I have to extract the string "Social Media Learning and behaviour" for this I used the below code:

```<code>gsub("        Uploaded on .* ", "", gsub("\n    Update Your Profile to Dissolve This Message\n", "",a))
</code>```

This gives me output as below

```<code>"Social Media Learning and behaviour\n\n"
</code>```

I am not able to match the exact pattern. What can be the exact pattern to extract "Social Media Learning and behaviour" without "\n\n"

答:
You could capture the previous line in a group and match the next line that contains Uploaded:

```<code>(.*)\r?\n[^\S\r\n]+Uploaded on
</code>```

Regex demo

```<code>a<-  "\n    Update Your Profile to Dissolve This Message\nSocial Media Learning and behaviour\n        Uploaded on May 3, 2020 at 10:56 in Research\n            View Forum\n        \n"
stringr::str_match(a, "(.*)\\r?\\n[^\\S\\r\\n]+Uploaded on")
</code>```

Body:
I have a string data as follows:

a<-  "\n    Update Your Profile to Dissolve This Message\nSocial Media Learning and behaviour\n        Uploaded on May 3, 2020 at 10:56 in Research\n            View Forum\n        \n"

I have to extract the string "Social Media Learning and behaviour" for this I used the below code:

gsub("        Uploaded on .* ", "", gsub("\n    Update Your Profile to Dissolve This Message\n", "",a))

This gives me output as below

"Social Media Learning and behaviour\n\n"

I am not able to match the exact pattern. What can be the exact pattern to extract "Social Media Learning and behaviour" without "\n\n"

Body:
You could capture the previous line in a group and match the next line that contains Uploaded:

(.*)\r?\n[^\S\r\n]+Uploaded on

Regex demo

a<-  "\n    Update Your Profile to Dissolve This Message\nSocial Media Learning and behaviour\n        Uploaded on May 3, 2020 at 10:56 in Research\n            View Forum\n        \n"
stringr::str_match(a, "(.*)\\r?\\n[^\\S\\r\\n]+Uploaded on")


问:
NSString init or alloc error?
I have this interface:

```<code> #import <Foundation/Foundation.h>
 @interface Cards : NSObject {  NSString* effect;   NSString* image;   }
-(NSString*) effect;
-(NSString*) image;
-(void) setEffect: (NSString*) effect2;
-(void) setImage: (NSString*) image2;

@end
</code>```

And this implementation:

```<code>#import "Cards.h"
@implementation Cards
-(NSString*) effect
{
    return [effect autorelease];
}
-(NSString*) image
{
    return [image autorelease];
}
-(void) setEffect: (NSString*) effect2
{
  effect = [[NSString alloc]initWithString:effect2];
}
-(void) setImage: (NSString*) image2
{
  image = [[NSString alloc]initWithString:@""];
}
-(void) dealloc
{
    [effect release];
    [image release];
    [super dealloc];
}
@end
</code>```

Now if I make a Cards object such as
Cards* card
and then I run the metod setEffect like so:
[card setEffect:@""];
It compiles but gives me a runtime error. Anyone know why? Thanks in advance!

答: I think you intended [image autorelease] to be [[image retain] autorelease]. Otherwise you will be autoreleasing it on every access of the property. You are also leaking on you set* methods as you're not releasing the older values prior to assigning the new one.

Title: NSString init or alloc error?

Body:
I have this interface:

 #import <Foundation/Foundation.h>
 @interface Cards : NSObject {  NSString* effect;   NSString* image;   }
-(NSString*) effect;
-(NSString*) image;
-(void) setEffect: (NSString*) effect2;
-(void) setImage: (NSString*) image2;

@end

And this implementation:

#import "Cards.h"
@implementation Cards
-(NSString*) effect
{
    return [effect autorelease];
}
-(NSString*) image
{
    return [image autorelease];
}
-(void) setEffect: (NSString*) effect2
{
  effect = [[NSString alloc]initWithString:effect2];
}
-(void) setImage: (NSString*) image2
{
  image = [[NSString alloc]initWithString:@""];
}
-(void) dealloc
{
    [effect release];
    [image release];
    [super dealloc];
}
@end

Now if I make a Cards object such as
Cards* card
and then I run the metod setEffect like so:
[card setEffect:@""];
It compiles but gives me a runtime error. Anyone know why? Thanks in advance!


问:
How to maintain a landscape aspect ratio with getUserMedia on mobile devices?
I'm using getUserMedia with the following constraints:

```<code>var constraints = {
    audio: true,
    video: {
        width: 960,
        height: 540,
    }
};

navigator.mediaDevices.getUserMedia(constraints).then(...);
</code>```

This works when using desktops or when using mobile devices while they are in landscape mode. However, when rotating the mobile device to portrait mode, the video object loses the aspect ratio:

When the device is held as Landscape:

When the device is held as Portrait:

This happens both on iOS and Android devices, on Chorme, Safari and Samsung browser.

I tried playing around with the constraints aspectRatio, min, ideal as suggested by the MDN docs, but it seems these constraints are of no effect at all.

Is there any way to always maintain the aspect ratio as 1.777 even if the mobile device is rotated as portrait mode?

答:
I found out that you can use reversed aspectRatio when in Portrait mode.

I use this constraints in Landscape mode:

```<code>mediaConstraints: MediaStreamConstraints = {
  video: {
    aspectRatio: 16/9
  }
};
</code>```

and this constraints in Portrait mode:

```<code>mediaConstraints: MediaStreamConstraints = {
  video: {
    aspectRatio: 9/16
  }
};
</code>```

The caveat of this solution is you have to detect orientation change and call again getUserMedia(), losing your stream.

Also if you are recording the stream, you should prevent screen rotation with ScreenOrientation.lock() (not working in Safari) so user is not able to reset stream by rotating device while recording.

Body:
I'm using getUserMedia with the following constraints:

var constraints = {
    audio: true,
    video: {
        width: 960,
        height: 540,
    }
};

navigator.mediaDevices.getUserMedia(constraints).then(...);

This works when using desktops or when using mobile devices while they are in landscape mode. However, when rotating the mobile device to portrait mode, the video object loses the aspect ratio:

When the device is held as Landscape:

When the device is held as Portrait:

This happens both on iOS and Android devices, on Chorme, Safari and Samsung browser.

I tried playing around with the constraints aspectRatio, min, ideal as suggested by the MDN docs, but it seems these constraints are of no effect at all.

Is there any way to always maintain the aspect ratio as 1.777 even if the mobile device is rotated as portrait mode?

Body:
I found out that you can use reversed aspectRatio when in Portrait mode.

I use this constraints in Landscape mode:

mediaConstraints: MediaStreamConstraints = {
  video: {
    aspectRatio: 16/9
  }
};

and this constraints in Portrait mode:

mediaConstraints: MediaStreamConstraints = {
  video: {
    aspectRatio: 9/16
  }
};

The caveat of this solution is you have to detect orientation change and call again getUserMedia(), losing your stream.

Also if you are recording the stream, you should prevent screen rotation with ScreenOrientation.lock() (not working in Safari) so user is not able to reset stream by rotating device while recording.


问:
How to filter/disable a scalac option for all subprojects in SBT in a DRY way
My project has multiple subprojects, and I use sbt-tpolecat1 in this project.
I use a Java framework in my code. This framework use fluent interface heavily so I need to suppress many "discarded non-Unit value" warnings in my code.

This sbt-tpolecat provided a lot of useful scalac options out of the box, and I just want to exclude the -Wvalue-discard scalac option for my use case.

The problem is I have 4-5 subprojects2 in this project. And now I need to add the below to every subproject's settings:

sub_project_name.settings(
  scalacOptions ~= (_.filterNot(Set("-Wvalue-discard")))
)
// or
sub_project_name.settings(valueDiscardSetting)

lazy val valueDiscardSetting =
  Seq(scalacOptions ~= (_.filterNot(Set("-Wvalue-discard"))))

```

<p>Is there a way to exclude this option in all subprojects in a DRY way?
My current subprojects hierarchy is similar to this:</p>

```App -> Frontend -> Common
    -> Backend  -> Common
```

答:
Common settings val

There is a common practice of factoring out common settings in multi-project builds

define a sequence of common settings in a val and add them to each
  project. Less concepts to learn that way.

for example

```<code>lazy val commonSettings = Seq(
  scalacOptions ~= (_.filterNot(Set("-Wvalue-discard"))),
  ...
)

lazy val util = (project in file("util")).settings(commonSettings)
lazy val core = (project in file("core")).settings(commonSettings)
</code>```

Common settings auto plugin

Auto plugins can set settings for every project. Create the following small plugin under project/CommonSettingsPlugin.scala

```<code>object CommonSettingsPlugin extends AutoPlugin {
  override def requires = plugins.JvmPlugin
  override def trigger = allRequirements
  override lazy val projectSettings = Seq(
    scalacOptions ~= (_.filterNot(Set("-Wvalue-discard")))
  )
}
</code>```

The override

```<code>override def requires = plugins.JvmPlugin
</code>```

should effectively enable the plugin without having to call explicitly enablePlugin in build.sbt.

Override settings with onLoad

onLoad happens at the end after all projects are built and loaded.

```<code>lazy val settingsAlreadyOverridden = SettingKey[Boolean]("settingsAlreadyOverridden","Has overrideSettings command already run?")
settingsAlreadyOverridden := false
commands += Command.command("removeScalacOptions") { state =>
  if (settingsAlreadyOverridden.value) {
    state
  } else {
    Project.extract(state).appendWithSession(
      Seq(
        settingsAlreadyOverridden := true,
        scalacOptions ~= (_.filterNot(Set("-Wvalue-discard")))
      ),
      state
    )
  }
}

onLoad in Global := (onLoad in Global).value andThen ("removeScalacOptions" :: _)
</code>```

Also consider how they addressed the problem in community-build via removeScalacOptions.

Body:
My project has multiple subprojects, and I use sbt-tpolecat1 in this project.
I use a Java framework in my code. This framework use fluent interface heavily so I need to suppress many "discarded non-Unit value" warnings in my code.

This sbt-tpolecat provided a lot of useful scalac options out of the box, and I just want to exclude the -Wvalue-discard scalac option for my use case.

The problem is I have 4-5 subprojects2 in this project. And now I need to add the below to every subproject's settings:

sub_project_name.settings(
  scalacOptions ~= (_.filterNot(Set("-Wvalue-discard")))
)
// or
sub_project_name.settings(valueDiscardSetting)

lazy val valueDiscardSetting =
  Seq(scalacOptions ~= (_.filterNot(Set("-Wvalue-discard"))))

Is there a way to exclude this option in all subprojects in a DRY way?
My current subprojects hierarchy is similar to this:

App -> Frontend -> Common
    -> Backend  -> Common

Body:
Common settings val

There is a common practice of factoring out common settings in multi-project builds

define a sequence of common settings in a val and add them to each
  project. Less concepts to learn that way.

for example

lazy val commonSettings = Seq(
  scalacOptions ~= (_.filterNot(Set("-Wvalue-discard"))),
  ...
)

lazy val util = (project in file("util")).settings(commonSettings)
lazy val core = (project in file("core")).settings(commonSettings)

Common settings auto plugin

Auto plugins can set settings for every project. Create the following small plugin under project/CommonSettingsPlugin.scala

object CommonSettingsPlugin extends AutoPlugin {
  override def requires = plugins.JvmPlugin
  override def trigger = allRequirements
  override lazy val projectSettings = Seq(
    scalacOptions ~= (_.filterNot(Set("-Wvalue-discard")))
  )
}

The override

override def requires = plugins.JvmPlugin

should effectively enable the plugin without having to call explicitly enablePlugin in build.sbt.

Override settings with onLoad

onLoad happens at the end after all projects are built and loaded.

lazy val settingsAlreadyOverridden = SettingKey[Boolean]("settingsAlreadyOverridden","Has overrideSettings command already run?")
settingsAlreadyOverridden := false
commands += Command.command("removeScalacOptions") { state =>
  if (settingsAlreadyOverridden.value) {
    state
  } else {
    Project.extract(state).appendWithSession(
      Seq(
        settingsAlreadyOverridden := true,
        scalacOptions ~= (_.filterNot(Set("-Wvalue-discard")))
      ),
      state
    )
  }
}

onLoad in Global := (onLoad in Global).value andThen ("removeScalacOptions" :: _)

Also consider how they addressed the problem in community-build via removeScalacOptions.


问:
Spread operator in Vuex not compiling correctly with babel, I keep getting module build failed
I am using a spread operator in my mapGetters object.  I am aware that you need to use a specific babel-preset-stage to compile ES6 properly.  I npm installed babel-preset-stage-2 and was getting this error still.

```<code>ERROR in ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/components/AnotherResult.vue
Module build failed: SyntaxError: Unexpected token (13:8)

  11 | export default {
  12 |     computed: {
> 13 |         ...mapGetters ([
     |         ^
  14 |             'doubleCounter',
  15 |             'stringCounter'
  16 |     ])
</code>```

I have looked around on the github and it seems like this is a common problem and it looks like people suggested to try babel-preset-stage-3 and other webpack configurations.

Here is my package.json

```<code>{
  "name": "vue-cli",
  "description": "A Vue.js project",
  "author": "Maximilian Schwarzmüller <mblacky0@gmail.com>",
  "private": true,
  "scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server --open --inline --hot",
    "build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
  },
  "dependencies": {
    "bootstrap": "^3.3.7",
    "vue": "^2.0.1",
    "vue-router": "^2.0.1",
    "vuex": "^3.1.1"
  },
  "devDependencies": {
    "babel-core": "^6.0.0",
    "babel-loader": "^6.0.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.0.0",
    "babel-preset-stage-2": "^6.24.1",
    "babel-preset-stage-3": "^6.24.1",
    "cross-env": "^3.0.0",
    "css-loader": "^0.25.0",
    "file-loader": "^0.9.0",
    "vue-loader": "^9.7.0",
    "webpack": "2.1.0-beta.25",
    "webpack-dev-server": "2.1.0-beta.0"
  }
}
</code>```

.babelrc file

```<code>{
    "presets": [
        ["es2015", {"modules": false}],
        ["stage-3", "env"]
    ],
    "plugins": ["transform-object-rest-spread"]
}
</code>```

It still doesn't want to compile under these new configurations.  Any insight would be appreciated please?

Thanks

答:
I try with this setup and for me work

babel.rc:

```<code>{
  "presets": [
    ["es2015", { "modules": false }],
    ["stage-2"]
  ]
}
</code>```

package.json

```<code>"devDependencies": {
    "babel-core": "^6.0.0",
    "babel-loader": "^6.0.0",
    "babel-preset-es2015": "^6.0.0",
    "babel-preset-stage-2": "^6.24.1",
    "cross-env": "^3.0.0",
    "css-loader": "^0.25.0",
    "file-loader": "^0.9.0",
    "vue-loader": "^9.7.0",
    "webpack": "2.1.0-beta.25",
    "webpack-dev-server": "2.1.0-beta.0"
  }
</code>```

webpack.config.js

```<code>{
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/
      }
</code>```

Body:
I am using a spread operator in my mapGetters object.  I am aware that you need to use a specific babel-preset-stage to compile ES6 properly.  I npm installed babel-preset-stage-2 and was getting this error still.

ERROR in ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/components/AnotherResult.vue
Module build failed: SyntaxError: Unexpected token (13:8)

  11 | export default {
  12 |     computed: {
> 13 |         ...mapGetters ([
     |         ^
  14 |             'doubleCounter',
  15 |             'stringCounter'
  16 |     ])

I have looked around on the github and it seems like this is a common problem and it looks like people suggested to try babel-preset-stage-3 and other webpack configurations.

Here is my package.json

{
  "name": "vue-cli",
  "description": "A Vue.js project",
  "author": "Maximilian Schwarzmüller <mblacky0@gmail.com>",
  "private": true,
  "scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server --open --inline --hot",
    "build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
  },
  "dependencies": {
    "bootstrap": "^3.3.7",
    "vue": "^2.0.1",
    "vue-router": "^2.0.1",
    "vuex": "^3.1.1"
  },
  "devDependencies": {
    "babel-core": "^6.0.0",
    "babel-loader": "^6.0.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.0.0",
    "babel-preset-stage-2": "^6.24.1",
    "babel-preset-stage-3": "^6.24.1",
    "cross-env": "^3.0.0",
    "css-loader": "^0.25.0",
    "file-loader": "^0.9.0",
    "vue-loader": "^9.7.0",
    "webpack": "2.1.0-beta.25",
    "webpack-dev-server": "2.1.0-beta.0"
  }
}

.babelrc file

{
    "presets": [
        ["es2015", {"modules": false}],
        ["stage-3", "env"]
    ],
    "plugins": ["transform-object-rest-spread"]
}

It still doesn't want to compile under these new configurations.  Any insight would be appreciated please?

Thanks

Body:
I try with this setup and for me work

babel.rc:

{
  "presets": [
    ["es2015", { "modules": false }],
    ["stage-2"]
  ]
}

package.json

"devDependencies": {
    "babel-core": "^6.0.0",
    "babel-loader": "^6.0.0",
    "babel-preset-es2015": "^6.0.0",
    "babel-preset-stage-2": "^6.24.1",
    "cross-env": "^3.0.0",
    "css-loader": "^0.25.0",
    "file-loader": "^0.9.0",
    "vue-loader": "^9.7.0",
    "webpack": "2.1.0-beta.25",
    "webpack-dev-server": "2.1.0-beta.0"
  }

webpack.config.js

{
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/
      }