问:
Add column value in panda data frame if certain condition is met
I have two lists:

```<code>    required=["api.gotinder.com","data.gotinder.com"]
    not_required=["graph.facebook.com","launches.appsflyer.com"]

</code>```

If the value in requested_server_name column is in required list then it should be labeled as Required if the value in requested_server_name column is in not_required list then it should be labeled as Not_Required

What I am doing at the moment:

```<code>for j in required:
    conditions = [
        (frame['requested_server_name'] == j)
        ]
    values = ["Required"]
    frame['label'] = np.select(conditions, values)

for k in not_required:
    conditions = [
        (frame['requested_server_name'] == k)
        ]
    values = ["Not_Required"]
    frame['label'] = np.select(conditions, values)
</code>```

What am I doing wrong?? It only populates the label for launches.appsflyer.com.

答:
```<code>for j in required:
    frame.loc[frame['requested_server_name'] == j, 'Label'] = "Required"

for k in not_required:
    frame.loc[frame['requested_server_name'] == k, 'Label'] = "Not_Required"

</code>```

This works as well.

Body:
I have two lists:

    required=["api.gotinder.com","data.gotinder.com"]
    not_required=["graph.facebook.com","launches.appsflyer.com"]

If the value in requested_server_name column is in required list then it should be labeled as Required if the value in requested_server_name column is in not_required list then it should be labeled as Not_Required

What I am doing at the moment:

for j in required:
    conditions = [
        (frame['requested_server_name'] == j)
        ]
    values = ["Required"]
    frame['label'] = np.select(conditions, values)

for k in not_required:
    conditions = [
        (frame['requested_server_name'] == k)
        ]
    values = ["Not_Required"]
    frame['label'] = np.select(conditions, values)

What am I doing wrong?? It only populates the label for launches.appsflyer.com.

Body:
for j in required:
    frame.loc[frame['requested_server_name'] == j, 'Label'] = "Required"

for k in not_required:
    frame.loc[frame['requested_server_name'] == k, 'Label'] = "Not_Required"

This works as well.


来源: stackexchange

问:
Flutter_form_builder errors
I'm trying to use flutter_form_builder: ^7.1.0 with form_builder_validators to create a form, but a getting undefined errors at

onChanged: _onChanged, and validator: FormBuilderValidators.compose.

I tried following the example at flutter_form_builder but the example seems to be either incomplete or not up to date. When I try to add autovalidate: true, I get another undefined error. How can I fix this?

```<code>class _CreateCompanyViewState extends State<CreateCompanyView> {

  @override
  void initState() {
    super.initState();
  }

  final _formKey = GlobalKey<FormBuilderState>();

  @override
  Widget build(BuildContext context) {
</code>```

```<code> FormBuilder(

                key: _formKey,

                child: Column(

                  children: <Widget>[

                    FormBuilderTextField(

                      name: 'age',

                      decoration: InputDecoration(

                      labelText: 'This value is passed along to the [Text.maxLines] attribute of the [Text] widget used to display the hint text.',

                      ),

                      onChanged: _onChanged,

                        validator: FormBuilderValidators.compose([

                          FormBuilderValidators.required(context),

                          FormBuilderValidators.numeric(context),

                          FormBuilderValidators.max(context, 70),

                        ]),

                          keyboardType: TextInputType.number,

                        ),

                  Row(

                    children: <Widget>[

                      Expanded(

                        child: MaterialButton(

                          color: Theme.of(context).colorScheme.secondary,

                        child: Text("Submit", style: TextStyle(color: Colors.white),),

                          onPressed: () {

                            _formKey.currentState?.save();

                            if (_formKey.currentState!.validate()) {

                              print(_formKey.currentState!.value);

                            } else {

                              print("validation failed");
                            }
                          },
                        ),
                      ),

                      SizedBox(width: 20),

                      Expanded(

                        child: MaterialButton(

                          color: Theme.of(context).colorScheme.secondary,

                          child: Text("Reset", style: TextStyle(color: Colors.white),),

                          onPressed: () {

                            _formKey.currentState!.reset();
                          },
                        ),
                      ),
                    ],
                  )
                ],
              )
            ),
            ],
          ),
        ),
      ),
    )));
  }
</code>```

答:
FormBuilderValidators is not handling null value. You need to check null value, then perform others validators.

validator: FormBuilderValidators.compose([
  (val) {
    return val == null ? "Field is empty" : null;
  },
  FormBuilderValidators.required(context),
/// others validator
]),
```

ContentLicense: CC BY-SA 4.0

Title: Flutter_form_builder errors

Body:
I'm trying to use flutter_form_builder: ^7.1.0 with form_builder_validators to create a form, but a getting undefined errors at

onChanged: _onChanged, and validator: FormBuilderValidators.compose.

I tried following the example at flutter_form_builder but the example seems to be either incomplete or not up to date. When I try to add autovalidate: true, I get another undefined error. How can I fix this?

class _CreateCompanyViewState extends State<CreateCompanyView> {

  @override
  void initState() {
    super.initState();
  }

  final _formKey = GlobalKey<FormBuilderState>();

  @override
  Widget build(BuildContext context) {

 FormBuilder(

                key: _formKey,

                child: Column(

                  children: <Widget>[

                    FormBuilderTextField(

                      name: 'age',

                      decoration: InputDecoration(

                      labelText: 'This value is passed along to the [Text.maxLines] attribute of the [Text] widget used to display the hint text.',

                      ),

                      onChanged: _onChanged,

                        validator: FormBuilderValidators.compose([

                          FormBuilderValidators.required(context),

                          FormBuilderValidators.numeric(context),

                          FormBuilderValidators.max(context, 70),

                        ]),

                          keyboardType: TextInputType.number,

                        ),

                  Row(

                    children: <Widget>[

                      Expanded(

                        child: MaterialButton(

                          color: Theme.of(context).colorScheme.secondary,

                        child: Text("Submit", style: TextStyle(color: Colors.white),),

                          onPressed: () {

                            _formKey.currentState?.save();

                            if (_formKey.currentState!.validate()) {

                              print(_formKey.currentState!.value);

                            } else {

                              print("validation failed");
                            }
                          },
                        ),
                      ),

                      SizedBox(width: 20),

                      Expanded(

                        child: MaterialButton(

                          color: Theme.of(context).colorScheme.secondary,

                          child: Text("Reset", style: TextStyle(color: Colors.white),),

                          onPressed: () {

                            _formKey.currentState!.reset();
                          },
                        ),
                      ),
                    ],
                  )
                ],
              )
            ),
            ],
          ),
        ),
      ),
    )));
  }


问:
Calculate Bezier curve and draw
I want to Calculate Bezier Curve which should return me x,y where I can plug and draw the line. I have to use this formula

where t is in [0,1]

   struct myPoint {
        int x;
        int y;
    };

void drawBezier(myPoint p0, myPoint p1, myPoint p2, myPoint p3) {
    myPoint result;

    for(double t = 0.0; t<=1.0; t+=0.001){
        result = pow((1-t),3) * p0 + 3 * pow((1-t),2) * t * p1 + 3 * (1-t) * pow(t,2) * p2 + pow(t,3) * p3;
    }

}
```

How can I actually receive x,y out of this? I am not sure how to calculate this correctly. Can someone give me advice

答:
In the above code, you don't need to return anything, since the loop will give you a result for each iteration, so you can draw the result after each iteration directly.

In case you need to return something from the function, you need to make the loop outside the function itself.

Title: Calculate Bezier curve and draw

Body:
I want to Calculate Bezier Curve which should return me x,y where I can plug and draw the line. I have to use this formula

where t is in [0,1]

   struct myPoint {
        int x;
        int y;
    };

void drawBezier(myPoint p0, myPoint p1, myPoint p2, myPoint p3) {
    myPoint result;

    for(double t = 0.0; t<=1.0; t+=0.001){
        result = pow((1-t),3) * p0 + 3 * pow((1-t),2) * t * p1 + 3 * (1-t) * pow(t,2) * p2 + pow(t,3) * p3;
    }

}

How can I actually receive x,y out of this? I am not sure how to calculate this correctly. Can someone give me advice


问:
How to download file from Google Cloud Storage?
I'm following up on this article to download objects from GCP Cloud storage bucket: https://cloud.google.com/storage/docs/downloading-objects#storage-download-object-nodejs

const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function downloadIntoMemory() {
  // Downloads the file into a buffer in memory.
  const contents = await storage.bucket(bucketName).file(fileName).download();

 return contents;
  );
}

downloadIntoMemory().catch(console.error);```

I'm currently getting a buffer data in contents. I've this code hooked upto a API on NodeJS backend. I'm using React Typescript on frontend. Calling the API, gives me data buffer. How can I use it to download the file instead of the data buffer?

I tried the above method explicitly providing file destination, but I'm still getting the following error: EISDIR: illegal operation on a directory, open '{file_path_which_i_was_set}. Err: -21

答:
As rightly pointed out by @John Hanley, you are referring to the documentation, where the code sample downloads an object into memory/ buffer in memory. If you want to download an object from a bucket to a file, refer to this code sample, where the ‘options’ parameter has to be passed to the download() method.
The code goes like this :</p>
```<code>// The ID of your GCS bucket
const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
const fileName = 'your-file-name';

// The path to which the file should be downloaded
const destFileName = '/local/path/to/file.txt';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function downloadFile() {
  const options = {
    destination: destFileName,
  };

  // Downloads the file to the destination file path
  await storage.bucket(bucketName).file(fileName).download(options);

  console.log(
    `gs://${bucketName}/${fileName} downloaded to ${destFileName}.`
  );
}

downloadFile().catch(console.error);
</code>```

Body:
I'm following up on this article to download objects from GCP Cloud storage bucket: https://cloud.google.com/storage/docs/downloading-objects#storage-download-object-nodejs

const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function downloadIntoMemory() {
  // Downloads the file into a buffer in memory.
  const contents = await storage.bucket(bucketName).file(fileName).download();

 return contents;
  );
}

downloadIntoMemory().catch(console.error);

I'm currently getting a buffer data in contents. I've this code hooked upto a API on NodeJS backend. I'm using React Typescript on frontend. Calling the API, gives me data buffer. How can I use it to download the file instead of the data buffer?

I tried the above method explicitly providing file destination, but I'm still getting the following error: EISDIR: illegal operation on a directory, open '{file_path_which_i_was_set}. Err: -21

Body:
As rightly pointed out by @John Hanley, you are referring to the documentation, where the code sample downloads an object into memory/ buffer in memory. If you want to download an object from a bucket to a file, refer to this code sample, where the ‘options’ parameter has to be passed to the download() method.
The code goes like this :

// The ID of your GCS bucket
const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
const fileName = 'your-file-name';

// The path to which the file should be downloaded
const destFileName = '/local/path/to/file.txt';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function downloadFile() {
  const options = {
    destination: destFileName,
  };

  // Downloads the file to the destination file path
  await storage.bucket(bucketName).file(fileName).download(options);

  console.log(
    `gs://${bucketName}/${fileName} downloaded to ${destFileName}.`
  );
}

downloadFile().catch(console.error);


问:
How to require child class method to call parent class method?
Let's say I have a parent class A.

```<code>class A
{
    public:
        A() {}

        void MyMethod()
        {
            printf( "A\n" );
        }
};
</code>```

And I have a child class B.

```<code>class B : public A
{
    public:
        B() {}

        void MyMethod()
        {
            printf( "B\n" );
        }
};
</code>```

Now, I would like to require class B to call A::MyMethod(), without explicitly calling it, as shown above. Resulting in:

```<code>A
B
</code>```

Or

```<code>B
A
</code>```

Would that be possible?

Right now B->MyMethod() only calls the child method.

答:
There's no way to require one class method to call another one, in C++, except for the requirement that a constructor and a destructor in a derived class must call the parent class's, in specific ways.

Except for that, there is no way to directly require this, in C++.

Body:
Let's say I have a parent class A.

class A
{
    public:
        A() {}

        void MyMethod()
        {
            printf( "A\n" );
        }
};

And I have a child class B.

class B : public A
{
    public:
        B() {}

        void MyMethod()
        {
            printf( "B\n" );
        }
};

Now, I would like to require class B to call A::MyMethod(), without explicitly calling it, as shown above. Resulting in:

A
B

Or

B
A

Would that be possible?

Right now B->MyMethod() only calls the child method.


问:
Is it advisable to write a test case for every class in your program?
Im am just getting introduced to unit testing and test driven development. Thus far, I have only used Junit as testing framework. A question which emerged and for which I have not yet found a definite answer is: how much test cases do I need to write? Do I have to write a test case for every single class in my program? Or is this a stupid question because unit testing implies testing at the lowest (i.e. class) level?

I think writing a test case for every class is probably the more safe way to go (after all the more you test the lower the number of unforeseen bugs). But I was wondering if there are any widely agreed upon strategies regarding the amount of test cases to write?

答: If you're trying on TDD, then you shouldn't be writing any code at all without having a failing test that tells you to do so. By implication, then, you'll never have a class that doesn't have one or more tests for it. A rule of thumb that tends to get quoted is that you should end up with about 2.5 times as much test source as main source.</p>

ContentLicense: CC BY-SA 3.0


问:
Linux bash weave two text files into one alternative line using all available lines
I am looking to merge two text files into one,
where all the lines from one text file become odd line numbers
and the other file becomes even line numbers
such as to weave the files together

input1.txt

```<code>1, 267, Note_on_c, 0, 67, 100
1, 758, Note_on_c, 0, 58, 100
1, 1248, Note_on_c, 0, 79, 100
1, 1739, Note_on_c, 0, 52, 100
</code>```

input2.txt

```<code>1, 368, Note_off_c, 0, 67, 127
1, 936, Note_off_c, 0, 58, 127
1, 1415, Note_off_c, 0, 79, 127
1, 1917, Note_off_c, 0, 52, 127
</code>```

and need to combine these text files to create the following output

```<code>1, 267, Note_on_c, 0, 67, 100
1, 368, Note_off_c, 0, 67, 127
1, 758, Note_on_c, 0, 58, 100
1, 936, Note_off_c, 0, 58, 127
1, 1248, Note_on_c, 0, 79, 100
1, 1415, Note_off_c, 0, 79, 127
1, 1739, Note_on_c, 0, 52, 100
1, 1917, Note_off_c, 0, 52, 127
</code>```

so I am looking to merge these files in the true since of the word weave

答:
With GNU sed's R command:

```<code>sed 'R input2.txt' input1.txt
</code>```

Output:

```
1, 267, Note_on_c, 0, 67, 100
1, 368, Note_off_c, 0, 67, 127
1, 758, Note_on_c, 0, 58, 100
1, 936, Note_off_c, 0, 58, 127
1, 1248, Note_on_c, 0, 79, 100
1, 1415, Note_off_c, 0, 79, 127
1, 1739, Note_on_c, 0, 52, 100
1, 1917, Note_off_c, 0, 52, 127
```

From man sed:

R filename:
Append  a  line read from filename.  Each invocation of the command reads a line from the file.  This is a GNU
extension.

Body:
I am looking to merge two text files into one,
where all the lines from one text file become odd line numbers
and the other file becomes even line numbers
such as to weave the files together

input1.txt

1, 267, Note_on_c, 0, 67, 100
1, 758, Note_on_c, 0, 58, 100
1, 1248, Note_on_c, 0, 79, 100
1, 1739, Note_on_c, 0, 52, 100

input2.txt

1, 368, Note_off_c, 0, 67, 127
1, 936, Note_off_c, 0, 58, 127
1, 1415, Note_off_c, 0, 79, 127
1, 1917, Note_off_c, 0, 52, 127

and need to combine these text files to create the following output

1, 267, Note_on_c, 0, 67, 100
1, 368, Note_off_c, 0, 67, 127
1, 758, Note_on_c, 0, 58, 100
1, 936, Note_off_c, 0, 58, 127
1, 1248, Note_on_c, 0, 79, 100
1, 1415, Note_off_c, 0, 79, 127
1, 1739, Note_on_c, 0, 52, 100
1, 1917, Note_off_c, 0, 52, 127

so I am looking to merge these files in the true since of the word weave

Body:
With GNU sed's R command:

sed 'R input2.txt' input1.txt

Output:

1, 267, Note_on_c, 0, 67, 100
1, 368, Note_off_c, 0, 67, 127
1, 758, Note_on_c, 0, 58, 100
1, 936, Note_off_c, 0, 58, 127
1, 1248, Note_on_c, 0, 79, 100
1, 1415, Note_off_c, 0, 79, 127
1, 1739, Note_on_c, 0, 52, 100
1, 1917, Note_off_c, 0, 52, 127

From man sed:

R filename:
Append  a  line read from filename.  Each invocation of the command reads a line from the file.  This is a GNU
extension.


问:
Google Chrome Extension: How to open a new tab in a discarded/hibernating state?
I have a Google Chrome Extension that involves creating new tabs. I want to be able to create lots of tabs at once, but I don't want them all to load at the same time. I just want to add the tab to the window and have it reload when it becomes active. Is this something that the Google Chrome Extension API supports? Or is this something I will need to build myself (use a placeholder page that loads the correct URL when active)?</p>

答:
I had the same question as you, and thanks to @wOxxOm comment I was able to answer it.

Here is my implementation, as it might help someone.

manifest.json

{
    ...
    "background": {
        "scripts": ["background.js"]
    }
    ...
}
```
<p>It's important to handle 'onActivated' event in a background script, otherwise it will only work while the extension panel is open.</p>
<p><strong>index.js</strong></p>
<pre class="lang-js prettyprint-override"><code>const link = 'https://stackoverflow.com/';

// Create new tab with our link as title
chrome.tabs.create({
    url:  'data:text/html,<title>' + link,
    active: false
});
</code>```

background.js

// When the new tab is selected, get the link in the title and load the page
chrome.tabs.onActivated.addListener(({tabId, windowId}) => {
    const splitText = 'data:text/html,<title>';

    chrome.tabs.get(tabId, tab => {
        if (tab.url.startsWith(splitText)) {
            const realTabUrl = tab.url.replace(splitText, '')

            chrome.tabs.update(tabId, {
                url: realTabUrl,
            });
        }
    });
})
```

Body:
I had the same question as you, and thanks to @wOxxOm comment I was able to answer it.

Here is my implementation, as it might help someone.

manifest.json

{
    ...
    "background": {
        "scripts": ["background.js"]
    }
    ...
}

It's important to handle 'onActivated' event in a background script, otherwise it will only work while the extension panel is open.

index.js

const link = 'https://stackoverflow.com/';

// Create new tab with our link as title
chrome.tabs.create({
    url:  'data:text/html,<title>' + link,
    active: false
});

background.js

// When the new tab is selected, get the link in the title and load the page
chrome.tabs.onActivated.addListener(({tabId, windowId}) => {
    const splitText = 'data:text/html,<title>';

    chrome.tabs.get(tabId, tab => {
        if (tab.url.startsWith(splitText)) {
            const realTabUrl = tab.url.replace(splitText, '')

            chrome.tabs.update(tabId, {
                url: realTabUrl,
            });
        }
    });
})


问:
Disable TabLayout
I'm using the new class provided by the design library : TabLayout. And I want in specific cases that the one I'm using can't change tab anymore.

I manage to disable swipe on its viewpager but I can't figure out how to disable the change of page by clicking on tabs.

Thank's in advance.

答:
Comprehensive solution for both ViewPager to prevent swiping between tabs, and TabLayout to prevent clicking the tabs when they are disabled.

First created the CustomViewPager and CustomTabLayout classes (inheriting the fuctionality of ViewPager and TabLayout base classes)

```<code>// content of CustomViewPager.java
package mypackage;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.viewpager.widget.ViewPager;

public class CustomViewPager extends ViewPager {

    private boolean enableSwipe;

    public CustomViewPager(Context context) {
        super(context);
        init();
    }

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        enableSwipe = true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return enableSwipe && super.onInterceptTouchEvent(event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return enableSwipe && super.onTouchEvent(event);
    }

    public void setEnableSwipe(boolean enableSwipe) {
        this.enableSwipe = enableSwipe;
    }
}

// content of CustomTabLayout.java
package mypackage;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.google.android.material.tabs.TabLayout;

public class CustomTabLayout extends TabLayout {
    private boolean enableTabs;

    public CustomTabLayout(Context context) {
        super(context);
        init();
    }

    public CustomTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        enableTabs = true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return !enableTabs;
    }

    public void setEnableTabs(boolean enable) {
        this.enableTabs = enable;
    }
}

</code>```

create the UI:

```<code>        <mypackage.CustomTabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary" />

        <mypackage.CustomViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="100dp"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</code>```

in the onCreate create the relation between the two controls:

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CustomViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(sectionsPagerAdapter);
        CustomTabLayout tabs = findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
    }
</code>```

EnableControls function to enable/disable the tab:

```<code>private void EnableControls(boolean b) {
        CustomViewPager viewPager = findViewById(R.id.view_pager);
        CustomTabLayout tabs = findViewById(R.id.tabs);

        viewPager.setEnableSwipe(b);
        tabs.setEnableTabs(b);
}
</code>```

Title: Disable TabLayout

Body:
Comprehensive solution for both ViewPager to prevent swiping between tabs, and TabLayout to prevent clicking the tabs when they are disabled.

First created the CustomViewPager and CustomTabLayout classes (inheriting the fuctionality of ViewPager and TabLayout base classes)

// content of CustomViewPager.java
package mypackage;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.viewpager.widget.ViewPager;

public class CustomViewPager extends ViewPager {

    private boolean enableSwipe;

    public CustomViewPager(Context context) {
        super(context);
        init();
    }

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        enableSwipe = true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return enableSwipe && super.onInterceptTouchEvent(event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return enableSwipe && super.onTouchEvent(event);
    }

    public void setEnableSwipe(boolean enableSwipe) {
        this.enableSwipe = enableSwipe;
    }
}

// content of CustomTabLayout.java
package mypackage;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.google.android.material.tabs.TabLayout;

public class CustomTabLayout extends TabLayout {
    private boolean enableTabs;

    public CustomTabLayout(Context context) {
        super(context);
        init();
    }

    public CustomTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        enableTabs = true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return !enableTabs;
    }

    public void setEnableTabs(boolean enable) {
        this.enableTabs = enable;
    }
}

create the UI:

        <mypackage.CustomTabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary" />

        <mypackage.CustomViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="100dp"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

in the onCreate create the relation between the two controls:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CustomViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(sectionsPagerAdapter);
        CustomTabLayout tabs = findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
    }

EnableControls function to enable/disable the tab:

private void EnableControls(boolean b) {
        CustomViewPager viewPager = findViewById(R.id.view_pager);
        CustomTabLayout tabs = findViewById(R.id.tabs);

        viewPager.setEnableSwipe(b);
        tabs.setEnableTabs(b);
}


问:
Typedef in C, but a different way
I am aware of the standard way to define a structure in C. But, in analogy with this:

// <typedef structureName alias>
typedef unsigned long int u_int32
```
<p>I was expecting this to work too:</p>
<pre class="lang-c prettyprint-override"><code>struct myStr {char name[100]; float avgProb; int severity;};
typedef myStr ms;
myStr ms = {name:"hell", avgProb:50.0, severity:5,};
printf("myR %f", ms.avgProb);
</code>```

Is it just not possible to do it or I am missing something?

答:
Is it just not possible to do it or I am missing something?

You simply need to learn C syntax and basics before coding

```<code>  struct myStr {char name[100]; float avgProb; int severity;};
  typedef struct myStr ms;
  ms m = {.name = "hell", .avgProb = 50.0, .severity = 5,};
  printf("myR %f", m.avgProb);
</code>```

Or simply

```<code>typedef struct
{
    char name[100];
    float avgProb;
    int severity;
}myStr;

  myStr m = {.name = "hell", .avgProb = 50.0, .severity = 5,};
  printf("myR %f", m.avgProb);
</code>```

Some good resources:
The Definitive C Book Guide and List

Title: Typedef in C, but a different way

Body:
I am aware of the standard way to define a structure in C. But, in analogy with this:

// <typedef structureName alias>
typedef unsigned long int u_int32

I was expecting this to work too:

struct myStr {char name[100]; float avgProb; int severity;};
typedef myStr ms;
myStr ms = {name:"hell", avgProb:50.0, severity:5,};
printf("myR %f", ms.avgProb);

Is it just not possible to do it or I am missing something?

Body:
Is it just not possible to do it or I am missing something?

You simply need to learn C syntax and basics before coding

  struct myStr {char name[100]; float avgProb; int severity;};
  typedef struct myStr ms;
  ms m = {.name = "hell", .avgProb = 50.0, .severity = 5,};
  printf("myR %f", m.avgProb);

Or simply

typedef struct
{
    char name[100];
    float avgProb;
    int severity;
}myStr;

  myStr m = {.name = "hell", .avgProb = 50.0, .severity = 5,};
  printf("myR %f", m.avgProb);

Some good resources:
The Definitive C Book Guide and List


问:
looping through nested array of object and add new row datatables.net
I am currently making tables from nested array of object.

So, i decided to use datatables library.

my problem is i can't found method to loop my array. and add another row  if the array length is more than 1.

here is my code

```<code>$(document).ready(function () {
    $('#table-nyadran').DataTable({
        "data": data,
        "columns": [
            {
                "data": "id",
                render: function (data, type, row, meta) {
                    return meta.row + meta.settings._iDisplayStart + 1;
                }
            },
            { "data": "name" },
            { "data": "address" },
            {
                "data": "arwahs.0",
                "render": function (data, type, row, meta) {
                    return data.arwah_type +'. '+ data.arwah_name;
                }
            },
            { "data": "arwahs.0.arwah_address"},
        ]
    });
</code>```

I can make it work using only jQuery, but I think datatables is more suitable for this.

```<code>for (i = 0; i < data.length; i++) {
    nomer = i + 1

    nyadran_table += "<tr><td>" + nomer + ".</td><td>" + data[i].name + "</td><td>" + data[i].address + "</td>"
    for (k = 0; k < data[i].arwahs.length; k++) {
        if (k > 0) {
            nyadran_table += "<tr class=" + oddeven + "><td colspan=''></td><td></td><td></td><td>" + data[i].arwahs[k].arwah_type + ". " + data[i].arwahs[k].arwah_name + "</td><td>" + data[i].arwahs[k].arwah_address + "</td></tr>"
        } else {
            nyadran_table += "<td>" + data[i].arwahs[k].arwah_type + ". " + data[i].arwahs[k].arwah_name + "</td><td>" + data[i].arwahs[k].arwah_address + "</td></tr>"
        }
    }
}
</code>```

here is my array

```<code>    [
  {
    "id": 36,
    "name": "Evelyn Stone",
    "phone": "1 (939) 117-4285",
    "address": "In ab ipsum id labor",
    "created_at": "2022-02-05T22:38:15.000000Z",
    "updated_at": "2022-02-05T22:38:15.000000Z",
    "arwahs": [
      {
        "id": 52,
        "sender_id": 36,
        "arwah_name": "Sydney Dyer",
        "arwah_address": "Optio dolore iusto",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:38:15.000000Z",
        "updated_at": "2022-02-05T22:38:15.000000Z"
      },
      {
        "id": 53,
        "sender_id": 36,
        "arwah_name": "Aretha Byers",
        "arwah_address": "Eu consectetur qui u",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:38:15.000000Z",
        "updated_at": "2022-02-05T22:38:15.000000Z"
      },
      {
        "id": 54,
        "sender_id": 36,
        "arwah_name": "Suki Dillard",
        "arwah_address": "Excepturi molestias",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:38:15.000000Z",
        "updated_at": "2022-02-05T22:38:15.000000Z"
      }
    ]
  },
  {
    "id": 37,
    "name": "Jeremy Browning",
    "phone": "1 (393) 741-9987",
    "address": "Et illo nihil sapien",
    "created_at": "2022-02-05T22:38:55.000000Z",
    "updated_at": "2022-02-05T22:38:55.000000Z",
    "arwahs": [
      {
        "id": 55,
        "sender_id": 37,
        "arwah_name": "Hermione Mcgowan",
        "arwah_address": "Aliqua Aut eum in u",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:38:55.000000Z",
        "updated_at": "2022-02-05T22:38:55.000000Z"
      },
      {
        "id": 56,
        "sender_id": 37,
        "arwah_name": "Carlos Dudley",
        "arwah_address": "Nulla reprehenderit",
        "arwah_type": "Ibu",
        "created_at": "2022-02-05T22:38:55.000000Z",
        "updated_at": "2022-02-05T22:38:55.000000Z"
      }
    ]
  },
  {
    "id": 38,
    "name": "Wallace Dorsey",
    "phone": "1 (848) 278-3114",
    "address": "Commodi ipsum et sa",
    "created_at": "2022-02-05T22:39:26.000000Z",
    "updated_at": "2022-02-05T22:39:26.000000Z",
    "arwahs": [
      {
        "id": 57,
        "sender_id": 38,
        "arwah_name": "Felix Lester",
        "arwah_address": "In ullam magni offic",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:39:26.000000Z",
        "updated_at": "2022-02-05T22:39:26.000000Z"
      },
      {
        "id": 58,
        "sender_id": 38,
        "arwah_name": "Jael Porter",
        "arwah_address": "Delectus esse dolo",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:39:26.000000Z",
        "updated_at": "2022-02-05T22:39:26.000000Z"
      },
      {
        "id": 59,
        "sender_id": 38,
        "arwah_name": "Charity Maldonado",
        "arwah_address": "Perferendis sed qui",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:39:26.000000Z",
        "updated_at": "2022-02-05T22:39:26.000000Z"
      },
      {
        "id": 60,
        "sender_id": 38,
        "arwah_name": "Xerxes Vance",
        "arwah_address": "Et ea quos aut hic c",
        "arwah_type": "Bapak",
        "created_at": "2022-02-05T22:39:26.000000Z",
        "updated_at": "2022-02-05T22:39:26.000000Z"
      }
    ]
  }
]
</code>```

current output

expected output

any clue or answer. I appreciated. Thank You

答: solved. datatables isn't supporting colspan. so, I just making basic table.</p>

Body:
I am currently making tables from nested array of object.

So, i decided to use datatables library.

my problem is i can't found method to loop my array. and add another row  if the array length is more than 1.

here is my code

$(document).ready(function () {
    $('#table-nyadran').DataTable({
        "data": data,
        "columns": [
            {
                "data": "id",
                render: function (data, type, row, meta) {
                    return meta.row + meta.settings._iDisplayStart + 1;
                }
            },
            { "data": "name" },
            { "data": "address" },
            {
                "data": "arwahs.0",
                "render": function (data, type, row, meta) {
                    return data.arwah_type +'. '+ data.arwah_name;
                }
            },
            { "data": "arwahs.0.arwah_address"},
        ]
    });

I can make it work using only jQuery, but I think datatables is more suitable for this.

for (i = 0; i < data.length; i++) {
    nomer = i + 1

    nyadran_table += "
" + nomer + ".	" + data[i].name + "	" + data[i].address + "	"
    for (k = 0; k < data[i].arwahs.length; k++) {
        if (k > 0) {
            nyadran_table += "
			" + data[i].arwahs[k].arwah_type + ". " + data[i].arwahs[k].arwah_name + "	" + data[i].arwahs[k].arwah_address + "
"
        } else {
            nyadran_table += "" + data[i].arwahs[k].arwah_type + ". " + data[i].arwahs[k].arwah_name + "	" + data[i].arwahs[k].arwah_address + "
"
        }
    }
}

here is my array

    [
  {
    "id": 36,
    "name": "Evelyn Stone",
    "phone": "1 (939) 117-4285",
    "address": "In ab ipsum id labor",
    "created_at": "2022-02-05T22:38:15.000000Z",
    "updated_at": "2022-02-05T22:38:15.000000Z",
    "arwahs": [
      {
        "id": 52,
        "sender_id": 36,
        "arwah_name": "Sydney Dyer",
        "arwah_address": "Optio dolore iusto",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:38:15.000000Z",
        "updated_at": "2022-02-05T22:38:15.000000Z"
      },
      {
        "id": 53,
        "sender_id": 36,
        "arwah_name": "Aretha Byers",
        "arwah_address": "Eu consectetur qui u",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:38:15.000000Z",
        "updated_at": "2022-02-05T22:38:15.000000Z"
      },
      {
        "id": 54,
        "sender_id": 36,
        "arwah_name": "Suki Dillard",
        "arwah_address": "Excepturi molestias",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:38:15.000000Z",
        "updated_at": "2022-02-05T22:38:15.000000Z"
      }
    ]
  },
  {
    "id": 37,
    "name": "Jeremy Browning",
    "phone": "1 (393) 741-9987",
    "address": "Et illo nihil sapien",
    "created_at": "2022-02-05T22:38:55.000000Z",
    "updated_at": "2022-02-05T22:38:55.000000Z",
    "arwahs": [
      {
        "id": 55,
        "sender_id": 37,
        "arwah_name": "Hermione Mcgowan",
        "arwah_address": "Aliqua Aut eum in u",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:38:55.000000Z",
        "updated_at": "2022-02-05T22:38:55.000000Z"
      },
      {
        "id": 56,
        "sender_id": 37,
        "arwah_name": "Carlos Dudley",
        "arwah_address": "Nulla reprehenderit",
        "arwah_type": "Ibu",
        "created_at": "2022-02-05T22:38:55.000000Z",
        "updated_at": "2022-02-05T22:38:55.000000Z"
      }
    ]
  },
  {
    "id": 38,
    "name": "Wallace Dorsey",
    "phone": "1 (848) 278-3114",
    "address": "Commodi ipsum et sa",
    "created_at": "2022-02-05T22:39:26.000000Z",
    "updated_at": "2022-02-05T22:39:26.000000Z",
    "arwahs": [
      {
        "id": 57,
        "sender_id": 38,
        "arwah_name": "Felix Lester",
        "arwah_address": "In ullam magni offic",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:39:26.000000Z",
        "updated_at": "2022-02-05T22:39:26.000000Z"
      },
      {
        "id": 58,
        "sender_id": 38,
        "arwah_name": "Jael Porter",
        "arwah_address": "Delectus esse dolo",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:39:26.000000Z",
        "updated_at": "2022-02-05T22:39:26.000000Z"
      },
      {
        "id": 59,
        "sender_id": 38,
        "arwah_name": "Charity Maldonado",
        "arwah_address": "Perferendis sed qui",
        "arwah_type": "Saudara",
        "created_at": "2022-02-05T22:39:26.000000Z",
        "updated_at": "2022-02-05T22:39:26.000000Z"
      },
      {
        "id": 60,
        "sender_id": 38,
        "arwah_name": "Xerxes Vance",
        "arwah_address": "Et ea quos aut hic c",
        "arwah_type": "Bapak",
        "created_at": "2022-02-05T22:39:26.000000Z",
        "updated_at": "2022-02-05T22:39:26.000000Z"
      }
    ]
  }
]

current output

expected output

any clue or answer. I appreciated. Thank You


问:
How to create HTML5 data-* in MVC3
I'm using JQuery mobile and I need to include data-prefetch attribute in a link created with HTML.ActionLink.   I've found examples on Stackoverflow of how to pass data-* attributes in the standard way with object Html attributes. However I can't seem  figure out how to create an attribute that has no value. Best I can create is data-prefetch="" by using new{data_prefetch=""} .  I'm assuming that isn't the same.

Any ideas?

答:
As far as I can see using data-prefetch="data-prefetch" works fine. So I guess there is no need to do anything else.

Thanks feeela

Title: How to create HTML5 data-* in MVC3


问:
Duplicate output file
I'm trying to run a react-native project using the command react-native run-ios but I'm getting the following errors:

```<code>Build system information
error: Multiple commands produce '/Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Products/Debug-iphonesimulator/Humboi.app/EvilIcons.ttf':
1) Target 'Humboi' (project 'Humboi') has copy command from '/Users/prikshetsharma/Desktop/Humboi/node_modules/react-native-vector-icons/Fonts/EvilIcons.ttf' to '/Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Products/Debug-iphonesimulator/Humboi.app/EvilIcons.ttf'
2) That command depends on command in Target 'Humboi' (project 'Humboi'): script phase “[CP] Copy Pods Resources”

Build system information
error: Multiple commands produce '/Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Products/Debug-iphonesimulator/Humboi.app/Entypo.ttf':
1) Target 'Humboi' (project 'Humboi') has copy command from '/Users/prikshetsharma/Desktop/Humboi/node_modules/react-native-vector-icons/Fonts/Entypo.ttf' to '/Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Products/Debug-iphonesimulator/Humboi.app/Entypo.ttf'
2) That command depends on command in Target 'Humboi' (project 'Humboi'): script phase “[CP] Copy Pods Resources”
... (and so on)

warning: duplicate output file '/Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Products/Debug-iphonesimulator/Humboi.app/Feather.ttf' on task: PhaseScriptExecution [CP] Copy Pods Resources /Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Intermediates.noindex/Humboi.build/Debug-iphonesimulator/Humboi.build/Script-725F34421484E3F6E70FFBB5.sh (in target 'Humboi' from project 'Humboi')
warning: duplicate output file '/Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Products/Debug-iphonesimulator/Humboi.app/FontAwesome.ttf' on task: PhaseScriptExecution [CP] Copy Pods Resources /Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Intermediates.noindex/Humboi.build/Debug-iphonesimulator/Humboi.build/Script-725F34421484E3F6E70FFBB5.sh (in target 'Humboi' from project 'Humboi')
...(and so on)
</code>```

How to fix the errors and the warnings?

答:
Because it happens by running this same file from bundle resources and pod resources

So you just open xcode -> your_project.xcodeproj -> click project folder -> build phases -> open copy bundle resources -> remove the error formed duplicate files only. don't remove all the files like if it is in .ttf format. check your error log and remove it carefully. because you may configured any custom fonts or files in copy bundle resources

Title: Duplicate output file

Body:
I'm trying to run a react-native project using the command react-native run-ios but I'm getting the following errors:

Build system information
error: Multiple commands produce '/Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Products/Debug-iphonesimulator/Humboi.app/EvilIcons.ttf':
1) Target 'Humboi' (project 'Humboi') has copy command from '/Users/prikshetsharma/Desktop/Humboi/node_modules/react-native-vector-icons/Fonts/EvilIcons.ttf' to '/Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Products/Debug-iphonesimulator/Humboi.app/EvilIcons.ttf'
2) That command depends on command in Target 'Humboi' (project 'Humboi'): script phase “[CP] Copy Pods Resources”

Build system information
error: Multiple commands produce '/Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Products/Debug-iphonesimulator/Humboi.app/Entypo.ttf':
1) Target 'Humboi' (project 'Humboi') has copy command from '/Users/prikshetsharma/Desktop/Humboi/node_modules/react-native-vector-icons/Fonts/Entypo.ttf' to '/Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Products/Debug-iphonesimulator/Humboi.app/Entypo.ttf'
2) That command depends on command in Target 'Humboi' (project 'Humboi'): script phase “[CP] Copy Pods Resources”
... (and so on)

warning: duplicate output file '/Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Products/Debug-iphonesimulator/Humboi.app/Feather.ttf' on task: PhaseScriptExecution [CP] Copy Pods Resources /Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Intermediates.noindex/Humboi.build/Debug-iphonesimulator/Humboi.build/Script-725F34421484E3F6E70FFBB5.sh (in target 'Humboi' from project 'Humboi')
warning: duplicate output file '/Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Products/Debug-iphonesimulator/Humboi.app/FontAwesome.ttf' on task: PhaseScriptExecution [CP] Copy Pods Resources /Users/prikshetsharma/Library/Developer/Xcode/DerivedData/Humboi-hjbrwqprmopoeybrdkwevgblfvis/Build/Intermediates.noindex/Humboi.build/Debug-iphonesimulator/Humboi.build/Script-725F34421484E3F6E70FFBB5.sh (in target 'Humboi' from project 'Humboi')
...(and so on)

How to fix the errors and the warnings?


问:
invalid SQL statement while declaring a rowtype record in oracle
i am trying to display a record rowtype in oracle, i am getting

SQL Error [900] [42000]: ORA-00900: invalid SQL statement at line 7

here :

```<code>intraftrecord xyz%rowtype;
</code>```

i can't seem to figure it out.

```<code>CREATE OR REPLACE PROCEDURE intraftresponseprocedure
IS
CURSOR xyz IS
select REGEXP_REPLACE(RESPONSE_PARAM , '-', '') from (
    select RESPONSE_PARAM from AUDIT_LOG WHERE ACTIVITY ='Intra Bank Funds Transfer' order by id asc
);
intraftrecord xyz%rowtype;
BEGIN
    OPEN xyz;
LOOP
FETCH xyz INTO intraftrecord;
EXIT WHEN intraftrecord%notfound;
dbms_output.put_line(intraftrecord);
END LOOP;
END;
</code>```

答:
You have to specify the column name in print statement -</p>
```<code>CREATE OR REPLACE PROCEDURE intraftresponseprocedure
IS
CURSOR xyz IS
select REGEXP_REPLACE(RESPONSE_PARAM , '-', '') col1 from (
    select RESPONSE_PARAM from AUDIT_LOG WHERE ACTIVITY ='Intra Bank Funds Transfer' order by id asc
);
intraftrecord xyz%rowtype;
BEGIN
    OPEN xyz;
LOOP
FETCH xyz INTO intraftrecord;
EXIT WHEN xyz%notfound;
dbms_output.put_line(intraftrecord.col1);
END LOOP;
END;
</code>```

Body:
i am trying to display a record rowtype in oracle, i am getting

SQL Error [900] [42000]: ORA-00900: invalid SQL statement at line 7

here :

intraftrecord xyz%rowtype;

i can't seem to figure it out.

CREATE OR REPLACE PROCEDURE intraftresponseprocedure
IS
CURSOR xyz IS
select REGEXP_REPLACE(RESPONSE_PARAM , '-', '') from (
    select RESPONSE_PARAM from AUDIT_LOG WHERE ACTIVITY ='Intra Bank Funds Transfer' order by id asc
);
intraftrecord xyz%rowtype;
BEGIN
    OPEN xyz;
LOOP
FETCH xyz INTO intraftrecord;
EXIT WHEN intraftrecord%notfound;
dbms_output.put_line(intraftrecord);
END LOOP;
END;

Body:
You have to specify the column name in print statement -

CREATE OR REPLACE PROCEDURE intraftresponseprocedure
IS
CURSOR xyz IS
select REGEXP_REPLACE(RESPONSE_PARAM , '-', '') col1 from (
    select RESPONSE_PARAM from AUDIT_LOG WHERE ACTIVITY ='Intra Bank Funds Transfer' order by id asc
);
intraftrecord xyz%rowtype;
BEGIN
    OPEN xyz;
LOOP
FETCH xyz INTO intraftrecord;
EXIT WHEN xyz%notfound;
dbms_output.put_line(intraftrecord.col1);
END LOOP;
END;


问:
Merging two Multivalue hashmaps based on value
Hi I have two hash maps as follows

```<code>[AdGenres-b:key:[177], SongTitle:[What I've Done], ArtistName:[Linkin Park], MusicVideoRating:[TV-14], PlayId:[1367], AdGenres-b:value:[Rock], MusicVideoProvider:[Warner Music Group], AssetId:[91744]]

[AdGenres-b:key:[184], SongTitle:[What I've Done], ArtistName:[Linkin Park], MusicVideoRating:[TV-14], PlayId:[1367], AdGenres-b:value:[Rock - Alternative], MusicVideoProvider:[Warner Music Group], AssetId:[91744]]
</code>```

I want result map as:

```<code>[AdGenres-b:key:[177, 184],SongTitle:[What I've Done], ArtistName:[Linkin Park], MusicVideoRating:[TV-14], PlayId:[1367], AdGenres-b:value:[Rock - Rock, Rock - Alternative], MusicVideoProvider:[Warner Music Group], AssetId:[91744]
</code>```

how to achive the above?

答:
The easy way: use a Guava Multimap

```<code>Multimap<String, String> mmap = HashMultimap.create();
for(Map<String, String> map : Arrays.asList(map1,map2)){
    for(Entry<String, String> entry:map.entrySet()){
        mmap.put(entry.getKey(), entry.getValue());
    }
}
</code>```

Body:
Hi I have two hash maps as follows

[AdGenres-b:key:[177], SongTitle:[What I've Done], ArtistName:[Linkin Park], MusicVideoRating:[TV-14], PlayId:[1367], AdGenres-b:value:[Rock], MusicVideoProvider:[Warner Music Group], AssetId:[91744]]

[AdGenres-b:key:[184], SongTitle:[What I've Done], ArtistName:[Linkin Park], MusicVideoRating:[TV-14], PlayId:[1367], AdGenres-b:value:[Rock - Alternative], MusicVideoProvider:[Warner Music Group], AssetId:[91744]]

I want result map as:

[AdGenres-b:key:[177, 184],SongTitle:[What I've Done], ArtistName:[Linkin Park], MusicVideoRating:[TV-14], PlayId:[1367], AdGenres-b:value:[Rock - Rock, Rock - Alternative], MusicVideoProvider:[Warner Music Group], AssetId:[91744]

how to achive the above?

Body:
The easy way: use a Guava Multimap

Multimap<String, String> mmap = HashMultimap.create();
for(Map<String, String> map : Arrays.asList(map1,map2)){
    for(Entry<String, String> entry:map.entrySet()){
        mmap.put(entry.getKey(), entry.getValue());
    }
}


问:
Lifting a sails app on Heroku fails
I'm not able to lift a Sails api application in a production environment on Heroku to connect against a mongolab db. This works well when running in a local setup. The Heroku logs shows the following...

```<code>`
/app/node_modules/mongodb/lib/server.js:235
        process.nextTick(function() { throw err; })
                                      ^
TypeError: Cannot read property 'close' of undefined
    at /app/node_modules/sails-mongo/lib/adapter.js:138:13
    at /app/node_modules/sails-mongo/node_modules/async/lib/async.js:187:20
    at /app/node_modules/sails-mongo/node_modules/async/lib/async.js:239:13
    at _arrayEach (/app/node_modules/sails-mongo/node_modules/async/lib/async.js:91:13)
    at _each (/app/node_modules/sails-mongo/node_modules/async/lib/async.js:82:13)
    at Object.async.forEachOf.async.eachOf (/app/node_modules/sails-mongo/node_modules/async/lib/async.js:238:9)
    at Object.async.forEach.async.each (/app/node_modules/sails-mongo/node_modules/async/lib/async.js:215:22)
    at Object.module.exports.adapter.teardown (/app/node_modules/sails-mongo/lib/adapter.js:137:22)
    at /app/node_modules/sails/lib/hooks/orm/index.js:244:19
    at /app/node_modules/async/lib/async.js:122:13
    at _each (/app/node_modules/async/lib/async.js:46:13)
    at Object.async.each (/app/node_modules/async/lib/async.js:121:9)
    at Sails.hook.teardown (/app/node_modules/sails/lib/hooks/orm/index.js:241:13)
    at Sails.g (events.js:260:16)
    at emitNone (events.js:67:13)
    at Sails.emit (events.js:166:7)
`
</code>```

Running sails version 0.11.2

Sails-mongo version 0.11.4

The process.env variables has been added and verified

connection.js

```<code>`
mongodb: {
  adapter: 'sails-mongo',
  url : process.env.CONNECTION_URL,
  host: process.env.DB_HOST,
  port: process.env.PORT_NR,
  user: proces.env.USER,
  password: process.env.PASSWORD,
  database: process.env.DB
},
</code>```

`
env/production.js

```<code>`
connections : {
  mongoLive: {
    adapter: 'sails-mongo',
    url : process.env.CONNECTION_URL
  }
},
models: {
  connection: 'mongoLive'
},
`
</code>```

development.js

```<code>`
connections : {
  mongoDev: {
    adapter: 'sails-mongo',
    host: 'localhost',
    port: 27017,
    database: 'threads_db'
  }
},

models: {
  connection: 'mongoDev'
}
`
</code>```

Procfile

```<code>`
web: npm start
`
</code>```

package.json

```<code>`
"scripts": {
  "debug": "node debug app.js",
  "start": "sails lift"
},
`
</code>```

models.js has been set to

```<code>`
 connection: 'mongodb',
`
</code>```

So, running this locally works fine with both a connection to a local mongo db and the remote mongolab db but deployment to Heroku fails. Sees to me that I'm missing something in the setup. Help with this appreciated.

答:
For those if the accepted answer didn't work after deploying in heroku , try to change the node js, sails-mongo versions along with sails and check.

It worked for me after changing the versions to the below:

1.nodejs - 14.15.1

2.sails - ^1.5.2

3.sails-mongo - ^2.0.0

Title: Lifting a sails app on Heroku fails

Body:
I'm not able to lift a Sails api application in a production environment on Heroku to connect against a mongolab db. This works well when running in a local setup. The Heroku logs shows the following...

`
/app/node_modules/mongodb/lib/server.js:235
        process.nextTick(function() { throw err; })
                                      ^
TypeError: Cannot read property 'close' of undefined
    at /app/node_modules/sails-mongo/lib/adapter.js:138:13
    at /app/node_modules/sails-mongo/node_modules/async/lib/async.js:187:20
    at /app/node_modules/sails-mongo/node_modules/async/lib/async.js:239:13
    at _arrayEach (/app/node_modules/sails-mongo/node_modules/async/lib/async.js:91:13)
    at _each (/app/node_modules/sails-mongo/node_modules/async/lib/async.js:82:13)
    at Object.async.forEachOf.async.eachOf (/app/node_modules/sails-mongo/node_modules/async/lib/async.js:238:9)
    at Object.async.forEach.async.each (/app/node_modules/sails-mongo/node_modules/async/lib/async.js:215:22)
    at Object.module.exports.adapter.teardown (/app/node_modules/sails-mongo/lib/adapter.js:137:22)
    at /app/node_modules/sails/lib/hooks/orm/index.js:244:19
    at /app/node_modules/async/lib/async.js:122:13
    at _each (/app/node_modules/async/lib/async.js:46:13)
    at Object.async.each (/app/node_modules/async/lib/async.js:121:9)
    at Sails.hook.teardown (/app/node_modules/sails/lib/hooks/orm/index.js:241:13)
    at Sails.g (events.js:260:16)
    at emitNone (events.js:67:13)
    at Sails.emit (events.js:166:7)
`

Running sails version 0.11.2

Sails-mongo version 0.11.4

The process.env variables has been added and verified

connection.js

`
mongodb: {
  adapter: 'sails-mongo',
  url : process.env.CONNECTION_URL,
  host: process.env.DB_HOST,
  port: process.env.PORT_NR,
  user: proces.env.USER,
  password: process.env.PASSWORD,
  database: process.env.DB
},

`
env/production.js

`
connections : {
  mongoLive: {
    adapter: 'sails-mongo',
    url : process.env.CONNECTION_URL
  }
},
models: {
  connection: 'mongoLive'
},
`

development.js

`
connections : {
  mongoDev: {
    adapter: 'sails-mongo',
    host: 'localhost',
    port: 27017,
    database: 'threads_db'
  }
},

models: {
  connection: 'mongoDev'
}
`

Procfile

`
web: npm start
`

package.json

`
"scripts": {
  "debug": "node debug app.js",
  "start": "sails lift"
},
`

models.js has been set to

`
 connection: 'mongodb',
`

So, running this locally works fine with both a connection to a local mongo db and the remote mongolab db but deployment to Heroku fails. Sees to me that I'm missing something in the setup. Help with this appreciated.


问:
when I try to run a flutter app it shows error : FAILURE: Build failed with an exception. full error shown below
Invalid depfile: C:\Users\bhard\AndroidStudioProjects\true_weather.dart_tool\flutter_build\54ec25ea3e00199f07d81cf92fc10210\kernel_snapshot.d
Invalid depfile: C:\Users\bhard\AndroidStudioProjects\true_weather.dart_tool\flutter_build\54ec25ea3e00199f07d81cf92fc10210\kernel_snapshot.d

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.

Multiple task action failures occurred:
A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
> The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.window:window-java:1.0.0-beta04.
AAR metadata file: C:\Users\bhard.gradle\caches\transforms-2\files-2.1\5695d8d932d545af38bf66b725566d02\jetified-window-java-1.0.0-beta04\META-INF\com\android\build\gradle\aar-metadata.properties.
A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
> The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.window:window:1.0.0-beta04.
AAR metadata file: C:\Users\bhard.gradle\caches\transforms-2\files-2.1\e4e324fde2799cc82a9b6d2e3e16efc2\jetified-window-1.0.0-beta04\META-INF\com\android\build\gradle\aar-metadata.properties.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 42s
Exception: Gradle task assembleDebug failed with exit code 1

答:
Thanks man for trying to help but I Got The solution Myself .

Solution:- If you have same error like mine then you only need to checkout your compileSdkVersion which are shown in your error like this "module's compileSdkVersion (android-30)." somewhere in error . then you need to find "minCompileSdk" this word written in your error , in my case it is like "minCompileSdk (31) " this show required minCompileSdk version. so you have to change your version to this one .

To do that first you need to go to "android>>build.gradle" finds in your project .
then open it in android studio by using the button find in top right corner. and change it to required version and save it.

You Did it.


问:
.NET Framework. How to get the text value from invisible column of datagridview?
My issue is very simple and it would be easy if I write my program on ASP.NET. But I apply .NET Framework 4.8 and I have no idea how to get the value from that datagridview if the column is hidden.

```<code>for (int i2 = 0; i2 < RowsAmount; i2++)
        {
            int er = Convert.ToInt32(dataGridView1.Rows[i2].Cells["id_contact"].Value.ToString());
            MessageBox.Show($"{er}");
            // to do smth with that value.
        }
</code>```

The column named as id_contact is hidden as you can guess. What should I do if the error is "object reference does not point to an instance of an object "?

答:
The decision turned out very simple. I have just forgotten about so-called datatype DataRow. With aid of it and the cycle for I could of solve it faster. I've decided to record the data into datagridview in this way:

```<code>if (dTable.Rows.Count > 0)
            {
                DataRow row;
                for (int i = 0; i < dTable.Rows.Count; i++)
                {
                    row = dTable.Rows[i];
                    dataGridView1.Rows.Add();
                    dataGridView1.Rows[i].Cells["id"].Value =
                        row["id"];
                    dataGridView1.Rows[i].Cells["Brief_name"].Value =
                        row["brief_name"];
                    dataGridView1.Rows[i].Cells["FullName"].Value =
                        row["full_official_name"];
                    dataGridView1.Rows[i].Cells["Adress"].Value =
                        row["ju_adress"];
                    dataGridView1.Rows[i].Cells["Code"].Value =
                        row["EDRPOU"];
                    dataGridView1.Rows[i].Cells["Branch"].Value =
                        row["branch_economy"];
                    dataGridView1.Rows[i].Cells["id_contact"].Value =
                        row["id_contact_person"];
                    RowsAmount++;
                }
            }
</code>```

Some of these columns are invisible and the previous command int er = Convert.ToInt32(dataGridView1.Rows[i2].Cells["id_contact"].Value.ToString()); works out.

Just I haven't willed to apply BindingSource, because the essential part of my program works without it. But anyway thank you for attention.

Body:
My issue is very simple and it would be easy if I write my program on ASP.NET. But I apply .NET Framework 4.8 and I have no idea how to get the value from that datagridview if the column is hidden.

for (int i2 = 0; i2 < RowsAmount; i2++)
        {
            int er = Convert.ToInt32(dataGridView1.Rows[i2].Cells["id_contact"].Value.ToString());
            MessageBox.Show($"{er}");
            // to do smth with that value.
        }

The column named as id_contact is hidden as you can guess. What should I do if the error is "object reference does not point to an instance of an object "?

Body:
The decision turned out very simple. I have just forgotten about so-called datatype DataRow. With aid of it and the cycle for I could of solve it faster. I've decided to record the data into datagridview in this way:

if (dTable.Rows.Count > 0)
            {
                DataRow row;
                for (int i = 0; i < dTable.Rows.Count; i++)
                {
                    row = dTable.Rows[i];
                    dataGridView1.Rows.Add();
                    dataGridView1.Rows[i].Cells["id"].Value =
                        row["id"];
                    dataGridView1.Rows[i].Cells["Brief_name"].Value =
                        row["brief_name"];
                    dataGridView1.Rows[i].Cells["FullName"].Value =
                        row["full_official_name"];
                    dataGridView1.Rows[i].Cells["Adress"].Value =
                        row["ju_adress"];
                    dataGridView1.Rows[i].Cells["Code"].Value =
                        row["EDRPOU"];
                    dataGridView1.Rows[i].Cells["Branch"].Value =
                        row["branch_economy"];
                    dataGridView1.Rows[i].Cells["id_contact"].Value =
                        row["id_contact_person"];
                    RowsAmount++;
                }
            }

Some of these columns are invisible and the previous command int er = Convert.ToInt32(dataGridView1.Rows[i2].Cells["id_contact"].Value.ToString()); works out.

Just I haven't willed to apply BindingSource, because the essential part of my program works without it. But anyway thank you for attention.


问:
Selenium 4 : frameToBeAvailableAndSwitchToIt doesn't seem to work
I am trying to work with a webpage in Selenium 4. The page has a few iframes and I am trying to wait for an iframe to load completely and then switch to it.

However, the code below doesn't seem to work:

```<code>driver = new ChromeDriver(options);

driver.get("https://www.stagecoachliquor.com/online-store-1/Whiskey-c20954043");

WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(30));

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("#TPASection_iw75naz9 > iframe")));

System.out.println(driver.getPageSource());
</code>```

The system out just prints an empty HTML snippet below:

```<code><html><head></head><body></body></html>
</code>```

As a result, when I try to select any element after the switch, it fails. The iframe is loading alright in the chrome window which seems strange to me. I have tried implicit wait as well which did not work and had the same result.

After a few hours of debugging, I have not been able to identify the root cause. Any help is much appreciated.

Best,
R

答:
I've reproduced the issue.

This behavior looks like a selenium bug, because, when it switches to frame, the frame has no any product elements (they are loaded a few seconds later). But then, when I was in debug and all the products loaded, and a I call driver.getPageSource(), the result is , and when I call this again, it loads the correct page source, but still the driver cannot find any element inside the iframe.

So, I've added a custom expected condition, which switches to frame and check if some element present for workaround this.

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

import static java.time.Duration.ofSeconds;

public class ChromeIframeTest {

    @Test
    public void test() {

        // I use https://github.com/bonigarcia/webdrivermanager lib for download chromedriver
        WebDriverManager.chromedriver().setup();
        ChromeOptions options = new ChromeOptions();
        WebDriver driver = new ChromeDriver(options);

        driver.get("https://www.stagecoachliquor.com/online-store-1/Whiskey-c20954043");

        WebDriverWait wait = new WebDriverWait(driver, ofSeconds(30));

        wait.until(
                frameToBeAvailableAndSwitchToItAndElementToBeAvailable(
                        By.cssSelector("#TPASection_iw75naz9 > iframe"),
                        By.cssSelector(".grid-product__shadow") // product in iframe
                )
        );
        System.out.println(driver.getPageSource());

        driver.quit();
    }

    // Custom expected condition
    public static ExpectedCondition<Boolean> frameToBeAvailableAndSwitchToItAndElementToBeAvailable(
            By frame, By frameElement) {
        return new ExpectedCondition<>() {
            private boolean isLoaded = false;

            @Override
            public Boolean apply(WebDriver driver) {
                if (ExpectedConditions.frameToBeAvailableAndSwitchToIt(frame).apply(driver) != null) {
                    isLoaded = ExpectedConditions.presenceOfAllElementsLocatedBy(frameElement).apply(driver) != null;
                }
                if (!isLoaded) {
                    driver.switchTo().defaultContent();
                }
                return isLoaded;
            }

            @Override
            public String toString() {
                return String.format("element \"%s\" should present in frame \"%s\", is present: \"%b\"", frameElement.toString(), frame.toString(), isLoaded);
            }
        };
    }

}
```

Body:
I am trying to work with a webpage in Selenium 4. The page has a few iframes and I am trying to wait for an iframe to load completely and then switch to it.

However, the code below doesn't seem to work:

driver = new ChromeDriver(options);

driver.get("https://www.stagecoachliquor.com/online-store-1/Whiskey-c20954043");

WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(30));

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("#TPASection_iw75naz9 > iframe")));

System.out.println(driver.getPageSource());

The system out just prints an empty HTML snippet below:

As a result, when I try to select any element after the switch, it fails. The iframe is loading alright in the chrome window which seems strange to me. I have tried implicit wait as well which did not work and had the same result.

After a few hours of debugging, I have not been able to identify the root cause. Any help is much appreciated.

Best,
R

Body:
I've reproduced the issue.

This behavior looks like a selenium bug, because, when it switches to frame, the frame has no any product elements (they are loaded a few seconds later). But then, when I was in debug and all the products loaded, and a I call driver.getPageSource(), the result is <html><head></head><body></body></html>, and when I call this again, it loads the correct page source, but still the driver cannot find any element inside the iframe.

So, I've added a custom expected condition, which switches to frame and check if some element present for workaround this.

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

import static java.time.Duration.ofSeconds;

public class ChromeIframeTest {

    @Test
    public void test() {

        // I use https://github.com/bonigarcia/webdrivermanager lib for download chromedriver
        WebDriverManager.chromedriver().setup();
        ChromeOptions options = new ChromeOptions();
        WebDriver driver = new ChromeDriver(options);

        driver.get("https://www.stagecoachliquor.com/online-store-1/Whiskey-c20954043");

        WebDriverWait wait = new WebDriverWait(driver, ofSeconds(30));

        wait.until(
                frameToBeAvailableAndSwitchToItAndElementToBeAvailable(
                        By.cssSelector("#TPASection_iw75naz9 > iframe"),
                        By.cssSelector(".grid-product__shadow") // product in iframe
                )
        );
        System.out.println(driver.getPageSource());

        driver.quit();
    }

    // Custom expected condition
    public static ExpectedCondition<Boolean> frameToBeAvailableAndSwitchToItAndElementToBeAvailable(
            By frame, By frameElement) {
        return new ExpectedCondition<>() {
            private boolean isLoaded = false;

            @Override
            public Boolean apply(WebDriver driver) {
                if (ExpectedConditions.frameToBeAvailableAndSwitchToIt(frame).apply(driver) != null) {
                    isLoaded = ExpectedConditions.presenceOfAllElementsLocatedBy(frameElement).apply(driver) != null;
                }
                if (!isLoaded) {
                    driver.switchTo().defaultContent();
                }
                return isLoaded;
            }

            @Override
            public String toString() {
                return String.format("element \"%s\" should present in frame \"%s\", is present: \"%b\"", frameElement.toString(), frame.toString(), isLoaded);
            }
        };
    }

}


问:
What is the practical use of the identity function in R?
Base R defines an identity function, a trivial identity function returning its argument (quoting from ?identity).

It is defined as :

```<code>identity <- function (x){x}
</code>```

Why would such a trivial function ever be useful?  Why would it be included in base R?

答:
Stepping away from functional programming, identity is also used in another context in R, namely statistics. Here, it is used to refer to the identity link function in generalized linear models. For more details about this, see ?family or ?glm. Here is an example:

```<code>> x <- rnorm(100)
> y <- rpois(100, exp(1+x))
> glm(y ~x, family=quasi(link=identity))

Call:  glm(formula = y ~ x, family = quasi(link = identity))

Coefficients:
(Intercept)            x
      4.835        5.842

Degrees of Freedom: 99 Total (i.e. Null);  98 Residual
Null Deviance:      6713
Residual Deviance: 2993         AIC: NA
</code>```

However, in this case parsing it as a string instead of a function will achieve the same: glm(y ~x, family=quasi(link="identity"))

EDIT: As noted in the comments below, the function base::identity is not what is used by the link constructor, and it is just used for parsing the link name. (Rather than deleting this answer, I'll leave it to help clarify the difference between the two.)

Body:
Base R defines an identity function, a trivial identity function returning its argument (quoting from ?identity).

It is defined as :

identity <- function (x){x}

Why would such a trivial function ever be useful?  Why would it be included in base R?

Body:
Stepping away from functional programming, identity is also used in another context in R, namely statistics. Here, it is used to refer to the identity link function in generalized linear models. For more details about this, see ?family or ?glm. Here is an example:

> x <- rnorm(100)
> y <- rpois(100, exp(1+x))
> glm(y ~x, family=quasi(link=identity))

Call:  glm(formula = y ~ x, family = quasi(link = identity))

Coefficients:
(Intercept)            x
      4.835        5.842

Degrees of Freedom: 99 Total (i.e. Null);  98 Residual
Null Deviance:      6713
Residual Deviance: 2993         AIC: NA

However, in this case parsing it as a string instead of a function will achieve the same: glm(y ~x, family=quasi(link="identity"))

EDIT: As noted in the comments below, the function base::identity is not what is used by the link constructor, and it is just used for parsing the link name. (Rather than deleting this answer, I'll leave it to help clarify the difference between the two.)


问:
CMD is recognizing PATH variables but VS Code is not
I'm having a problem where PATH variables are recognized in CMD but once I try to use them in the VS Code terminal they seem to break. Obviously, I've tried restarting my computer and VS Code but I can't get to bottom of this problem. If anyone has some idea of what's going on I'd greatly appreciate it.

Visual Proof of Issue

答:
Uh oh, it seems my problem was a quite silly mistake on my part. I had a different value for the User Setting "terminal.integrated.cwd" which was causing VS Code to completely ignore my windows PATH.
If you're having the same problem, try edit the user preference "terminal.integrated.cwd" to "".</p>


问:
How to detect if word is camelcased or not?

identify if the word is correctly camelcased when a set containing list of words is given.

isMyWordCamelCased - True

ismyWordCamelCased - False

```<code>("isMyWordCamelCased", ["cased", "my", "is", "word", "camel", ])
</code>```

Here is my answer but I need help for last word "Cased" my loop finishing at "Case"

```<code>public class Exercise {

    public static void main(String[] args) {

        String str = "isMyWordCamelCased";

        int counter = 0;

        String[] arr = {"cased", "my", "is", "word", "camel"};

        ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(arr));
        ArrayList<String> arrayList2 = new ArrayList<String>();

        for (String s : arrayList) {
            if (str.startsWith(s)) {
                arrayList2.add(0, s);
            } else {
                String temp1 = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
                arrayList2.add(0, temp1);
            }
        }
        for (int i = 0; i < str.length() - 1; i++) {
            for (int j = i + 1; j <= str.length(); j++) {
                String temp = (str.substring(i, j));

                if (arrayList2.contains(str.substring(i,j))){
                    counter++;
                }
            }
        }

        if (counter == arr.length) {
            System.out.println("word is camel case");
        } else {
            System.out.println("word is NOT camel case");
        }
    }
}
</code>```

答:
From the given description, it may help to loop around the string by each character and storing words in another list. Something like this might be useful:</p>
```<code>    public static void main(String[] args) {
        String str = "isMyWordCamelCased";
        String[] arr = {"cased", "my", "is", "word", "camel"};
        if(str == null || Character.isUpperCase(str.charAt(0))){
            System.out.println(false);
            return;
        }
        List<String> resArr = new ArrayList<>();
        StringBuilder tempValue = new StringBuilder();
        for(int i=0; i< str.length(); i++){
            if(Character.isUpperCase(str.charAt(i))){
                resArr.add(tempValue.toString().toLowerCase());
                tempValue = new StringBuilder(""+str.charAt(i));
            }else{
                tempValue.append(str.charAt(i));
            }
        }
        if(!"".equals(tempValue.toString())){
            resArr.add(tempValue.toString().toLowerCase());
        }
        System.out.println(Arrays.asList(arr).containsAll(resArr));
    }
</code>```

Body:
identify if the word is correctly camelcased when a set containing list of words is given.

isMyWordCamelCased - True

ismyWordCamelCased - False

("isMyWordCamelCased", ["cased", "my", "is", "word", "camel", ])

Here is my answer but I need help for last word "Cased" my loop finishing at "Case"

public class Exercise {

    public static void main(String[] args) {

        String str = "isMyWordCamelCased";

        int counter = 0;

        String[] arr = {"cased", "my", "is", "word", "camel"};

        ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(arr));
        ArrayList<String> arrayList2 = new ArrayList<String>();

        for (String s : arrayList) {
            if (str.startsWith(s)) {
                arrayList2.add(0, s);
            } else {
                String temp1 = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
                arrayList2.add(0, temp1);
            }
        }
        for (int i = 0; i < str.length() - 1; i++) {
            for (int j = i + 1; j <= str.length(); j++) {
                String temp = (str.substring(i, j));

                if (arrayList2.contains(str.substring(i,j))){
                    counter++;
                }
            }
        }

        if (counter == arr.length) {
            System.out.println("word is camel case");
        } else {
            System.out.println("word is NOT camel case");
        }
    }
}

Body:
From the given description, it may help to loop around the string by each character and storing words in another list. Something like this might be useful:

    public static void main(String[] args) {
        String str = "isMyWordCamelCased";
        String[] arr = {"cased", "my", "is", "word", "camel"};
        if(str == null || Character.isUpperCase(str.charAt(0))){
            System.out.println(false);
            return;
        }
        List<String> resArr = new ArrayList<>();
        StringBuilder tempValue = new StringBuilder();
        for(int i=0; i< str.length(); i++){
            if(Character.isUpperCase(str.charAt(i))){
                resArr.add(tempValue.toString().toLowerCase());
                tempValue = new StringBuilder(""+str.charAt(i));
            }else{
                tempValue.append(str.charAt(i));
            }
        }
        if(!"".equals(tempValue.toString())){
            resArr.add(tempValue.toString().toLowerCase());
        }
        System.out.println(Arrays.asList(arr).containsAll(resArr));
    }


问:
Distribution of dice sums
I want to study the distributions of sums of dice, especially what happens when the number of dice increases

And for that I know that I have to create a function using a list of numbers and an integer n as arguments and allowing to produce another list of numbers corresponding to the sum of n numbers, a list of
if the input list of numbers is {xi}
and they asked to use a while loop to iterate through the list of numbers.

If anyone has any ideas that would be greatly appreciated :)

答:
Well this is a fun experiment, If i understand your question correctly you are looking for distribution of dice sums with variation in dice counts.

Below is the code to get you started

```<code>import random
def simulatediceplay(num_of_dice):
  sum = 0
  for i in range(num_of_dice):
    sum +=random.randint(1,6)
  return sum

def generateplay(num_of_dice,num_of_runs):
  lst = []
  for i in range(num_of_runs):
    lst.append(simulatediceplay(num_of_dice))
  return lst

lst = generateplay(4,1000)
import seaborn as sns
sns.distplot(lst);
</code>```

Output (for simulation of 1000 dice throws of 4 dices :

Output (for simulation of 1000 dice throws of 8 dices :

Below code can help you generate how the stddev and mean changes for the different dice counts

```<code>import statistics
listdice =[]
listdev = []
listmean = []
for i in range(1,20):
  lst = generateplay(i,1000)
  listdice.append(i)
  listdev.append(statistics.stdev(lst))
  listmean.append(statistics.mean(lst))

# draw lineplot
sns.lineplot(x=listdice, y=listmean)
# draw lineplot
sns.lineplot(x=listdice, y=listdev)
</code>```

Title: Distribution of dice sums

Body:
Well this is a fun experiment, If i understand your question correctly you are looking for distribution of dice sums with variation in dice counts.

Below is the code to get you started

import random
def simulatediceplay(num_of_dice):
  sum = 0
  for i in range(num_of_dice):
    sum +=random.randint(1,6)
  return sum

def generateplay(num_of_dice,num_of_runs):
  lst = []
  for i in range(num_of_runs):
    lst.append(simulatediceplay(num_of_dice))
  return lst

lst = generateplay(4,1000)
import seaborn as sns
sns.distplot(lst);

Output (for simulation of 1000 dice throws of 4 dices :

Output (for simulation of 1000 dice throws of 8 dices :

Below code can help you generate how the stddev and mean changes for the different dice counts

import statistics
listdice =[]
listdev = []
listmean = []
for i in range(1,20):
  lst = generateplay(i,1000)
  listdice.append(i)
  listdev.append(statistics.stdev(lst))
  listmean.append(statistics.mean(lst))

# draw lineplot
sns.lineplot(x=listdice, y=listmean)
# draw lineplot
sns.lineplot(x=listdice, y=listdev)


问:
VPS Squid proxy, how to access a remote video from HTML
I've seen the video below on how to install Squid , but in the official doc I can't see how do I access a remote video in HTML using Squid.
I suppose I need to create a node but not sure how, and how do I reference it in my script:

HTML

```<code><video id="fplayer" class="video-js vjs-default-skin"
    class="video-js"
    controls
    preload="auto"
    width="640"
    height="264"
    data-setup="{}"
  >
    <p class="vjs-no-js">
        Please enable JavaScript ..</a>
    </p>

    <source src="my/vps/path/to/squid/node/myfile.mp4" type="video/mp4" />
       // myfiles.mp4 is actually hosted here: mediafire.com/files/myfile.mp4
</video>
</code>```

https://wiki.squid-cache.org/ConfigExamples  ** Squid Doc

https://www.youtube.com/watch?v=C7BobNN4UJg  ** SSH Install

Many thanks

答:
I think Squid is not the right proxy to achieve what I need.
Express JS is a better tool, and can route the request to stream a video available in the server.
To stream a video from a remote server (eg.mediafire.com) we need to have access to the HTTP Headers (eg. mediafire.com) , which they're not willing to provide.</p>

Body:
I've seen the video below on how to install Squid , but in the official doc I can't see how do I access a remote video in HTML using Squid.
I suppose I need to create a node but not sure how, and how do I reference it in my script:

HTML

<video id="fplayer" class="video-js vjs-default-skin"
    class="video-js"
    controls
    preload="auto"
    width="640"
    height="264"
    data-setup="{}"
  >

        Please enable JavaScript ..

    <source src="my/vps/path/to/squid/node/myfile.mp4" type="video/mp4" />
       // myfiles.mp4 is actually hosted here: mediafire.com/files/myfile.mp4
</video>

https://wiki.squid-cache.org/ConfigExamples  ** Squid Doc

https://www.youtube.com/watch?v=C7BobNN4UJg  ** SSH Install

Many thanks


问:
git aware but (remote) svn ignore
I have a publicly hosted svn repository on google code, however locally I switched to git because of various reasons. I'm currently the only developer with access to the googlecode repo so no need to do fetches. All commits go via a dev branch, to the master branch to svn, with git svn dcommit. All well. Now i'm in the situation that I've some files locally in version control with git, but I do not EVER want them to make public available.

So I had an idea: I create a directory private and add a svn:ignore "private/*" property to my svn repo. But than after

```<code>git svn dcommmit
</code>```

I get an error: Merge conflict during commit: File or directory '.' is out of date; try updating: resource out of date; try updating at /usr/local/git/libexec/git-core/git-svn line 574

I tried importing the svn:ignore property into .git/info/exclude but that excludes all my git files in the 'private' from git which is definitely not what I want.

[08-06-2011]

I think the error is not because of the svn:ignore, it seems that git svn completely ignore the svn:ignore, but due to some other yet unknown reason. The question becomes: is it possible to exclude paths from git svn dcommit in the same way as it is possible to exclude paths from git svn fetch with --ignore-path

答:
The git-svn man page indicates this is possible with the following config key:</p>

```<code>svn-remote.<name>.ignore-paths
</code>```

Title: git aware but (remote) svn ignore

Body:
I have a publicly hosted svn repository on google code, however locally I switched to git because of various reasons. I'm currently the only developer with access to the googlecode repo so no need to do fetches. All commits go via a dev branch, to the master branch to svn, with git svn dcommit. All well. Now i'm in the situation that I've some files locally in version control with git, but I do not EVER want them to make public available.

So I had an idea: I create a directory private and add a svn:ignore "private/*" property to my svn repo. But than after

git svn dcommmit

I get an error: Merge conflict during commit: File or directory '.' is out of date; try updating: resource out of date; try updating at /usr/local/git/libexec/git-core/git-svn line 574

I tried importing the svn:ignore property into .git/info/exclude but that excludes all my git files in the 'private' from git which is definitely not what I want.

[08-06-2011]

I think the error is not because of the svn:ignore, it seems that git svn completely ignore the svn:ignore, but due to some other yet unknown reason. The question becomes: is it possible to exclude paths from git svn dcommit in the same way as it is possible to exclude paths from git svn fetch with --ignore-path

Body:
The git-svn man page indicates this is possible with the following config key:

svn-remote.<name>.ignore-paths


问:
react-router error pathname.match is not a function
I'm getting

pathname.match is not a function

error when I use matchPath of react-router.

Here is the code that throws the exception:

```<code>import { matchPath, useLocation } from "react-router";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";

const MatcherControl = () => {
  const location = useLocation();
  const match = matchPath(location.pathname, {
    path: "/users/:id",
    exact: true,
    strict: false
  });
  return <div>{match ? "matches" : "not matches"}</div>;
};
</code>```

This is the minimal example sandbox to reproduce the error.

答:
You are using react-router v6 that the order of matchPath arguments is inverted in new version:

```<code>declare function matchPath<
  ParamKey extends string = string
>(
  pattern: PathPattern | string,
  pathname: string
): PathMatch<ParamKey> | null;

interface PathMatch<ParamKey extends string = string> {
  params: Params<ParamKey>;
  pathname: string;
  pattern: PathPattern;
}

interface PathPattern {
  path: string;
  caseSensitive?: boolean;
  end?: boolean;
}
</code>```

Check it here

You should pass the pattern first , and then pathname :

```<code>const match = matchPath(
  { path: "/users/:id" },
  location.pathname,
);
</code>```

Body:
I'm getting

pathname.match is not a function

error when I use matchPath of react-router.

Here is the code that throws the exception:

import { matchPath, useLocation } from "react-router";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";

const MatcherControl = () => {
  const location = useLocation();
  const match = matchPath(location.pathname, {
    path: "/users/:id",
    exact: true,
    strict: false
  });
  return
{match ? "matches" : "not matches"}
;
};

This is the minimal example sandbox to reproduce the error.

Body:
You are using react-router v6 that the order of matchPath arguments is inverted in new version:

declare function matchPath<
  ParamKey extends string = string
>(
  pattern: PathPattern | string,
  pathname: string
): PathMatch<ParamKey> | null;

interface PathMatch<ParamKey extends string = string> {
  params: Params<ParamKey>;
  pathname: string;
  pattern: PathPattern;
}

interface PathPattern {
  path: string;
  caseSensitive?: boolean;
  end?: boolean;
}

Check it here

You should pass the pattern first , and then pathname :

const match = matchPath(
  { path: "/users/:id" },
  location.pathname,
);


问:
Add % labels to pie chart ggplot2 after specifying factor orders
I have a data frame from which I want to make a pie chart that shows the % label

Here's what I did first

```<code>SubSegment<- c('S1','S2','S3','S4')
v <- c(100, 300, 500, 200)
df<- cbind.data.frame(SubSegment, v)

#calculations for % labels in chart
df <- df %>%
  arrange(desc(SubSegment)) %>%
  mutate(prop = v / sum(df$v)) %>%
  mutate(ypos = cumsum(prop)- 0.5*prop ) %>%
  mutate(label= prop*1)
df[5] = sapply(df[5], function(x) scales::percent(x, accuracy = 0.1))

plot.ex <- ggplot(df, aes(x = "", y = prop, fill = SubSegment)) +
  geom_bar(width = 1, stat = "identity", color="white", alpha=0.8) +
  coord_polar("y", start = 0) +
  theme_void() +
  geom_text(aes(y = ypos, label = label), size=3, color = "white") +
  scale_fill_brewer(palette="Set1")
</code>```

The result:

As you can see, the labels look great and they are on the right place but it bothers me that the order of the factors is alphabetical, I would want the company with the biggest value to show first in the legend so I added one line of code before the plot:

```<code>df$SubSegment <- factor(df$SubSegment, levels=df$SubSegment[order(-(df$prop))], ordered=TRUE)
</code>```

After doing that the order of the factors in the legend of the plot is as I wanted but the labels get all messed up (they don't move accordingly with the pie pieces).

Here's what my second pie chart looks like:

Basically I want to know how to edit my ypos line so that the labels will move accordingly when the pie pieces move.

答:
You want to show the subsegments based on their proportions and therefore should calculate your ypos based on your proporations. This can be simply done by changing your arrange() line:

```<code>df <- df %>%
  mutate(prop = v / sum(df$v),
         label= scales::percent(prop, accuracy = 0.1)) %>%
  arrange(prop) %>%
  mutate(ypos = cumsum(prop)- 0.5*prop,
         SubSegment = factor(SubSegment, levels=SubSegment[order(-(prop))], ordered=TRUE))

ggplot(df, aes(x = "", y = prop, fill = SubSegment)) +
  geom_bar(width = 1, stat = "identity", color="white", alpha=0.8) +
  coord_polar("y", start = 0) +
  theme_void() +
  geom_text(aes(y = ypos, label = label), size=3, color = "white") +
  scale_fill_brewer(palette="Set1")
</code>```

Body:
I have a data frame from which I want to make a pie chart that shows the % label

Here's what I did first

SubSegment<- c('S1','S2','S3','S4')
v <- c(100, 300, 500, 200)
df<- cbind.data.frame(SubSegment, v)

#calculations for % labels in chart
df <- df %>%
  arrange(desc(SubSegment)) %>%
  mutate(prop = v / sum(df$v)) %>%
  mutate(ypos = cumsum(prop)- 0.5*prop ) %>%
  mutate(label= prop*1)
df[5] = sapply(df[5], function(x) scales::percent(x, accuracy = 0.1))

plot.ex <- ggplot(df, aes(x = "", y = prop, fill = SubSegment)) +
  geom_bar(width = 1, stat = "identity", color="white", alpha=0.8) +
  coord_polar("y", start = 0) +
  theme_void() +
  geom_text(aes(y = ypos, label = label), size=3, color = "white") +
  scale_fill_brewer(palette="Set1")

The result:

As you can see, the labels look great and they are on the right place but it bothers me that the order of the factors is alphabetical, I would want the company with the biggest value to show first in the legend so I added one line of code before the plot:

df$SubSegment <- factor(df$SubSegment, levels=df$SubSegment[order(-(df$prop))], ordered=TRUE)

After doing that the order of the factors in the legend of the plot is as I wanted but the labels get all messed up (they don't move accordingly with the pie pieces).

Here's what my second pie chart looks like:

Basically I want to know how to edit my ypos line so that the labels will move accordingly when the pie pieces move.

Body:
You want to show the subsegments based on their proportions and therefore should calculate your ypos based on your proporations. This can be simply done by changing your arrange() line:

df <- df %>%
  mutate(prop = v / sum(df$v),
         label= scales::percent(prop, accuracy = 0.1)) %>%
  arrange(prop) %>%
  mutate(ypos = cumsum(prop)- 0.5*prop,
         SubSegment = factor(SubSegment, levels=SubSegment[order(-(prop))], ordered=TRUE))

ggplot(df, aes(x = "", y = prop, fill = SubSegment)) +
  geom_bar(width = 1, stat = "identity", color="white", alpha=0.8) +
  coord_polar("y", start = 0) +
  theme_void() +
  geom_text(aes(y = ypos, label = label), size=3, color = "white") +
  scale_fill_brewer(palette="Set1")