问:
Spring MVC - Error 404 with @EnableGlobalMethodSecurity when testing Controller using @WebMvcTest
We are trying to add unit testing to our Spring project Controllers (BTW, the Integration tests work fine), but we are suffering a very odd behavior, When we add the Configuration with @EnableGlobalMethodSecurity (with JSR-250 annotations) if the Controller implements an interface (whatever interface) the Controller is not included by Spring application context as "request handler" (I checked it on method: org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.processCandidateBean(String beanName)), that is, the requests mappings defined in the Controler (@PostMapping, ...) are not registered as potential locations, but if the interface is removed, then the Controller and the path is found without problem.

This is my Controller (simplified) with a simple interface MyInterface:

```<code>@RestController
@RequestMapping(path = "/api/customer")
@RolesAllowed({Role.Const.ADMIN})
public class CustomerController implements MyInterface {
    @Override // The only method in MyInterface
    public void myMethod(Object param) throws QOException {
        System.out.println("Hello");
    }
    @PostMapping(path = {"/", ""})
    public Customer create(@RequestBody Customer data) throws QOException {
        return customerService.create(data);
    }
}
</code>```

And this is the Test class (if I remove the @EnableGlobalMethodSecurity config class all works fine):

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(controllers = CustomerController.class)
@Import({ CustomerController.class, TestAuthConfiguration.class, TestAuthConfiguration2.class})  //, TestAuthConfiguration.class })
@ActiveProfiles({"test", "unittest"})
@WithMockUser(username = "test", authorities = { Role.Const.ADMIN })
class CustomerControllerTest {
    private static final Logger LOG = LogManager.getLogger(CustomerControllerTest.class);
    @EnableWebSecurity
    protected static class TestAuthConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            LOG.info("configure(HttpSecurity http) ");
            http.csrf().disable().authorizeRequests().filterSecurityInterceptorOncePerRequest(true)
                    .antMatchers("/api/session/**").permitAll() //
                    .antMatchers("/api/**").authenticated() //
                    .anyRequest().permitAll().and() //
                    .addFilterBefore(new OncePerRequestFilter() {
                        @Override
                        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                FilterChain filterChain) throws ServletException, IOException {
                            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                            if (auth != null) {
                                LOG.info("User authenticated: {}, roles: {}", auth.getName(), auth.getAuthorities());
                            }
                            filterChain.doFilter(request, response);
                        }
                    }, BasicAuthenticationFilter.class).sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }

    }

    @EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = false)
    protected static class TestAuthConfiguration2 extends GlobalMethodSecurityConfiguration {
        @Bean
        public GrantedAuthorityDefaults grantedAuthorityDefaults() {
            return new GrantedAuthorityDefaults(""); // Remove the ROLE_ prefix
        }
    }

    @Autowired
    MockMvc mockMvc;

    @Test
    void testCreate() throws Exception {
        Customer bean = new Customer();
        bean.setName("Test company");
        when(customerServiceMock.create(bean)).thenReturn(bean);
        mockMvc.perform(post("/api/customer")
        .content(JsonUtils.toJSON(bean)).contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("Test company"));
    }
}
</code>```

I don't understand what is happeing, I've tried to find an example of unit testing in controllers with security based on anotations JSR-250 (@RollesAllowed), but I didn't find anything useful, anyway this problem sounds (to me) to a bug, but I'm not sure, so any help is welcome.

The libraries versions:

Spring Boot version: 2.2.2

Spring Core: 5.2.1

Mockito Core: 3.1.0

答:
Try setting proxyTargetClass attribute to true. I was facing a similar problem and solved it by adding this.

```<code>@EnableGlobalMethodSecurity(jsr250Enabled = true, proxyTargetClass = true)
</code>```

Also i would recommend reading javadocs for EnableGlobalMethodSecurity especially paying attention to proxyTargetClass and mode attributes.

Body:
We are trying to add unit testing to our Spring project Controllers (BTW, the Integration tests work fine), but we are suffering a very odd behavior, When we add the Configuration with @EnableGlobalMethodSecurity (with JSR-250 annotations) if the Controller implements an interface (whatever interface) the Controller is not included by Spring application context as "request handler" (I checked it on method: org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.processCandidateBean(String beanName)), that is, the requests mappings defined in the Controler (@PostMapping, ...) are not registered as potential locations, but if the interface is removed, then the Controller and the path is found without problem.

This is my Controller (simplified) with a simple interface MyInterface:

@RestController
@RequestMapping(path = "/api/customer")
@RolesAllowed({Role.Const.ADMIN})
public class CustomerController implements MyInterface {
    @Override // The only method in MyInterface
    public void myMethod(Object param) throws QOException {
        System.out.println("Hello");
    }
    @PostMapping(path = {"/", ""})
    public Customer create(@RequestBody Customer data) throws QOException {
        return customerService.create(data);
    }
}

And this is the Test class (if I remove the @EnableGlobalMethodSecurity config class all works fine):

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = CustomerController.class)
@Import({ CustomerController.class, TestAuthConfiguration.class, TestAuthConfiguration2.class})  //, TestAuthConfiguration.class })
@ActiveProfiles({"test", "unittest"})
@WithMockUser(username = "test", authorities = { Role.Const.ADMIN })
class CustomerControllerTest {
    private static final Logger LOG = LogManager.getLogger(CustomerControllerTest.class);
    @EnableWebSecurity
    protected static class TestAuthConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            LOG.info("configure(HttpSecurity http) ");
            http.csrf().disable().authorizeRequests().filterSecurityInterceptorOncePerRequest(true)
                    .antMatchers("/api/session/**").permitAll() //
                    .antMatchers("/api/**").authenticated() //
                    .anyRequest().permitAll().and() //
                    .addFilterBefore(new OncePerRequestFilter() {
                        @Override
                        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                FilterChain filterChain) throws ServletException, IOException {
                            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                            if (auth != null) {
                                LOG.info("User authenticated: {}, roles: {}", auth.getName(), auth.getAuthorities());
                            }
                            filterChain.doFilter(request, response);
                        }
                    }, BasicAuthenticationFilter.class).sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }

    }

    @EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = false)
    protected static class TestAuthConfiguration2 extends GlobalMethodSecurityConfiguration {
        @Bean
        public GrantedAuthorityDefaults grantedAuthorityDefaults() {
            return new GrantedAuthorityDefaults(""); // Remove the ROLE_ prefix
        }
    }

    @Autowired
    MockMvc mockMvc;

    @Test
    void testCreate() throws Exception {
        Customer bean = new Customer();
        bean.setName("Test company");
        when(customerServiceMock.create(bean)).thenReturn(bean);
        mockMvc.perform(post("/api/customer")
        .content(JsonUtils.toJSON(bean)).contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("Test company"));
    }
}

I don't understand what is happeing, I've tried to find an example of unit testing in controllers with security based on anotations JSR-250 (@RollesAllowed), but I didn't find anything useful, anyway this problem sounds (to me) to a bug, but I'm not sure, so any help is welcome.

The libraries versions:

Spring Boot version: 2.2.2

Spring Core: 5.2.1

Mockito Core: 3.1.0

Body:
Try setting proxyTargetClass attribute to true. I was facing a similar problem and solved it by adding this.

@EnableGlobalMethodSecurity(jsr250Enabled = true, proxyTargetClass = true)

Also i would recommend reading javadocs for EnableGlobalMethodSecurity especially paying attention to proxyTargetClass and mode attributes.


来源: stackexchange

问:
Add a function to String class using JavaScript's String.prototype
I have to create a function to be added to the string class. For example "hi".exclamify(3) should return hi with three !!! at the end of the string. I know I have to make use of

```<code>String.prototype.exclamify = function(n)
{
  // Function definition goes here
  console.log(this);
}
"hi".exclamify(2);
</code>```

When I call the function as "hi".exclamify(2); the console returns [String: 'Hello'], what to do to get only the value of the string which is "Hello"? I used Object.values(this) which returned [ 'H', 'e', 'l', 'l', 'o' ]. I want the exact string to implement the function.

答:
It looks like the value of this was working for you and contained the correct string. Here's a quick try at your problem:

String.prototype.exclamify=function(n){ return `${this}${'!'.repeat(n)}` }

const testString = "hello";

console.log(testString.exclamify(3));
console.log(testString.exclamify(5));```

ContentLicense: CC BY-SA 4.0

Body:
I have to create a function to be added to the string class. For example "hi".exclamify(3) should return hi with three !!! at the end of the string. I know I have to make use of

String.prototype.exclamify = function(n)
{
  // Function definition goes here
  console.log(this);
}
"hi".exclamify(2);

When I call the function as "hi".exclamify(2); the console returns [String: 'Hello'], what to do to get only the value of the string which is "Hello"? I used Object.values(this) which returned [ 'H', 'e', 'l', 'l', 'o' ]. I want the exact string to implement the function.


问:
Plot validation loss in Tensorflow Object Detection API
I'm using Tensorflow Object Detection API for detection and localization of one class object in images. For these purposes, I use the pre-trained faster_rcnn_resnet50_coco_2018_01_28 model.

I want to detect under/overfitting after training the model. I see training loss, but after evaluating Tensorboard only shows mAP and Precision metrics and no loss.

Is this possible to plot a validation loss on Tensorboard too?

答:
Using model_main.py for training gives two curves in tensorboard. They supposed to be train and validation losses.

you can use the following command at CMD.

python object_detection/model_main.py --num_eval_steps=10 --num_train_steps=50000 --alsologtostderr --pipeline_config_path=C:/DroneMaskRCNN/DroneMaskRCNN1/mask_rcnn_inception_v2_coco.config  --model_dir=C:/DroneMaskRCNN/DroneMaskRCNN1/CP


问:
Excel VBA Textfile to 2d array
I am new to excel vba. I want to read a textfile that contains text like this:

```<code>John Smith Engineer Chicago
Bob Alice Doctor New York
Jane Smith Teacher St. Louis
</code>```

So, I want to convert this into a 2D array so if I do print(3,3), it should return 'Teacher'.
I am able to read entire file contents into one string but am having difficulty in converting it to
a 2d array like above. Please advice on how to proceed. Thanks

答:
as mentioned by NautMeg, You have to make some assumptions on the data based on the provided template.

However we can assume that :

a space is the delimiter

The Final column is City, which can contain a space

there are 4 columns

First Name

Last Name

Profession

City/Location

Using this information:

```<code>While Not EOF(my_file)
    Line Input #my_file, text_line
    // text_line contains the independent line
    i = i + 1
    // i is the line number
Wend
</code>```

is how we retrieve each line.

```<code>Split ( Expression, [Delimiter], [Limit], [Compare] )
</code>```

This will give you each item in the list. For index's < 3 (0 based index), they are unique columns of data and you can handle them however you want.
For Index >=3, Join these together into 1 string .

```<code>Join( SourceArray, [Delimiter] )
</code>```

You'll likely want to make the delimiter in this case a simple space, since the split function will remove the space.

That will allow you to parse the data AS is.

However, for future reference if you can control the export of the text file, you should try exporting as a CSV file.

Good luck

Title: Excel VBA Textfile to 2d array

Body:
I am new to excel vba. I want to read a textfile that contains text like this:

John Smith Engineer Chicago
Bob Alice Doctor New York
Jane Smith Teacher St. Louis

So, I want to convert this into a 2D array so if I do print(3,3), it should return 'Teacher'.
I am able to read entire file contents into one string but am having difficulty in converting it to
a 2d array like above. Please advice on how to proceed. Thanks

Body:
as mentioned by NautMeg, You have to make some assumptions on the data based on the provided template.

However we can assume that :

a space is the delimiter

The Final column is City, which can contain a space

there are 4 columns

First Name

Last Name

Profession

City/Location

Using this information:

While Not EOF(my_file)
    Line Input #my_file, text_line
    // text_line contains the independent line
    i = i + 1
    // i is the line number
Wend

is how we retrieve each line.

Split ( Expression, [Delimiter], [Limit], [Compare] )

This will give you each item in the list. For index's < 3 (0 based index), they are unique columns of data and you can handle them however you want.
For Index >=3, Join these together into 1 string .

Join( SourceArray, [Delimiter] )

You'll likely want to make the delimiter in this case a simple space, since the split function will remove the space.

That will allow you to parse the data AS is.

However, for future reference if you can control the export of the text file, you should try exporting as a CSV file.

Good luck


问:
I'm unable to launch my unreal game with error code 5
So I've set up a test game and added some widgets and c++ to it, and when I play my game everything works fine. However when I try and launch my game i get this error:

LogPlayLevel: Error:   ERROR: Unable to instantiate module 'UnrealEd': Unable to instantiate UnrealEd module for non-editor targets.

and i just don't know how to solve it. I've tried to find answers however it doesn't seem like anyone else gets this.

I'm still new to unreal so any help would be appreciated.

答:
I had the same problem and found a fix that worked for me.

The .uproject file contains a list of additional dependencies, for example:

```<code>"AdditionalDependencies": [
            "Engine",
            "UnrealEd",
            "UMGEditor",
            "UMG"
        ]
</code>```

From those four i had to remove both UnrealEd and UMGEditor which depends on the former.

I didn't reproduce this situation in a clean project, but I suspect it to be either a widget editor bug, or the change occured while building with incorrect headers.

Body:
I had the same problem and found a fix that worked for me.

The .uproject file contains a list of additional dependencies, for example:

"AdditionalDependencies": [
            "Engine",
            "UnrealEd",
            "UMGEditor",
            "UMG"
        ]

From those four i had to remove both UnrealEd and UMGEditor which depends on the former.

I didn't reproduce this situation in a clean project, but I suspect it to be either a widget editor bug, or the change occured while building with incorrect headers.


问:
Javascript is not doing sum of all records
I'm trying to do the sum of all cart items but it is not doing it.
It is showing only the sum of first or last item added in the cart.

What is the issue i cannot understand. I have tried by moving code in the java but no use.

Suppose i have 2 items.

Item1 total is = 100
Item2 total is = 200

Total should be 300 not only the 1 items total.

Below is my code.

Thanks in advance

```<code><script type="text/javascript" src="js/jquery-1.12.1.min.js"></script>

<table class="table mg-bottom-45 refresh" id="myTable">
    <thead>
    <tr>
    <th class="product-cart-price"><span>PRICE</span></th>
    <th class="product-cart-price"><span>TOTAL</span></th>
    </tr>
    </thead>

<tbody>
<?php
include ('inc/db.php');

$citem  = "select * from orders_temp
where user_id = 1 order by id
";
$ciquery    = $dba2->query($citem);
while ($cifetch = $ciquery->fetch_assoc()){
    $orderID    =   $cifetch['id'];
    $userID =   $cifetch['user_id'];
?>
    <td class="product-cart-thumbnail">
    <input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
    data-price="" value="<?php echo $cifetch['qty']; ?>"
    class="un quant" />
    </td>

    <td class="product-cart-thumbnail">
    <input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
    data-price="<?php echo $cifetch['price']; ?>"
    value="<?php echo $cifetch['price']; ?>" class="un pricex" />
    </td>

<?php } ?>
    <td class="totalAmount"></td>
</tbody>
</table>

<script type="text/javascript">
$(document).ready(function() {
  updatexx<?php echo $orderID; ?>();
  function updatexx<?php echo $orderID; ?>() {
    var sumx = '';
    $('#myTable > tbody  > tr').each(function() {
      var quantityx = $(this).find('.quant').val();
      var pricex = $(this).find('.pricex').attr('data-price').replace(',', '.');
      var amountx = (quantityx * pricex).toFixed(3);

      sumx += amountx;
    });
    $('.totalAmount').text(sumx);
  }
});
</script>
</code>```

答:
So here is the solution with some changes in my code.
Now it is working perfectly as required. It is doing the sum of all items and everything what i want.</p>

```<code><table class="table mg-bottom-45 refresh" id="myTable">
<tbody>
<?php
$i = 0;
//error_reporting(0);
$ses_mem    =   1;
include ('inc/db.php');

$citem      = "select id, user_id, qty, org_price  from orders_temp
where user_id = '".$ses_mem."' and status = 1
order by id
";
$ciquery    = $dba2->query($citem);
while ($cifetch = $ciquery->fetch_assoc()){
    $orderID    =   $cifetch['id'];
?>

<tr>

<script type="text/javascript" src="js/jquery-1.12.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  updatexx<?php echo $orderID; ?>();
  function updatexx<?php echo $orderID; ?>() {
var sumx = 0.000;
var quantity;
$('#myTable > tbody  > tr').each(function() {

  quantity = $(this).find('.quant').val();
  var price = $(this).find('.pricex').attr('data-price').replace(',', '.');
  var amountx = (quantity * price);
      var munterx = amountx.toFixed(3);

  sumx += amountx;
  $(this).find('.amountx<?php echo $orderID; ?>').text('' + munterx);
});
    var sumxx = sumx.toFixed(3);
$('.total').text(sumxx);
  }
});
</script>

        <td class="single-qty" style="border: 0;">
        <input id="<?php echo $orderID; ?>" name="quantity" type="text"
        data-id="<?php echo $orderID; ?>"
        data-price="" value="<?php echo $cifetch['qty']; ?>"
        class="un quant" />
        </td>

        <td class="product-cart-price pricex" data-price="<?php echo $cifetch['org_price']; ?>">
        </td>

        <td class="amountx<?php echo $orderID; ?>">
        </td>
</tr>
<?php } ?>
</tbody>
</table>

<table class="table">
<tbody>
<tr>
<td>Sub Total (RS)</td>
<td class="text-right"
    style="text-shadow: 2px 2px 3px #999999; font-weight: bold;
    color: black; direction: rtl;">
        <span class="total">
        </span>
    </td>
</tr>
</tbody>
</table>
</code>```

Body:
I'm trying to do the sum of all cart items but it is not doing it.
It is showing only the sum of first or last item added in the cart.

What is the issue i cannot understand. I have tried by moving code in the java but no use.

Suppose i have 2 items.

Item1 total is = 100
Item2 total is = 200

Total should be 300 not only the 1 items total.

Below is my code.

Thanks in advance

    PRICE
    TOTAL

<?php
include ('inc/db.php');

$citem  = "select * from orders_temp
where user_id = 1 order by id
";
$ciquery    = $dba2->query($citem);
while ($cifetch = $ciquery->fetch_assoc()){
    $orderID    =   $cifetch['id'];
    $userID =   $cifetch['user_id'];
?>

    <input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
    data-price="" value="<?php echo $cifetch['qty']; ?>"
    class="un quant" />

    <input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
    data-price="<?php echo $cifetch['price']; ?>"
    value="<?php echo $cifetch['price']; ?>" class="un pricex" />

<?php } ?>

Body:
So here is the solution with some changes in my code.
Now it is working perfectly as required. It is doing the sum of all items and everything what i want.

<table class="table mg-bottom-45 refresh" id="myTable">
<tbody>
<?php
$i = 0;
//error_reporting(0);
$ses_mem    =   1;
include ('inc/db.php');

$citem      = "select id, user_id, qty, org_price  from orders_temp
where user_id = '".$ses_mem."' and status = 1
order by id
";
$ciquery    = $dba2->query($citem);
while ($cifetch = $ciquery->fetch_assoc()){
    $orderID    =   $cifetch['id'];
?>

<tr>

<script type="text/javascript" src="js/jquery-1.12.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  updatexx<?php echo $orderID; ?>();
  function updatexx<?php echo $orderID; ?>() {
var sumx = 0.000;
var quantity;
$('#myTable > tbody  > tr').each(function() {

  quantity = $(this).find('.quant').val();
  var price = $(this).find('.pricex').attr('data-price').replace(',', '.');
  var amountx = (quantity * price);
      var munterx = amountx.toFixed(3);

  sumx += amountx;
  $(this).find('.amountx<?php echo $orderID; ?>').text('' + munterx);
});
    var sumxx = sumx.toFixed(3);
$('.total').text(sumxx);
  }
});
</script>

        <td class="single-qty" style="border: 0;">
        <input id="<?php echo $orderID; ?>" name="quantity" type="text"
        data-id="<?php echo $orderID; ?>"
        data-price="" value="<?php echo $cifetch['qty']; ?>"
        class="un quant" />
        </td>

        <td class="product-cart-price pricex" data-price="<?php echo $cifetch['org_price']; ?>">
        </td>

        <td class="amountx<?php echo $orderID; ?>">
        </td>
</tr>
<?php } ?>
</tbody>
</table>

<table class="table">
<tbody>
<tr>
<td>Sub Total (RS)</td>
<td class="text-right"
    style="text-shadow: 2px 2px 3px #999999; font-weight: bold;
    color: black; direction: rtl;">
        <span class="total">
        </span>
    </td>
</tr>
</tbody>
</table>


问:
Adding an external jar library to Intellij IDEA
I'm having a silly problem : I'm trying to add the Jsoup library (which is just an external jar) to my android application developed in Intellij Idea and it seems and don't do it right .
I put the library in the libs folder , then I went in Project Structure -> modules and selected dependencies , select add global library , select attach source and click ok.

When I write code  it is able to automatically import classes  and to compile , but when running I get " java.lang.NoClassDefFoundError: org.jsoup.Jsoup"

答:
Have a look at the newer artifacts section.  Perhaps you don't add the JAR into your deployment properly.

UPDATE:

I'd like to update my answer based on lessons learned over the past six years since I first answered this question.

The best way to manage 3rd party JAR dependencies in Java projects is to learn Maven (my preference) or Gradle.  IntelliJ has terrific integration with both.

If you combine those with an enterprise repository like Nexus you'll have no problems.  Your dependencies and versions will be completely specified.  Conflicts will be identified for you.  Updates will be relatively simple.

ContentLicense: CC BY-SA 3.0


问:
Laravel 6: how do I send user_id with role_id(s) to controller, in order to sync user_role pivot table?
I'm pretty new to Laravel and need help. I'm creating an admin page where users can be assigned multiple roles by means of checkboxes. I have the usual many-to-many relationships set up and a pivot table, "roles_users" with two columns: role_id and user_id. Users' various roles display fine, but I'm having trouble with the update function. My form sends an array of roles to admincontroller@update, but of course they need to be associated with users -- and I can't figure out how to do that.

Here's my form:

```<code>
        <form method="POST" action="{{ route('admin.update') }}" enctype="multipart/form-data">
        {{ csrf_field() }}
        <table>
            <thead>
                <th>Name</th>
                <th>Email</th>
                @foreach ($roles as $role)
                <th>{{ $role->name }}</th>
                @endforeach
            </thead>
            <tbody>
                @foreach ($users as $user)
                <tr>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                    <input type="hidden" name="user[]" value="{{ $user->id }}">
                    @foreach($roles as $role)
                        <td><input type="checkbox" name="roles[]" value={{ $role->id }}
                            @if (in_array($role->id, $user->roles->pluck('id')->toArray() ))
                                checked ="1"
                            @endif />
                        </td>
                    @endforeach
                </tr>
                @endforeach
            </tbody>
        </table>
        <input type="submit" class="tableSubmit" value="Update" />
</code>```

Here's my update method:

```<code>    public function update(Request $request, $id) {

        $id = $request->input('user');
        $user = User::with('roles')->find($id);
        $user->roles()->sync(($request->roles), false);

        return redirect('/admin');
    }
</code>```

This all throws an error, "Method Illuminate\Database\Eloquent\Collection::roles does not exist." But of course I do have a roles() method in my User model:

```<code>    public function roles() {
        return $this->belongsToMany('App\Role');
    }
</code>```

How do I pass through the user_id with the roles' ids, so that the sync method works? Thanks in advance for any help!

答:
Your problem is that you are using the with method directly to the collection, the correct way is:

```<code>$user = User::where('id',$id)->with('roles')->first();
</code>```

Hope it works!

EDIT:

Not sure why is a "false" after the array inside the sync method, try changing to this:

```<code>$user->roles()->sync($request->roles);
</code>```

Body:
I'm pretty new to Laravel and need help. I'm creating an admin page where users can be assigned multiple roles by means of checkboxes. I have the usual many-to-many relationships set up and a pivot table, "roles_users" with two columns: role_id and user_id. Users' various roles display fine, but I'm having trouble with the update function. My form sends an array of roles to admincontroller@update, but of course they need to be associated with users -- and I can't figure out how to do that.

Here's my form:

        <form method="POST" action="{{ route('admin.update') }}" enctype="multipart/form-data">
        {{ csrf_field() }}

                Name
                Email
                @foreach ($roles as $role)
                {{ $role->name }}
                @endforeach

                @foreach ($users as $user)

                    {{ $user->name }}
                    {{ $user->email }}
                    <input type="hidden" name="user[]" value="{{ $user->id }}">
                    @foreach($roles as $role)
                        <input type="checkbox" name="roles[]" value={{ $role->id }}
                            @if (in_array($role->id, $user->roles->pluck('id')->toArray() ))
                                checked ="1"
                            @endif />

                    @endforeach

                @endforeach

        <input type="submit" class="tableSubmit" value="Update" />

Here's my update method:

    public function update(Request $request, $id) {

        $id = $request->input('user');
        $user = User::with('roles')->find($id);
        $user->roles()->sync(($request->roles), false);

        return redirect('/admin');
    }

This all throws an error, "Method Illuminate\Database\Eloquent\Collection::roles does not exist." But of course I do have a roles() method in my User model:

    public function roles() {
        return $this->belongsToMany('App\Role');
    }

How do I pass through the user_id with the roles' ids, so that the sync method works? Thanks in advance for any help!

Body:
Your problem is that you are using the with method directly to the collection, the correct way is:

$user = User::where('id',$id)->with('roles')->first();

Hope it works!

EDIT:

Not sure why is a "false" after the array inside the sync method, try changing to this:

$user->roles()->sync($request->roles);


问:
How to integrate Fake.Build and JetBrains Rider
In our team, we're (happily) using JetBrains Rider as IDE for our C# and frontend projects. Now, we've inherited a project that uses Fake.Build as a build system. It works very well on console, but I didn't find a good way to integrate it into the Run/Debug Dialogs Rider offers. Some of our devs clearly prefer the Gui to control their builds, and I want to offer them a good develop experience.

How can I integrate Rider with Fake.Build so we can enjoy the same comfort as we have with MSBuild-based builds?

答:
The best way I found until now is to integrate it is to create a package.json file and define script tasks that run the fake tasks:

```<code>  "scripts": {
    "start": "dotnet fake build -t run",
    "build": "dotnet fake build -t build",
    "test": "dotnet fake build -t test"
}
</code>```

These can be clicked explicitly or easily added as config for run/debug in Rider.

Body:
The best way I found until now is to integrate it is to create a package.json file and define script tasks that run the fake tasks:

  "scripts": {
    "start": "dotnet fake build -t run",
    "build": "dotnet fake build -t build",
    "test": "dotnet fake build -t test"
}

These can be clicked explicitly or easily added as config for run/debug in Rider.


Title: Get Start and Stop Values For Incrementing Groups in NumPy Vector

Body:
I have a NumPy vector that is sorted and contains no repeats like:

[  1,   2,   6,  12,  13,  14,  16,  18,  19,  22,  23,  26,  29,
  31,  32,  34,  37,  38,  39,  40,  42,  43,  44,  49,  50,  52,
  55,  63,  64,  67,  68,  75,  78,  82,  84,  86,  88,  90,  93,
  95,  97,  98, 100, 103, 104, 106, 114, 119, 123, 124, 127, 129,
 130, 131, 134, 137, 139, 141, 142, 146, 149, 151, 153, 154, 155,
 159, 160, 161, 162, 165, 166, 167, 171, 173, 180, 181, 184, 186,
 189, 191, 194, 195, 196, 202, 208, 210, 212, 215, 216, 218, 223,
 224, 225, 226, 231, 233, 235, 239, 240, 241, 245, 248, 252, 253,
 259, 260, 261, 264, 271, 272, 273, 276, 279, 280, 285, 287, 290,
 291, 292, 293, 296, 297, 301, 304, 306, 307, 311, 312, 313, 319,
 320, 323, 324, 325, 326, 332, 335, 336, 337, 338, 339, 341, 342,
 345, 346, 349, 352, 355, 359, 364, 365, 367, 369, 373, 376, 378,
 380, 382, 386, 387, 388, 391, 399, 400, 401, 405, 408, 409, 410,
 413, 414, 415, 416, 423, 427, 428, 429, 432, 433, 434, 435, 437,
 439, 440, 443, 448, 449, 451, 453, 455, 459, 461, 464, 465, 466,
 467, 468, 470, 471, 473, 476, 478, 482, 487, 488, 491, 495, 498,
 501, 502, 503, 505, 506, 507, 514, 518, 519, 520, 522, 523, 525,
 528, 530, 532, 534, 538, 539, 540, 544, 550, 551, 556, 558, 568,
 571, 573, 577, 578, 582, 584, 585, 592, 597, 599, 603, 605, 607,
 609, 610, 612, 616, 618, 621, 623, 625, 626, 628, 630, 631, 632,
 633, 636, 637, 639, 642, 644, 647, 651, 653, 654, 656, 661, 662,
 666, 668, 670, 672, 673, 674, 675, 676, 682, 684, 687, 688, 690,
 692, 693, 694, 696, 697, 698, 699, 705, 706, 707, 708, 713, 714,
 719, 726, 727, 729, 730, 736, 737, 739, 740, 741, 742, 744, 748,
 749, 753, 758, 759, 762, 766, 771, 772, 774, 775, 778, 780, 782,
 786, 787, 789, 791, 793, 796, 797, 798, 799, 803, 804, 807, 809,
 811, 814, 815, 817, 819, 821, 827, 831, 833, 837, 842, 846, 849,
 851, 854, 855, 858, 865, 866, 867, 868, 870, 872, 873, 874, 880,
 881, 882, 884, 885, 890, 892, 893, 894, 895, 896, 897, 899, 900,
 902, 908, 912, 913, 915, 916, 920, 921, 924, 927, 930, 933, 941,
 942, 946, 950, 953, 957, 960, 963, 964, 967, 969, 972, 973, 975,
 978, 981, 983, 985, 986, 991, 992, 993, 995]

What I need is to find the start and stop values where consecutive (increment by one) numbers exist. So the output would be something like:

[[  1,  2],
 [  6,  6],
 [ 12, 14],
 [ 16, 16],
 [ 18, 19],
 [ 22, 23],
 [ 26, 26],
 [ 29, 29],
 [ 31, 32],
 [ 34, 34],
 [ 37, 40],
 [ 42, 44],
 .
 .
 .]

I think that I could do something like (x[:-1] - x[1:]) == 1 to build a True/False vector but then I'd have to loop through this vector to identify the start/stop values. I can't seem to come up with a vectorized solution beyond this.

Body:
IIUC, you can try something like this:

arr = np.array([  1,   2,   6,  12,  13,  14,  16,  18,  19,  22,  23,  26,  29,
  31,  32,  34,  37,  38,  39,  40,  42,  43,  44,  49,  50,  52,
  55,  63,  64,  67,  68,  75,  78,  82,  84,  86,  88,  90,  93,
  95,  97,  98, 100, 103, 104, 106, 114, 119, 123, 124, 127, 129,
 130, 131, 134, 137, 139, 141, 142, 146, 149, 151, 153, 154, 155,
 159, 160, 161, 162, 165, 166, 167, 171, 173, 180, 181, 184, 186,
 189, 191, 194, 195, 196, 202, 208, 210, 212, 215, 216, 218, 223,
 224, 225, 226, 231, 233, 235, 239, 240, 241, 245, 248, 252, 253,
 259, 260, 261, 264, 271, 272, 273, 276, 279, 280, 285, 287, 290,
 291, 292, 293, 296, 297, 301, 304, 306, 307, 311, 312, 313, 319,
 320, 323, 324, 325, 326, 332, 335, 336, 337, 338, 339, 341, 342,
 345, 346, 349, 352, 355, 359, 364, 365, 367, 369, 373, 376, 378,
 380, 382, 386, 387, 388, 391, 399, 400, 401, 405, 408, 409, 410,
 413, 414, 415, 416, 423, 427, 428, 429, 432, 433, 434, 435, 437,
 439, 440, 443, 448, 449, 451, 453, 455, 459, 461, 464, 465, 466,
 467, 468, 470, 471, 473, 476, 478, 482, 487, 488, 491, 495, 498,
 501, 502, 503, 505, 506, 507, 514, 518, 519, 520, 522, 523, 525,
 528, 530, 532, 534, 538, 539, 540, 544, 550, 551, 556, 558, 568,
 571, 573, 577, 578, 582, 584, 585, 592, 597, 599, 603, 605, 607,
 609, 610, 612, 616, 618, 621, 623, 625, 626, 628, 630, 631, 632,
 633, 636, 637, 639, 642, 644, 647, 651, 653, 654, 656, 661, 662,
 666, 668, 670, 672, 673, 674, 675, 676, 682, 684, 687, 688, 690,
 692, 693, 694, 696, 697, 698, 699, 705, 706, 707, 708, 713, 714,
 719, 726, 727, 729, 730, 736, 737, 739, 740, 741, 742, 744, 748,
 749, 753, 758, 759, 762, 766, 771, 772, 774, 775, 778, 780, 782,
 786, 787, 789, 791, 793, 796, 797, 798, 799, 803, 804, 807, 809,
 811, 814, 815, 817, 819, 821, 827, 831, 833, 837, 842, 846, 849,
 851, 854, 855, 858, 865, 866, 867, 868, 870, 872, 873, 874, 880,
 881, 882, 884, 885, 890, 892, 893, 894, 895, 896, 897, 899, 900,
 902, 908, 912, 913, 915, 916, 920, 921, 924, 927, 930, 933, 941,
 942, 946, 950, 953, 957, 960, 963, 964, 967, 969, 972, 973, 975,
 978, 981, 983, 985, 986, 991, 992, 993, 995])

grp = np.cumsum(np.diff(np.append(0,arr))!=1)

[i[np.r_[0,-1]]
    for i in np.split(arr, np.cumsum(np.unique(grp, return_counts=True)[1]))[:-1]]

Output:

[array([1, 2]),
 array([6, 6]),
 array([12, 14]),
 array([16, 16]),
 array([18, 19]),
 array([22, 23]),
 array([26, 26]),
 array([29, 29]),
 array([31, 32]),
 array([34, 34]),
 array([37, 40]),
 array([42, 44]),
 array([49, 50]),
 array([52, 52]),
 array([55, 55]),
 array([63, 64]),
 array([67, 68]),
 array([75, 75]),
 array([78, 78]),
 array([82, 82]),
 array([84, 84]),
 array([86, 86]),
 array([88, 88]),
 array([90, 90]),
 array([93, 93]),
 array([95, 95]),
 array([97, 98]),
 array([100, 100]),
 array([103, 104]),
 array([106, 106]),
 array([114, 114]),
 array([119, 119]),
 array([123, 124]),
 array([127, 127]),
 array([129, 131]),
 array([134, 134]),
 array([137, 137]),
 array([139, 139]),
 array([141, 142]),
 array([146, 146]),
 array([149, 149]),
 array([151, 151]),
 array([153, 155]),
 array([159, 162]),
 array([165, 167]),
 array([171, 171]),
 array([173, 173]),
 array([180, 181]),
 array([184, 184]),
 array([186, 186]),
 array([189, 189]),
 array([191, 191]),
 array([194, 196]),
 array([202, 202]),
 array([208, 208]),
 array([210, 210]),
 array([212, 212]),
 array([215, 216]),
 array([218, 218]),
 array([223, 226]),
 array([231, 231]),
 array([233, 233]),
 array([235, 235]),
 array([239, 241]),
 array([245, 245]),
 array([248, 248]),
 array([252, 253]),
 array([259, 261]),
 array([264, 264]),
 array([271, 273]),
 array([276, 276]),
 array([279, 280]),
 array([285, 285]),
 array([287, 287]),
 array([290, 293]),
 array([296, 297]),
 array([301, 301]),
 array([304, 304]),
 array([306, 307]),
 array([311, 313]),
 array([319, 320]),
 array([323, 326]),
 array([332, 332]),
 array([335, 339]),
 array([341, 342]),
 array([345, 346]),
 array([349, 349]),
 array([352, 352]),
 array([355, 355]),
 array([359, 359]),
 array([364, 365]),
 array([367, 367]),
 array([369, 369]),
 array([373, 373]),
 array([376, 376]),
 array([378, 378]),
 array([380, 380]),
 array([382, 382]),
 array([386, 388]),
 array([391, 391]),
 array([399, 401]),
 array([405, 405]),
 array([408, 410]),
 array([413, 416]),
 array([423, 423]),
 array([427, 429]),
 array([432, 435]),
 array([437, 437]),
 array([439, 440]),
 array([443, 443]),
 array([448, 449]),
 array([451, 451]),
 array([453, 453]),
 array([455, 455]),
 array([459, 459]),
 array([461, 461]),
 array([464, 468]),
 array([470, 471]),
 array([473, 473]),
 array([476, 476]),
 array([478, 478]),
 array([482, 482]),
 array([487, 488]),
 array([491, 491]),
 array([495, 495]),
 array([498, 498]),
 array([501, 503]),
 array([505, 507]),
 array([514, 514]),
 array([518, 520]),
 array([522, 523]),
 array([525, 525]),
 array([528, 528]),
 array([530, 530]),
 array([532, 532]),
 array([534, 534]),
 array([538, 540]),
 array([544, 544]),
 array([550, 551]),
 array([556, 556]),
 array([558, 558]),
 array([568, 568]),
 array([571, 571]),
 array([573, 573]),
 array([577, 578]),
 array([582, 582]),
 array([584, 585]),
 array([592, 592]),
 array([597, 597]),
 array([599, 599]),
 array([603, 603]),
 array([605, 605]),
 array([607, 607]),
 array([609, 610]),
 array([612, 612]),
 array([616, 616]),
 array([618, 618]),
 array([621, 621]),
 array([623, 623]),
 array([625, 626]),
 array([628, 628]),
 array([630, 633]),
 array([636, 637]),
 array([639, 639]),
 array([642, 642]),
 array([644, 644]),
 array([647, 647]),
 array([651, 651]),
 array([653, 654]),
 array([656, 656]),
 array([661, 662]),
 array([666, 666]),
 array([668, 668]),
 array([670, 670]),
 array([672, 676]),
 array([682, 682]),
 array([684, 684]),
 array([687, 688]),
 array([690, 690]),
 array([692, 694]),
 array([696, 699]),
 array([705, 708]),
 array([713, 714]),
 array([719, 719]),
 array([726, 727]),
 array([729, 730]),
 array([736, 737]),
 array([739, 742]),
 array([744, 744]),
 array([748, 749]),
 array([753, 753]),
 array([758, 759]),
 array([762, 762]),
 array([766, 766]),
 array([771, 772]),
 array([774, 775]),
 array([778, 778]),
 array([780, 780]),
 array([782, 782]),
 array([786, 787]),
 array([789, 789]),
 array([791, 791]),
 array([793, 793]),
 array([796, 799]),
 array([803, 804]),
 array([807, 807]),
 array([809, 809]),
 array([811, 811]),
 array([814, 815]),
 array([817, 817]),
 array([819, 819]),
 array([821, 821]),
 array([827, 827]),
 array([831, 831]),
 array([833, 833]),
 array([837, 837]),
 array([842, 842]),
 array([846, 846]),
 array([849, 849]),
 array([851, 851]),
 array([854, 855]),
 array([858, 858]),
 array([865, 868]),
 array([870, 870]),
 array([872, 874]),
 array([880, 882]),
 array([884, 885]),
 array([890, 890]),
 array([892, 897]),
 array([899, 900]),
 array([902, 902]),
 array([908, 908]),
 array([912, 913]),
 array([915, 916]),
 array([920, 921]),
 array([924, 924]),
 array([927, 927]),
 array([930, 930]),
 array([933, 933]),
 array([941, 942]),
 array([946, 946]),
 array([950, 950]),
 array([953, 953]),
 array([957, 957]),
 array([960, 960]),
 array([963, 964]),
 array([967, 967]),
 array([969, 969]),
 array([972, 973]),
 array([975, 975]),
 array([978, 978]),
 array([981, 981]),
 array([983, 983]),
 array([985, 986]),
 array([991, 993]),
 array([995, 995])]


问:
Angular App cannot compile after update from V8 to V9
I have recently updated my angular app from V8 to V9 using this guide provided by the official Angular site. I followed all the steps from the guide and the app was successfully updated, but now when I try to build, I get loads of errors related to pipes directives and even components that I am using in my templates.

Here's one example for errors on pipes:

Cannot declare 'TimeAgoPipe' in an NgModule as it's not a part of the current compilation.

Another example of errors on directives:

Can't bind to 'ngModel' since it isn't a known property of 'input'

This code worked perfectly fine on Angular 8:

```<code><input required name="password" class="form-control mr-sm-2" type="password" placeholder="Password" [(ngModel)]="model.password"/>
</code>```

It can't even find components that I have created even though they have been declared in the app.module.ts file. It's giving me this error:

'app-nav' is not a known element:

If 'app-nav' is an Angular component, then verify that it is part of this module.

If 'app-nav' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

Here's my app.module.ts file where everything it is not finding has been included:

    import { BrowserModule, HammerGestureConfig, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser';
    import { NgModule, Injectable } from '@angular/core';
    import { HttpClientModule } from '@angular/common/http';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    import { RouterModule } from '@angular/router';
    import { JwtModule } from '@auth0/angular-jwt';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { BsDropdownModule, PaginationModule, ButtonsModule } from 'ngx-bootstrap';
    import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
    import { TabsModule } from 'ngx-bootstrap/tabs';
    import { NgxGalleryModule } from 'ngx-gallery';
    import { FileUploadModule } from 'ng2-file-upload';
    import { TimeAgoPipe } from 'time-ago-pipe';
    import { CommonModule, DatePipe } from '@angular/common';

    import { AppComponent } from './app.component';
    import { NavComponent } from './nav/nav.component';
    import { AuthService } from './_services/auth.service';
    import { HomeComponent } from './home/home.component';
    import { RegisterComponent } from './register/register.component';
    import { ErrorInterceptorProvider } from './_services/error.interceptor';
    import { MembersListComponent } from './members/members-list/members-list.component';
    import { ListsComponent } from './lists/lists.component';
    import { MessagesComponent } from './messages/messages.component';
    import { appRoutes } from './routes';
    import { MemberCardComponent } from './members/member-card/member-card.component';
    import { environment } from 'src/environments/environment';
    import { MemberDetailComponent } from './members/member-detail/member-detail.component';
    import { UserService } from './_services/user.service';
    import { AlertifyService } from './_services/alertify.service';
    import { AuthGuard } from './_guards/auth.guard';
    import { MemberDetailResolver } from './_resolvers/member-detail.resolver';
    import { MemberListResolver } from './_resolvers/member-list.resolver';
    import { MemberEditComponent } from './members/member-edit/member-edit.component';
    import { MemberEditResolver } from './_resolvers/member-edit.resolver';
    import { PreventUsavedChangesGuard } from './_guards/prevent-usaved-changes.guard';
    import { DetailCardContentComponent } from './members/detail-card-content/detail-card-content.component';
    import { PhotoEditorComponent } from './members/photo-editor/photo-editor.component';

    export function tokenGetter() {
      return localStorage.getItem(environment.authTokenName);
    }
    @Injectable()
    export class CustomHammerConfig extends HammerGestureConfig {
      overrides = {
        pinch: { enable: false },
        rotate: { enable: false }
      };
    }
    @NgModule({
      declarations: [
        AppComponent,
        NavComponent,
        HomeComponent,
        RegisterComponent,
        MembersListComponent,
        ListsComponent,
        MessagesComponent,
        MemberCardComponent,
        MemberDetailComponent,
        MemberEditComponent,
        DetailCardContentComponent,
        PhotoEditorComponent,
        TimeAgoPipe,
        DatePipe
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        FormsModule,
        ReactiveFormsModule,
        CommonModule,
        BsDropdownModule.forRoot(),
        TabsModule.forRoot(),
        BsDatepickerModule.forRoot(),
        ButtonsModule.forRoot(),
        BrowserAnimationsModule,
        RouterModule.forRoot(appRoutes),
        PaginationModule.forRoot(),
        NgxGalleryModule,
        FileUploadModule,
        JwtModule.forRoot({
          config: {
            tokenGetter,
            whitelistedDomains: environment.routesWithAuthorization,
            blacklistedRoutes: environment.routesWithoutAuthorization
          }
        })
      ],
      providers: [
        AuthService,
        UserService,
        AlertifyService,
        AuthGuard,
        PreventUsavedChangesGuard,
        MemberDetailResolver,
        MemberListResolver,
        MemberEditResolver,
        ErrorInterceptorProvider,
        { provide: HAMMER_GESTURE_CONFIG, useClass: CustomHammerConfig }
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
```

Update

The solution suggested by Instinct and from https://github.com/AndrewPoyntz/time-ago-pipe/issues/33 works. You have to remember to disable AOT compilation on angular.json though

答:
It looks like this module isn't updated for Angular 9. I found a workaround here

https://github.com/AndrewPoyntz/time-ago-pipe/issues/33

```<code>import { TimeAgoPipe } from 'time-ago-pipe';

@Pipe({
    name: 'timeAgo',
    pure: false
})
export class TimeAgoExtendsPipe extends TimeAgoPipe {}

@NgModule({
    declarations: [
        TimeAgoExtendsPipe,
...
</code>```

Body:
I have recently updated my angular app from V8 to V9 using this guide provided by the official Angular site. I followed all the steps from the guide and the app was successfully updated, but now when I try to build, I get loads of errors related to pipes directives and even components that I am using in my templates.

Here's one example for errors on pipes:

Cannot declare 'TimeAgoPipe' in an NgModule as it's not a part of the current compilation.

Another example of errors on directives:

Can't bind to 'ngModel' since it isn't a known property of 'input'

This code worked perfectly fine on Angular 8:

<input required name="password" class="form-control mr-sm-2" type="password" placeholder="Password" [(ngModel)]="model.password"/>

It can't even find components that I have created even though they have been declared in the app.module.ts file. It's giving me this error:

'app-nav' is not a known element:

If 'app-nav' is an Angular component, then verify that it is part of this module.

If 'app-nav' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

Here's my app.module.ts file where everything it is not finding has been included:

    import { BrowserModule, HammerGestureConfig, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser';
    import { NgModule, Injectable } from '@angular/core';
    import { HttpClientModule } from '@angular/common/http';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    import { RouterModule } from '@angular/router';
    import { JwtModule } from '@auth0/angular-jwt';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { BsDropdownModule, PaginationModule, ButtonsModule } from 'ngx-bootstrap';
    import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
    import { TabsModule } from 'ngx-bootstrap/tabs';
    import { NgxGalleryModule } from 'ngx-gallery';
    import { FileUploadModule } from 'ng2-file-upload';
    import { TimeAgoPipe } from 'time-ago-pipe';
    import { CommonModule, DatePipe } from '@angular/common';

    import { AppComponent } from './app.component';
    import { NavComponent } from './nav/nav.component';
    import { AuthService } from './_services/auth.service';
    import { HomeComponent } from './home/home.component';
    import { RegisterComponent } from './register/register.component';
    import { ErrorInterceptorProvider } from './_services/error.interceptor';
    import { MembersListComponent } from './members/members-list/members-list.component';
    import { ListsComponent } from './lists/lists.component';
    import { MessagesComponent } from './messages/messages.component';
    import { appRoutes } from './routes';
    import { MemberCardComponent } from './members/member-card/member-card.component';
    import { environment } from 'src/environments/environment';
    import { MemberDetailComponent } from './members/member-detail/member-detail.component';
    import { UserService } from './_services/user.service';
    import { AlertifyService } from './_services/alertify.service';
    import { AuthGuard } from './_guards/auth.guard';
    import { MemberDetailResolver } from './_resolvers/member-detail.resolver';
    import { MemberListResolver } from './_resolvers/member-list.resolver';
    import { MemberEditComponent } from './members/member-edit/member-edit.component';
    import { MemberEditResolver } from './_resolvers/member-edit.resolver';
    import { PreventUsavedChangesGuard } from './_guards/prevent-usaved-changes.guard';
    import { DetailCardContentComponent } from './members/detail-card-content/detail-card-content.component';
    import { PhotoEditorComponent } from './members/photo-editor/photo-editor.component';

    export function tokenGetter() {
      return localStorage.getItem(environment.authTokenName);
    }
    @Injectable()
    export class CustomHammerConfig extends HammerGestureConfig {
      overrides = {
        pinch: { enable: false },
        rotate: { enable: false }
      };
    }
    @NgModule({
      declarations: [
        AppComponent,
        NavComponent,
        HomeComponent,
        RegisterComponent,
        MembersListComponent,
        ListsComponent,
        MessagesComponent,
        MemberCardComponent,
        MemberDetailComponent,
        MemberEditComponent,
        DetailCardContentComponent,
        PhotoEditorComponent,
        TimeAgoPipe,
        DatePipe
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        FormsModule,
        ReactiveFormsModule,
        CommonModule,
        BsDropdownModule.forRoot(),
        TabsModule.forRoot(),
        BsDatepickerModule.forRoot(),
        ButtonsModule.forRoot(),
        BrowserAnimationsModule,
        RouterModule.forRoot(appRoutes),
        PaginationModule.forRoot(),
        NgxGalleryModule,
        FileUploadModule,
        JwtModule.forRoot({
          config: {
            tokenGetter,
            whitelistedDomains: environment.routesWithAuthorization,
            blacklistedRoutes: environment.routesWithoutAuthorization
          }
        })
      ],
      providers: [
        AuthService,
        UserService,
        AlertifyService,
        AuthGuard,
        PreventUsavedChangesGuard,
        MemberDetailResolver,
        MemberListResolver,
        MemberEditResolver,
        ErrorInterceptorProvider,
        { provide: HAMMER_GESTURE_CONFIG, useClass: CustomHammerConfig }
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {}

Update

The solution suggested by Instinct and from https://github.com/AndrewPoyntz/time-ago-pipe/issues/33 works. You have to remember to disable AOT compilation on angular.json though

Body:
It looks like this module isn't updated for Angular 9. I found a workaround here

https://github.com/AndrewPoyntz/time-ago-pipe/issues/33

import { TimeAgoPipe } from 'time-ago-pipe';

@Pipe({
    name: 'timeAgo',
    pure: false
})
export class TimeAgoExtendsPipe extends TimeAgoPipe {}

@NgModule({
    declarations: [
        TimeAgoExtendsPipe,
...


问:
How do I change the name of an existing project in Visual Studio 2008?
How to change the name of a project in VS 2008 to something else? I have already created a project and now I want to change its name.</p>

答:
Several ways:

Right click the project and select Rename

Select and press F2

Click-wait-click

To change the name of the output assembly you need to right click and select Properties. Change Assembly Name in the Application tab.


问:
DBeaver can only see default PostgreSQL database in connection
I use DBeaver v 5.2.5 on Windows and use it to connect to PostgreSQL databases.

To create a connection, I must specify the database and I have no mean to see other databases on the same server.

A colleague using DBeaver 5.3 on Mac has an option to see all databases, not just the default one.

Is there an equivalent setup on the windows version?

答: On the connection, right-click -> Edit connection -> Connection settings -> on the tabbed panel, select PostgreSQL, check the box Show all databases.


问:
Function that returns one value from two columns
I have a DataFrame df:

```<code>    Country    Currency
 1   China       YEN
 2   USA         USD
 3   Russia      USD
 4   Germany     EUR
 5   Nigeria     NGN
 6   Nigeria     USD
 7   China       CNY
 8   USA         EUR
 9   Nigeria     EUR
10   Sweden      SEK
</code>```

I want to make a function that reads both of these columns, by column name, and returns a value that indicates if the currency is a local currency or not.

Result would look like this:

```<code>    Country    Currency    LCY?
 1   China       YEN        0
 2   USA         USD        1
 3   Russia      USD        0
 4   Germany     EUR        1
 5   Nigeria     NGN        1
 6   Nigeria     USD        0
 7   China       CNY        1
 8   USA         EUR        0
 9   Nigeria     EUR        0
10   Sweden      SEK        1
</code>```

I tried this, but it didn't work:

```<code>LOCAL_CURRENCY =  {'China':'CNY',
                    'USA':'USD',
                    'Russia':'RUB',
                    'Germany':'EUR',
                    'Nigeria':'NGN',
                    'Sweden':'SEK'}
def f(x,y):
        if x in LOCAL_CURRENCY and y in LOCAL_CURRENCY:
            return (1)
        else:
            return (0)
</code>```

Any thoughts?

答:
You can use map and compare:

```<code>df['LCY'] = df['Country'].map(LOCAL_CURRENCY).eq(df['Currency']).astype(int)
</code>```

Output:

```<code>    Country Currency  LCY
1     China      YEN    0
2       USA      USD    1
3    Russia      USD    0
4   Germany      EUR    1
5   Nigeria      NGN    1
6   Nigeria      USD    0
7     China      CNY    1
8       USA      EUR    0
9   Nigeria      EUR    0
10   Sweden      SEK    1
</code>```

Body:
I have a DataFrame df:

    Country    Currency
 1   China       YEN
 2   USA         USD
 3   Russia      USD
 4   Germany     EUR
 5   Nigeria     NGN
 6   Nigeria     USD
 7   China       CNY
 8   USA         EUR
 9   Nigeria     EUR
10   Sweden      SEK

I want to make a function that reads both of these columns, by column name, and returns a value that indicates if the currency is a local currency or not.

Result would look like this:

    Country    Currency    LCY?
 1   China       YEN        0
 2   USA         USD        1
 3   Russia      USD        0
 4   Germany     EUR        1
 5   Nigeria     NGN        1
 6   Nigeria     USD        0
 7   China       CNY        1
 8   USA         EUR        0
 9   Nigeria     EUR        0
10   Sweden      SEK        1

I tried this, but it didn't work:

LOCAL_CURRENCY =  {'China':'CNY',
                    'USA':'USD',
                    'Russia':'RUB',
                    'Germany':'EUR',
                    'Nigeria':'NGN',
                    'Sweden':'SEK'}
def f(x,y):
        if x in LOCAL_CURRENCY and y in LOCAL_CURRENCY:
            return (1)
        else:
            return (0)

Any thoughts?

Body:
You can use map and compare:

df['LCY'] = df['Country'].map(LOCAL_CURRENCY).eq(df['Currency']).astype(int)

Output:

    Country Currency  LCY
1     China      YEN    0
2       USA      USD    1
3    Russia      USD    0
4   Germany      EUR    1
5   Nigeria      NGN    1
6   Nigeria      USD    0
7     China      CNY    1
8       USA      EUR    0
9   Nigeria      EUR    0
10   Sweden      SEK    1


问:
MINIX 3.3.0: How do I add a new command binary?
I am trying to make a new command in the src/bin folder as a test (called "tcom" for test command, not to be confused with "test" command). I already tried editing src/bin/tcom/Makefile to add the program name and src/bin/Makefile to include the program name.

However, it's never there when I build Minix. Is there anything I need to include in the command source code (written in C)? Any other Makefile references?

src/bin/tcom/tcom.c

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

int main() {

    (void)printf("Hello World!");

    return 0;

}
</code>```

src/bin/tcom/Makefile

```<code>#   $NetBSD: Makefile,v 1.9 1997/07/20 22:36:37 christos Exp $
#   @(#)Makefile    8.1 (Berkeley) 5/31/93

PROG=   tcom
SRCS=   tcom.c

.include <bsd.prog.mk>
</code>```

src/bin/Makefile

```<code>#   $NetBSD: Makefile,v 1.22 2007/12/31 15:31:24 ad Exp $
#   @(#)Makefile    8.1 (Berkeley) 5/31/93

#__MINIX: chio mt ps

SUBDIR= cat chmod cp csh date dd df domainname echo ed expr hostname \
    kill ksh ln ls mkdir mv pax ps pwd rcp rcmd rm rmdir sh \
    sleep stty sync tcom test \

.include <bsd.subdir.mk>
</code>```

(ported over from minix3 group because people are more likely to answer here)

答: Your command is probably built, but not installed in the destination tree. You should probably add it to distrib/sets/lists/minix-base/mi for a start (and minix-debug if it applies). Also consider locating your code in src/minix/bin if it is MINIX-specific; src/bin is more appropriate for NetBSD inherited code.

Body:
I am trying to make a new command in the src/bin folder as a test (called "tcom" for test command, not to be confused with "test" command). I already tried editing src/bin/tcom/Makefile to add the program name and src/bin/Makefile to include the program name.

However, it's never there when I build Minix. Is there anything I need to include in the command source code (written in C)? Any other Makefile references?

src/bin/tcom/tcom.c

#include <stdio.h>

int main() {

    (void)printf("Hello World!");

    return 0;

}

src/bin/tcom/Makefile

#   $NetBSD: Makefile,v 1.9 1997/07/20 22:36:37 christos Exp $
#   @(#)Makefile    8.1 (Berkeley) 5/31/93

PROG=   tcom
SRCS=   tcom.c

.include <bsd.prog.mk>

src/bin/Makefile

#   $NetBSD: Makefile,v 1.22 2007/12/31 15:31:24 ad Exp $
#   @(#)Makefile    8.1 (Berkeley) 5/31/93

#__MINIX: chio mt ps

SUBDIR= cat chmod cp csh date dd df domainname echo ed expr hostname \
    kill ksh ln ls mkdir mv pax ps pwd rcp rcmd rm rmdir sh \
    sleep stty sync tcom test \

.include <bsd.subdir.mk>

(ported over from minix3 group because people are more likely to answer here)


问:
jQuery volume UI different than what I pushed out?
I recently finished the UI for a volume slider and then published the code to my website. However, the slider design that shows up on the website is different than the one I had designed.

Why is this and how can I fix this?

Original:

Final (shown on website):

```<code><link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</code>```

$(function() {
  // var audioElement = $("<audio>");

  function setVolume(myVolume) {
    if (audioElement != undefined) {
      audioElement.volume = myVolume;
    }
  }

  $("#volume").slider({
    min: 0,
    max: 1,
    value: 1,
    step: 0.01,
    range: "min",
    slide: function(event, ui) {
      setVolume(ui.value);
    }
  });
});

$("#player").hover(
  function() {
    $('.ui-slider-range-min').css("background-color", "#483EF1")
    $('.ui-slider-handle').css("display", "block")
  },
  function() {
    $('.ui-slider-range-min').css("background-color", "#B3B3B3")
    $('.ui-slider-handle').css("display", "none")
  }
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* audioUtilities */

.audioUtilitiesDiv {
  display: inline-block;
  /* background-color: darkblue; */
  width: 350px;
  height: 100%;
  position: fixed;
  right: 0px;
}

#player {
  width: 140px;
  height: 30px;
  /* position: relative; */
  /* margin: 0 auto; */
  bottom: 40px;
  /* background: black; */
  position: fixed;
  right: 15px;
}

/* #player:hover {
  background: #483EF1;
} */

i {
  position: absolute;
  margin-top: -6px;
  color: #666;
}

i.fa-volume-down {
  margin-left: -8px;
}

i.fa-volume-up {
  margin-right: -8px;
  right: 0;
}

#volume {
  position: absolute;
  left: 24px;
  margin: 0 auto;
  height: 5px;
  width: 100px;
  background: #505050;
  border-radius: 15px;
}

.ui-slider-range-min {
  height: 5px;
  width: 300px;
  position: absolute;
  background: #B3B3B3;
  border: none;
  border-radius: 10px;
  outline: none;
}

/* .ui-slider-range-min:hover {
  background: #483EF1;
} */

.ui-slider-handle {
  width: 16px;
  height: 16px;
  border-radius: 20px;
  background: #FFF;
  position: absolute;
  margin-left: -8px;
  margin-top: -6px;
  cursor: pointer;
  outline: none;
  display: none;
}

/* Volume slider */</code>```

```

Update:

It seems like jquery ui file is not found I get this error in the console:

file://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css net::ERR_FILE_NOT_FOUND

(Do I have to do something in the terminal maybe? Install it?)

答:
try this: </p>

```<code><link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</code>```

<p>instead of this: </p>

```<code><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</code>```

Body:
I recently finished the UI for a volume slider and then published the code to my website. However, the slider design that shows up on the website is different than the one I had designed.

Why is this and how can I fix this?

Original:

Final (shown on website):

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

$(function() {
  // var audioElement = $("<audio>");

  function setVolume(myVolume) {
    if (audioElement != undefined) {
      audioElement.volume = myVolume;
    }
  }

  $("#volume").slider({
    min: 0,
    max: 1,
    value: 1,
    step: 0.01,
    range: "min",
    slide: function(event, ui) {
      setVolume(ui.value);
    }
  });
});

$("#player").hover(
  function() {
    $('.ui-slider-range-min').css("background-color", "#483EF1")
    $('.ui-slider-handle').css("display", "block")
  },
  function() {
    $('.ui-slider-range-min').css("background-color", "#B3B3B3")
    $('.ui-slider-handle').css("display", "none")
  }
);

/* audioUtilities */

.audioUtilitiesDiv {
  display: inline-block;
  /* background-color: darkblue; */
  width: 350px;
  height: 100%;
  position: fixed;
  right: 0px;
}

#player {
  width: 140px;
  height: 30px;
  /* position: relative; */
  /* margin: 0 auto; */
  bottom: 40px;
  /* background: black; */
  position: fixed;
  right: 15px;
}

/* #player:hover {
  background: #483EF1;
} */

i {
  position: absolute;
  margin-top: -6px;
  color: #666;
}

i.fa-volume-down {
  margin-left: -8px;
}

i.fa-volume-up {
  margin-right: -8px;
  right: 0;
}

#volume {
  position: absolute;
  left: 24px;
  margin: 0 auto;
  height: 5px;
  width: 100px;
  background: #505050;
  border-radius: 15px;
}

.ui-slider-range-min {
  height: 5px;
  width: 300px;
  position: absolute;
  background: #B3B3B3;
  border: none;
  border-radius: 10px;
  outline: none;
}

/* .ui-slider-range-min:hover {
  background: #483EF1;
} */

.ui-slider-handle {
  width: 16px;
  height: 16px;
  border-radius: 20px;
  background: #FFF;
  position: absolute;
  margin-left: -8px;
  margin-top: -6px;
  cursor: pointer;
  outline: none;
  display: none;
}

/* Volume slider */

Update:

It seems like jquery ui file is not found I get this error in the console:

file://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css net::ERR_FILE_NOT_FOUND

(Do I have to do something in the terminal maybe? Install it?)

Body:
try this:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

instead of this:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">


问:
Assignment as parameter in jetpack compose
What is the difference between  Text(text="Hi") and Text("Hi")?

How can I make CustomText( text = "Hi")

```<code>class MainActivity : Base() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        MaterialTheme {
            Column {
                Text(text = "Hi")
                Text("Hi")

                //CustomText(text = "Hi")
                CustomText("Hi")
            }
        }
    }
}
}

open class Base : AppCompatActivity() {
    fun CustomText(inputString: String) {
        Text(
            inputString,
            style = TextStyle(color = Color.Green, fontSize = 22.sp)
        )
    }
}
</code>```

答:
What is the difference between Text(text="Hi") and Text("Hi")?

There is no difference between these.  The text="Hi" version is simply using a named argument.

How can I make CustomText( text = "Hi")

Your CustomText needs a String argument named text.  That is, you should change

```<code>fun CustomText(inputString: String) {
</code>```

to

```<code>fun CustomText(text: String) {
</code>```

Body:
What is the difference between  Text(text="Hi") and Text("Hi")?

How can I make CustomText( text = "Hi")

class MainActivity : Base() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        MaterialTheme {
            Column {
                Text(text = "Hi")
                Text("Hi")

                //CustomText(text = "Hi")
                CustomText("Hi")
            }
        }
    }
}
}

open class Base : AppCompatActivity() {
    fun CustomText(inputString: String) {
        Text(
            inputString,
            style = TextStyle(color = Color.Green, fontSize = 22.sp)
        )
    }
}

Body:
What is the difference between Text(text="Hi") and Text("Hi")?

There is no difference between these.  The text="Hi" version is simply using a named argument.

How can I make CustomText( text = "Hi")

Your CustomText needs a String argument named text.  That is, you should change

fun CustomText(inputString: String) {

to

fun CustomText(text: String) {


问:
How can I implement a boolean tag search in SQL?
Given a table of items, a table of tags and a join table between them, what is a good and efficient way to implement queries of the form:

p1 AND p2 AND ... AND pn AND NOT n1 AND NOT n2 ... AND NOT nk

I am using SQL. So to find all items that match all tags p1...pn and none of n1...nk?

Is there a good "standard" solution for this?

答:
Difficult to say without knowing your schema, but something like this would work:

```<code>select article_id from articles
inner join tag t1 on t1.article_id=articles.article_id and t1.tag='included_tag'
inner join tag t2 on t2.article_id=articles.article_id and t2.tag='another_included_tag'
left outer join tag t3 on t3.article_id=articles.article_id and t3.tag='dont_include_tag'
left outer join tag t4 on t4.article_id=articles.article_id and t4.tag='also_dont_include_tag'
where t3.tag_id is null and t4.tag_id is null
</code>```

inner join to tags that are to be included, and do an anti-join (outer join + where a required column is null) to tags that are not to be included

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

Body:
Difficult to say without knowing your schema, but something like this would work:

select article_id from articles
inner join tag t1 on t1.article_id=articles.article_id and t1.tag='included_tag'
inner join tag t2 on t2.article_id=articles.article_id and t2.tag='another_included_tag'
left outer join tag t3 on t3.article_id=articles.article_id and t3.tag='dont_include_tag'
left outer join tag t4 on t4.article_id=articles.article_id and t4.tag='also_dont_include_tag'
where t3.tag_id is null and t4.tag_id is null

inner join to tags that are to be included, and do an anti-join (outer join + where a required column is null) to tags that are not to be included

OwnerDisplayName: ʞɔıu


问:
multi-language app not working (javascript)
I am trying to build a dice game with three languages: English, Italian and German.
I've made three js file with the words to be translated, and then with querySelector and getElementById i replace the words in the three different languages.
The problem is: when i press one of the three button the language switch correctly, but then it remain stuck forever. For example, if i press "italian" button, the language change in italian but if i press english or german nothing happens. I cant figure out whats wrong, can someone help me? thanks

//set date from moment.js
var mydate = new Date();

moment.locale('en');
mydate=moment().format('LL');
document.getElementById("date").innerHTML=mydate;

//create a new element
var langScript = document.createElement('script');

//declaration variables
var lang='winner!',player=['player 1','player 2'];

startGame();

var prefix1='';
var prefix2='';
var prefix3='';

    //when i click the language IT button, the language's variables were changed
document.querySelector('.btn-it').addEventListener('click',function ita(){
    //window.location.reload();

    moment.locale('it');
    mydate=moment().format('LL');

    document.getElementById("date").innerHTML=mydate;

    langScript.src="./it.js";
    document.head.appendChild(langScript);

        langScript.addEventListener('load', function  () {
            console.log('test');
            document.getElementById("btn-new").innerHTML=prefix1+ui.textButtonNewGame;
            document.getElementById("btn-roll").innerHTML=prefix2+ui.textButtonRollDice;
            document.getElementById("btn-hold").innerHTML=prefix3+ui.textButtonHold;
            document.getElementById("currentTXT-0").innerHTML=ui.textCurrentInBotton;
            document.getElementById("currentTXT-1").innerHTML=ui.textCurrentInBotton;
            document.getElementById("name-0").innerHTML=ui.namePlayer1;
            document.getElementById("name-1").innerHTML=ui.namePlayer2;
            document.getElementById("btn-en").innerHTML=ui.buttonChangeLanguageEnglish;
            document.getElementById("btn-it").innerHTML=ui.buttonChangeLanguageItalian;
            document.getElementById("btn-de").innerHTML=ui.buttonChangeLanguageGerman;
            lang =ui.textWinner;
            player[0]=ui.namePlayer1;
            player[1]=ui.namePlayer2;

    })

})

//when i click the language DE button, the language's variables were changed
document.querySelector('.btn-de').addEventListener('click',function ger(){

    moment.locale('de');
    mydate=moment().format('LL');

    document.getElementById("date").innerHTML=mydate;

    langScript.src="./de.js";
    document.head.appendChild(langScript);

    langScript.addEventListener('load', function() {
        console.log('test');
        document.getElementById("btn-new").innerHTML=prefix1+ui.textButtonNewGame;
        document.getElementById("btn-roll").innerHTML=prefix2+ui.textButtonRollDice;
        document.getElementById("btn-hold").innerHTML=prefix3+ui.textButtonHold;
        document.getElementById("currentTXT-0").innerHTML=ui.textCurrentInBotton;
        document.getElementById("currentTXT-1").innerHTML=ui.textCurrentInBotton;
        document.getElementById("name-0").innerHTML=ui.namePlayer1;
        document.getElementById("name-1").innerHTML=ui.namePlayer2;
        document.getElementById("btn-en").innerHTML=ui.buttonChangeLanguageEnglish;
        document.getElementById("btn-it").innerHTML=ui.buttonChangeLanguageItalian;
        document.getElementById("btn-de").innerHTML=ui.buttonChangeLanguageGerman;
        lang =ui.textWinner;
        player[0]=ui.namePlayer1;
        player[1]=ui.namePlayer2;

    })
        //window.location.reload();

})

//when i click the language EN button, the language's variables were changed
document.querySelector('.btn-en').addEventListener('click',function eng(){

    langScript.src="./en.js";
    document.head.appendChild(langScript);

    langScript.addEventListener('load', function() {
        console.log('test');
        document.getElementById("btn-new").innerHTML=prefix1+ui.textButtonNewGame;
        document.getElementById("btn-roll").innerHTML=prefix2+ui.textButtonRollDice;
        document.getElementById("btn-hold").innerHTML=prefix3+ui.textButtonHold;
        document.getElementById("currentTXT-0").innerHTML=ui.textCurrentInBotton;
        document.getElementById("currentTXT-1").innerHTML=ui.textCurrentInBotton;
        document.getElementById("name-0").innerHTML=ui.namePlayer1;
        document.getElementById("name-1").innerHTML=ui.namePlayer2;
        document.getElementById("btn-en").innerHTML=ui.buttonChangeLanguageEnglish;
        document.getElementById("btn-it").innerHTML=ui.buttonChangeLanguageItalian;
        document.getElementById("btn-de").innerHTML=ui.buttonChangeLanguageGerman;
        lang =ui.textWinner;
        player[0]=ui.namePlayer1;
        player[1]=ui.namePlayer2;

    })

        //window.location.reload();

})```

答:
Instead of having three different JS files for each language, make an array with all the strings inside, like ("languages" variable):

```<code>var selected_language=0;
//0=English
//1=Italian
//2=German
//Allow the player to change this number before the game starts.

var languages = [
/*ENGLISH*/["winner!","player1","player2","more english..."],
/*ITALIAN*/["winner in italian!","player1 in italian","player2 in italian","more italian..."],
/*GERMAN*/["winner in german!","player1 in german","player2 in german","more german..."]
];

alert( languages[selected_language][0] );
//Gives "winner!", as the selected language is English (0)
</code>```

And depending on the amount of translated strings, you maybe want to move it to a JSON file.

But you can start with this.

You could otherwise put the strings inside objects but I think that this goes quicker.

Sorry if something was hard to understand (I wrote this on mobile).
Good luck!

Body:
Instead of having three different JS files for each language, make an array with all the strings inside, like ("languages" variable):

var selected_language=0;
//0=English
//1=Italian
//2=German
//Allow the player to change this number before the game starts.

var languages = [
/*ENGLISH*/["winner!","player1","player2","more english..."],
/*ITALIAN*/["winner in italian!","player1 in italian","player2 in italian","more italian..."],
/*GERMAN*/["winner in german!","player1 in german","player2 in german","more german..."]
];

alert( languages[selected_language][0] );
//Gives "winner!", as the selected language is English (0)

And depending on the amount of translated strings, you maybe want to move it to a JSON file.

But you can start with this.

You could otherwise put the strings inside objects but I think that this goes quicker.

Sorry if something was hard to understand (I wrote this on mobile).
Good luck!


问:
R package "infer" - Iterative bootstrapping / looping over column names
I'm bootstrapping with the infer package.
The statistic of interest is the mean, example data is given by a tibble with 3 columns and 5 rows. My real tibble has 86 rows and 40 columns. For every column I want to do a bootstrap simulation, like shown below for the column "x" in tibble "test_tibble".

```<code>library(infer)
library(tidyverse)

test_tibble <- tibble(x = 1:5, y = 6:10, z = 11:15)

# A tibble: 5 x 3
      x     y     z
  <int> <int> <int>
1     1     6    11
2     2     7    12
3     3     8    13
4     4     9    14
5     5    10    15

specify(test_tibble, response = x) %>%
  generate(reps = 100, type = "bootstrap") %>%
  calculate(stat = "mean") %>%
  summarise(
    lower_CI = quantile(probs = 0.025, stat),
    upper_CI = quantile(probs = 0.975, stat)
  )
# A tibble: 1 x 2
  lower_CI upper_CI
     <dbl>    <dbl>
1     2.10        4
</code>```

I am now looking for a way of doing the same thing for the other columns in my tibble. I have tried a for-loop like this:

```<code>for (i in 1:ncol(test_tibble)){

  var_name <- names(test_tibble)[i]

  specify(test_tibble, response = var_name) %>%
  generate(reps = 100, type = "bootstrap") %>%
  calculate(stat = "mean") %>%
  summarise(
    lower_CI = quantile(probs = 0.025, stat),
    upper_CI = quantile(probs = 0.975, stat)
  )
}
</code>```

Unfortunately, this returns the follwing error

```<code>Error: The response variable `var_name` cannot be found in this dataframe.
</code>```

Is there any way of iterating over the columns x, y and z without entering them manually as arguments for "response"? That'd be quite tedious for 40 columns.

答:
This is a tricky question with a tricky answer.

Take a look at the response argument of the specify function in documentation:

The variable name in x that will serve as the response. This is alternative to using the formula argument.

With this in mind I modified the code to automate the process, adding one more column to the original dataframe and using the formula  argument to obtain the same result, using a column of ones as explanatory variable.

```<code>library(infer)
library(tidyverse)

test_tibble <- tibble(x = 1:5, y = 6:10, z = 11:15, w = seq(1, 1, length.out = 5))

for (i in 1:ncol(test_tibble)){

  var_name <- names(test_tibble)[i]

  specify(test_tibble, formula = eval(parse(text = paste0(var_name, "~", "w"))))[, 1] %>%
    generate(reps = 100, type = "bootstrap") %>%
    calculate(stat = "mean") %>%
    summarise(
      lower_CI = quantile(probs = 0.025, stat),
      upper_CI = quantile(probs = 0.975, stat)
    )
}
</code>```

Hope it helps

Body:
I'm bootstrapping with the infer package.
The statistic of interest is the mean, example data is given by a tibble with 3 columns and 5 rows. My real tibble has 86 rows and 40 columns. For every column I want to do a bootstrap simulation, like shown below for the column "x" in tibble "test_tibble".

library(infer)
library(tidyverse)

test_tibble <- tibble(x = 1:5, y = 6:10, z = 11:15)

# A tibble: 5 x 3
      x     y     z
  <int> <int> <int>
1     1     6    11
2     2     7    12
3     3     8    13
4     4     9    14
5     5    10    15

specify(test_tibble, response = x) %>%
  generate(reps = 100, type = "bootstrap") %>%
  calculate(stat = "mean") %>%
  summarise(
    lower_CI = quantile(probs = 0.025, stat),
    upper_CI = quantile(probs = 0.975, stat)
  )
# A tibble: 1 x 2
  lower_CI upper_CI
     <dbl>    <dbl>
1     2.10        4

I am now looking for a way of doing the same thing for the other columns in my tibble. I have tried a for-loop like this:

for (i in 1:ncol(test_tibble)){

  var_name <- names(test_tibble)[i]

  specify(test_tibble, response = var_name) %>%
  generate(reps = 100, type = "bootstrap") %>%
  calculate(stat = "mean") %>%
  summarise(
    lower_CI = quantile(probs = 0.025, stat),
    upper_CI = quantile(probs = 0.975, stat)
  )
}

Unfortunately, this returns the follwing error

Error: The response variable `var_name` cannot be found in this dataframe.

Is there any way of iterating over the columns x, y and z without entering them manually as arguments for "response"? That'd be quite tedious for 40 columns.

Body:
This is a tricky question with a tricky answer.

Take a look at the response argument of the specify function in documentation:

The variable name in x that will serve as the response. This is alternative to using the formula argument.

With this in mind I modified the code to automate the process, adding one more column to the original dataframe and using the formula  argument to obtain the same result, using a column of ones as explanatory variable.

library(infer)
library(tidyverse)

test_tibble <- tibble(x = 1:5, y = 6:10, z = 11:15, w = seq(1, 1, length.out = 5))

for (i in 1:ncol(test_tibble)){

  var_name <- names(test_tibble)[i]

  specify(test_tibble, formula = eval(parse(text = paste0(var_name, "~", "w"))))[, 1] %>%
    generate(reps = 100, type = "bootstrap") %>%
    calculate(stat = "mean") %>%
    summarise(
      lower_CI = quantile(probs = 0.025, stat),
      upper_CI = quantile(probs = 0.975, stat)
    )
}

Hope it helps


问:
How to search for values in TinyDB
I would like to search my database for a value. I know you can do this for a key with db.search() but there does not seem to be any kind of similar function for searching for a value

I've tried using the contains() function but I have the same issue. It checks if the key is contained in the database. I would like to know if a certain value is contained in the database.

I would like to do something like this that would search for values in tinydb

db.search('value')
```

If I was able to execute the above command and get the value(if it does exist) or Nothing if it doesn't that would be ideal. Alternatively, if the able returned True or False accordingly, that would be fine as well

答: I'm new here (doing some reading to see if TinyDB would even be applicable for my use case) so perhaps wrong, and also aware that this question is a little old. But I wonder if you can't address this by iterating over each field and searching within for your value. Then, you couldget the key or field wherein a value match was located.</p>

Title: How to search for values in TinyDB

Body:
I would like to search my database for a value. I know you can do this for a key with db.search() but there does not seem to be any kind of similar function for searching for a value

I've tried using the contains() function but I have the same issue. It checks if the key is contained in the database. I would like to know if a certain value is contained in the database.

I would like to do something like this that would search for values in tinydb

db.search('value')

If I was able to execute the above command and get the value(if it does exist) or Nothing if it doesn't that would be ideal. Alternatively, if the able returned True or False accordingly, that would be fine as well


问:
Defining jenkinsfile script path when creating pipeline
I want to checkout my repository from github.I create a pipeline and chose
Here are the steps that I followed

Click on new item on jenkins main page

Entered name and chose pipeline form list

Under Pipeline I chose definition as Pipeline script from SCM

Chose SCM as GIT

Under Repository entered the Repository Url with the credentials

Under Branches to build entered by branch as */my_branch_here

Now the jenkisfile does not belong in the root directory.Is there a way to naviagate to the directory using jenkins UI

答:
From Jenkins site,

In the Script Path field, specify the location (and name) of your
  Jenkinsfile. This location is the one that Jenkins checks out/clones
  the repository containing your Jenkinsfile, which should match that of
  the repository’s file structure. The default value of this field
  assumes that your Jenkinsfile is named "Jenkinsfile" and is located at
  the root of the repository.

Jenkinsfile should be committed to SCM and put the relative path of the Jenkinsfile in SCM repository root. Careful on the name(Jenkinsfile or JenkinsFile)!


问:
How can I align the tag with the displayed text?
I'm using the code below to build a shiny app but I don't get why text displays below the tag, it's supossed to be in the same line, anybody knows how to fix it?
Fixed the first answear in this question to make it display the text I was aiming for, but the tag is missaligned! I don't know if there is something else needed to write in this question!</p>

```<code>############################ GLOBAL #########################################

#1. App
if("shiny" %in% rownames(installed.packages()) == FALSE){ install.packages("shiny") }
library(shiny)

#2. Easier data handling
if("dplyr" %in% rownames(installed.packages()) == FALSE){ install.packages("dplyr") }
library(dplyr)

#3. Interactive graphs
if("plotly" %in% rownames(installed.packages()) == FALSE){ install.packages("plotly") }
library(plotly)

############################ UI #########################################
ui <- fluidPage(
  # Set bullet size
  tags$style(type='text/css', "#select {font-size: 16px !important} "),
  # 32px - h1() size || 24px - h2() size || 18.72px - h3() size || 16px - h4() size || 13.28px - h5() size
  navbarPage("Analysis",
             tabPanel("Home",
                      sidebarPanel(

                        h5(tags$li(textOutput("patent_scape_tag1")))
             ),
             mainPanel(
               plotlyOutput("treemap")
               )
             )
  ))

############################ SERVER #########################################

server <- function(input, output, session) {
  dtd1 <- NULL
  output$treemap <- renderPlotly({
    dtd1 <<- structure(list(V1 = structure(c(9L, 8L, 4L, 7L, 2L, 6L, 1L, 3L,
                                            5L, 10L, 13L, 11L, 12L), .Label = c("Apple", "Avocado", "Banana",
                                                                                "Carrot", "Mango", "Mushroom", "Onion", "Orange", "Pineapple",
                                                                                "Strawberry", "Sweet-lemon", "Watermelon", "Wildberry"), class = "factor"),
                           V2 = structure(c(4L, 3L, 9L, 11L, 12L, 2L, 1L, 6L, 10L, 5L,
                                            7L, 8L, 1L), .Label = c("23", "24", "36", "42", "43", "46",
                                                                    "48", "52", "56", "61", "82", "94"), class = "factor")), class = "data.frame", row.names = c(NA,
                                                                                -13L))
    p <- plot_ly(
      dtd1,
      labels = ~ V1,
      parents = NA,
      values = ~ V2,
      type = 'treemap',
      hovertemplate = "Ingredient: %{label}<br>Count: %{value}<extra></extra>"
    )

    p
  })

  output$patent_scape_tag1 <- renderText({
    paste0("Topic ",
           as.character(dtd1$V1[which.max(dtd1$V2)]),
           " reached the highest number!")
  })
}

shinyApp(ui, server)
</code>```

答:
Is it what you want ? </p>

```<code>ui <- fluidPage(

  tags$head(
    tags$style(HTML("#patent_scape_tag1 {display: list-item;}"))
  ),

  navbarPage("Analysis",
             tabPanel("Home",
                      sidebarPanel(
                        textOutput("patent_scape_tag1")
                      ),
                      mainPanel(
                        plotlyOutput("treemap")
                      )
             )
  )
)
</code>```

Body:
I'm using the code below to build a shiny app but I don't get why text displays below the tag, it's supossed to be in the same line, anybody knows how to fix it?
Fixed the first answear in this question to make it display the text I was aiming for, but the tag is missaligned! I don't know if there is something else needed to write in this question!

############################ GLOBAL #########################################

#1. App
if("shiny" %in% rownames(installed.packages()) == FALSE){ install.packages("shiny") }
library(shiny)

#2. Easier data handling
if("dplyr" %in% rownames(installed.packages()) == FALSE){ install.packages("dplyr") }
library(dplyr)

#3. Interactive graphs
if("plotly" %in% rownames(installed.packages()) == FALSE){ install.packages("plotly") }
library(plotly)

############################ UI #########################################
ui <- fluidPage(
  # Set bullet size
  tags$style(type='text/css', "#select {font-size: 16px !important} "),
  # 32px - h1() size || 24px - h2() size || 18.72px - h3() size || 16px - h4() size || 13.28px - h5() size
  navbarPage("Analysis",
             tabPanel("Home",
                      sidebarPanel(

                        h5(tags$li(textOutput("patent_scape_tag1")))
             ),
             mainPanel(
               plotlyOutput("treemap")
               )
             )
  ))

############################ SERVER #########################################

server <- function(input, output, session) {
  dtd1 <- NULL
  output$treemap <- renderPlotly({
    dtd1 <<- structure(list(V1 = structure(c(9L, 8L, 4L, 7L, 2L, 6L, 1L, 3L,
                                            5L, 10L, 13L, 11L, 12L), .Label = c("Apple", "Avocado", "Banana",
                                                                                "Carrot", "Mango", "Mushroom", "Onion", "Orange", "Pineapple",
                                                                                "Strawberry", "Sweet-lemon", "Watermelon", "Wildberry"), class = "factor"),
                           V2 = structure(c(4L, 3L, 9L, 11L, 12L, 2L, 1L, 6L, 10L, 5L,
                                            7L, 8L, 1L), .Label = c("23", "24", "36", "42", "43", "46",
                                                                    "48", "52", "56", "61", "82", "94"), class = "factor")), class = "data.frame", row.names = c(NA,
                                                                                -13L))
    p <- plot_ly(
      dtd1,
      labels = ~ V1,
      parents = NA,
      values = ~ V2,
      type = 'treemap',
      hovertemplate = "Ingredient: %{label}
Count: %{value}<extra></extra>"
    )

    p
  })

  output$patent_scape_tag1 <- renderText({
    paste0("Topic ",
           as.character(dtd1$V1[which.max(dtd1$V2)]),
           " reached the highest number!")
  })
}

shinyApp(ui, server)

Body:
Is it what you want ?

ui <- fluidPage(

  tags$head(
    tags$style(HTML("#patent_scape_tag1 {display: list-item;}"))
  ),

  navbarPage("Analysis",
             tabPanel("Home",
                      sidebarPanel(
                        textOutput("patent_scape_tag1")
                      ),
                      mainPanel(
                        plotlyOutput("treemap")
                      )
             )
  )
)


问:
How to scrape tables from some URL in Javascript?
In Python it is very simple: pandas.read_html("some URL");

I am wondering what's the best way to do this in Javascript. Is there some existing library that can help with this?

答:
You might want to take a look at DOMParser this will create a document object where you can perform any kind of manipulation as any normal html page.

example:

```<code>var doc = DOMParser.parseFromString("<html code here>", "text/html");
var tables = doc.querySelectorAll('table'); // returns NodeList
</code>```

You should fetch the html string from another part of your program.

Body:
You might want to take a look at DOMParser this will create a document object where you can perform any kind of manipulation as any normal html page.

example:

var doc = DOMParser.parseFromString("<html code here>", "text/html");
var tables = doc.querySelectorAll('table'); // returns NodeList

You should fetch the html string from another part of your program.


问:
slice and replace string before assigns to a variable
I was looking, to replace and slice a string/text before assigns to a variable,
but I did in two, I want to know if this can be done.

Example:

```<code>    SET MY_TIME=%%time:~0,8%::=_%
    ECHO %MY_TIME%
    #output: %12:50:47::=_%
</code>```

My current result, because i didn't find the way to replace and slice in the same line..

```<code>    SET GET_TIME=%time:~0,8%
    SET MY_TIME=%GET_TIME::=_%
    ECHO %MY_TIME%
    #output: 12_42_48
</code>```

答:
cmd does not allow for multiple inline replacements, as you have already learned. The closest you will probably get is:

from cmd:

```<code>set "mytime=%time:~0,8%" & call echo %mytime::=_%
</code>```

From batch-file:

```<code>set "mytime=%time:~0,8%" & call echo %%mytime::=_%%
</code>```

As a side note, if you want to retain the format, you need to consider single digit hours to be amended as well:

```<code>set "mytime=%time =%
</code>```

The above will replace the whitespace before a single digit hour (1am to 9am) with a zero, which retains your format hhmmss

When getting to this however, there is no longer a purpose to run it as a one liner and you might as well add it line by line:

```<code>set "mytime=%time:~0,8%"
set "mytime=%mytime: =0%"
echo %mytime::=_%
</code>```

Body:
I was looking, to replace and slice a string/text before assigns to a variable,
but I did in two, I want to know if this can be done.

Example:

    SET MY_TIME=%%time:~0,8%::=_%
    ECHO %MY_TIME%
    #output: %12:50:47::=_%

My current result, because i didn't find the way to replace and slice in the same line..

    SET GET_TIME=%time:~0,8%
    SET MY_TIME=%GET_TIME::=_%
    ECHO %MY_TIME%
    #output: 12_42_48

Body:
cmd does not allow for multiple inline replacements, as you have already learned. The closest you will probably get is:

from cmd:

set "mytime=%time:~0,8%" & call echo %mytime::=_%

From batch-file:

set "mytime=%time:~0,8%" & call echo %%mytime::=_%%

As a side note, if you want to retain the format, you need to consider single digit hours to be amended as well:

set "mytime=%time =%

The above will replace the whitespace before a single digit hour (1am to 9am) with a zero, which retains your format hhmmss

When getting to this however, there is no longer a purpose to run it as a one liner and you might as well add it line by line:

set "mytime=%time:~0,8%"
set "mytime=%mytime: =0%"
echo %mytime::=_%