问:
TypeError: expected string or bytes-like object.where do i change it to string?
when i try to run this python :

```<code>import subprocess, smtplib
def send_mail(email,password,message):
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(email,password)
    server.sendmail(email, email, message)
    server.quit()

a = subprocess.check_output(['netsh','wlan','show','profiles']).decode('utf-8').split('\n')
a = [i.split(":")[1][1:-1] for i in a if "All User Profile" in i]
for i in a:
    results = subprocess.check_output(['netsh','wlan','show','profile',i,'key=clear']).decode('utf-8').split('\n')
    results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
    try:
        print ("{:<30}| {:<}".format(i, results[0]))
    except IndexError:
        print ("{:<30}| {:<}".format(i,""))
send_mail("example@gmail.com","Example123",results)
</code>```

i get this error

```<code>Traceback (most recent call last):
  File "wifi.py", line 18, in <module>
    send_mail("Example@gmail.com","Example123",results)
  File "wifi.py", line 6, in send_mail
    server.sendmail(email, email, message)
  File "C:\Users\TARUN\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 886, in sendmail
    (code, resp) = self.data(msg)
  File "C:\Users\TARUN\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 568, in data
    q = _quote_periods(msg)
  File "C:\Users\TARUN\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 176, in _quote_periods
    return re.sub(br'(?m)^\.', b'..', bindata)
  File "C:\Users\TARUN\AppData\Local\Programs\Python\Python38-32\lib\re.py", line 210, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object
</code>```

i understand that i need to put 'str' somewhere but i don't know which part(i'm kinda new to python)

答:
you have results as list just convert it into string This will send both username and pwd</p>

```<code>import subprocess, smtplib
def send_mail(email,password,message):
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(email,password)
    server.sendmail(email, email, message)
    server.quit()

a = subprocess.check_output(['netsh','wlan','show','profiles']).decode('utf-8').split('\n')
a = [i.split(":")[1][1:-1] for i in a if "All User Profile" in i]
to_send = []
for i in a:
    results = subprocess.check_output(['netsh','wlan','show','profile',i,'key=clear']).decode('utf-8').split('\n')
    results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
    # in order to send everything store it in another list and then join them with new line.
    to_send.append(i+":"+"".join(results))
    try:
        print ("{:<30}| {:<}".format(i, results[0]))
    except IndexError:
        print ("{:<30}| {:<}".format(i,""))
# convert list to string
send_mail("example@gmail.com","Example123","\n".join(to_send))
</code>```

Body:
when i try to run this python :

import subprocess, smtplib
def send_mail(email,password,message):
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(email,password)
    server.sendmail(email, email, message)
    server.quit()

a = subprocess.check_output(['netsh','wlan','show','profiles']).decode('utf-8').split('\n')
a = [i.split(":")[1][1:-1] for i in a if "All User Profile" in i]
for i in a:
    results = subprocess.check_output(['netsh','wlan','show','profile',i,'key=clear']).decode('utf-8').split('\n')
    results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
    try:
        print ("{:<30}| {:<}".format(i, results[0]))
    except IndexError:
        print ("{:<30}| {:<}".format(i,""))
send_mail("example@gmail.com","Example123",results)

i get this error

Traceback (most recent call last):
  File "wifi.py", line 18, in <module>
    send_mail("Example@gmail.com","Example123",results)
  File "wifi.py", line 6, in send_mail
    server.sendmail(email, email, message)
  File "C:\Users\TARUN\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 886, in sendmail
    (code, resp) = self.data(msg)
  File "C:\Users\TARUN\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 568, in data
    q = _quote_periods(msg)
  File "C:\Users\TARUN\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 176, in _quote_periods
    return re.sub(br'(?m)^\.', b'..', bindata)
  File "C:\Users\TARUN\AppData\Local\Programs\Python\Python38-32\lib\re.py", line 210, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

i understand that i need to put 'str' somewhere but i don't know which part(i'm kinda new to python)

Body:
you have results as list just convert it into string This will send both username and pwd

import subprocess, smtplib
def send_mail(email,password,message):
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(email,password)
    server.sendmail(email, email, message)
    server.quit()

a = subprocess.check_output(['netsh','wlan','show','profiles']).decode('utf-8').split('\n')
a = [i.split(":")[1][1:-1] for i in a if "All User Profile" in i]
to_send = []
for i in a:
    results = subprocess.check_output(['netsh','wlan','show','profile',i,'key=clear']).decode('utf-8').split('\n')
    results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
    # in order to send everything store it in another list and then join them with new line.
    to_send.append(i+":"+"".join(results))
    try:
        print ("{:<30}| {:<}".format(i, results[0]))
    except IndexError:
        print ("{:<30}| {:<}".format(i,""))
# convert list to string
send_mail("example@gmail.com","Example123","\n".join(to_send))


来源: stackexchange

问:
Extract data from a website in winforms c#
i want to extract some data from a website. f.e. (https://www.chefkoch.de/rezepte/drucken/512261146932016/Annas-Rouladen-mit-Seidenkloessen.html). The text on the left side an the ingredients table on the right.

i tried several ways like with a webclient and regex the parts but the problem was here that if the table has more than one list like in my example i cant split them.

i also tried it with an htmldocument and get the elements but the
elements doesnt have an id; only a class.

so is there any way to get these two thing out of the website?
im pretty new too html and that kind of stuff..

答: You should consider using some sort of web scraping library like https://ironsoftware.com/csharp/webscraper/ or Selenium. Doing so, you'll be able to target HTML elements and css classes (to extract the data).</p>

ContentLicense: CC BY-SA 4.0


问:
What's the standard duration for turnstile page animation on Windows Phone?
I'm displaying a control that pretends to be a page, and I'm wondering how long my turnstile-type transition should take so that it fits in with the rest of the system. How long do normal turnstile page transitions take?</p>

答:
You can view the Storyboard for the Turnstile transition in the Toolkit on Codeplex, here's TurnstileForwardIn.xaml.

From a quick glance it looks like 350ms.

ContentLicense: CC BY-SA 3.0


问:
efficiently aggregate multi-row data in a single row representation in pandas dataframe
I have onehot coded pandas dataframe like following

```<code>p  c1 c2 c3
A  1  0  0
B  1  0  0
A  0  1  0
A  0  0  1
B  0  0  1
</code>```

I want to put the values of missing cells in one column from the following rows as follows

```<code>desired output

p  c1 c2 c3
A  1  1  1
B  1  0  1
</code>```

答:
```<code>s = df.set_index('p').stack()
df = s[s.eq(1)].unstack().fillna(0).astype(int).reset_index()
df.shape()
</code>```

Body:
I have onehot coded pandas dataframe like following

p  c1 c2 c3
A  1  0  0
B  1  0  0
A  0  1  0
A  0  0  1
B  0  0  1

I want to put the values of missing cells in one column from the following rows as follows

desired output

p  c1 c2 c3
A  1  1  1
B  1  0  1


问:
Ideal way to config all the buttons of my Tkinter application at once?
This is my first tkinter/gui project. I set up a mvc pattern and have a view class for each window of my application.

An example for the main window:

```<code>class ViewMain(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master, height = 300, width = 500)
        self.pack(fill='both', expand=True)
        self.BUTTON_SIZE = {'relheight' : 0.3, 'relwidth' : 0.35}
        self._set_widgets()
        self._set_layout()

    def _set_widgets(self):
        self.button = tk.Button(self, text = 'Text')

    def _set_layout(self):
        self.button.place(relx = 0.1, rely = 0.15, **self.BUTTON_SIZE)
</code>```

Currently, I have 6 view classes and I want to change the relief of the buttons to groove. As I have 30+ buttons, I look for a way to not write the following all the time:

```<code>self.button = tk.Button(self, text = 'Text', relief = 'groove')
</code>```

As you can see, one flaw in my train of thought is that I'm already using a repetitive approach to configure the size of the buttons. But let's just ignore that.

As I'm fairly new to all of this, I see three ways of doing this:

Add "relief = 'groove'" as an option every time I create a button

Use a ttk.Button and config the style. But I'd have to do this for every view class and add the style every time I create a button as well

Write a wrapper for the tk.Button and use that instead

The last option led me to this:

```<code>class CustomButton(tk.Button):
def __init__(self, master, text):
    super().__init__(master, text = text, relief = 'groove')
</code>```

Which works but I cannot stop thinking if there is a better way to approach this?

答:
I didn't test it but the way I would work around is like this:

```<code>for widget in root.winfo_children():
    if isinstance(widget, tk.Button):
        widget.configure(relief = 'groove')
</code>```

the winfo_children() gives you all widgets.
With if isinstance you checking if the widget is an instance of tkinter.Button.
If it's true you configure the Button how you like.

I did something like this before and it worked fine.

Body:
This is my first tkinter/gui project. I set up a mvc pattern and have a view class for each window of my application.

An example for the main window:

class ViewMain(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master, height = 300, width = 500)
        self.pack(fill='both', expand=True)
        self.BUTTON_SIZE = {'relheight' : 0.3, 'relwidth' : 0.35}
        self._set_widgets()
        self._set_layout()

    def _set_widgets(self):
        self.button = tk.Button(self, text = 'Text')

    def _set_layout(self):
        self.button.place(relx = 0.1, rely = 0.15, **self.BUTTON_SIZE)

Currently, I have 6 view classes and I want to change the relief of the buttons to groove. As I have 30+ buttons, I look for a way to not write the following all the time:

self.button = tk.Button(self, text = 'Text', relief = 'groove')

As you can see, one flaw in my train of thought is that I'm already using a repetitive approach to configure the size of the buttons. But let's just ignore that.

As I'm fairly new to all of this, I see three ways of doing this:

Add "relief = 'groove'" as an option every time I create a button

Use a ttk.Button and config the style. But I'd have to do this for every view class and add the style every time I create a button as well

Write a wrapper for the tk.Button and use that instead

The last option led me to this:

class CustomButton(tk.Button):
def __init__(self, master, text):
    super().__init__(master, text = text, relief = 'groove')

Which works but I cannot stop thinking if there is a better way to approach this?

Body:
I didn't test it but the way I would work around is like this:

for widget in root.winfo_children():
    if isinstance(widget, tk.Button):
        widget.configure(relief = 'groove')

the winfo_children() gives you all widgets.
With if isinstance you checking if the widget is an instance of tkinter.Button.
If it's true you configure the Button how you like.

I did something like this before and it worked fine.


问:
numpy not-equally distant range of numbers
Using np.linspace(0,3,100) would give a range of numbers that are equally distant between 0 and 3. what's the best way to get a range of numbers between 0 and 3 but more densely close to 3 and less dense in the beginning, perhaps in a logarithmic way.

----------edit

(np.log10(1), np.log10(4), 100)-1 gives more dense samples close to 0 than 3.

In addition is there also a more mathematically explicit way?

------edit:

This is the best I myself could come up with:
s = -1*(3*10**(-np.linspace(0,4,25))-1)

答: Try np.logspace(). You will need to use np.log10() for arguments.


问:
how to get uibutton exactly same width and height of custom uitableviewcell
I am trying to get my button to be exactly the same width and height as my custom uitableviewcell.

Here is how I'm trying to do it

```<code>// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return cellCode;
        }
        if (indexPath.row == 1) {
            cellManufacture.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cellManufacture;
        }
        if (indexPath.row == 2) {
            cellModel.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cellModel;
        }
        if (indexPath.row == 3) {
            cellYear.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cellYear;
        }
    }
    submitButton.frame = cellSubmit.bounds; //<<<<<<HERE IS WHERE I SET SIZING :)
    return cellSubmit;
}
</code>```

however this is the result I get....

答:
How about using Table Footer View with UIButton?

```<code>CGSize buttonSize = CGSizeMake(300, 45);
CGRect viewRect = CGRectMake(0, 0, self.view.frame.size.width, buttonSize.height);
CGRect buttonRect = CGRectMake((viewRect.size.width-buttonSize.width) / 2 ,
                               (viewRect.size.height-buttonSize.height) / 2 ,
                               buttonSize.width,
                               buttonSize.height);

UIView *footerView = [[UIView alloc] initWithFrame: viewRect];
footerView.backgroundColor = [UIColor clearColor];

UIButton *submitButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
submitButton.frame = buttonRect;
[submitButton setTitle:@"SUBMIT" forState:UIControlStateNormal];
[footerView addSubview: submitButton];

[(UITableView *)self.view setTableFooterView: footerView];

[footerView release];
</code>```

However, if you want exactly same appearance, you should use a default UITableCell(UITableViewCellStyleDefault) in the next section, not UIButton.

```<code>UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
cell.textLabel.text = @"SUBMIT";
cell.textLabel.textAlignment = UITextAlignmentCenter;
</code>```

Body:
I am trying to get my button to be exactly the same width and height as my custom uitableviewcell.

Here is how I'm trying to do it

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return cellCode;
        }
        if (indexPath.row == 1) {
            cellManufacture.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cellManufacture;
        }
        if (indexPath.row == 2) {
            cellModel.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cellModel;
        }
        if (indexPath.row == 3) {
            cellYear.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cellYear;
        }
    }
    submitButton.frame = cellSubmit.bounds; //<<<<<<HERE IS WHERE I SET SIZING :)
    return cellSubmit;
}

however this is the result I get....

Body:
How about using Table Footer View with UIButton?

CGSize buttonSize = CGSizeMake(300, 45);
CGRect viewRect = CGRectMake(0, 0, self.view.frame.size.width, buttonSize.height);
CGRect buttonRect = CGRectMake((viewRect.size.width-buttonSize.width) / 2 ,
                               (viewRect.size.height-buttonSize.height) / 2 ,
                               buttonSize.width,
                               buttonSize.height);

UIView *footerView = [[UIView alloc] initWithFrame: viewRect];
footerView.backgroundColor = [UIColor clearColor];

UIButton *submitButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
submitButton.frame = buttonRect;
[submitButton setTitle:@"SUBMIT" forState:UIControlStateNormal];
[footerView addSubview: submitButton];

[(UITableView *)self.view setTableFooterView: footerView];

[footerView release];

However, if you want exactly same appearance, you should use a default UITableCell(UITableViewCellStyleDefault) in the next section, not UIButton.

UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
cell.textLabel.text = @"SUBMIT";
cell.textLabel.textAlignment = UITextAlignmentCenter;


问:
How can I delete a property from object returned by mongoose
I am querying users collection and I don't want to send back password. My main point is that if I can perform javascript operations on mongodb objects or not. Here is my code:

```<code>router.get("/:userId", async (req, res) => {
  try {
    const user = await User.findById(req.params.userId);
    delete user.password;
    if (user.parent !== undefined) {
      const referrer = await User.findOne({ _id: user.parent });
      return res.json({ user, referrer });
    }
    res.json(user);
  } catch (error) {
    res.status(400).json(error);
  }
});
</code>```

I am getting this output

```<code>{
    "is_deleted": false,
    "packages": [],
    "_id": "5ed102f3fefa080404db01df",
    "name": "parent",
    "email": "parent@parent.com",
    "gender": "m",
    "password": "$2b$10$HTGaoy.AVmoG/A0c/vkikO0NnEBte7f2tvwt2FQE94bZlNiYTeX8i",
    "__v": 0
}
</code>```

I tried to perform filter on a list of mongodb objects and that failed too.

答:
You can destructure the object returned from the query

```<code>const {password, ...restProps } = await User.findById(req.params.userId);
const user = restProps;
</code>```

You can also configure your User model so that password field is excluded by default from query result.

```<code>const UserSchema = new mongoose.Schema({
    ...
    password: {
       ...
       select: false
    }
});
</code>```

if you don't want to exclude a field by default, you can call select function and specify the properties you don't want to include in the query results.

```<code>const user = await User.findById(req.params.userId).select('-password');
</code>```

for more info on this, see SchemaType.prototype.select()

Body:
I am querying users collection and I don't want to send back password. My main point is that if I can perform javascript operations on mongodb objects or not. Here is my code:

router.get("/:userId", async (req, res) => {
  try {
    const user = await User.findById(req.params.userId);
    delete user.password;
    if (user.parent !== undefined) {
      const referrer = await User.findOne({ _id: user.parent });
      return res.json({ user, referrer });
    }
    res.json(user);
  } catch (error) {
    res.status(400).json(error);
  }
});

I am getting this output

{
    "is_deleted": false,
    "packages": [],
    "_id": "5ed102f3fefa080404db01df",
    "name": "parent",
    "email": "parent@parent.com",
    "gender": "m",
    "password": "$2b$10$HTGaoy.AVmoG/A0c/vkikO0NnEBte7f2tvwt2FQE94bZlNiYTeX8i",
    "__v": 0
}

I tried to perform filter on a list of mongodb objects and that failed too.

Body:
You can destructure the object returned from the query

const {password, ...restProps } = await User.findById(req.params.userId);
const user = restProps;

You can also configure your User model so that password field is excluded by default from query result.

const UserSchema = new mongoose.Schema({
    ...
    password: {
       ...
       select: false
    }
});

if you don't want to exclude a field by default, you can call select function and specify the properties you don't want to include in the query results.

const user = await User.findById(req.params.userId).select('-password');

for more info on this, see SchemaType.prototype.select()


问:
How to test immutability and if reducer if pure function in Jest
In multiple places of my app, there're bugs: people wrote reducers that were not pure and also reducers modified existing state by working on existing objects.

Now, before fixing it I would like to write tests that prove that reducers had bugs and modified existing state.

I could do this manually by doing dozens of assertions, but perhaps there's a better way to do it. Are there any matchers / libs that could help me with that in the context on Jest?

答:
I normally use this library: redux-testkit, you can easily test the reducers and if some reducer mutates the test will fail. Also can test actions (by thunk) and selectors. Here is an example:

```<code>  test("when SET_FORM_VALUE, should set formValues", () => {
    const previousState = { formValues: null };
    const fakeFormValues = {
      fakeValue: "fake-value"
    };
    Reducer(reducer)
      .withState(previousState)
      .expect({ type: SET_FORM_VALUE, payload: fakeFormValues })
      .toChangeInState({
        formValues: fakeFormValues
      });
  });
</code>```

Also, you can use another library like deep-freeze. This one applies the Object.freeze deeply. The test raise an error if the object is modified in the method you are testing.

    test("should not be modified", () => {
      const obj = { value: 5 };

      deepFreeze(obj);

      obj.value = 6;
    });
```

Body:
I normally use this library: redux-testkit, you can easily test the reducers and if some reducer mutates the test will fail. Also can test actions (by thunk) and selectors. Here is an example:

  test("when SET_FORM_VALUE, should set formValues", () => {
    const previousState = { formValues: null };
    const fakeFormValues = {
      fakeValue: "fake-value"
    };
    Reducer(reducer)
      .withState(previousState)
      .expect({ type: SET_FORM_VALUE, payload: fakeFormValues })
      .toChangeInState({
        formValues: fakeFormValues
      });
  });

Also, you can use another library like deep-freeze. This one applies the Object.freeze deeply. The test raise an error if the object is modified in the method you are testing.

    test("should not be modified", () => {
      const obj = { value: 5 };

      deepFreeze(obj);

      obj.value = 6;
    });


问:
Need DOM selector for class and attribute
```<code><div class="ag-header-cell ag-header-cell-sortable grid-column-header-forecast" col-id="AD" >

<div class="ag-header-cell ag-header-cell-sortable grid-column-header" col-id="AD" >
</code>```

I have divs that are like above. Some have 'forecast' at end of class name, some don't.

I would like a document.querySelector that would yield col-id attribute of the first forecast div.

答:
You can use @v.kostenko answer if you have a specific string name.

But for more dynamic handling use this

```<code>document.querySelector('*[class$="forecast"]')
</code>```

The above code will provide you with the first element details whose class contain forecast string, in the end, irrespective of any HTML element

Body:
You can use @v.kostenko answer if you have a specific string name.

But for more dynamic handling use this

document.querySelector('*[class$="forecast"]')

The above code will provide you with the first element details whose class contain forecast string, in the end, irrespective of any HTML element


问:
Pandas Dateoffset behaviour not consistent
I'm trying to add months to a timestamp object and do not understand the following behaviour:

```<code>import pandas as pd

t1 = pd.Timestamp('2020-05-29')+4*pd.DateOffset(months=3)
t2 = pd.Timestamp('2020-05-29')+2*pd.DateOffset(months=6)
</code>```

I would think that t1 and t2 should be equal (12 months in both cases) but t1 is Timestamp('2021-05-28 00:00:00') and t2 is Timestamp('2021-05-29 00:00:00')

Is this a bug? the correct answer should be t2

答:
Adding DateOffsets expressed in months is a tricky issue.
Actually expression like pd.Timestamp('2020-05-29') + 4 * pd.DateOffset(months=3)
is executed under the hood by adding this offset 4 times.

Run such a code:

```<code>tt = pd.Timestamp('2020-05-29')
for i in range(4):
    tt += pd.DateOffset(months=3)
    print(f'{i}: {tt}')
</code>```

and you will get:

```<code>0: 2020-08-29 00:00:00
1: 2020-11-29 00:00:00
2: 2021-02-28 00:00:00
3: 2021-05-28 00:00:00
</code>```

Note that when you add 3 months to 2020-11-29 the result is 28-th
day of February, since Feruary in 2021 has only 28 days.

The next addition, starting from this date, yields 2021-05-28 (day is
also 28).

But when you add DateOffset of 6 months, the situation is as you
executed:

```<code>tt = pd.Timestamp('2020-05-29')
for i in range(2):
    tt += pd.DateOffset(months=6)
    print(f'{i}: {tt}')
</code>```

the result is:

```<code>0: 2020-11-29 00:00:00
1: 2021-05-29 00:00:00
</code>```

Just as intended, since no "stop" on the end of February occurred.

Body:
I'm trying to add months to a timestamp object and do not understand the following behaviour:

import pandas as pd

t1 = pd.Timestamp('2020-05-29')+4*pd.DateOffset(months=3)
t2 = pd.Timestamp('2020-05-29')+2*pd.DateOffset(months=6)

I would think that t1 and t2 should be equal (12 months in both cases) but t1 is Timestamp('2021-05-28 00:00:00') and t2 is Timestamp('2021-05-29 00:00:00')

Is this a bug? the correct answer should be t2

Body:
Adding DateOffsets expressed in months is a tricky issue.
Actually expression like pd.Timestamp('2020-05-29') + 4 * pd.DateOffset(months=3)
is executed under the hood by adding this offset 4 times.

Run such a code:

tt = pd.Timestamp('2020-05-29')
for i in range(4):
    tt += pd.DateOffset(months=3)
    print(f'{i}: {tt}')

and you will get:

0: 2020-08-29 00:00:00
1: 2020-11-29 00:00:00
2: 2021-02-28 00:00:00
3: 2021-05-28 00:00:00

Note that when you add 3 months to 2020-11-29 the result is 28-th
day of February, since Feruary in 2021 has only 28 days.

The next addition, starting from this date, yields 2021-05-28 (day is
also 28).

But when you add DateOffset of 6 months, the situation is as you
executed:

tt = pd.Timestamp('2020-05-29')
for i in range(2):
    tt += pd.DateOffset(months=6)
    print(f'{i}: {tt}')

the result is:

0: 2020-11-29 00:00:00
1: 2021-05-29 00:00:00

Just as intended, since no "stop" on the end of February occurred.


问:
Does parenthesis influence the index usage in SQL Server?
I understand that the order of criteria in the where clause does not influence index usage.

Does parenthesis influence the index usage in SQL Server? Is there any example?

答:
Obviously.  If I have an index on (y) and an expression like this:

```<code> where y > 10 and x = 'a' or x = 'c'
</code>```

then no index will be used.

If I put:

```<code> where y > 10 and( x = 'a' or x = 'c')
</code>```

Then the index will probably be used.

These do different things, but that is not part of your question.  Parentheses can change the meaning of a SQL statement and that changes the use of indexes.

Body:
Obviously.  If I have an index on (y) and an expression like this:

 where y > 10 and x = 'a' or x = 'c'

then no index will be used.

If I put:

 where y > 10 and( x = 'a' or x = 'c')

Then the index will probably be used.

These do different things, but that is not part of your question.  Parentheses can change the meaning of a SQL statement and that changes the use of indexes.


问:
Why is parameter to string.indexOf method is an int in Java
I am wondering why the parameter to indexOf method an int , when the description says a char.

public int indexOf(int ch)

```<code>Returns the index within this string of the first occurrence of the specified **character**
</code>```

http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#indexOf%28int%29

```<code>Also, both of these compiles fine:
char c = 'p';
str.indexOf(2147483647);
str.indexOf(c);
</code>```

a]Basically, what I am confused about is int in java is 32bit , while unicode characters are 16 bits .

b]Why not use the character themselves rather than using int . Is this any performance optimization ?. Are chars difficult to represent than int ? How ?

I assume this should be simple reasoning for this and that makes me know about it even more !

Thanks!

答:
Characters in Java are stored in their unicode integer representation. The Character class documentation has more details about this format.

From the docs on that page:

The methods that accept an int value support all Unicode characters, including supplementary characters. For example, Character.isLetter(0x2F81A) returns true because the code point value represents a letter (a CJK ideograph).

Body:
I am wondering why the parameter to indexOf method an int , when the description says a char.

public int indexOf(int ch)

Returns the index within this string of the first occurrence of the specified **character**

http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#indexOf%28int%29

Also, both of these compiles fine:
char c = 'p';
str.indexOf(2147483647);
str.indexOf(c);

a]Basically, what I am confused about is int in java is 32bit , while unicode characters are 16 bits .

b]Why not use the character themselves rather than using int . Is this any performance optimization ?. Are chars difficult to represent than int ? How ?

I assume this should be simple reasoning for this and that makes me know about it even more !

Thanks!


问:
Keyboard input without upper and lower case discrimination in Python
I want to create something like this:

```<code>answer = input("What's your name?")
if answer == "Mike":
    # code
if answer == "John":
    # code
else:
    # code
</code>```

What I want to do is to write Mike or MIKE or mIke ... (and same with John) and make all of that cases True, but I don't know how to do that instead of using answer.lower(), answer.upper() ...

答:
If you need to re-invent the wheel, here you go:

def is_upper(letter):
    return ord(letter) > 64 and ord(letter) < 91

def to_lower(word):
    lowered = ""
    for letter in list(word):
        if is_upper(letter):
            lowered += chr(ord(letter) + 32)
        else:
            lowered += letter
    return lowered

print(to_lower("MIKE"))
# >>> mike
print(to_lower("MikE"))
# >>> mike
print(to_lower("mIKe"))
# >>> mike
```

Body:
I want to create something like this:

answer = input("What's your name?")
if answer == "Mike":
    # code
if answer == "John":
    # code
else:
    # code

What I want to do is to write Mike or MIKE or mIke ... (and same with John) and make all of that cases True, but I don't know how to do that instead of using answer.lower(), answer.upper() ...


问:
In what order are the variables multiplied
In what order will the variables be multiplied.

```<code>int a = 5;
int b = 3;

a *= b;
</code>```

is that

```<code>a = a X b;
</code>```

or

```<code>a = b X a;
</code>```

答:
The standard defines that a *= b is the same as a = a * b, unless the types have been overloaded.

See section [expr.ass] in the standard (section 5.17 Assignment and compound assignment operators in the C++11 version).

For a * b * c, the operation is grouped left-to-right, i.e. (a * b) * c. See [expr.mul]. This also holds for overloaded operators, however, as overloaded operators can do all wacky kinds of things, their resulting effect can be arbitrary.

Body:
In what order will the variables be multiplied.

int a = 5;
int b = 3;

a *= b;

is that

a = a X b;

or

a = b X a;


问:
Checking for variable to be non-empty in bash
I want to run a remote command over ssh. So, the one line command is

```<code>ssh root@10.1.1.101 'VMID=`./run_prog` && if [ -n $VMID ]; then echo "id=$VMID"; vim-cmd vmsvc/power.off $VMID; else echo "$VMID empty"; fi'
</code>```

Problem is that if VMID is empty or non-empty, I see the output of vim-cmd.

```<code>id=
Usage: power.off vmid
</code>```

or

```<code>34
Powering off VM:
</code>```

How can I be sure that vim-cmd is executed for non-empty VMID values?

答:
The problem is that you do not quote the variable inside the if condition. You have to do it this way:

```<code>if [ -n "$VMID" ]
</code>```

You might wonder why if you don't quote you face problems. Well the answer is in man test:

-n STRING

    the length of STRING is nonzero

STRING

    equivalent to -n STRING

So when VMID is empty, the if condition results like this:

```<code>if [ -n ]
</code>```

and test will assume that you want to check if -n is an empty string. It won't undestand that you have used -n as an option. So, -n is not empty and the test passes.

If you use quotation, test will understand what you want.

If I can add a suggestion, don't use backquotes for command substitution. Use $(./run_prog) instead. Check this answer if you want more information about it.

Body:
I want to run a remote command over ssh. So, the one line command is

ssh root@10.1.1.101 'VMID=`./run_prog` && if [ -n $VMID ]; then echo "id=$VMID"; vim-cmd vmsvc/power.off $VMID; else echo "$VMID empty"; fi'

Problem is that if VMID is empty or non-empty, I see the output of vim-cmd.

id=
Usage: power.off vmid

or

34
Powering off VM:

How can I be sure that vim-cmd is executed for non-empty VMID values?

Body:
The problem is that you do not quote the variable inside the if condition. You have to do it this way:

if [ -n "$VMID" ]

You might wonder why if you don't quote you face problems. Well the answer is in man test:

-n STRING

    the length of STRING is nonzero

STRING

    equivalent to -n STRING

So when VMID is empty, the if condition results like this:

if [ -n ]

and test will assume that you want to check if -n is an empty string. It won't undestand that you have used -n as an option. So, -n is not empty and the test passes.

If you use quotation, test will understand what you want.

If I can add a suggestion, don't use backquotes for command substitution. Use $(./run_prog) instead. Check this answer if you want more information about it.


答: The method str.indexOf(int) takes an int. If you pass a char into it, java will cast the char to int, since char is a 16-bit number.

Title: Why is parameter to string.indexOf method is an int in Java


问:
reading input till EOF in java
In C++ if I wish to read input till the EOF I can do it in the following manner

```<code>while(scanf("%d",&n))
{
    A[i]=n;
    i++;
}
</code>```

I can then run this code as ./a.out < input.txt. What is the java equivalent of this code?

答:
In Java, One way of reading till EOF is:-

```<code>     Scanner scan = new Scanner(System.in);
     while(scan.hasNextLine())   //read until condition is true
     {
        String line = scan.nextLine();
        System.out.println(line);
        i++;
     }
</code>```

Title: reading input till EOF in java

Body:
In C++ if I wish to read input till the EOF I can do it in the following manner

while(scanf("%d",&n))
{
    A[i]=n;
    i++;
}

I can then run this code as ./a.out < input.txt. What is the java equivalent of this code?

Body:
In Java, One way of reading till EOF is:-

     Scanner scan = new Scanner(System.in);
     while(scan.hasNextLine())   //read until condition is true
     {
        String line = scan.nextLine();
        System.out.println(line);
        i++;
     }


问:
How to create a EditText box which opens a dialog on click?
I'm trying to create an EditView box which is being used as a button that you click. It opens a dialog with checkboxes you choose and then it inserts the chosen options into the textview with comma separated. For example the dialog has the following options:

```<code>Please select options:
[] Option1
[X] Option2
[] Option3
[X] Option4
</code>```

Then after you exit the dialog you will have in the EditText box:

```<code>Option2,Option4
</code>```

I have created the EditText:

```<code>            <EditText
                android:id="@+id/text_data"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="Add data"
                android:drawSelectorOnTop="true" />
</code>```

And a currently empty dialog xml called dialog_adding_data.xml. In the Java file I have:

```<code>        EditText dataEditText = findViewById(R.id.text_data);
        dataEditText.setClickable(true);
        dataEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(AddData.this);
                View mView = getLayoutInflater().inflate(R.layout.dialog_adding_data,null);
                // Now what?
            }
        });
</code>```

But how do I continue? How should I display the data in the dialog and get it when clicked ok? Also, when I click the EditText, it still opens the keyword so I can add the text (which I don't want). It should be blocked somehow. Only the dialog should "add" text to the EditText box.

答:
You need to get the data from your alert dialog and set the text of the edittext, something like</p>

```<code>        dataEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(AddData.this);
                View mView = getLayoutInflater().inflate(R.layout.dialog_adding_data,null);
                // Now what?

                mBuilder.setView(mView)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                   // Change the following to the view in your dialog that has the user data
                   EditText editText = (EditText) mView.findViewById(R.id.EDIT_TEXT_ID);

                   String value = editText.getText().toString();
                   dataEditText.setText(value);
                })
            }
        });

</code>```

Body:
I'm trying to create an EditView box which is being used as a button that you click. It opens a dialog with checkboxes you choose and then it inserts the chosen options into the textview with comma separated. For example the dialog has the following options:

Please select options:
[] Option1
[X] Option2
[] Option3
[X] Option4

Then after you exit the dialog you will have in the EditText box:

Option2,Option4

I have created the EditText:

            <EditText
                android:id="@+id/text_data"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="Add data"
                android:drawSelectorOnTop="true" />

And a currently empty dialog xml called dialog_adding_data.xml. In the Java file I have:

        EditText dataEditText = findViewById(R.id.text_data);
        dataEditText.setClickable(true);
        dataEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(AddData.this);
                View mView = getLayoutInflater().inflate(R.layout.dialog_adding_data,null);
                // Now what?
            }
        });

But how do I continue? How should I display the data in the dialog and get it when clicked ok? Also, when I click the EditText, it still opens the keyword so I can add the text (which I don't want). It should be blocked somehow. Only the dialog should "add" text to the EditText box.

Body:
You need to get the data from your alert dialog and set the text of the edittext, something like

        dataEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(AddData.this);
                View mView = getLayoutInflater().inflate(R.layout.dialog_adding_data,null);
                // Now what?

                mBuilder.setView(mView)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                   // Change the following to the view in your dialog that has the user data
                   EditText editText = (EditText) mView.findViewById(R.id.EDIT_TEXT_ID);

                   String value = editText.getText().toString();
                   dataEditText.setText(value);
                })
            }
        });


问:
Top Down Shooter Player Movement Control in Unity
Background: Making a small game in Unity 3D. It is a top down shooter. I am moving the player by using the MovePosition() function on its rigidbody with isKinematic set to false and not using gravity.

Desired behavior: When the player collides with a obstacle in the scene I want the script that controls the player to stop trying to force it into the object.

Problem: The rigidbody and colliders of the game objects successfully prevent the player from moving through solid objects but the player jitters sometimes and if the object is small enough the player glitches over the object even though the Y-position of the player is locked.

Question: What is the best way to do player movement for a Top Down Shooter? Should I use a NavMesh? rigidBody?

答:
Here is the code I used for my Top-Down shooter, I hope this helps :)

Code -

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shooting : MonoBehaviour
{
    public Transform firePoint;
    public GameObject bulletPrefab;

    public float bulletForce = 20f;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Shoot();
        }
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
        rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
    }
}
</code>```

Body:
Here is the code I used for my Top-Down shooter, I hope this helps :)

Code -

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shooting : MonoBehaviour
{
    public Transform firePoint;
    public GameObject bulletPrefab;

    public float bulletForce = 20f;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Shoot();
        }
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
        rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
    }
}


问:
Extract a value from @Message as float in logsearch and in Kibana calculate the sum from that extracted value
I have a value in my @message part that I need to extract out and then provide the sum of that value for that day. I have written below in my filters-default.conf file

```<code>if "NETAMT" in [@message] {
 grok {
  match => { "@message" => "<NETAMT>(?<NETAMT>.*?)<\/NETAMT>" }
 }
 mutate {
  convert => [ "NETAMT", "float" ]
 }
}
</code>```

The field starts appearing in the Kibana UI [![NETAMT Field][1]][1][1]: https://i.stack.imgur.com/r3uHH.jpg

Now when I am trying to sum it using STATS panel, it always gives 0.
[![Panel Setting][1]][1][1]: https://i.stack.imgur.com/RWNQv.jpg

[![Stats Data][1]][1][1]: https://i.stack.imgur.com/QTthu.jpg

Can anyone help here, please?

答: This got resolved after refreshing the index through kibana so that the new field becomes indexable and searchable.</p>

Body:
I have a value in my @message part that I need to extract out and then provide the sum of that value for that day. I have written below in my filters-default.conf file

if "NETAMT" in [@message] {
 grok {
  match => { "@message" => "<NETAMT>(?<NETAMT>.*?)<\/NETAMT>" }
 }
 mutate {
  convert => [ "NETAMT", "float" ]
 }
}

The field starts appearing in the Kibana UI [![NETAMT Field][1]][1][1]: https://i.stack.imgur.com/r3uHH.jpg

Now when I am trying to sum it using STATS panel, it always gives 0.
[![Panel Setting][1]][1][1]: https://i.stack.imgur.com/RWNQv.jpg

[![Stats Data][1]][1][1]: https://i.stack.imgur.com/QTthu.jpg

Can anyone help here, please?


问:
Very simple Mongo .save gives no error and saves no record
I tried several examples from here, but none seems to work.
I must be missing a small important thing.

This is my model

```<code>var mongoose = require('mongoose');
var Schema   = mongoose.Schema;
var mySchema = new Schema({
    _id:  Schema.Types.ObjectId,
    foo:  String,
    bar:  String
}, { versionKey: false });
module.exports = mongoose.model('myModel', mySchema, 'my');
</code>```

And this is my code

```<code>let myModel= require('/models/myModel');

let myRec = new myModel({
    "foo" : "whatever",
    "bar" : "whatever"
});

myRec.save(function (err, res) {
    if (err) {
        console.log("ERROR " + err);
    } else {
        console.log("Saved " + res);
    }
})
</code>```

I dont get ERROR or Saved, and it does not save anything in the database either.

Can anyone see what I am missing here?

答: Since you have explicitly declared the _id field in your Schema while creating a document you need to pass the _id field also. You can remove _id if you want so Mongoose will automatically create _id of type ObjectId for the document

Body:
I tried several examples from here, but none seems to work.
I must be missing a small important thing.

This is my model

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;
var mySchema = new Schema({
    _id:  Schema.Types.ObjectId,
    foo:  String,
    bar:  String
}, { versionKey: false });
module.exports = mongoose.model('myModel', mySchema, 'my');

And this is my code

let myModel= require('/models/myModel');

let myRec = new myModel({
    "foo" : "whatever",
    "bar" : "whatever"
});

myRec.save(function (err, res) {
    if (err) {
        console.log("ERROR " + err);
    } else {
        console.log("Saved " + res);
    }
})

I dont get ERROR or Saved, and it does not save anything in the database either.

Can anyone see what I am missing here?


问:
Doctests to check the radius, area and circumference of a circle using python
I have written the below mentioned code but got the following error:

"ValueError: line 2 of the docstring for main.Circle.circumference lacks blank after >>>: '        >>>c1 = Circle(2.5)'.

Please tell me how to resolve this error?

class Circle:

```<code>def __init__(self, radius):
    """
    >>> c1 = Circle(2.5)
    >>> c1.radius
    2.5
    """
    self.radius = radius

def area(self):
    """
    >>> c1 = Circle(2.5)
    >>> c1.area()
    19.63
    """
    a = math.pi * self.radius * self.radius
    return round(a,2)

def circumference(self):
    """
    >>>c1 = Circle(2.5)
    >>>c1.circumference()
    15.71
    """
    c = 2 * math.pi * self.radius
    return round(c,2)
</code>```

答:
Use this code as reference you may get answer...

class Circle:

```<code>def __init__(self, radius):

    """
    >>> c1 = Circle(2.5)
    >>> c1.radius
    2.5
    """
    self.radius = radius

def area(self):

    """
    >>> c1 = Circle(2.5)
    >>> c1.area()
    19.63

    """

    return round(math.pi*(self.radius**2),2)
def circumference(self):
    """
    >>> c1=Circle(2.5)
    >>> c1.circumference()
    15.71

    """

    return round(math.pi*(self.radius*2),2)
</code>```

Body:
I have written the below mentioned code but got the following error:

"ValueError: line 2 of the docstring for main.Circle.circumference lacks blank after >>>: '        >>>c1 = Circle(2.5)'.

Please tell me how to resolve this error?

class Circle:

def __init__(self, radius):
    """
    >>> c1 = Circle(2.5)
    >>> c1.radius
    2.5
    """
    self.radius = radius

def area(self):
    """
    >>> c1 = Circle(2.5)
    >>> c1.area()
    19.63
    """
    a = math.pi * self.radius * self.radius
    return round(a,2)

def circumference(self):
    """
    >>>c1 = Circle(2.5)
    >>>c1.circumference()
    15.71
    """
    c = 2 * math.pi * self.radius
    return round(c,2)

Body:
Use this code as reference you may get answer...

class Circle:

def __init__(self, radius):

    """
    >>> c1 = Circle(2.5)
    >>> c1.radius
    2.5
    """
    self.radius = radius

def area(self):

    """
    >>> c1 = Circle(2.5)
    >>> c1.area()
    19.63

    """

    return round(math.pi*(self.radius**2),2)
def circumference(self):
    """
    >>> c1=Circle(2.5)
    >>> c1.circumference()
    15.71

    """

    return round(math.pi*(self.radius*2),2)


问:
Pasting a very long string in eclipse editor
I am trying to paste a very long string in eclipse like:

```<code>String str = "verrrrrrrrry long string that hass 9000 characters";

I want it to appear as
String str = "verrrrrrrrry long"+
             "string that hass "+
             "9000 characters";
</code>```

I tried the option mentioned here : Paste a multi-line Java String in Eclipse , but that gives me a bunch of new lines inserted in the string which I dont want.

What I am getting currently is a long string that just wraps over itself on the same line.

Any pointers ?

答:
None of the settings worked for me , though they might be correct and I might have some other issue with my workspace.

Anyways, I was able to work through my problem with this expression:

```<code>cat Data.txt  | grep -o -E '.{1,70}' | sed -r 's/(.*)/        "\1"+/'
</code>```

P.S:
If anyone else confirms that one of the answers given by anyone in this post works, I will accept it on their behalf , since I think my answer is not a direct answer to my question.

Body:
I am trying to paste a very long string in eclipse like:

String str = "verrrrrrrrry long string that hass 9000 characters";

I want it to appear as
String str = "verrrrrrrrry long"+
             "string that hass "+
             "9000 characters";

I tried the option mentioned here : Paste a multi-line Java String in Eclipse , but that gives me a bunch of new lines inserted in the string which I dont want.

What I am getting currently is a long string that just wraps over itself on the same line.

Any pointers ?

Body:
None of the settings worked for me , though they might be correct and I might have some other issue with my workspace.

Anyways, I was able to work through my problem with this expression:

cat Data.txt  | grep -o -E '.{1,70}' | sed -r 's/(.*)/        "\1"+/'

P.S:
If anyone else confirms that one of the answers given by anyone in this post works, I will accept it on their behalf , since I think my answer is not a direct answer to my question.


问:
path to background-image in css with specific base href in Angular 9
The baseHref param in angular.json is /iofrog/ + there are 7 languages defined in i18n.locales, so the final baseHref in index.html is /iofrog/en for English build.

in css file for app component I have:

```<code>background-image: url('~/assets/img/background.jpg');
</code>```

This is translated by Angular 9 CLI to path /iofrog/assets/img/background.jpg, so /en/ is skipped! Is it a bug in Angular CLI?

I also tried:

```<code>background-image: url('/assets/img/background.jpg');  // not showing the image
background-image: url('./assets/img/background.jpg'); // compiler error
background-image: url('assets/img/background.jpg');  // not showing the image
</code>```

I also found --rebaseRootRelativeCssUrls=true|false option but it is depreciated.

The workaround that is working is in TS:

```<code>this.backgroundImageURL = `url(${this.baseHref}assets/img/background.jpg)`;
</code>```

And in HTML template:

```<code>[style.background-image]="backgroundImageURL ? backgroundImageURL : ''"
</code>```

But this is not elegant and the image is loading after the html is rendered.

What is the correct solution in Angular 9?

答:
There were some issues with i18n building angular app and base href.

It should work with that syntax for scss files:

```<code>background-image: url('~src/assets/img/background.jpg');
</code>```

Hope this helps.

Body:
The baseHref param in angular.json is /iofrog/ + there are 7 languages defined in i18n.locales, so the final baseHref in index.html is /iofrog/en for English build.

in css file for app component I have:

background-image: url('~/assets/img/background.jpg');

This is translated by Angular 9 CLI to path /iofrog/assets/img/background.jpg, so /en/ is skipped! Is it a bug in Angular CLI?

I also tried:

background-image: url('/assets/img/background.jpg');  // not showing the image
background-image: url('./assets/img/background.jpg'); // compiler error
background-image: url('assets/img/background.jpg');  // not showing the image

I also found --rebaseRootRelativeCssUrls=true|false option but it is depreciated.

The workaround that is working is in TS:

this.backgroundImageURL = `url(${this.baseHref}assets/img/background.jpg)`;

And in HTML template:

[style.background-image]="backgroundImageURL ? backgroundImageURL : ''"

But this is not elegant and the image is loading after the html is rendered.

What is the correct solution in Angular 9?

Body:
There were some issues with i18n building angular app and base href.

It should work with that syntax for scss files:

background-image: url('~src/assets/img/background.jpg');

Hope this helps.


问:
Deny permissions to execute PowerShell Get-AzAutomationCertificate
I am trying to create a custom reader role on Azure that does not allow the user to run the PowerShell command Get-AzAutomationCertificate. I have gone through the options and removed quite a few permissions related to reading certificates from the automation service provider. However, it appears it is still not enough.

These are the deny options present in the custom role :

```<code>"notActions": [
 "Microsoft.Automation/automationAccounts/listKeys/action",
 "Microsoft.Automation/automationAccounts/certificates/read",
 "Microsoft.Automation/automationAccounts/certificates/getCount/action",
 "Microsoft.Automation/automationAccounts/jobs/read",
 "Microsoft.Automation/automationAccounts/jobs/runbookContent/action",
 "Microsoft.Automation/automationAccounts/credentials/read",
 "Microsoft.Automation/automationAccounts/runbooks/content/read",
 "Microsoft.Automation/automationAccounts/runbooks/read",
 "Microsoft.Automation/automationAccounts/python2Packages/read",
 "Microsoft.Automation/automationAccounts/python3Packages/read",
 "Microsoft.Automation/automationAccounts/privateEndpointConnectionProxies/read",
 "Microsoft.Automation/automationAccounts/connections/read",
 "Microsoft.Automation/automationAccounts/connectionTypes/read
]
</code>```

More details about the command :
https://github.com/Azure/azure-powershell/blob/master/src/Automation/Automation/help/Get-AzAutomationCertificate.md

Any ideas on how to achieve this?

Thank you

答:
Firstly, I would like to clarify that the NotActions permission specifies the management operations that are excluded from the allowed Actions. See reference here.

So if the Action is not included in Actions, it's unnecessary to put it into NotActions in order to make it lose effectiveness. In this case, the user will not have the permission to do the action.

The action "Microsoft.Automation/automationAccounts/certificates/read" is what you want to make the PowerShell command Get-AzAutomationCertificate effective. Please note that it allows Get-AzAutomationCertificate to be executed but won't return results.

Here is my example:

```<code>{
  "Name": "Custom Role 2",
  "Id": null,
  "IsCustom": true,
  "Description": "Don't allow for Get-AzAutomationCertificate",
  "Actions": [
  "Microsoft.Automation/automationAccounts/certificates/read",
  "Microsoft.Automation/automationAccounts/read"
  ],
  "NotActions": [
  "Microsoft.Automation/automationAccounts/certificates/read"
  ],
  "AssignableScopes": [
    "/subscriptions/{subscription id}"
  ]
}
</code>```

Please pay attention to the note in above link:

If a user is assigned a role that excludes an operation in NotActions,
  and is assigned a second role that grants access to the same
  operation, the user is allowed to perform that operation. NotActions
  is not a deny rule – it is simply a convenient way to create a set of
  allowed operations when specific operations need to be excluded.

After you update the custom role and assign it to the user, you should reopen an PowerShell window and re-login with the user. Then it will work for you.

Body:
I am trying to create a custom reader role on Azure that does not allow the user to run the PowerShell command Get-AzAutomationCertificate. I have gone through the options and removed quite a few permissions related to reading certificates from the automation service provider. However, it appears it is still not enough.

These are the deny options present in the custom role :

"notActions": [
 "Microsoft.Automation/automationAccounts/listKeys/action",
 "Microsoft.Automation/automationAccounts/certificates/read",
 "Microsoft.Automation/automationAccounts/certificates/getCount/action",
 "Microsoft.Automation/automationAccounts/jobs/read",
 "Microsoft.Automation/automationAccounts/jobs/runbookContent/action",
 "Microsoft.Automation/automationAccounts/credentials/read",
 "Microsoft.Automation/automationAccounts/runbooks/content/read",
 "Microsoft.Automation/automationAccounts/runbooks/read",
 "Microsoft.Automation/automationAccounts/python2Packages/read",
 "Microsoft.Automation/automationAccounts/python3Packages/read",
 "Microsoft.Automation/automationAccounts/privateEndpointConnectionProxies/read",
 "Microsoft.Automation/automationAccounts/connections/read",
 "Microsoft.Automation/automationAccounts/connectionTypes/read
]

More details about the command :
https://github.com/Azure/azure-powershell/blob/master/src/Automation/Automation/help/Get-AzAutomationCertificate.md

Any ideas on how to achieve this?

Thank you

Body:
Firstly, I would like to clarify that the NotActions permission specifies the management operations that are excluded from the allowed Actions. See reference here.

So if the Action is not included in Actions, it's unnecessary to put it into NotActions in order to make it lose effectiveness. In this case, the user will not have the permission to do the action.

The action "Microsoft.Automation/automationAccounts/certificates/read" is what you want to make the PowerShell command Get-AzAutomationCertificate effective. Please note that it allows Get-AzAutomationCertificate to be executed but won't return results.

Here is my example:

{
  "Name": "Custom Role 2",
  "Id": null,
  "IsCustom": true,
  "Description": "Don't allow for Get-AzAutomationCertificate",
  "Actions": [
  "Microsoft.Automation/automationAccounts/certificates/read",
  "Microsoft.Automation/automationAccounts/read"
  ],
  "NotActions": [
  "Microsoft.Automation/automationAccounts/certificates/read"
  ],
  "AssignableScopes": [
    "/subscriptions/{subscription id}"
  ]
}

Please pay attention to the note in above link:

If a user is assigned a role that excludes an operation in NotActions,
  and is assigned a second role that grants access to the same
  operation, the user is allowed to perform that operation. NotActions
  is not a deny rule – it is simply a convenient way to create a set of
  allowed operations when specific operations need to be excluded.

After you update the custom role and assign it to the user, you should reopen an PowerShell window and re-login with the user. Then it will work for you.


问:
How to map to custom field type by fetching from repository in MapStruct
In springboot app I have used UserDateAudit class which means whichever entity class extends it, that class automatically has 4 fields populated when they should be createdBy createdAt updatedBy updatedAt. The UserSummary class contains info about the User.  I have an entity Branch which extends UserDateAudit. Now when I convert Branch to BranchDTO I also need to have UserSummary object to know who created the record. The Branch records are saving successfully with the appropriate user_id in createdBy db column. So I am thinking I would have a custom function in mapper which will take user_id from Branch then find in Db then create UserSummary object and assign to BRanchDTO. Is there a proper way to acheive this?

```<code>@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring")
public interface BranchMapper
{
    Branch toBranch(BranchDTO branchDTO);
    BranchDTO toBranchDTO(Branch branch);
    List<BranchDTO> toBranchDTOS(List<Branch> branches);
    Branch updateBranch(BranchDTO branchDTO, @MappingTarget Branch branch);

}
</code>```

DateAudit.java

```<code>@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(
        value = {"createdAt", "updatedAt"},
        allowGetters = true
)
public abstract class DateAudit implements Serializable
{
    @CreatedDate
    @Column(nullable = false, updatable = false)
    private Instant createdAt;

    @LastModifiedDate
    @Column(nullable = false)
    private Instant updatedAt;
}
</code>```

UserDateAudit.java

```<code>@MappedSuperclass
@JsonIgnoreProperties(
        value = {"createdBy", "updatedBy"},
        allowGetters = true
)
public class UserDateAudit extends DateAudit
{
    @CreatedBy
    @Column(nullable = false, updatable = false)
    private Long createdBy;

    @LastModifiedBy
    @Column(nullable = false)
    private Long updatedBy;
}
</code>```

Branch.java

```<code>@Entity
@Table(name = "branches")
public class Branch extends UserDateAudit
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    @Column(name = "name", nullable = false)
    @Size(max = 20)
    private String name;

    @Column(name = "default_branch", nullable = false)
    private boolean defaultBranch;
}
</code>```

BranchDTO.java

```<code>public class BranchDTO
{
    private Long id;
    private String name;
    private boolean defaultBranch;
    UserSummary createdBy;
}
</code>```

UserSummary.java

```<code>public class UserSummary
{
    private Long id;
    private String username;
    private String name;
}
</code>```

答:
MapStruct has the possibility to use other mappers or services via Mapper#uses.

Let's imagine that you have a service which looks like the following:

```<code>public interface UserSummaryService {

    UserSummary getUserSummary(Long userId);

}
</code>```

then in your mapper you can do:

```<code>@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring", uses = UserSummaryService.class)
public interface BranchMapper {

    @Mapping(target = "createdBy", ignore = true)
    Branch toBranch(BranchDTO branchDTO);

    BranchDTO toBranchDTO(Branch branch);

    List<BranchDTO> toBranchDTOS(List<Branch> branches);

    @InheritConfiguration
    Branch updateBranch(BranchDTO branchDTO, @MappingTarget Branch branch);

}
</code>```

With this mapper when mapping from the BranchDTO into Branch the createdBy will be ignored.

By using @InheritConfiguration the updateBranch mapping will inherit the configuration from the toBranch method and ignore the createdBy mapping.

MapStruct will automatically see that there is a mapping method between Long and UserSummary in the UserSummaryService and will invoke it to map the createdBy between Branch and BranchDTO in the toBranchDTO method.

Body:
In springboot app I have used UserDateAudit class which means whichever entity class extends it, that class automatically has 4 fields populated when they should be createdBy createdAt updatedBy updatedAt. The UserSummary class contains info about the User.  I have an entity Branch which extends UserDateAudit. Now when I convert Branch to BranchDTO I also need to have UserSummary object to know who created the record. The Branch records are saving successfully with the appropriate user_id in createdBy db column. So I am thinking I would have a custom function in mapper which will take user_id from Branch then find in Db then create UserSummary object and assign to BRanchDTO. Is there a proper way to acheive this?

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring")
public interface BranchMapper
{
    Branch toBranch(BranchDTO branchDTO);
    BranchDTO toBranchDTO(Branch branch);
    List<BranchDTO> toBranchDTOS(List<Branch> branches);
    Branch updateBranch(BranchDTO branchDTO, @MappingTarget Branch branch);

}

DateAudit.java

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(
        value = {"createdAt", "updatedAt"},
        allowGetters = true
)
public abstract class DateAudit implements Serializable
{
    @CreatedDate
    @Column(nullable = false, updatable = false)
    private Instant createdAt;

    @LastModifiedDate
    @Column(nullable = false)
    private Instant updatedAt;
}

UserDateAudit.java

@MappedSuperclass
@JsonIgnoreProperties(
        value = {"createdBy", "updatedBy"},
        allowGetters = true
)
public class UserDateAudit extends DateAudit
{
    @CreatedBy
    @Column(nullable = false, updatable = false)
    private Long createdBy;

    @LastModifiedBy
    @Column(nullable = false)
    private Long updatedBy;
}

Branch.java

@Entity
@Table(name = "branches")
public class Branch extends UserDateAudit
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    @Column(name = "name", nullable = false)
    @Size(max = 20)
    private String name;

    @Column(name = "default_branch", nullable = false)
    private boolean defaultBranch;
}

BranchDTO.java

public class BranchDTO
{
    private Long id;
    private String name;
    private boolean defaultBranch;
    UserSummary createdBy;
}

UserSummary.java

public class UserSummary
{
    private Long id;
    private String username;
    private String name;
}

Body:
MapStruct has the possibility to use other mappers or services via Mapper#uses.

Let's imagine that you have a service which looks like the following:

public interface UserSummaryService {

    UserSummary getUserSummary(Long userId);

}

then in your mapper you can do:

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring", uses = UserSummaryService.class)
public interface BranchMapper {

    @Mapping(target = "createdBy", ignore = true)
    Branch toBranch(BranchDTO branchDTO);

    BranchDTO toBranchDTO(Branch branch);

    List<BranchDTO> toBranchDTOS(List<Branch> branches);

    @InheritConfiguration
    Branch updateBranch(BranchDTO branchDTO, @MappingTarget Branch branch);

}

With this mapper when mapping from the BranchDTO into Branch the createdBy will be ignored.

By using @InheritConfiguration the updateBranch mapping will inherit the configuration from the toBranch method and ignore the createdBy mapping.

MapStruct will automatically see that there is a mapping method between Long and UserSummary in the UserSummaryService and will invoke it to map the createdBy between Branch and BranchDTO in the toBranchDTO method.


问:
LARAVEL 7 - How to pass variables to views
I have two tables, Companies and Projects. A company hasMany projects and a project belongsTo a company.

Company.php model

```<code>protected $fillable = [
    'id', 'name', 'description'
];

public function projects()
{
    return $this->hasMany('App/Project');
}
</code>```

Project.php model

```<code>protected $fillable = [
    'name', 'description', 'company_id', 'days'
];

public function company()
{
    return $this->belongsTo('App/Company');
}
</code>```

From my index.blade.php, I list the companies only and I have made them clickable so that when a user clicks on a company listed, they are taken to show.blade.php where the name of the company and the projects that belong to that company are displayed like so.

```<code><div class="jumbotron">
     <h1>{{ $company->name }}</h1>
       <p class="lead">{{ $company->description }}</p>
    </div>

<div class="row">
    @foreach($company->projects as $project)
    <div class="col-lg-4">
        <h2>{{ $project->name }}</h2>
        <p class="text-danger">{{ $project->description }}</p>
        <p><a class="btn btn-primary" href="/projects/{{ $project->id }}" role="button">View Projects »</a></p>
    </div>
    @endforeach
</div>
</code>```

Now am getting an undefined variable $project error. So I decided to declare variable in my show() function of the CompaniesController.php like so

```<code>public function show(Company $company)
{
    $company = Company::find($company->id);
    $projects = Company::find(1)->projects;

    return view('companies.show', ['company' => $company, 'projects' => $projects]);
}
</code>```

And access variable in show.blade.php like so

```<code>    <div class="jumbotron">

    <h1>{{ $company->name }}</h1>
    <p class="lead">{{ $company->description }}</p>
</div>
<div class="row">

    @foreach($projects as $project)
    <div class="col-lg-4">
        <h2>{{ $project->name }}</h2>
        <p class="text-danger">{{ $project->description }}</p>
        <p><a class="btn btn-primary" href="/projects/{{ $project->id }}" role="button">View Projects »</a></p>
    </div>
    @endforeach
</div>
</code>```

Now am getting a Class 'App/Project' not found error when I access show.blade.php. I am having a challenge passing company projects to the view. Any help will be appreciated. Here are my routes;

```<code>    Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::resource('companies', 'CompaniesController');
Route::resource('projects', 'ProjectsController');
</code>```

答:
You're already using model binding. In your show method, you do not need to find. just return what you need

```<code>public function show(Company $company)
{
    return view('companies.show', ['company' => $company];
}
</code>```

In your view, you can then do:

```<code>@foreach($company->projects as $project)
...
@endforeach
</code>```

Body:
I have two tables, Companies and Projects. A company hasMany projects and a project belongsTo a company.

Company.php model

protected $fillable = [
    'id', 'name', 'description'
];

public function projects()
{
    return $this->hasMany('App/Project');
}

Project.php model

protected $fillable = [
    'name', 'description', 'company_id', 'days'
];

public function company()
{
    return $this->belongsTo('App/Company');
}

From my index.blade.php, I list the companies only and I have made them clickable so that when a user clicks on a company listed, they are taken to show.blade.php where the name of the company and the projects that belong to that company are displayed like so.

{{ $company->name }}

{{ $company->description }}

    @foreach($company->projects as $project)

{{ $project->name }}

{{ $project->description }}

id }}" role="button">View Projects »

    @endforeach

Now am getting an undefined variable $project error. So I decided to declare variable in my show() function of the CompaniesController.php like so

public function show(Company $company)
{
    $company = Company::find($company->id);
    $projects = Company::find(1)->projects;

    return view('companies.show', ['company' => $company, 'projects' => $projects]);
}

And access variable in show.blade.php like so

{{ $company->name }}

{{ $company->description }}

    @foreach($projects as $project)

{{ $project->name }}

{{ $project->description }}

id }}" role="button">View Projects »

    @endforeach

Now am getting a Class 'App/Project' not found error when I access show.blade.php. I am having a challenge passing company projects to the view. Any help will be appreciated. Here are my routes;

    Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::resource('companies', 'CompaniesController');
Route::resource('projects', 'ProjectsController');

Body:
You're already using model binding. In your show method, you do not need to find. just return what you need

public function show(Company $company)
{
    return view('companies.show', ['company' => $company];
}

In your view, you can then do:

@foreach($company->projects as $project)
...
@endforeach


问:
Google Colab is so slow while reading images from Google Drive
I have my own dataset for a deep learning project. I uploaded that into Google Drive and linked it to a Colab page. But Colab could read only 2-3 images in a second, where my computer can dozens of them. (I used imread to read images.)

There is no speed problem with model compiling process of keras, but only with reading images from Google Drive. Does anybody know a solution? Someone suffered of this problem too, but it's still unsolved: Google Colab very slow reading data (images) from Google Drive (I know this is kind of a duplication of the question in the link, but I reposted it because it is still unsolved. I hope this is not a violation of Stack Overflow rules.)

Edit: The code piece that I use for reading images:

```<code>def getDataset(path, classes, pixel=32, rate=0.8):
    X = []
    Y = []

    i = 0
    # getting images:
    for root, _, files in os.walk(path):
        for file in files:
            imagePath = os.path.join(root, file)
            className = os.path.basename(root)

            try:
                image = Image.open(imagePath)
                image = np.asarray(image)
                image = np.array(Image.fromarray(image.astype('uint8')).resize((pixel, pixel)))
                image = image if len(image.shape) == 3 else color.gray2rgb(image)
                X.append(image)
                Y.append(classes[className])
            except:
                print(file, "could not be opened")

    X = np.asarray(X, dtype=np.float32)
    Y = np.asarray(Y, dtype=np.int16).reshape(1, -1)

    return shuffleDataset(X, Y, rate)
</code>```

答: I recommend you to upload your file to GitHub then clone it to Colab. It can reduce my training time from 1 hour to 3 minutes.</p>

Body:
I have my own dataset for a deep learning project. I uploaded that into Google Drive and linked it to a Colab page. But Colab could read only 2-3 images in a second, where my computer can dozens of them. (I used imread to read images.)

There is no speed problem with model compiling process of keras, but only with reading images from Google Drive. Does anybody know a solution? Someone suffered of this problem too, but it's still unsolved: Google Colab very slow reading data (images) from Google Drive (I know this is kind of a duplication of the question in the link, but I reposted it because it is still unsolved. I hope this is not a violation of Stack Overflow rules.)

Edit: The code piece that I use for reading images:

def getDataset(path, classes, pixel=32, rate=0.8):
    X = []
    Y = []

    i = 0
    # getting images:
    for root, _, files in os.walk(path):
        for file in files:
            imagePath = os.path.join(root, file)
            className = os.path.basename(root)

            try:
                image = Image.open(imagePath)
                image = np.asarray(image)
                image = np.array(Image.fromarray(image.astype('uint8')).resize((pixel, pixel)))
                image = image if len(image.shape) == 3 else color.gray2rgb(image)
                X.append(image)
                Y.append(classes[className])
            except:
                print(file, "could not be opened")

    X = np.asarray(X, dtype=np.float32)
    Y = np.asarray(Y, dtype=np.int16).reshape(1, -1)

    return shuffleDataset(X, Y, rate)


问:
C / Getting line string from text file and storing them in array/pointer
I want to get all lines from the text file and store them in my char** pointer (array of strings). The problem is that when I try to set indices for pointer's strings, the program assigns the last scanned sentence for all indices.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE 10000

int main()
{
    FILE *fp = NULL;
    char line[MAX_LINE];
    char** lines = (char**) malloc(10000*200*sizeof(char));

    int count = 0;

    fp = fopen("test.txt","r");

    while(fgets(line,10000,fp)) {
      lines[count] = line;
      count++;
    }

    fclose(fp);

    for(int i =0; i<2000;i++){
      printf("%s",lines[i]);
    }

    return 0;
}

</code>```

lets assume test.txt is like this:

```<code>Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, and what is the use of a book, thought Alice without pictures or
conversations?
</code>```

When I print like this, every time I get the last sentence (in this case conversations? ) in my text file. However, I want to set every scanned sentence from the text file to the different index in my char**. For example, I want to set like this:

```<code>lines[0] gives "Alice was beginning to get very tired of sitting by her sister on the"
lines[1] gives "bank, and of having nothing to do: once or twice she had peeped into the"
and so on.
</code>```

答:
You can't copy characters from one string buffer to another simply by assigning a pointer (all that does is to make the destination point to the source, as you have noticed).

Instead, you must actually copy the characters, using the strcpy function. So, instead of:

    lines[count] = line; // Just makes each pointer point to the same buffer
```

<p>use:</p>

<pre class="lang-c prettyprint-override"><code>    strcpy(lines[count], line); // Copies the CURRENT contents of "line"
</code>```

You also have a severe problem in the way you are using your char** lines buffer. If you want an array of 200 lines, each with a maximum length of 10000 characters, you should allocate them as follows:

char** lines = malloc(200 * sizeof(char*)); // Make 200 pointers
// Now allocate 10000 chars to each of these pointers:
for (int i = 0; i < 200; ++i) lines[i] = malloc(10000 * sizeof(char));
```

<p>Note: The 200 buffers will be uninitialized (contain random data) so, in your print loop, you should only use those you have copied real data to, using the <code>count</code> variable as the loop limit:</p>

<pre class="lang-c prettyprint-override"><code>for(int i = 0; i < count; i++) {
     printf("%s", lines[i]);
}
</code>```

Also, don't forget to free the memory allocated when you're done:

for (int i = 0; i < 200; ++i) free(lines[i]); // Free each line buffer...
free(lines); // ... then free the array of pointers itself
```

Body:
I want to get all lines from the text file and store them in my char** pointer (array of strings). The problem is that when I try to set indices for pointer's strings, the program assigns the last scanned sentence for all indices.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE 10000

int main()
{
    FILE *fp = NULL;
    char line[MAX_LINE];
    char** lines = (char**) malloc(10000*200*sizeof(char));

    int count = 0;

    fp = fopen("test.txt","r");

    while(fgets(line,10000,fp)) {
      lines[count] = line;
      count++;
    }

    fclose(fp);

    for(int i =0; i<2000;i++){
      printf("%s",lines[i]);
    }

    return 0;
}

lets assume test.txt is like this:

Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, and what is the use of a book, thought Alice without pictures or
conversations?

When I print like this, every time I get the last sentence (in this case conversations? ) in my text file. However, I want to set every scanned sentence from the text file to the different index in my char**. For example, I want to set like this:

lines[0] gives "Alice was beginning to get very tired of sitting by her sister on the"
lines[1] gives "bank, and of having nothing to do: once or twice she had peeped into the"
and so on.

Body:
You can't copy characters from one string buffer to another simply by assigning a pointer (all that does is to make the destination point to the source, as you have noticed).

Instead, you must actually copy the characters, using the strcpy function. So, instead of:

    lines[count] = line; // Just makes each pointer point to the same buffer

use:

    strcpy(lines[count], line); // Copies the CURRENT contents of "line"

You also have a severe problem in the way you are using your char** lines buffer. If you want an array of 200 lines, each with a maximum length of 10000 characters, you should allocate them as follows:

char** lines = malloc(200 * sizeof(char*)); // Make 200 pointers
// Now allocate 10000 chars to each of these pointers:
for (int i = 0; i < 200; ++i) lines[i] = malloc(10000 * sizeof(char));

Note: The 200 buffers will be uninitialized (contain random data) so, in your print loop, you should only use those you have copied real data to, using the count variable as the loop limit:

for(int i = 0; i < count; i++) {
     printf("%s", lines[i]);
}

Also, don't forget to free the memory allocated when you're done:

for (int i = 0; i < 200; ++i) free(lines[i]); // Free each line buffer...
free(lines); // ... then free the array of pointers itself


问:
Yii echmultiselect showing error on console and not working
I was following the Option no 3 here https://www.yiiframework.com/extension/echmultiselect#3-use-as-a-filter-in-cgridview to add multiselect dropdown on my Yii project. But it is showing,

jquery.js:6920 Uncaught TypeError: jQuery.easing[this.easing] is not a
  function
      at init.run (jquery.js:6920)

On my cgridview, this is the column that has to be multiple select checkbox,

```<code>array (
                'name'=>'brand_id',
                'filter'=> $this->widget('ext.EchMultiSelect.EchMultiSelect', array(
                    'model' => $model,
                    'dropDownAttribute' => 'brand_id',
                    'data' => CHtml::listData(Brands::model()->findAll(array("order" => "sortOrder")), 'id', 'name'),
                    'options' => array('buttonWidth' => 80, 'ajaxRefresh' => true,'filter'=>true),
                ),
                    true // capture output; needed so the widget displays inside the grid
                ),
           ),
</code>```

On my layout,

I've included the jquery,

```<code><?php Yii::app()->clientScript->registerCoreScript('jquery'); ?>
</code>```

Dropdown page:

Because of that jQuery.easing[this.easing] is not a function error the multi-select functionality is not working, as per the suggestion here: https://stackoverflow.com/a/12592301/1138192 I've added the jquery UI also but it doesn't work even it breaks the existing dropdown.

Error on the console:

答:
The problem is in jquery.multiselect.js (EchMultiSelect-v1.3) as the effect method arguments are inverted (at least for the current jQuery version):

.show( effect, speed ) and .hide( effect, speed ) on lines 566, 573, 600 should be replaced by the correct order .show( speed, effect ) and .hide( speed, effect ).

Body:
I was following the Option no 3 here https://www.yiiframework.com/extension/echmultiselect#3-use-as-a-filter-in-cgridview to add multiselect dropdown on my Yii project. But it is showing,

jquery.js:6920 Uncaught TypeError: jQuery.easing[this.easing] is not a
  function
      at init.run (jquery.js:6920)

On my cgridview, this is the column that has to be multiple select checkbox,

array (
                'name'=>'brand_id',
                'filter'=> $this->widget('ext.EchMultiSelect.EchMultiSelect', array(
                    'model' => $model,
                    'dropDownAttribute' => 'brand_id',
                    'data' => CHtml::listData(Brands::model()->findAll(array("order" => "sortOrder")), 'id', 'name'),
                    'options' => array('buttonWidth' => 80, 'ajaxRefresh' => true,'filter'=>true),
                ),
                    true // capture output; needed so the widget displays inside the grid
                ),
           ),

On my layout,

I've included the jquery,

<?php Yii::app()->clientScript->registerCoreScript('jquery'); ?>

Dropdown page:

Because of that jQuery.easing[this.easing] is not a function error the multi-select functionality is not working, as per the suggestion here: https://stackoverflow.com/a/12592301/1138192 I've added the jquery UI also but it doesn't work even it breaks the existing dropdown.

Error on the console:


问:
Emacs bookmark-jump: how to jump to bmark and only one of the split-windows changes contents?
I start with a file visible in one window; then i do a split-window, therefore now both windows show the same contents (at same buffer point).

Now I want to jump to a different location in the file via a bookmark in only 1 of the 2 windows, but when i execute the bookmark-jump, both windows end up at the bookmark's point.

Leave the other window's point alone!

How can i configure this?

Thanks

(running on linux, GNU Emacs 23.2.1; xemacs does not behave this way)

post-note:

What I'd like to do is to have the same file shown on both windows, and while one window (w1) shows a section of the file, in the other window (w2) I jump around to different sections, using the various bookmarks, while w1's position does not change.

答:
This doesn't answer your question directly, but provides an alternative solution to your problem. I use bm.el for visible bookmarks. If the same file is visible in two windows then jumping around using visible bookmarks only modifies the point in the current buffer.

I've configured the package with the following:

```<code>(require 'bm)
(setq bm-highlight-style 'bm-highlight-only-fringe)

(global-set-key (kbd "<C-f2>") 'bm-toggle)
(global-set-key (kbd "<f2>") 'bm-next)
(global-set-key (kbd "<S-f2>") 'bm-previous)
</code>```

Body:
This doesn't answer your question directly, but provides an alternative solution to your problem. I use bm.el for visible bookmarks. If the same file is visible in two windows then jumping around using visible bookmarks only modifies the point in the current buffer.

I've configured the package with the following:

(require 'bm)
(setq bm-highlight-style 'bm-highlight-only-fringe)

(global-set-key (kbd "<C-f2>") 'bm-toggle)
(global-set-key (kbd "<f2>") 'bm-next)
(global-set-key (kbd "<S-f2>") 'bm-previous)