问:
Print string while adding newlines
I'm trying to print out a string with embedded ruby to a webpage, if I use the following it ends up going off of the page.

```<code><%= comment.body %>
</code>```

I want to do something like this so that it automatically prints everything with new lines

```<code><%= comment.body[0..136] %>
<%= "\n" %>
<%= comment.body[137..250] %>
</code>```

I've done the following however it prints the characters with spaces between them and ignores spaces in the string.

```<code><% for i in 0..comment.body.length do %>
<%= i %>
<% end %>
</code>```

Thanks

答:
Solved it by using CSS

in HTML:

```<code><p id="commentBody">
  ...
</p>
</code>```

in CSS:

```<code>#commentBody {
  word-wrap: break-word;
}
</code>```

Title: Print string while adding newlines

Body:
I'm trying to print out a string with embedded ruby to a webpage, if I use the following it ends up going off of the page.

<%= comment.body %>

I want to do something like this so that it automatically prints everything with new lines

<%= comment.body[0..136] %>
<%= "\n" %>
<%= comment.body[137..250] %>

I've done the following however it prints the characters with spaces between them and ignores spaces in the string.

<% for i in 0..comment.body.length do %>
<%= i %>
<% end %>

Thanks

Body:
Solved it by using CSS

in HTML:

<p id="commentBody">
  ...
</p>

in CSS:

#commentBody {
  word-wrap: break-word;
}


来源: stackexchange

问:
How to get part of filename into a variable?
I have a lot of .csv files and I'd like to parse the file names.

The file names are in this format:

```<code>name.surname.csv
</code>```

How can I write a function that populates two variables with the components of the file name?

```<code>A = name
B = surname
</code>```

答:
If you have file saved at a specific location in the system , then you have to first get only the file name :

```<code># if filename = name.surname.csv then discard first two lines
filename = "C://CSVFolder//name.surname.csv"
absfilename = filename.split('//')[-1]
# by concept of packing unpacking
A,B,ext = absfilename.split('.')
</code>```

else you can just provide

```<code>A,B,ext = "name.surname.csv".split('.')
print A,B,ext
</code>```

Happy coding :)

ContentLicense: CC BY-SA 3.0

Body:
I have a lot of .csv files and I'd like to parse the file names.

The file names are in this format:

name.surname.csv

How can I write a function that populates two variables with the components of the file name?

A = name
B = surname

Body:
If you have file saved at a specific location in the system , then you have to first get only the file name :

# if filename = name.surname.csv then discard first two lines
filename = "C://CSVFolder//name.surname.csv"
absfilename = filename.split('//')[-1]
# by concept of packing unpacking
A,B,ext = absfilename.split('.')

else you can just provide

A,B,ext = "name.surname.csv".split('.')
print A,B,ext

Happy coding :)


问:
What is the difference between bin/rake and bundle exec rake
What is the difference between using bin/rake and bundle exec rake.
And which is one preferred style?</p>

```<code>bin/rake db:migrate
bundle exec rake db:migrate
</code>```

答:
bundle exec executes a command in the context of your application.
As each application can have different versions of gem used. Using bundle exec guarantees that you use the correct versions.

I use bundle exec always instead of rake because i have multiple applications running on my system.

Try to use bundle exec rake db:migrate always.

You can learn more about it here Official documentation

Body:
What is the difference between using bin/rake and bundle exec rake.
And which is one preferred style?

bin/rake db:migrate
bundle exec rake db:migrate


问:
PHP sort array by two field values
I've an array like this

```
Array (
 [0] => Array( "destination" => "Sydney",
               "airlines" => "airline_1",
               "one_way_fare" => 100,
               "return_fare => 300
       ),
 [2] => Array( "destination" => "Sydney",
               "airlines" => "airline_2",
               "one_way_fare" => 150,
               "return_fare => 350
       ),
 [3] => Array( "destination" => "Sydney",
               "airlines" => "airline_3",
               "one_way_fare" => 180,
               "return_fare => 380
       )
)
```

How can i sort the value by return_fare asc , one_way_fare asc ?

I tried array_multisort() but i ended up getting mixed up data..

asort only works for one dimensional array, i need to sort by two values or more, how can i achieve this like in SQL, order by field1 asc,field2 asc ?

答:
Another example using the spaceship operator.</p>

```<code>usort($data, function($a, $b) {
    return $a['return_fare'] <=> $b['return_fare'] ?: $a['one_way_fare'] <=> $b['one_way_fare'];
});
</code>```

Title: PHP sort array by two field values

Body:
I've an array like this

Array (
 [0] => Array( "destination" => "Sydney",
               "airlines" => "airline_1",
               "one_way_fare" => 100,
               "return_fare => 300
       ),
 [2] => Array( "destination" => "Sydney",
               "airlines" => "airline_2",
               "one_way_fare" => 150,
               "return_fare => 350
       ),
 [3] => Array( "destination" => "Sydney",
               "airlines" => "airline_3",
               "one_way_fare" => 180,
               "return_fare => 380
       )
)

How can i sort the value by return_fare asc , one_way_fare asc ?

I tried array_multisort() but i ended up getting mixed up data..

asort only works for one dimensional array, i need to sort by two values or more, how can i achieve this like in SQL, order by field1 asc,field2 asc ?

Body:
Another example using the spaceship operator.

usort($data, function($a, $b) {
    return $a['return_fare'] <=> $b['return_fare'] ?: $a['one_way_fare'] <=> $b['one_way_fare'];
});

ContentLicense: CC BY-SA 4.0


问:
How do I change the URI (URL) for a remote Git repository?
I have a repo (origin) on a USB key that I cloned on my hard drive (local). I moved "origin" to a NAS and successfully tested cloning it from here.

I would like to know if I can change the URI of "origin" in the settings of "local" so it will now pull from the NAS, and not from the USB key.

For now, I can see two solutions:

push everything to the USB origin, and copy it to the NAS again (implies a lot of work due to new commits to NAS origin);

add a new remote to "local" and delete the old one (I fear I'll break my history).

答:
Switching remote URLs

Open Terminal.

Ist Step:- Change the current working directory to your local project.

2nd Step:- List your existing remotes in order to get the name of the remote you want to change.

git remote -v

```<code>origin  https://github.com/USERNAME/REPOSITORY.git (fetch)

origin  https://github.com/USERNAME/REPOSITORY.git (push)
</code>```

Change your remote's URL from HTTPS to SSH with the git remote set-url command.

3rd Step:-  git remote set-url origin git@github.com:USERNAME/REPOSITORY.git

4th Step:- Now Verify that the remote URL has changed.

git remote -v
Verify new remote URL

```<code>origin  git@github.com:USERNAME/REPOSITORY.git (fetch)
origin  git@github.com:USERNAME/REPOSITORY.git (push)
</code>```

Body:
Switching remote URLs

Open Terminal.

Ist Step:- Change the current working directory to your local project.

2nd Step:- List your existing remotes in order to get the name of the remote you want to change.

git remote -v

origin  https://github.com/USERNAME/REPOSITORY.git (fetch)

origin  https://github.com/USERNAME/REPOSITORY.git (push)

Change your remote's URL from HTTPS to SSH with the git remote set-url command.

3rd Step:-  git remote set-url origin git@github.com:USERNAME/REPOSITORY.git

4th Step:- Now Verify that the remote URL has changed.

git remote -v
Verify new remote URL

origin  git@github.com:USERNAME/REPOSITORY.git (fetch)
origin  git@github.com:USERNAME/REPOSITORY.git (push)


问:
Is it possible to set gravity programmatically for RecyclerView children in Android?
I'm trying to set gravity for children in RecyclerView, but it looks like the LayoutParams does not have a gravity method. I have tried the following:

```<code>RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(
                RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
</code>```

I have also tried the following:

```<code>RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
</code>```

In both cases params.setMargin(int, int, int, int) works just fine and the margin is set correctly.

My RecyclerView:

```<code><android.support.v7.widget.RecyclerView
    android:id="@+id/messages_list_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/toolbar"
    android:layout_marginTop="20dp"/>
</code>```

My RelativeLayout (child of RecyclerView):

```<code><RelativeLayout
android:id="@+id/message_text_wrapper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:background="@drawable/chat_bubble"
android:layout_margin="16dp"
android:padding="10dp"
xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:textColor="@android:color/primary_text_light"
        android:textSize="18sp"
        />

</RelativeLayout>
</code>```

What I want to be able to do is params.setGravity(int) or any other hack that makes this possible. Thanks.

答:
Wrap your item view inside a FrameLayout, make sure its layout_width is set to match_parent.

Give your layout which you wrapped in the FrameLayout an id and connect it to your ViewHolder.
(I think you've already done this with @+id/message_text_wrapper)

Then in onBindViewHolder do this:

```<code>FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) holder.yourLayout.getLayoutParams()
if (condition) {
    params.gravity = Gravity.END // or Gravity.RIGHT
} else {
    params.gravity = Gravity.START // or Gravity.LEFT
}
</code>```

Body:
I'm trying to set gravity for children in RecyclerView, but it looks like the LayoutParams does not have a gravity method. I have tried the following:

RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(
                RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);

I have also tried the following:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

In both cases params.setMargin(int, int, int, int) works just fine and the margin is set correctly.

My RecyclerView:

<android.support.v7.widget.RecyclerView
    android:id="@+id/messages_list_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/toolbar"
    android:layout_marginTop="20dp"/>

My RelativeLayout (child of RecyclerView):

<RelativeLayout
android:id="@+id/message_text_wrapper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:background="@drawable/chat_bubble"
android:layout_margin="16dp"
android:padding="10dp"
xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:textColor="@android:color/primary_text_light"
        android:textSize="18sp"
        />

</RelativeLayout>

What I want to be able to do is params.setGravity(int) or any other hack that makes this possible. Thanks.

Body:
Wrap your item view inside a FrameLayout, make sure its layout_width is set to match_parent.

Give your layout which you wrapped in the FrameLayout an id and connect it to your ViewHolder.
(I think you've already done this with @+id/message_text_wrapper)

Then in onBindViewHolder do this:

FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) holder.yourLayout.getLayoutParams()
if (condition) {
    params.gravity = Gravity.END // or Gravity.RIGHT
} else {
    params.gravity = Gravity.START // or Gravity.LEFT
}


问:
import html template in typescript
I'm trying to import my html template so that webpack will recognize them and include them when I build. (webpack -d)

According to this GitHub issue I should do this

```<code>declare module '*.html' {
    const _: string;
    export default _;
}
</code>```

Then import template from './myTemplate.html'; should work.

But it doesn't quite do the trick.

```<code>import template from './myTemplate.html';
console.log(template); // undefined
</code>```

However this "works"

```<code>import * as template from './myTemplate.html';
console.log(template); // <p>Hello world!</p>
</code>```

Very strange.

But now this doesn't work

```<code>$routeProvider.when("/test", {
    template: template, // ERROR! template is typeof(*.html) expected string
    controller: MyController,
    controllerAs: "$ctrl"
});
</code>```

However if I change my *.html module to

```<code>declare module '*.html' {
    const _: string;
    export = _; // changed this
}
</code>```

I can now do

```<code>import * as template from './myTemplate.html';

$routeProvider.when("/test", {
    template: template, // Great success!
    controller: MyController,
    controllerAs: "$ctrl"
});
</code>```

It works, but why doesn't import template from './myTemplate.html'; work? What am I doing wrong as the others in the GitHub issue seemed to get it to work like that.

答:
You are not doing anything wrong, in order to use import template from './myTemplate.html'; you need to use export default syntax.

Because of the fact that webpack is the one that handles html imports it doesn't do export default by default.

But you can configure your html-loader to use export default.

Title: import html template in typescript

Body:
I'm trying to import my html template so that webpack will recognize them and include them when I build. (webpack -d)

According to this GitHub issue I should do this

declare module '*.html' {
    const _: string;
    export default _;
}

Then import template from './myTemplate.html'; should work.

But it doesn't quite do the trick.

import template from './myTemplate.html';
console.log(template); // undefined

However this "works"

import * as template from './myTemplate.html';
console.log(template); //
Hello world!

Very strange.

But now this doesn't work

$routeProvider.when("/test", {
    template: template, // ERROR! template is typeof(*.html) expected string
    controller: MyController,
    controllerAs: "$ctrl"
});

However if I change my *.html module to

declare module '*.html' {
    const _: string;
    export = _; // changed this
}

I can now do

import * as template from './myTemplate.html';

$routeProvider.when("/test", {
    template: template, // Great success!
    controller: MyController,
    controllerAs: "$ctrl"
});

It works, but why doesn't import template from './myTemplate.html'; work? What am I doing wrong as the others in the GitHub issue seemed to get it to work like that.


问:
Either use @Param on all parameters except Pageable and Sort typed once Spring boot
I saw some questions about this error but I could not find a solution for my case.

I'm implementing a paging in the spring boot application.

I Have this method in my controller

```<code>@RequestMapping(method = RequestMethod.GET, value = "/distrito",  params = { "page", "size" })
    public ResponseEntity<Page<Distritos>> buscarTodosDistritos(HttpServletRequest request, @RequestParam("page") int page, @RequestParam("size") int size) throws ServletException {
        Map<String, String>informacaoUsuario = uService.getInformacoesUsuario(request);

        Page<Distritos> distritosBuscados = distritosService.buscarFiltro(Long.parseLong(informacaoUsuario.get("idEntidadeSelecionada")), page, size);
            return new ResponseEntity<>(distritosBuscados, HttpStatus.OK);
    }
</code>```

and my service

```<code>    public Page<Distritos> buscarFiltro(Long usuarioEntidade ,int size, int page){
        return distritosRepository.encontrar(usuarioEntidade, size, page);
    }
</code>```

my repository

```<code>@Query( nativeQuery=true, value="SELECT dist.nome, dist.id_distrito, dist.id_entidade, dist.id_municipio, dist.id_uf, dist.codigo_dne, dist.flag_ativo,  enti.nome Entidade, muni.nome Municipio, unfe.nome UF FROM glb.distritos  dist, glb.entidades  enti, glb.municipios muni, glb.ufs unfe WHERE dist.id_entidade  = enti.id_entidade AND dist.id_municipio = muni.id_municipio AND muni.id_uf = unfe.id_uf and enti.id_entidade = :parametroId order by nome   ")
    public  Page<Distritos>  encontrar(@Param ("parametroId")Long usuarioEntidade, int size, int page);
</code>```

and i got this error

```<code>Caused by: java.lang.IllegalArgumentException: Either use @Param on all parameters except Pageable and Sort typed once, or none at all!
    at org.springframework.util.Assert.isTrue(Assert.java:92) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.data.repository.query.Parameters.assertEitherAllParamAnnotatedOrNone(Parameters.java:297) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.Parameters.<init>(Parameters.java:91) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
</code>```

how can i solve that ???

答:
Pass the Pageable object instead:

```<code>public Page<Distritos> buscarFiltro(Long usuarioEntidade ,int size, int page){
       Pageable pageable = new PageRequest(page, size);
       return distritosRepository.encontrar(usuarioEntidade, pageable);
}
</code>```

and repo:

```<code>public  Page<Distritos>  encontrar(@Param ("parametroId")Long usuarioEntidade
         , Pageable pageable);
</code>```

Body:
I saw some questions about this error but I could not find a solution for my case.

I'm implementing a paging in the spring boot application.

I Have this method in my controller

@RequestMapping(method = RequestMethod.GET, value = "/distrito",  params = { "page", "size" })
    public ResponseEntity<Page<Distritos>> buscarTodosDistritos(HttpServletRequest request, @RequestParam("page") int page, @RequestParam("size") int size) throws ServletException {
        Map<String, String>informacaoUsuario = uService.getInformacoesUsuario(request);

        Page<Distritos> distritosBuscados = distritosService.buscarFiltro(Long.parseLong(informacaoUsuario.get("idEntidadeSelecionada")), page, size);
            return new ResponseEntity<>(distritosBuscados, HttpStatus.OK);
    }

and my service

    public Page<Distritos> buscarFiltro(Long usuarioEntidade ,int size, int page){
        return distritosRepository.encontrar(usuarioEntidade, size, page);
    }

my repository

@Query( nativeQuery=true, value="SELECT dist.nome, dist.id_distrito, dist.id_entidade, dist.id_municipio, dist.id_uf, dist.codigo_dne, dist.flag_ativo,  enti.nome Entidade, muni.nome Municipio, unfe.nome UF FROM glb.distritos  dist, glb.entidades  enti, glb.municipios muni, glb.ufs unfe WHERE dist.id_entidade  = enti.id_entidade AND dist.id_municipio = muni.id_municipio AND muni.id_uf = unfe.id_uf and enti.id_entidade = :parametroId order by nome   ")
    public  Page<Distritos>  encontrar(@Param ("parametroId")Long usuarioEntidade, int size, int page);

and i got this error

Caused by: java.lang.IllegalArgumentException: Either use @Param on all parameters except Pageable and Sort typed once, or none at all!
    at org.springframework.util.Assert.isTrue(Assert.java:92) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.data.repository.query.Parameters.assertEitherAllParamAnnotatedOrNone(Parameters.java:297) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.Parameters.<init>(Parameters.java:91) ~[spring-data-commons-1.13.4.RELEASE.jar:na]

how can i solve that ???

Body:
Pass the Pageable object instead:

public Page<Distritos> buscarFiltro(Long usuarioEntidade ,int size, int page){
       Pageable pageable = new PageRequest(page, size);
       return distritosRepository.encontrar(usuarioEntidade, pageable);
}

and repo:

public  Page<Distritos>  encontrar(@Param ("parametroId")Long usuarioEntidade
         , Pageable pageable);


问:
How to verify response of any Http Request is valid JSON or not?
Suppose i have a Http request in json/xml when i post this request then we get some JSON response, then First i need to verify  this response is valid json or not in java.how to do that in one go?</p>

答:
A wild idea, try parsing it and catch the exception:</p>

```<code>public boolean isJSONValid(String test) {
    try {
        new JSONObject(test);
    } catch (JSONException ex) {

        // e.g. in case JSONArray is valid as well...
        try {
            new JSONArray(test);
        } catch (JSONException ex1) {
            return false;
        }
    }
    return true;
}
</code>```

Body:
A wild idea, try parsing it and catch the exception:

public boolean isJSONValid(String test) {
    try {
        new JSONObject(test);
    } catch (JSONException ex) {

        // e.g. in case JSONArray is valid as well...
        try {
            new JSONArray(test);
        } catch (JSONException ex1) {
            return false;
        }
    }
    return true;
}


问:
Get vector of Tuesdays, but if Tuesday falls on a holiday, then replace it with Wednesday in R
I would like to find all of the Tuesdays between two dates. But if the Tuesday falls on a user-defined list of holidays, then I would like Wednesday instead.

This code works in my tests, but it is pretty janky and I am afraid it will fail silently.

```<code>low.date <- "1996-01-01"
high.date <- "1997-01-01"
holidays = c("01-01", "07-04", "12-25")
tues <- seq(as.Date(low.date), as.Date(high.date), by = 1)
tues <- subset(tues, format(tues, "%a") == "Tue")
tues <- ifelse(format(tues, "%m-%d") %in% holidays, tues + 1, tues)
tues <- as.Date(tues, origin = "1970-01-01")
</code>```

Thanks! I see answers pointing to the timeDate package, but I only see methods for finding business days or holidays. Is there a cleaner/safer logic than what I'm using?

答:
It's difficult to modify the logic of your solution. But here is a different form  using wday function from lubridate package.

```<code>hol_tue <-  wday(tues) == 3L & format(tues, "%m-%d") %in% holidays
wday(tues)[hol_tue] <- 4
</code>```

Slightly inconveniently in lubridate package day count starts from Sunday with Sunday being day 1 as opposed to POSIXlt where it's 0.

ContentLicense: CC BY-SA 2.5

Body:
I would like to find all of the Tuesdays between two dates. But if the Tuesday falls on a user-defined list of holidays, then I would like Wednesday instead.

This code works in my tests, but it is pretty janky and I am afraid it will fail silently.

low.date <- "1996-01-01"
high.date <- "1997-01-01"
holidays = c("01-01", "07-04", "12-25")
tues <- seq(as.Date(low.date), as.Date(high.date), by = 1)
tues <- subset(tues, format(tues, "%a") == "Tue")
tues <- ifelse(format(tues, "%m-%d") %in% holidays, tues + 1, tues)
tues <- as.Date(tues, origin = "1970-01-01")

Thanks! I see answers pointing to the timeDate package, but I only see methods for finding business days or holidays. Is there a cleaner/safer logic than what I'm using?

Body:
It's difficult to modify the logic of your solution. But here is a different form  using wday function from lubridate package.

hol_tue <-  wday(tues) == 3L & format(tues, "%m-%d") %in% holidays
wday(tues)[hol_tue] <- 4

Slightly inconveniently in lubridate package day count starts from Sunday with Sunday being day 1 as opposed to POSIXlt where it's 0.


问:
Javascript function to read url and to assign active class not working
my problem is about an internal menu I created in a wordpress website. I can't correctly assign an "active" class to a text links of the menu when I go to the third level pages.

I make an example that can help you to understand the problem:

url type structure: www../servizi-ai-privati/fisioterapia-riabilitazione

code of the menu item:

```<code><a href="/servizi-ai-privati/fisioterapia-riabilitazione" class="active">
   <div id="fisioterapia-riabilitazione" class="menu_servizi_privati_sezione">
      <img src="/wp-content/uploads/2017/09/icona_fisioterapia.svg"
         class="menu_servizi_icona">
      <h6>Fisioterapia e riabilitazione</h6>
   </div>
</a>
</code>```

It works good when I am in this page and the menu item takes the "active" class I created.

url: http://www.test.com/servizi-ai-privati/fisioterapia-riabilitazione/massoterapia/

Menu item didn't take the active class.

I assign the active class with this js function:

```<code>jQuery(function () {
    var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace(/\/$/, '') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there

        // now grab every link from the navigation
        jQuery('.menu_servizi_privati a ').each(function(){
        // and test its normalized href against the url pathname regexp
            if(urlRegExp.test(this.href.replace(/\/$/,' '))){
                jQuery(this).addClass(' active ');
            }
        });
    });
</code>```

How do I have to change this function to make it read correctly the entire url? Sorry but I'm not so practiced with javascript. I hope I explained clearly my problem.

This is the full code of the menu I created:

```<code><div class="cmsmasters_sidebar sidebar_layout_11 widget_menu_servizi_privati">
   <aside id="custom_html-3" class="widget_text widget widget_custom_html">
      <div class="textwidget custom-html-widget">
         <div style="text-align: center">
            <div class="menu_servizi_privati">
               <a href="/servizi-ai-privati/prenota-visita">
                  <div id="prenota-visita" class="menu_servizi_privati_sezione">
                     <img src="/wp-content/uploads/2017/09/icona_prenota_visita.svg" class="menu_servizi_icona">
                     <h6>Prenota una visita</h6>
                  </div>
               </a>
               <a href="/servizi-ai-privati/visite-specialistiche">
                  <div id="visite-specialistiche" class="menu_servizi_privati_sezione">
                     <img src="/wp-content/uploads/2017/09/icona_visite_specialistiche.svg" class="menu_servizi_icona">
                     <h6>Visite specialistiche</h6>
                  </div>
               </a>
               <a href="/servizi-ai-privati/check-up">
                  <div id="check-up" class="menu_servizi_privati_sezione">
                     <img src="/wp-content/uploads/2017/09/icona_checkup.svg" class="menu_servizi_icona">
                     <h6>Check up</h6>
                  </div>
               </a>
               <a href="/servizi-ai-privati/fisioterapia-riabilitazione" class="active">
                  <div id="fisioterapia-riabilitazione" class="menu_servizi_privati_sezione">
                     <img src="/wp-content/uploads/2017/09/icona_fisioterapia.svg" class="menu_servizi_icona">
                     <h6>Fisioterapia e riabilitazione</h6>
                  </div>
               </a>
               <a href="/servizi-ai-privati/punto-prelievi">
                  <div id="punto-prelievi" class="menu_servizi_privati_sezione">
                     <img src="/wp-content/uploads/2017/09/icona_punto_prelievi.svg"     class="menu_servizi_icona">
                     <h6>Punto prelievi</h6>
                  </div>
               </a>
               <a href="/servizi-ai-privati/medici">
                  <div id="medici"     class="menu_servizi_privati_sezione">
                     <img src="/wp-    content/uploads/2017/09/icona_medici.svg" class="menu_servizi_icona">
                     <h6>I medici</h6>
                  </div>
               </a>
            </div>
         </div>
      </div>
   </aside>
</div>
</code>```

Thank you.

答:
Okay. You have many issues here.

First:
You are using jQuery('.menu_servizi_privati a ') but your a-tag is not within any container. Please provide more code or fix this issue.

Second:
You are using this.href which is providing the full URL, but you compare it to windows.location.pathname, which is providing only the URL path.

Third: Instead of removing trailing slashes, you should make sure that your website is reachable by only one URL version (URL redirecting). That's better for Google / SEO (unique content).

Solution:
Get rid off of the regex and fix the code. This is working perfectly fine for me. I rewrote the code a bit. When you need to specify jQuery, you can just replace the $-sign with jQuery.

Fiddle: https://jsfiddle.net/gpq3ptm3/

Body:
my problem is about an internal menu I created in a wordpress website. I can't correctly assign an "active" class to a text links of the menu when I go to the third level pages.

I make an example that can help you to understand the problem:

url type structure: www../servizi-ai-privati/fisioterapia-riabilitazione

code of the menu item:

Fisioterapia e riabilitazione

It works good when I am in this page and the menu item takes the "active" class I created.

url: http://www.test.com/servizi-ai-privati/fisioterapia-riabilitazione/massoterapia/

Menu item didn't take the active class.

I assign the active class with this js function:

jQuery(function () {
    var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace(/\/$/, '') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there

        // now grab every link from the navigation
        jQuery('.menu_servizi_privati a ').each(function(){
        // and test its normalized href against the url pathname regexp
            if(urlRegExp.test(this.href.replace(/\/$/,' '))){
                jQuery(this).addClass(' active ');
            }
        });
    });

How do I have to change this function to make it read correctly the entire url? Sorry but I'm not so practiced with javascript. I hope I explained clearly my problem.

This is the full code of the menu I created:

Prenota una visita

Visite specialistiche

Check up

Fisioterapia e riabilitazione

Punto prelievi

I medici

Thank you.


问:
How do I get my AVPlayer to play while app is in background?
I've done my homework... been reading here, the docs, googling, stackoverflowing... but still no luck in making my sound stick when the user makes the app go into the background.

What I have done so far:
Added the UIBackgroundModes, audio to the plist-file.

First this code:

```<code>radioAudio = [[AVAudioSession alloc] init];
[radioAudio setCategory:AVAudioSessionCategoryPlayback error:nil];
[radioAudio setActive:YES error:nil];
</code>```

Then this:

```<code>NSString *radioURL = @"http://xxx.xxx.xxx/radio.m3u";
radioPlayer = [[AVPlayer playerWithURL:[NSURL URLWithString:radioURL]] retain];
</code>```

But as soon as the user hits the home-button, my sound dies.

I also found this, but not added yet cuase some stuff I've read says it is not needed;

```<code>newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
     if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid)
        [[UIApplication sharedApplication] endBackgroundTask: bgTaskId];
bgTaskId = newTaskId;
</code>```

Right now I have no idea where I should go to make my AVPlayer let the radio sing while the user does other stuff on the phone.
I am testing this on an iPhone 4 with 4.2. Building it for 4.0.

Anyone have any suggestions what I should do?

答:
I have successfully made audio run in the background by adding the following to my applicationDidFinishLaunching

```<code>// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];
// Allow the app sound to continue to play when the screen is locked.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
</code>```

Body:
I've done my homework... been reading here, the docs, googling, stackoverflowing... but still no luck in making my sound stick when the user makes the app go into the background.

What I have done so far:
Added the UIBackgroundModes, audio to the plist-file.

First this code:

radioAudio = [[AVAudioSession alloc] init];
[radioAudio setCategory:AVAudioSessionCategoryPlayback error:nil];
[radioAudio setActive:YES error:nil];

Then this:

NSString *radioURL = @"http://xxx.xxx.xxx/radio.m3u";
radioPlayer = [[AVPlayer playerWithURL:[NSURL URLWithString:radioURL]] retain];

But as soon as the user hits the home-button, my sound dies.

I also found this, but not added yet cuase some stuff I've read says it is not needed;

newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
     if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid)
        [[UIApplication sharedApplication] endBackgroundTask: bgTaskId];
bgTaskId = newTaskId;

Right now I have no idea where I should go to make my AVPlayer let the radio sing while the user does other stuff on the phone.
I am testing this on an iPhone 4 with 4.2. Building it for 4.0.

Anyone have any suggestions what I should do?

Body:
I have successfully made audio run in the background by adding the following to my applicationDidFinishLaunching

// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];
// Allow the app sound to continue to play when the screen is locked.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];


答:
You have to pass a Pageable Object and not the size and page like you do :

```<code>public  Page<Distritos>  encontrar(@Param ("parametroId") Long usuarioEntidade,
                                                          Pageable pageable);
</code>```

and call your method like this

```<code>return distritosRepository.encontrar(usuarioEntidade, new PageRequest(size, page));
</code>```

You can either create a Pageable Object which hold a sorted attribute, so instead of using order by nome in your query you can use :

```<code>Sort sort = new Sort(new Sort.Order(Direction.ASC, "nome"));
Pageable pageable = new PageRequest(size, page, sort);
return distritosRepository.encontrar(usuarioEntidade, pageable);
</code>```

Title: Either use @Param on all parameters except Pageable and Sort typed once Spring boot

Body:
You have to pass a Pageable Object and not the size and page like you do :

public  Page<Distritos>  encontrar(@Param ("parametroId") Long usuarioEntidade,
                                                          Pageable pageable);

and call your method like this

return distritosRepository.encontrar(usuarioEntidade, new PageRequest(size, page));

You can either create a Pageable Object which hold a sorted attribute, so instead of using order by nome in your query you can use :

Sort sort = new Sort(new Sort.Order(Direction.ASC, "nome"));
Pageable pageable = new PageRequest(size, page, sort);
return distritosRepository.encontrar(usuarioEntidade, pageable);


问:
Can i fire long click event for a view programmatically?
can I fire long click event for a view programmatically ? I know there is performClick() function for firing click event but I'm looking for long click event</p>

答:
```<code>public static void longClickView(View v) {

    final int viewWidth = v.getWidth();
    final int viewHeight = v.getHeight();

    final float x = viewWidth / 2.0f;
    final float y = viewHeight / 2.0f;

    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis();

    MotionEvent event = MotionEvent.obtain(downTime, eventTime,
            MotionEvent.ACTION_DOWN, x, y, 0);
    v.onTouchEvent(event);

    eventTime = SystemClock.uptimeMillis();
    final int touchSlop = ViewConfiguration.get(v.getContext()).getScaledTouchSlop();
    event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE,
            x + touchSlop / 2, y + touchSlop / 2, 0);
    v.onTouchEvent(event);

    v.postDelayed(() -> {
        long eventTime2 = SystemClock.uptimeMillis();
        MotionEvent event2 = MotionEvent.obtain(downTime, eventTime2, MotionEvent.ACTION_UP, x, y, 0);
        v.onTouchEvent(event2);
    }, (long) (ViewConfiguration.getLongPressTimeout() * 1.5f));
}
</code>```


问:
Packaging project reference in nuget : .net core
Currently I have a requirement where we have separate assemblies for contract and implementation.  After creating a nuget package and attempting to consume nuget package, it fails because Package manager is unable to find dependent (contract) assembly.

This seems to be an open issue in .net core.

https://github.com/dotnet/cli/issues/3959

Unable to understand why such simple thing will not work in .net core.  Looking for workaround for this issue.

答:
After reading documentation I understood .net core discourages project reference instead advises to use package reference. This is mentioned in description heading in following doc.

https://github.com/dotnet/docs/blob/master/docs/core/tools/dotnet-pack.md

I published my contract assembly to nuget package and consumed it in implementation as nuget package.


问:
Timeout for multiprocessing?
This code pings various machines. Could you please help me change this code so if a process of pinging hangs for more then 7 seconds it shuts down and returns some flag?

(I'd like to pull various data from machines using WMI. For that I'll change ping function to something else. The issue is on some machines WMI is corrupted and process of pulling data hangs indefinitely. Timeout is needed.)

```<code>import multiprocessing.dummy
import subprocess
import numpy as np
import time

start_time = time.time()

def ping(ipadd):
    try:
        response = subprocess.check_output(['ping', ipadd])
        return True
    except subprocess.CalledProcessError as e:
        return False
#print(ping('10.25.59.20'))
machine_names = \
'''
ya.ru
microsoft.com
www.google.com
www.amazon.com
www.nasa.com
'''.split()

np_machine_names = np.array(machine_names)
p = multiprocessing.dummy.Pool(7)
ping_status = p.map(ping, machine_names)
np_ping_status = np.fromiter(ping_status, dtype=bool)
print(*np_machine_names[np_ping_status], sep = '\n')

run_time = time.time() - start_time
print(f'Runtime: {run_time:.0f}')
</code>```

UPDATE:
While I appreciate for the tip on adding timeout to subprocess the question remains. How do I shutdown hanged function? Let's say I've changed pinging to pulling WMI data from a machine (this one pulls list of installed software from Windows machine). There is no subprocess to set timer on:

```<code>#pip install pypiwin32
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Product")
for objItem in colItems:
    print( "Caption: ", objItem.Caption )
</code>```

答:
Popen is a default choice when it comes to using subprocess module. It allows you to create a process and then read its stdout and stderr with specified timeout:

```<code>def ping(ipadd):
    process = subprocess.Popen(['ping', ipadd])
    try:
        response, stderr_response = process.communicate(timeout=10)
        return True
    except subprocess.TimeoutExpired:
        return False
    finally:
        process.kill()
</code>```

Also, beware that ping on a linux or osx may never exit and continue to ping so this is going to return false on these OSes:

```<code>>>> ping('127.0.0.1')
PING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.058 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.033 ms
...
64 bytes from 127.0.0.1: icmp_seq=8 ttl=64 time=0.064 ms
64 bytes from 127.0.0.1: icmp_seq=9 ttl=64 time=0.031 ms
False
</code>```

Title: Timeout for multiprocessing?

Body:
This code pings various machines. Could you please help me change this code so if a process of pinging hangs for more then 7 seconds it shuts down and returns some flag?

(I'd like to pull various data from machines using WMI. For that I'll change ping function to something else. The issue is on some machines WMI is corrupted and process of pulling data hangs indefinitely. Timeout is needed.)

import multiprocessing.dummy
import subprocess
import numpy as np
import time

start_time = time.time()

def ping(ipadd):
    try:
        response = subprocess.check_output(['ping', ipadd])
        return True
    except subprocess.CalledProcessError as e:
        return False
#print(ping('10.25.59.20'))
machine_names = \
'''
ya.ru
microsoft.com
www.google.com
www.amazon.com
www.nasa.com
'''.split()

np_machine_names = np.array(machine_names)
p = multiprocessing.dummy.Pool(7)
ping_status = p.map(ping, machine_names)
np_ping_status = np.fromiter(ping_status, dtype=bool)
print(*np_machine_names[np_ping_status], sep = '\n')

run_time = time.time() - start_time
print(f'Runtime: {run_time:.0f}')

UPDATE:
While I appreciate for the tip on adding timeout to subprocess the question remains. How do I shutdown hanged function? Let's say I've changed pinging to pulling WMI data from a machine (this one pulls list of installed software from Windows machine). There is no subprocess to set timer on:

#pip install pypiwin32
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Product")
for objItem in colItems:
    print( "Caption: ", objItem.Caption )

Body:
Popen is a default choice when it comes to using subprocess module. It allows you to create a process and then read its stdout and stderr with specified timeout:

def ping(ipadd):
    process = subprocess.Popen(['ping', ipadd])
    try:
        response, stderr_response = process.communicate(timeout=10)
        return True
    except subprocess.TimeoutExpired:
        return False
    finally:
        process.kill()

Also, beware that ping on a linux or osx may never exit and continue to ping so this is going to return false on these OSes:

>>> ping('127.0.0.1')
PING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.058 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.033 ms
...
64 bytes from 127.0.0.1: icmp_seq=8 ttl=64 time=0.064 ms
64 bytes from 127.0.0.1: icmp_seq=9 ttl=64 time=0.031 ms
False


问:
Visualize the path on the 2D square
I want to visualize all of the paths on 2D square in matlab.

This code gives me the following figure which consists of a 2D square and randomly distributed of 1 and 0.

https://i.hizliresim.com/Ey4G4D.png

Each 1's must connected with lines from top to bottom.

If there is 1, then there is a way and I have to plot line. Otherwise therre is no way and stop.

Without the boundary elements, there are 3 way for each elements. Each element can go left side, right side or down side.

The top left hand corner's element can go right and down direction.

The top right hand corner's element can go left and down direction.

This is the algorithm of the modelling.

https://i.hizliresim.com/Dy0z0y.jpg

How can I write this code ?

I am waiting your advise :)

答:
Problem analysis

To get an information on the possible paths in your matrix/image you can use the diff function. It calculates the difference between two neighbouring matrix elements along the specified dimension.
The conditions for the existence of a path are:

The difference between the element and its neighbour must be 0

The element itself must be 1

Solution

The following matlab program will create 3 matrices containing the value 1 or true for each element with a path existing to its neighbour.

```<code>matrix = logical([1 1 1 1 0; ...
          1 1 0 1 1; ...
          0 0 0 1 0; ...
          0 0 1 1 0])

hasPathtoRight = false(size(matrix));
hasPathtoRight(:,1:end-1) = (diff(matrix,1,2)==0) & (matrix(:,1:end-1)==1)

hasPathtoLeft = false(size(matrix));
hasPathtoLeft(:,2:end) = (diff(matrix,1,2)==0) & (matrix(:,2:end)==1)

hasPathDown = false(size(matrix));
hasPathDown(1:end-1,:) = (diff(matrix,1,1)==0) & (matrix(1:end-1,:)==1)
</code>```

Result

The result for the example matrix is shown here:

```<code>matrix =

  1  1  1  1  0
  1  1  0  1  1
  0  0  0  1  0
  0  0  1  1  0

hasPathtoRight =

  1  1  1  0  0
  1  0  0  1  0
  0  0  0  0  0
  0  0  1  0  0

hasPathtoLeft =

  0  1  1  1  0
  0  1  0  0  1
  0  0  0  0  0
  0  0  0  1  0

hasPathDown =

  1  1  0  1  0
  0  0  0  1  0
  0  0  0  1  0
  0  0  0  0  0
</code>```

You can use these matrices to draw the paths in a graphical display.

Title: Visualize the path on the 2D square

Body:
Problem analysis

To get an information on the possible paths in your matrix/image you can use the diff function. It calculates the difference between two neighbouring matrix elements along the specified dimension.
The conditions for the existence of a path are:

The difference between the element and its neighbour must be 0

The element itself must be 1

Solution

The following matlab program will create 3 matrices containing the value 1 or true for each element with a path existing to its neighbour.

matrix = logical([1 1 1 1 0; ...
          1 1 0 1 1; ...
          0 0 0 1 0; ...
          0 0 1 1 0])

hasPathtoRight = false(size(matrix));
hasPathtoRight(:,1:end-1) = (diff(matrix,1,2)==0) & (matrix(:,1:end-1)==1)

hasPathtoLeft = false(size(matrix));
hasPathtoLeft(:,2:end) = (diff(matrix,1,2)==0) & (matrix(:,2:end)==1)

hasPathDown = false(size(matrix));
hasPathDown(1:end-1,:) = (diff(matrix,1,1)==0) & (matrix(1:end-1,:)==1)

Result

The result for the example matrix is shown here:

matrix =

  1  1  1  1  0
  1  1  0  1  1
  0  0  0  1  0
  0  0  1  1  0

hasPathtoRight =

  1  1  1  0  0
  1  0  0  1  0
  0  0  0  0  0
  0  0  1  0  0

hasPathtoLeft =

  0  1  1  1  0
  0  1  0  0  1
  0  0  0  0  0
  0  0  0  1  0

hasPathDown =

  1  1  0  1  0
  0  0  0  1  0
  0  0  0  1  0
  0  0  0  0  0

You can use these matrices to draw the paths in a graphical display.


问:
How to plot multiple points on mapbox using a for each statement?
I have a 2D array of longitudes and latitudes and I want to be able to map each of these points on MapBox.

My problem is that the example given is for two points, so I tried applying a for-each loop to iterate through my 2D array and plot the points.
The problem is you need a unique ID to add a layer. I have being following this tutorial located here :
https://www.mapbox.com/help/getting-started-directions-api/

This is the code I have so far, any help would be greatly appreciated!

```<code><body>
//create the map
<div id='map'></div>
<div id='instructions'></div>
<script>
mapboxgl.accessToken = 'ACCESS TOKEN KEY';
var map = new mapboxgl.Map({
  container: 'map', // container id
  style: 'mapbox://styles/mapbox/streets-v9', //stylesheet location
  center: [-6.266155,53.350140], // starting position
  zoom: 12 // starting zoom
});

//load the route function
map.on('load', function(){
  getRoute();
});

//get route takes start and end (lat,long)
function getRoute() {
  //create an array
  var arr = [
    [-6.3053, 53.3562],
    [-6.802586, 53.176861],
    [-6.5991, 53.0918],
    [-6.3053, 53.3562]];

  arr.forEach(function(el, index)
  {

    var nodeOnes = [];
    nodeOnes = arr[0];

    console.log("here" + n);
      map.addLayer({
      id: nodeOnes,
      type: 'circle',
      source: {
        type: 'geojson',
        data: {
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: nodeOnes
          }
        }
      }
    });
});
}
</script>
</code>```

Note I do not include my access token

答:
Instead of adding independent points with their own layer, you could add a FeatureCollection with all your points:</p>

```<code>const allPoints = arr.map(point => ({
    type: 'Feature',
    geometry: {
        type: 'Point',
        coordinates: point
    }
}));

map.addLayer({
    id: 'path',
    type: 'circle',
    source: {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: allPoints
        }
    }
});
</code>```

Body:
I have a 2D array of longitudes and latitudes and I want to be able to map each of these points on MapBox.

My problem is that the example given is for two points, so I tried applying a for-each loop to iterate through my 2D array and plot the points.
The problem is you need a unique ID to add a layer. I have being following this tutorial located here :
https://www.mapbox.com/help/getting-started-directions-api/

This is the code I have so far, any help would be greatly appreciated!

//create the map

Note I do not include my access token

Body:
Instead of adding independent points with their own layer, you could add a FeatureCollection with all your points:

const allPoints = arr.map(point => ({
    type: 'Feature',
    geometry: {
        type: 'Point',
        coordinates: point
    }
}));

map.addLayer({
    id: 'path',
    type: 'circle',
    source: {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: allPoints
        }
    }
});


问:
Is loop a good choice instead of what I have created?
I am learning JS by my own and I have created first little script :). Script is counting the number of signs for the tag tittle of a webpage to be between 50 and 60 etc.... Below there is one button that resets all the data in the script and its working 100% but I have a question -  Can I use some kind of loop instead of that code that I have created? A loop that will be reseting all elements below. Thx for Your help :) and advice...</p>

```<code>// reset Title tag check
document.getElementById("resetTitleBtn").addEventListener("click", function(){
  document.getElementById('inputTitleTag').value = "";
  document.getElementById('titleTag').innerHTML = "";
  document.getElementById('example').innerHTML = "";
  document.getElementById("tytul").style.color = "";
  document.getElementById("good").innerHTML = "";
});
</code>```

答:
If what you are concerned about is being more dry.  Or do not repeat yourself then you could alias a few of your more commonly used functions.  Then looping mechanisms are also nice when a pattern is noticed such as all three of the same prop.  Usually two or less of the same prop is pointless for a loop as a minimum loop is usually 2-3 lines to declare.

```<code>const clear = (element, prop) => element[prop] = "";
const get = (id) => document.getElementById(id);

get("resetTitleBtn").addEventListener("click", () => {
  ['titleTag', 'example', 'good'].forEach(id => clear(get(id), 'innerHTML'));
  clear(get('inputTitleTag'), 'value'));
  clear(get('tytul').style, 'color'));
});
</code>```

This doesn't necessarily improve this sample segment of code but can lead to a more dry pattern throughout the project for commonly used functions.

Body:
I am learning JS by my own and I have created first little script :). Script is counting the number of signs for the tag tittle of a webpage to be between 50 and 60 etc.... Below there is one button that resets all the data in the script and its working 100% but I have a question -  Can I use some kind of loop instead of that code that I have created? A loop that will be reseting all elements below. Thx for Your help :) and advice...

// reset Title tag check
document.getElementById("resetTitleBtn").addEventListener("click", function(){
  document.getElementById('inputTitleTag').value = "";
  document.getElementById('titleTag').innerHTML = "";
  document.getElementById('example').innerHTML = "";
  document.getElementById("tytul").style.color = "";
  document.getElementById("good").innerHTML = "";
});

Body:
If what you are concerned about is being more dry.  Or do not repeat yourself then you could alias a few of your more commonly used functions.  Then looping mechanisms are also nice when a pattern is noticed such as all three of the same prop.  Usually two or less of the same prop is pointless for a loop as a minimum loop is usually 2-3 lines to declare.

const clear = (element, prop) => element[prop] = "";
const get = (id) => document.getElementById(id);

get("resetTitleBtn").addEventListener("click", () => {
  ['titleTag', 'example', 'good'].forEach(id => clear(get(id), 'innerHTML'));
  clear(get('inputTitleTag'), 'value'));
  clear(get('tytul').style, 'color'));
});

This doesn't necessarily improve this sample segment of code but can lead to a more dry pattern throughout the project for commonly used functions.


问:
PacketTrace Default Gateway
I've set up the default gateway of the router I am configurating as serial2/0 as they call it on packet trace with the address of 172.16.68.1. When I try and ping the gateway from the pc with the address 172.16.16.1 I just get an error saying request timed out.

Have I done the default gateway correctly and if I have can anyone suggest what is causing the time out?

答: Answered my own question. The gateway was correct it was the DTE and the DCE that was messed up on my end and causing problems with the pinging as I can now ping it with no problems. Thank you for all your help :)</p>

Title: PacketTrace Default Gateway


问:
How to execute two EF linq query with one db round trip
when we work with ado.net then we can pass multiple sql separated by comma. here is one example.

```<code>SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = @"
     update table
     set somecol = somevalue;
     insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;

try
{
    connection.Open();
}
finally
{
    command.Dispose();
    connection.Dispose();
}
</code>```

i like to know how could i construct EF linq based query which will fetch data from multiple table but there is no relation between two table. so we can not perform join.

so show me a example where EF will fetch data from student and product table without any join with one db round trip. is it possible which was possible by ado.net as per my above example.

```<code> var query = from data in context.Student
                orderby data.name
                select data;

 var query = from data in context.Product
                orderby data.name
                select data;
</code>```

when two above query will run then two database round trip will occur or one ?

i need to fetch data from two table called student and product with one db round trip just like my above EF linq query.

if possible then discuss with sample code. thanks

答: This is not supported out of the box, but there exists a "future queries" package that enables this: https://www.nuget.org/packages/Z.EntityFramework.Plus.QueryFuture.EF6/</p>

Body:
when we work with ado.net then we can pass multiple sql separated by comma. here is one example.

SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = @"
     update table
     set somecol = somevalue;
     insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;

try
{
    connection.Open();
}
finally
{
    command.Dispose();
    connection.Dispose();
}

i like to know how could i construct EF linq based query which will fetch data from multiple table but there is no relation between two table. so we can not perform join.

so show me a example where EF will fetch data from student and product table without any join with one db round trip. is it possible which was possible by ado.net as per my above example.

 var query = from data in context.Student
                orderby data.name
                select data;

 var query = from data in context.Product
                orderby data.name
                select data;

when two above query will run then two database round trip will occur or one ?

i need to fetch data from two table called student and product with one db round trip just like my above EF linq query.

if possible then discuss with sample code. thanks


问:
Python and arduino Serial Communication error
Python3 Code:

```<code>import serial

arduinoData = serial.Serial(4, 9600)

while(1):
    if (arduinoData.inWaiting()>0):
         myData=  arduinoData.readline()
         print (myData)
         arduinoData.open()
</code>```

Error:

```<code>Traceback (most recent call last):
  File "E:/Scripts/Examples/arduinopython.py", line 3, in <module>
    arduinoData = serial.Serial(4, 9600)
  File "C:\Users\Om\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 31, in __init__
    SerialBase.__init__(self, *args, **kwargs)
  File "C:\Users\Om\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialutil.py", line 171, in __init__
    self.open()
  File "C:\Users\Om\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 47, in open
    if port.upper().startswith('COM') and int(port[3:]) > 8:
AttributeError: 'int' object has no attribute 'upper'
</code>```

Can anyone help in finding where I am going wrong ?

答:
serial.Serial constructor need this:

```<code>arduinoData = serial.Serial("COM4", 9600)
</code>```

com_number is string and not int.

Body:
Python3 Code:

import serial

arduinoData = serial.Serial(4, 9600)

while(1):
    if (arduinoData.inWaiting()>0):
         myData=  arduinoData.readline()
         print (myData)
         arduinoData.open()

Error:

Traceback (most recent call last):
  File "E:/Scripts/Examples/arduinopython.py", line 3, in <module>
    arduinoData = serial.Serial(4, 9600)
  File "C:\Users\Om\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 31, in __init__
    SerialBase.__init__(self, *args, **kwargs)
  File "C:\Users\Om\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialutil.py", line 171, in __init__
    self.open()
  File "C:\Users\Om\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 47, in open
    if port.upper().startswith('COM') and int(port[3:]) > 8:
AttributeError: 'int' object has no attribute 'upper'

Can anyone help in finding where I am going wrong ?

Body:
serial.Serial constructor need this:

arduinoData = serial.Serial("COM4", 9600)

com_number is string and not int.


问:
Flexdashboard multiple attributes page
I'm learning flexdashboard and trying some different lay-outs for a future app. But I'm having trouble assigning different attributes for the same page.

I want the second page to have a row lay-out, be listed in nav-bar A and have an icon in front of the title.
When I write them like this: {data-orientation=rows, data-navmenu="Menu A", data-icon="fa-list"} none of them is used. When written like this: {data-orientation=rows}, {data-navmenu="Menu A"}, {data-icon="fa-list"} only the last one is executed and the first two are put in the page-title. When using the second one without commas, the same thing happens.

I haven't found any examples of muliple attributes for a page in the examples.

How do I combine them? It must be possible as I can't imagine I have to chose between giving my page a row-format and putting it in a drop-down menu...

This is the code I used:

```<code>title: "My flexdash"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
```

Page 1 {data-navmenu="Menu A"}
======================================
Column {data-width=350}
-----------------------------------------------------------------------
### Chart A
```{r}

```
Column {data-width=650}
-----------------------------------------------------------------------
### Chart B
```{r}

```
# need these attributes to be working but invisible
Page 2 {data-orientation=rows}, {data-navmenu="Menu A"}, {data-icon="fa-list"}
=============================================
Row {data-width=650}
-----------------------------------------------------------------------
### Chart C
```{r}

```
Row {data-width=350}
-----------------------------------------------------------------------
### Chart D
```{r}

```
</code>```

答:
Found the answer: I only had to separate them by a space...</p>

```<code>Page 2 {data-orientation=rows data-navmenu="Menu A" data-icon="fa-list"}
</code>```

Title: Flexdashboard multiple attributes page

Body:
I'm learning flexdashboard and trying some different lay-outs for a future app. But I'm having trouble assigning different attributes for the same page.

I want the second page to have a row lay-out, be listed in nav-bar A and have an icon in front of the title.
When I write them like this: {data-orientation=rows, data-navmenu="Menu A", data-icon="fa-list"} none of them is used. When written like this: {data-orientation=rows}, {data-navmenu="Menu A"}, {data-icon="fa-list"} only the last one is executed and the first two are put in the page-title. When using the second one without commas, the same thing happens.

I haven't found any examples of muliple attributes for a page in the examples.

How do I combine them? It must be possible as I can't imagine I have to chose between giving my page a row-format and putting it in a drop-down menu...

This is the code I used:

title: "My flexdash"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
```

Page 1 {data-navmenu="Menu A"}
======================================
Column {data-width=350}
-----------------------------------------------------------------------
### Chart A
```{r}

```
Column {data-width=650}
-----------------------------------------------------------------------
### Chart B
```{r}

```
# need these attributes to be working but invisible
Page 2 {data-orientation=rows}, {data-navmenu="Menu A"}, {data-icon="fa-list"}
=============================================
Row {data-width=650}
-----------------------------------------------------------------------
### Chart C
```{r}

```
Row {data-width=350}
-----------------------------------------------------------------------
### Chart D
```{r}

```

Body:
Found the answer: I only had to separate them by a space...

Page 2 {data-orientation=rows data-navmenu="Menu A" data-icon="fa-list"}


问:
Android choose image from gallery showing memory error
I am working on a code sample where I have to choose an image from gallery the code is working but after selection of image from gallery I get OutOfMemoryError in my OnActivityResult

I am able to get small images but large images are creating problem.

Here is my code:

```<code>try{
                    Uri selectedImageUri = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String filePath = cursor.getString(columnIndex);
                    cursor.close();
                    bitmap = BitmapFactory.decodeFile(filePath);
                    _profileImage.setImageBitmap(bitmap);
                    _profileImage.setScaleType(ScaleType.FIT_XY);
                    Constant._addPhotoBitmap=bitmap;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    Bitmap resizedbitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
                    resizedbitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    byte [] _byteArray = baos.toByteArray();
                    String base64 = Base64.encodeToString(_byteArray,Base64.DEFAULT);
                    Constant._addPhotoBase64 = base64;
                }catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    Constant.showAlertDialog(Constant.errorTitle,
                            "Image size is too large.Please upload small image.",
                            DriverProfileScreen.this, false);
                }   catch (Exception e) {
                    e.printStackTrace();
                }
</code>```

答:
I have used below code and used bitmap to store resized Image in local storage and It worked like charm

```<code>final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 8;

        Bitmap b = BitmapFactory.decodeFile(path, options);
</code>```

here path is image Uri path in String

Body:
I am working on a code sample where I have to choose an image from gallery the code is working but after selection of image from gallery I get OutOfMemoryError in my OnActivityResult

I am able to get small images but large images are creating problem.

Here is my code:

try{
                    Uri selectedImageUri = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String filePath = cursor.getString(columnIndex);
                    cursor.close();
                    bitmap = BitmapFactory.decodeFile(filePath);
                    _profileImage.setImageBitmap(bitmap);
                    _profileImage.setScaleType(ScaleType.FIT_XY);
                    Constant._addPhotoBitmap=bitmap;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    Bitmap resizedbitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
                    resizedbitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    byte [] _byteArray = baos.toByteArray();
                    String base64 = Base64.encodeToString(_byteArray,Base64.DEFAULT);
                    Constant._addPhotoBase64 = base64;
                }catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    Constant.showAlertDialog(Constant.errorTitle,
                            "Image size is too large.Please upload small image.",
                            DriverProfileScreen.this, false);
                }   catch (Exception e) {
                    e.printStackTrace();
                }

Body:
I have used below code and used bitmap to store resized Image in local storage and It worked like charm

final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 8;

        Bitmap b = BitmapFactory.decodeFile(path, options);

here path is image Uri path in String


问:
Get value from json with non unique key in php
I have a json object as follows. I need to get val1. I can do this using the following code if I specify the non_unique_name however as the name implied this can change so I am unable to retrieve it.

```<code><?php
$json = '{"key": {"non_unique_name": {"val1": true, "val2": flase}}}';
$array = json_decode( $json, true );
print_r( $array );
$location = $array['key'];
echo $location['non_unique_name']['val1'];
?>
</code>```

I have tried to access it using echo $location[0]['val1']; however this doesn't work. Would anyone know the correct way to access this?

答:
use array_values to get the 'non_unique_name' key values

```<code>$array = json_decode(json_encode($json ),true);
$a =array_values($array['key']);
print_r($a[0]['val1']);
</code>```

Body:
I have a json object as follows. I need to get val1. I can do this using the following code if I specify the non_unique_name however as the name implied this can change so I am unable to retrieve it.

<?php
$json = '{"key": {"non_unique_name": {"val1": true, "val2": flase}}}';
$array = json_decode( $json, true );
print_r( $array );
$location = $array['key'];
echo $location['non_unique_name']['val1'];
?>

I have tried to access it using echo $location[0]['val1']; however this doesn't work. Would anyone know the correct way to access this?

Body:
use array_values to get the 'non_unique_name' key values

$array = json_decode(json_encode($json ),true);
$a =array_values($array['key']);
print_r($a[0]['val1']);


问:
Typing Scala collections
I wanted to learn the new Scala collections framework by making a very general prefix tree. Not only must the keys and the values be parameters, but the type of the maps used in each node must be parameters too. So I tried this:

```<code>import collection.immutable.MapLike

class PrefixMap[+M[K1,+V1] <: Map[K1,V1] with MapLike[K1,V1,M[K1,V1]],K,+V](val content: Option[V], val children: M[K,PrefixMap[M,K,V]])
  extends Map[Iterable[K],V]
  with MapLike[Iterable[K],V,PrefixMap[M,K,V]] {

    override def empty: PrefixMap[M,K,V] = new PrefixMap[M,K,V](None, children.empty)
}
</code>```

But this doesn't compile:

```<code>PrefixMap.scala:19: error: type mismatch;
 found   : scala.collection.immutable.Map[K,PrefixMap[M,K,V]]
 required: M[K,PrefixMap[M,K,V]]
    override def empty: PrefixMap[M,K,V] = new PrefixMap[M,K,V](None, children.empty)
                                                                               ^
one error found
</code>```

This confuses me. I can see from the documentation that a MapLike has an empty that returns "This". So, since children is of type M[K,PrefixMap[M,K,V]], children.empty should be of that type too.

What's going wrong, and can it be mended?

答:
Well, the problem is that MapLike defines an empty that returns This, but Map.empty returns Map!

Try, for instance:

```<code>override def empty: PrefixMap[M,K,V] = new PrefixMap[M,K,V](None, (children: MapLike[K,PrefixMap[M,K,V],M[K,PrefixMap[M,K,V]]]).empty)
</code>```

This will compile, because you are hiding Map's type. The code won't compile because it is missing abstract methods, but that's another matter.

Title: Typing Scala collections

Body:
I wanted to learn the new Scala collections framework by making a very general prefix tree. Not only must the keys and the values be parameters, but the type of the maps used in each node must be parameters too. So I tried this:

import collection.immutable.MapLike

class PrefixMap[+M[K1,+V1] <: Map[K1,V1] with MapLike[K1,V1,M[K1,V1]],K,+V](val content: Option[V], val children: M[K,PrefixMap[M,K,V]])
  extends Map[Iterable[K],V]
  with MapLike[Iterable[K],V,PrefixMap[M,K,V]] {

    override def empty: PrefixMap[M,K,V] = new PrefixMap[M,K,V](None, children.empty)
}

But this doesn't compile:

PrefixMap.scala:19: error: type mismatch;
 found   : scala.collection.immutable.Map[K,PrefixMap[M,K,V]]
 required: M[K,PrefixMap[M,K,V]]
    override def empty: PrefixMap[M,K,V] = new PrefixMap[M,K,V](None, children.empty)
                                                                               ^
one error found

This confuses me. I can see from the documentation that a MapLike has an empty that returns "This". So, since children is of type M[K,PrefixMap[M,K,V]], children.empty should be of that type too.

What's going wrong, and can it be mended?

Body:
Well, the problem is that MapLike defines an empty that returns This, but Map.empty returns Map!

Try, for instance:

override def empty: PrefixMap[M,K,V] = new PrefixMap[M,K,V](None, (children: MapLike[K,PrefixMap[M,K,V],M[K,PrefixMap[M,K,V]]]).empty)

This will compile, because you are hiding Map's type. The code won't compile because it is missing abstract methods, but that's another matter.


问:
Python error: global variable in class undefined
I have a class with two variables set to some default value. I have defined a function where I declare these variables as global inside my function.  I get this error which says the variable is not defined. One variable is counter, which will increment on each function call and other variable has to append message on each call. After appending multiple messages and counter value reaches some threshold I want to insert all these messages into MySQL database.
But the variable is not appending the values. It shows the variable is undefined.</p>

```<code>class Message():
     insertStatement= ''
     insertCounter = 0

    def Save(self, msg)
        global insertCounter
        global insertStatement

        if  msg.topic.startswith("topic1/"):
            insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic2/"):
            insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic3/")
            insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("messages"):
            insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
       else:
            return
       insertcounter +=1
       if(insertCounter > 1000):
         for result in cursor.execute(insertStatement, multi=True):
             print result.row_count  # i changed it to result
</code>```

答: Please check the last line. It should be result instead of reslut.

Body:
I have a class with two variables set to some default value. I have defined a function where I declare these variables as global inside my function.  I get this error which says the variable is not defined. One variable is counter, which will increment on each function call and other variable has to append message on each call. After appending multiple messages and counter value reaches some threshold I want to insert all these messages into MySQL database.
But the variable is not appending the values. It shows the variable is undefined.

class Message():
     insertStatement= ''
     insertCounter = 0

    def Save(self, msg)
        global insertCounter
        global insertStatement

        if  msg.topic.startswith("topic1/"):
            insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic2/"):
            insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic3/")
            insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("messages"):
            insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
       else:
            return
       insertcounter +=1
       if(insertCounter > 1000):
         for result in cursor.execute(insertStatement, multi=True):
             print result.row_count  # i changed it to result


问:
swift 4 error: load html string to webview
I tried to load a html string in my webview with the code :

```<code>let htmlFile = Bundle.main.path(forResource: "code", ofType: "html")
        let html = try! String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
        self.weview.loadHTMLString(html, baseURL: nil)
</code>```

I run the app, everything works fine, but if i press on a website link, i get the error in my AppDelegate: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)
Can someone give me a code for swift 4, where I can load a html string and interact with it? Would be really nice.

答:
Try This :</p>

```<code>let link = "https://google.co.in"
do {
    let htmlStr = try String(contentsOf : URL(string:link)!)
    let separateHtmlStr = htmlStr.components(separatedBy:"") // any html tag you want to interact with

    let newURL = URL(string: link)
    yourWebView.loadHTMLString(separateHtmlStr, baseURL: newURL) // in case if you have changed anything

   }catch{
        print("Exception")
    }
}
</code>```

Body:
I tried to load a html string in my webview with the code :

let htmlFile = Bundle.main.path(forResource: "code", ofType: "html")
        let html = try! String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
        self.weview.loadHTMLString(html, baseURL: nil)

I run the app, everything works fine, but if i press on a website link, i get the error in my AppDelegate: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)
Can someone give me a code for swift 4, where I can load a html string and interact with it? Would be really nice.

Body:
Try This :

let link = "https://google.co.in"
do {
    let htmlStr = try String(contentsOf : URL(string:link)!)
    let separateHtmlStr = htmlStr.components(separatedBy:"") // any html tag you want to interact with

    let newURL = URL(string: link)
    yourWebView.loadHTMLString(separateHtmlStr, baseURL: newURL) // in case if you have changed anything

   }catch{
        print("Exception")
    }
}


问:
How to get part of filename into a variable?
I have a lot of .csv files and I'd like to parse the file names.

The file names are in this format:

```<code>name.surname.csv
</code>```

How can I write a function that populates two variables with the components of the file name?

```<code>A = name
B = surname
</code>```

答:
First find all the files in your directory with the extention '.csv', then split it by '.'</p>

```<code>import os
for file in os.listdir("/mydir"):
    if file.endswith(".csv"):
        # print the file name
        print(os.path.join("/mydir", file))
        # split the file name by '.'
        name, surname, ext = file.split(".")
        # print or append or whatever you will do with the result here
</code>```

Body:
I have a lot of .csv files and I'd like to parse the file names.

The file names are in this format:

name.surname.csv

How can I write a function that populates two variables with the components of the file name?

A = name
B = surname

Body:
First find all the files in your directory with the extention '.csv', then split it by '.'

import os
for file in os.listdir("/mydir"):
    if file.endswith(".csv"):
        # print the file name
        print(os.path.join("/mydir", file))
        # split the file name by '.'
        name, surname, ext = file.split(".")
        # print or append or whatever you will do with the result here


问:
function onEdit() runs only partially
I have a very frustrating problem on my hands and I turn to you for help once more. I had the onEdit() function below which, together with the auxiliary functions, worked fine.

```<code>function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var activeSheet = ss.getActiveSheet();
  var activeCell = activeSheet.getActiveCell();

  //Check if the sheet is a JOb sheet and the cell us the status cell
  if ( activeSheet.getName().indexOf("Job ID") != -1 && activeCell.getRow() == 4 && activeCell.getColumn() == 15 ) {
    var targetSheet = ss.getSheetByName('Active Jobs');
    var jobRowNumber = findJobIdRow();
    var sourceCell = activeSheet.getRange(4,15);
    sourceCell.copyTo(targetSheet.getRange(jobRowNumber,16));
  }

  if (activeSheet.getName().indexOf("Job ID") != -1 && activeCell.getRow() == 2 && activeCell.getColumn() == 15){
    var switchValue = activeCell.getValue();
    switch (switchValue){
      case "On hold (i)":
      case "On hold (ii)":
      case "On hold (iii)":
      case "To be assigned":
        //Write date to active jobs sheet
        addDateToActive("TBC");
        break;
      case "In progress":
        var newDate = Browser.inputBox("Please enter report out date, example 18-Aug-2017");
        addDateToActive(newDate);
        break;
      //default:
        //Browser.msgBox("GOTHERE");
    }
  }
}

function findJobIdRow() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var jobID = ss.getActiveSheet().getRange(2,1).getValue();
  var column = ss.getSheetByName('Active Jobs').getRange(2,1,ss.getSheetByName('Active Jobs').getMaxRows()-2,1);
  var values = column.getValues(); // get all data in one call
  for(var ct = 0; ct < values.length-1; ct++){
    if(values[ct][0] == jobID){
      var ct = ct+2;
      break;
    }
  }
  return ct;
}

function addDateToActive(input){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var activeSheet = ss.getActiveSheet();
  var activeCell = activeSheet.getActiveCell();
  var jobid = activeSheet.getRange(2,1).getValue().toString();
  var activeJobSheet = ss.getSheetByName("Active Jobs");
  var activeJobs = activeJobSheet.getRange(1,1,activeJobSheet.getLastRow(),1).getValues();
  activeJobs = ColumnToArray(activeJobs);
  var jobrow = activeJobs.indexOf(jobid)+1;
  if (jobrow == -1){
    Browser.msgBox("Job Id not preent on Active Jobs sheet");
  }else{
    activeJobSheet.getRange(jobrow,15).setValue(input);
  }
}
</code>```

Then I included some code in this script which was supposed to send out some e-mails to people if some dates were approaching today's date. There were some problems with that code because of authorization requirement so I moved it into it's own separate function and came back to the original script that is posted above. Now the problem I am facing is, although this script works fine if ran from the script editor, manually run from a drawing button in the spreadsheet, or is ran by a on edit trigger I set up from the "Current project triggers" menu, it will not do the entire script if the script is triggered by the onEdit() function name. It does the first bit where it copies the content of a cell across but not the second bit with the case switch.

The obvious fix would be to just set up the trigger from the "Current project triggers" but this onEdit detection needs to apply to anyone in my team that edits this sheet. If I set it up like that it will work for me but no one else from my team.

Any help would be appreciated.

答:
Setting up the trigger via the function name onEdit() proving tricky I wrote this bit of code and attached it to a drawing in the sheet. Then instructed all the users to click it which set up the trigger for them. This solved the problem and the trigger works fine now.</p>

```<code>function triggerSetUp(){
  var sheet = SpreadsheetApp.getActive();
 ScriptApp.newTrigger("enforcer").forSpreadsheet(sheet).onEdit().create();
}
</code>```

Title: function onEdit() runs only partially

Body:
I have a very frustrating problem on my hands and I turn to you for help once more. I had the onEdit() function below which, together with the auxiliary functions, worked fine.

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var activeSheet = ss.getActiveSheet();
  var activeCell = activeSheet.getActiveCell();

  //Check if the sheet is a JOb sheet and the cell us the status cell
  if ( activeSheet.getName().indexOf("Job ID") != -1 && activeCell.getRow() == 4 && activeCell.getColumn() == 15 ) {
    var targetSheet = ss.getSheetByName('Active Jobs');
    var jobRowNumber = findJobIdRow();
    var sourceCell = activeSheet.getRange(4,15);
    sourceCell.copyTo(targetSheet.getRange(jobRowNumber,16));
  }

  if (activeSheet.getName().indexOf("Job ID") != -1 && activeCell.getRow() == 2 && activeCell.getColumn() == 15){
    var switchValue = activeCell.getValue();
    switch (switchValue){
      case "On hold (i)":
      case "On hold (ii)":
      case "On hold (iii)":
      case "To be assigned":
        //Write date to active jobs sheet
        addDateToActive("TBC");
        break;
      case "In progress":
        var newDate = Browser.inputBox("Please enter report out date, example 18-Aug-2017");
        addDateToActive(newDate);
        break;
      //default:
        //Browser.msgBox("GOTHERE");
    }
  }
}

function findJobIdRow() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var jobID = ss.getActiveSheet().getRange(2,1).getValue();
  var column = ss.getSheetByName('Active Jobs').getRange(2,1,ss.getSheetByName('Active Jobs').getMaxRows()-2,1);
  var values = column.getValues(); // get all data in one call
  for(var ct = 0; ct < values.length-1; ct++){
    if(values[ct][0] == jobID){
      var ct = ct+2;
      break;
    }
  }
  return ct;
}

function addDateToActive(input){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var activeSheet = ss.getActiveSheet();
  var activeCell = activeSheet.getActiveCell();
  var jobid = activeSheet.getRange(2,1).getValue().toString();
  var activeJobSheet = ss.getSheetByName("Active Jobs");
  var activeJobs = activeJobSheet.getRange(1,1,activeJobSheet.getLastRow(),1).getValues();
  activeJobs = ColumnToArray(activeJobs);
  var jobrow = activeJobs.indexOf(jobid)+1;
  if (jobrow == -1){
    Browser.msgBox("Job Id not preent on Active Jobs sheet");
  }else{
    activeJobSheet.getRange(jobrow,15).setValue(input);
  }
}

Then I included some code in this script which was supposed to send out some e-mails to people if some dates were approaching today's date. There were some problems with that code because of authorization requirement so I moved it into it's own separate function and came back to the original script that is posted above. Now the problem I am facing is, although this script works fine if ran from the script editor, manually run from a drawing button in the spreadsheet, or is ran by a on edit trigger I set up from the "Current project triggers" menu, it will not do the entire script if the script is triggered by the onEdit() function name. It does the first bit where it copies the content of a cell across but not the second bit with the case switch.

The obvious fix would be to just set up the trigger from the "Current project triggers" but this onEdit detection needs to apply to anyone in my team that edits this sheet. If I set it up like that it will work for me but no one else from my team.

Any help would be appreciated.

Body:
Setting up the trigger via the function name onEdit() proving tricky I wrote this bit of code and attached it to a drawing in the sheet. Then instructed all the users to click it which set up the trigger for them. This solved the problem and the trigger works fine now.

function triggerSetUp(){
  var sheet = SpreadsheetApp.getActive();
 ScriptApp.newTrigger("enforcer").forSpreadsheet(sheet).onEdit().create();
}


问:
Linux Apache PHP: ERR_EMPTY_RESPONSE
Apache and PHP are installed right now.
I test my php code which is right on windows.

Chrome report page can not load:ERR_EMPTY_RESPONSE.

It seems $_POST do not work.

note.php

```<code><?php
  session_start();
  _SESSION['note']='<p>'.$_POST['text'].'</p>'.$_SESSION['note'];
?>
<html>
  <body>
    <title>Note</title>
    <form method="post" action="note.php" name=form1>
      <input type="text" name="text" size=100 required>
      <input type="submit" value="submit" name="B1">
      <input type="reset" value="reset" name="B2">
    </form>
    <?php
      echo $_SESSION['note'];
    ?>
  </body>
</html>
</code>```

Change the form to GET method, it works well.

```<code><?php
  session_start();
  $_SESSION['note']='<p>'.$_GET['text'].'</p>'.$_SESSION['note'];
?>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>
  <body>
    <title>Note</title>
    <form method="get" action="note.php" name=form1>
      <input type="text" name="text" size=100>
      <input type="submit" value="submit" name="B1">
      <input type="reset" value="reset" name="B2">
    </form>
    <?php
      echo $_SESSION['note'];
    ?>
  </body>
</html>
</code>```

答: I had a similar issue. My problem was that I had some invalid settings in the .htaccess file. It could be a good idea to deactivate line by line in the htaccess to see if that's causing the problem

Title: Linux Apache PHP: ERR_EMPTY_RESPONSE

Body:
Apache and PHP are installed right now.
I test my php code which is right on windows.

Chrome report page can not load:ERR_EMPTY_RESPONSE.

It seems $_POST do not work.

note.php

<?php
  session_start();
  _SESSION['note']='
'.$_POST['text'].'
'.$_SESSION['note'];
?>

    <title>Note</title>
    <form method="post" action="note.php" name=form1>
      <input type="text" name="text" size=100 required>
      <input type="submit" value="submit" name="B1">
      <input type="reset" value="reset" name="B2">
    </form>
    <?php
      echo $_SESSION['note'];
    ?>

Change the form to GET method, it works well.

<?php
  session_start();
  $_SESSION['note']='
'.$_GET['text'].'
'.$_SESSION['note'];
?>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <title>Note</title>
    <form method="get" action="note.php" name=form1>
      <input type="text" name="text" size=100>
      <input type="submit" value="submit" name="B1">
      <input type="reset" value="reset" name="B2">
    </form>
    <?php
      echo $_SESSION['note'];
    ?>


问:
Run inner query once, use results for math in outer query
Aloha,

I need to run a simple (SELECT * FROM tbl1 WHERE Col1=x) then use the single row that results from this query to perform math on another query. For example, the outer query could be SELECT tbl2.col4 * tbl1.col5 AS firstResult

Basically, tbl1 is full of numeric statistical weights that I need to use to multiply on the values in tbl2. the query on tbl1 will only ever return 1 row.

I would be perfectly happy joining the resulting tbl1 row to all returned tbl2 rows and then doing math, but I have no join values in the tables. I tried to add a '1' AS JoinID to both tables, but that didn't work either.

Thanks guys,
Chris

答:
First thing came to my mind was to use something like this:

```<code>select tbl2.col4 * tbl1x.col5 from tbl2, (select * from tbl1 where col1 = x) as tbl1x;
</code>```

if I'm getting your question right.

Body:
First thing came to my mind was to use something like this:

select tbl2.col4 * tbl1x.col5 from tbl2, (select * from tbl1 where col1 = x) as tbl1x;

if I'm getting your question right.


问:
How to use Coroutines and Callback properly? Retrieving an array out of an IEnumerator
we have some trouble with an IEnumerator and don't know how to retrieve an array out of it. We found out that you have to do it with a callback , but we don't really know how to use it. Here is the code of the IEnumerator and the void that needs to receive a string array from it.

```<code>public void StartRoutineGetProjects(string username, string password, string url){
    StartCoroutine(GetProjects(username, password, url));

    // here we dont know how to receive the array, need some help here
}

public IEnumerator GetProjects (string username, string password, string url, Action<string[]> callback)
{
    string privateURL = "http://" + url + "/Unity/myprojects.php";

    WWWForm form = new WWWForm ();
    form.AddField ("username", username);
    form.AddField ("password", password);

    // Send WWWForm
    WWW projects_get = new WWW (privateURL, form);

    if (projects_get.error != null && projects_get.error != "") {
        Debug.Log ("Internal Error");
    } else {
        // splitting the result at "|"
        string[] tempProjects = projects_get.text.Split ("|".ToCharArray ());

        yield return tempProjects;

        callback(tempProjects) // <-- here we want to return the array

    }
}
</code>```

We would be glad for every help we can get.

答:
Thank you very much for your help, I changed my code as you said.
Unfortunately I missed something in my first post. The void function is a string[]-function as well, that shall pass the array to another script. Here is the code , how it looks now. I have to return the string[] somehow , but i don't know exactly where to do this.</p>

```<code>    public string[] StartRoutineGetProjects(string username, string password, string url){
    string[] temp;

    StartCoroutine(GetProjects(username, password, url,(stringArray)=>{
        temp = stringArray;
    }));
}

public IEnumerator GetProjects (string username, string password, string url, Action<string[]> callback)
{
    string privateURL = "http://" + url + "/Unity/myprojects.php";

    WWWForm form = new WWWForm ();
    form.AddField ("username", username);
    form.AddField ("password", password);

    // send WWWForm
    WWW projects_get = new WWW (privateURL, form);

    // Receiving projects
    yield return projects_get;

    if (projects_get.error != null && projects_get.error != "") {
        Debug.Log ("Interner Fehler");
        callback (null);
    } else {
        // splitting the result at "|"
        string[] tempProjekte = projects_get.text.Split ("|".ToCharArray ());

        callback (tempProjekte);
    }
}
</code>```

Body:
we have some trouble with an IEnumerator and don't know how to retrieve an array out of it. We found out that you have to do it with a callback , but we don't really know how to use it. Here is the code of the IEnumerator and the void that needs to receive a string array from it.

public void StartRoutineGetProjects(string username, string password, string url){
    StartCoroutine(GetProjects(username, password, url));

    // here we dont know how to receive the array, need some help here
}

public IEnumerator GetProjects (string username, string password, string url, Action<string[]> callback)
{
    string privateURL = "http://" + url + "/Unity/myprojects.php";

    WWWForm form = new WWWForm ();
    form.AddField ("username", username);
    form.AddField ("password", password);

    // Send WWWForm
    WWW projects_get = new WWW (privateURL, form);

    if (projects_get.error != null && projects_get.error != "") {
        Debug.Log ("Internal Error");
    } else {
        // splitting the result at "|"
        string[] tempProjects = projects_get.text.Split ("|".ToCharArray ());

        yield return tempProjects;

        callback(tempProjects) // <-- here we want to return the array

    }
}

We would be glad for every help we can get.

Body:
Thank you very much for your help, I changed my code as you said.
Unfortunately I missed something in my first post. The void function is a string[]-function as well, that shall pass the array to another script. Here is the code , how it looks now. I have to return the string[] somehow , but i don't know exactly where to do this.

    public string[] StartRoutineGetProjects(string username, string password, string url){
    string[] temp;

    StartCoroutine(GetProjects(username, password, url,(stringArray)=>{
        temp = stringArray;
    }));
}

public IEnumerator GetProjects (string username, string password, string url, Action<string[]> callback)
{
    string privateURL = "http://" + url + "/Unity/myprojects.php";

    WWWForm form = new WWWForm ();
    form.AddField ("username", username);
    form.AddField ("password", password);

    // send WWWForm
    WWW projects_get = new WWW (privateURL, form);

    // Receiving projects
    yield return projects_get;

    if (projects_get.error != null && projects_get.error != "") {
        Debug.Log ("Interner Fehler");
        callback (null);
    } else {
        // splitting the result at "|"
        string[] tempProjekte = projects_get.text.Split ("|".ToCharArray ());

        callback (tempProjekte);
    }
}