问:
My Views are not Visible in my RecyclerView
In am app I get data from the server but when I run the program, I don't get any error and I don't see anything on the screen. so basically my RecyclerView is blank. I don't know what is wrong.
MainActivity class:

```<code>public class MainActivity extends AppCompatActivity implements RecyclerView.OnClickListener {
    RecyclerView recyclerView;
    List<BlogResponse> blogResponses;
    RetrofitAdapter retrofitAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        blogResponses = new ArrayList<>();
        recyclerView =(RecyclerView) findViewById(R.id.recyclerView);
        LinearLayoutManager linear = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linear);
        getBlogpost();

        recyclerView.setOnClickListener(this);
    }

    private void getBlogpost() {
        //final ProgressDialog loading = ProgressDialog.show(this, "Fetching Data for blog", " Please wait...", false, false);
        BlogaPI apiService = ApiClient.getClient().create(BlogaPI.class);
        Call<BlogList> call = apiService.getBlogpost();
        call.enqueue(new Callback<BlogList>() {
            @Override
            public void onResponse(Call<BlogList> call, Response<BlogList> response) {
               // loading.dismiss();
                if (response.isSuccessful()){
                    blogResponses = response.body().getBlogResponses();
                    retrofitAdapter = new RetrofitAdapter(blogResponses,getApplicationContext());
                    recyclerView.setAdapter(retrofitAdapter);
                } else {
                    Toast.makeText(MainActivity.this, "Something is wrong", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<BlogList> call, Throwable t) {
            //    loading.dismiss();
                Log.e("MainActivity:", t.toString());

            }
        });/*
        Call<List<BlogResponse>> call = apiService.getBlogpost();
        call.enqueue(new Callback<List<BlogResponse>>() {
            @Override
            public void onResponse(Call<List<BlogResponse>> call, Response<List<BlogResponse>> response) {
                List<BlogResponse> blogresp = response.body();
                recyclerView.setAdapter(new RetrofitAdapter(blogresp,R.layout.custom_view,getApplicationContext(),
                        new RetrofitAdapter.ItemListener(){

                            @Override
                            public void onPostClick(String blogId) {
                                Toast.makeText(getApplicationContext(), "Post ID is " + blogId, Toast.LENGTH_SHORT).show();
                            }
                        }));
            }

            @Override
            public void onFailure(Call<List<BlogResponse>> call, Throwable t) {
                Log.e("MainActivity:", t.toString());
            }
        });*/
    }

    @Override
    public void onClick(View view) {

    }
}
</code>```

Adapter class:

```<code>public class RetrofitAdapter extends RecyclerView.Adapter<RetrofitAdapter.RetrofitViewHolder> {
List<BlogResponse> blogResponseList;
Context context;

public RetrofitAdapter (List<BlogResponse> blogResponseList, Context context){
    this.blogResponseList = blogResponseList;
    this.context = context;
}
@Override
public RetrofitAdapter.RetrofitViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_view, parent, false);
    return new RetrofitViewHolder(view);
}

@Override
public void onBindViewHolder(RetrofitViewHolder holder, int position) {
    Log.i("RetrofitAdapter", "onBindViewHolder: "+ position);
    BlogResponse blogResponse = blogResponseList.get(position);
    holder.summary.setText(blogResponse.getBlogExcerpt());
    holder.title.setText(blogResponse.getBlogTitle());
    holder.thumbnail_cover.setImageResource(Integer.getInteger(blogResponse.getBlogThumbnail()));
}

@Override
public int getItemCount() {
    return blogResponseList.size() ;
}
public void updateItems(List items ){
    this.blogResponseList = items;
    notifyDataSetChanged();
}

public class RetrofitViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    TextView title;
    TextView summary;
    ImageView thumbnail_cover;
    public RetrofitViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.post_title);
        summary = (TextView) itemView.findViewById(R.id.post_summary);
        thumbnail_cover = (ImageView) itemView.findViewById(R.id.post_thumbnail);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        BlogResponse items = getItem(getAdapterPosition());
        this.getAdapterPosition();
        notifyDataSetChanged();
    }
}

private BlogResponse getItem(int adapterPosition) {
    return blogResponseList.get(adapterPosition);
}
}
</code>```

Blogapi interface

```<code> public interface BlogaPI {
  @GET("blog")
  Call<BlogList> getBlogpost();
}
</code>```

BlogList class:

```<code>public class BlogList  {
    @SerializedName("blog")
    @Expose
    private ArrayList<BlogResponse> blogResponses = new ArrayList<>();
}
</code>```

BlogResponse class

```<code>import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class BlogResponse {

    @SerializedName("blog_id")
    @Expose
    private String blogId;
    @SerializedName("blog_title")
    @Expose
    private String blogTitle;
    @SerializedName("blog_subtitle")
    @Expose
    private String blogSubtitle;
    @SerializedName("blog_excerpt")
    @Expose
    private String blogExcerpt;
    @SerializedName("blog_content")
    @Expose
    private String blogContent;
    @SerializedName("blog_thumbnail")
    @Expose
    private String blogThumbnail;
    @SerializedName("blog_medimg")
    @Expose
    private String blogMedimg;
    @SerializedName("category_title")
    @Expose
    private String categoryTitle;
    public  BlogResponse(String blogId, String blogTitle, String blogSubtitle, String blogExcerpt,String blogContent, String blogThumbnail, String blogMedimg){
        this.blogId = blogId;
        this.blogTitle = blogTitle;
        this.blogSubtitle = blogSubtitle;
        this.blogExcerpt = blogExcerpt;
        this.blogContent = blogContent;
        this.blogThumbnail = blogThumbnail;
        this.blogMedimg = blogMedimg;
    }

    public String getBlogId() {
        return blogId;
    }

    public void setBlogId(String blogId) {
        this.blogId = blogId;
    }

    public String getBlogTitle() {
        return blogTitle;
    }

    public void setBlogTitle(String blogTitle) {
        this.blogTitle = blogTitle;
    }

    public String getBlogSubtitle() {
        return blogSubtitle;
    }

    public void setBlogSubtitle(String blogSubtitle) {
        this.blogSubtitle = blogSubtitle;
    }

    public String getBlogExcerpt() {
        return blogExcerpt;
    }

    public void setBlogExcerpt(String blogExcerpt) {
        this.blogExcerpt = blogExcerpt;
    }

    public String getBlogContent() {
        return blogContent;
    }

    public void setBlogContent(String blogContent) {
        this.blogContent = blogContent;
    }

    public String getBlogThumbnail() {
        return blogThumbnail;
    }

    public void setBlogThumbnail(String blogThumbnail) {
        this.blogThumbnail = blogThumbnail;
    }

    public String getBlogMedimg() {
        return blogMedimg;
    }

    public void setBlogMedimg(String blogMedimg) {
        this.blogMedimg = blogMedimg;
    }

    public String getCategoryTitle() {
        return categoryTitle;
    }

    public void setCategoryTitle(String categoryTitle) {
        this.categoryTitle = categoryTitle;
    }
}
</code>```

ApiClient:

```<code> public class ApiClient {
    private static final String STAGING_BASE_URL = "https://watchnollywood.ml/api/";
    private  static Retrofit retrofit = null;

    public static Retrofit getClient(){
      if (retrofit == null){
        retrofit = new Retrofit.Builder()
               .baseUrl(STAGING_BASE_URL)
               .addConverterFactory(GsonConverterFactory.create())
               .build();
   }
    return retrofit;
}
}
</code>```

Please help. Thanks

答:
Basic things needs to taken care of while working with RecyclerView.Adapter<> and you got stuck into problems like above

My Views are not Visible in my RecyclerView

Make sure your data passed correctly

 Try printing your dataset size into getItemCount() method

Make sure row_item height is set to wrap_content(Common mistakes that beginners do.)

Make sure you are adding items into dataset using add() or addAll() rather than direct assigning a reference.

Body:
In am app I get data from the server but when I run the program, I don't get any error and I don't see anything on the screen. so basically my RecyclerView is blank. I don't know what is wrong.
MainActivity class:

public class MainActivity extends AppCompatActivity implements RecyclerView.OnClickListener {
    RecyclerView recyclerView;
    List<BlogResponse> blogResponses;
    RetrofitAdapter retrofitAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        blogResponses = new ArrayList<>();
        recyclerView =(RecyclerView) findViewById(R.id.recyclerView);
        LinearLayoutManager linear = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linear);
        getBlogpost();

        recyclerView.setOnClickListener(this);
    }

    private void getBlogpost() {
        //final ProgressDialog loading = ProgressDialog.show(this, "Fetching Data for blog", " Please wait...", false, false);
        BlogaPI apiService = ApiClient.getClient().create(BlogaPI.class);
        Call<BlogList> call = apiService.getBlogpost();
        call.enqueue(new Callback<BlogList>() {
            @Override
            public void onResponse(Call<BlogList> call, Response<BlogList> response) {
               // loading.dismiss();
                if (response.isSuccessful()){
                    blogResponses = response.body().getBlogResponses();
                    retrofitAdapter = new RetrofitAdapter(blogResponses,getApplicationContext());
                    recyclerView.setAdapter(retrofitAdapter);
                } else {
                    Toast.makeText(MainActivity.this, "Something is wrong", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<BlogList> call, Throwable t) {
            //    loading.dismiss();
                Log.e("MainActivity:", t.toString());

            }
        });/*
        Call<List<BlogResponse>> call = apiService.getBlogpost();
        call.enqueue(new Callback<List<BlogResponse>>() {
            @Override
            public void onResponse(Call<List<BlogResponse>> call, Response<List<BlogResponse>> response) {
                List<BlogResponse> blogresp = response.body();
                recyclerView.setAdapter(new RetrofitAdapter(blogresp,R.layout.custom_view,getApplicationContext(),
                        new RetrofitAdapter.ItemListener(){

                            @Override
                            public void onPostClick(String blogId) {
                                Toast.makeText(getApplicationContext(), "Post ID is " + blogId, Toast.LENGTH_SHORT).show();
                            }
                        }));
            }

            @Override
            public void onFailure(Call<List<BlogResponse>> call, Throwable t) {
                Log.e("MainActivity:", t.toString());
            }
        });*/
    }

    @Override
    public void onClick(View view) {

    }
}

Adapter class:

public class RetrofitAdapter extends RecyclerView.Adapter<RetrofitAdapter.RetrofitViewHolder> {
List<BlogResponse> blogResponseList;
Context context;

public RetrofitAdapter (List<BlogResponse> blogResponseList, Context context){
    this.blogResponseList = blogResponseList;
    this.context = context;
}
@Override
public RetrofitAdapter.RetrofitViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_view, parent, false);
    return new RetrofitViewHolder(view);
}

@Override
public void onBindViewHolder(RetrofitViewHolder holder, int position) {
    Log.i("RetrofitAdapter", "onBindViewHolder: "+ position);
    BlogResponse blogResponse = blogResponseList.get(position);
    holder.summary.setText(blogResponse.getBlogExcerpt());
    holder.title.setText(blogResponse.getBlogTitle());
    holder.thumbnail_cover.setImageResource(Integer.getInteger(blogResponse.getBlogThumbnail()));
}

@Override
public int getItemCount() {
    return blogResponseList.size() ;
}
public void updateItems(List items ){
    this.blogResponseList = items;
    notifyDataSetChanged();
}

public class RetrofitViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    TextView title;
    TextView summary;
    ImageView thumbnail_cover;
    public RetrofitViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.post_title);
        summary = (TextView) itemView.findViewById(R.id.post_summary);
        thumbnail_cover = (ImageView) itemView.findViewById(R.id.post_thumbnail);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        BlogResponse items = getItem(getAdapterPosition());
        this.getAdapterPosition();
        notifyDataSetChanged();
    }
}

private BlogResponse getItem(int adapterPosition) {
    return blogResponseList.get(adapterPosition);
}
}

Blogapi interface

 public interface BlogaPI {
  @GET("blog")
  Call<BlogList> getBlogpost();
}

BlogList class:

public class BlogList  {
    @SerializedName("blog")
    @Expose
    private ArrayList<BlogResponse> blogResponses = new ArrayList<>();
}

BlogResponse class

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class BlogResponse {

    @SerializedName("blog_id")
    @Expose
    private String blogId;
    @SerializedName("blog_title")
    @Expose
    private String blogTitle;
    @SerializedName("blog_subtitle")
    @Expose
    private String blogSubtitle;
    @SerializedName("blog_excerpt")
    @Expose
    private String blogExcerpt;
    @SerializedName("blog_content")
    @Expose
    private String blogContent;
    @SerializedName("blog_thumbnail")
    @Expose
    private String blogThumbnail;
    @SerializedName("blog_medimg")
    @Expose
    private String blogMedimg;
    @SerializedName("category_title")
    @Expose
    private String categoryTitle;
    public  BlogResponse(String blogId, String blogTitle, String blogSubtitle, String blogExcerpt,String blogContent, String blogThumbnail, String blogMedimg){
        this.blogId = blogId;
        this.blogTitle = blogTitle;
        this.blogSubtitle = blogSubtitle;
        this.blogExcerpt = blogExcerpt;
        this.blogContent = blogContent;
        this.blogThumbnail = blogThumbnail;
        this.blogMedimg = blogMedimg;
    }

    public String getBlogId() {
        return blogId;
    }

    public void setBlogId(String blogId) {
        this.blogId = blogId;
    }

    public String getBlogTitle() {
        return blogTitle;
    }

    public void setBlogTitle(String blogTitle) {
        this.blogTitle = blogTitle;
    }

    public String getBlogSubtitle() {
        return blogSubtitle;
    }

    public void setBlogSubtitle(String blogSubtitle) {
        this.blogSubtitle = blogSubtitle;
    }

    public String getBlogExcerpt() {
        return blogExcerpt;
    }

    public void setBlogExcerpt(String blogExcerpt) {
        this.blogExcerpt = blogExcerpt;
    }

    public String getBlogContent() {
        return blogContent;
    }

    public void setBlogContent(String blogContent) {
        this.blogContent = blogContent;
    }

    public String getBlogThumbnail() {
        return blogThumbnail;
    }

    public void setBlogThumbnail(String blogThumbnail) {
        this.blogThumbnail = blogThumbnail;
    }

    public String getBlogMedimg() {
        return blogMedimg;
    }

    public void setBlogMedimg(String blogMedimg) {
        this.blogMedimg = blogMedimg;
    }

    public String getCategoryTitle() {
        return categoryTitle;
    }

    public void setCategoryTitle(String categoryTitle) {
        this.categoryTitle = categoryTitle;
    }
}

ApiClient:

 public class ApiClient {
    private static final String STAGING_BASE_URL = "https://watchnollywood.ml/api/";
    private  static Retrofit retrofit = null;

    public static Retrofit getClient(){
      if (retrofit == null){
        retrofit = new Retrofit.Builder()
               .baseUrl(STAGING_BASE_URL)
               .addConverterFactory(GsonConverterFactory.create())
               .build();
   }
    return retrofit;
}
}

Please help. Thanks


来源: stackexchange

问:
uncaught TypeError: Cannot read property 'style' of null at frame
Im making a loading bar.

And now i got an error when i click on download

Uncaught TypeError: Cannot read property 'style' of null

I dont know what i am dong wrong please can someone help me here is my code

```<code><a class="tooltip-test" id="header"><div class="progress" id="headerTop" style="cursor:default">
                <div id="myElement" class="progress-bar bg-info progress-bar-striped progress-bar-animated myBar" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
                    <p class="text-center">0%</p>
                </div>
            </div></a>
            <button onclick="move()" type="button" class="btn btn-outline-primary btn-lg">download</button>
        </div>
        <script type="text/javascript">
            function move() {
                document.getElementById("headerTop").style.cursor = "wait";
                var elem = document.getElementById("myBar");
                var width = 0;
                var id = setInterval(frame, 1000);
                function frame() {
                    if (width >= 99) {
                        var number = random(99, 100)
                        if(number = 99) {
                            clearInterval(id);
                            document.getElementById("MyElement").className =
                            document.getElementById("MyElement").className.replace
                            ( /(?:^|\s)bg-info(?!\S)/g , 'bg-danger' )
                            document.getElementById("header").title = "Oops looks like something has gone wrong reload the page to start over";
                        }else if (number = 100) {
                            clearInterval(id);
                            document.getElementById("MyElement").className =
                            document.getElementById("MyElement").className.replace
                            ( /(?:^|\s)bg-info(?!\S)/g , 'bg-success' )
                            document.getElementById("header").title = "download is ready";
                        }
                    } else {
                        width++;
                        elem.style.width = width + '%';
                        elem.innerHTML = width * 1 + '%';
                    }
                }
            }
    </script>
</code>```

F.Y.I i am using bootstrap for the styling

答:
After Jonathan's correction, another issue might be that elem, width and id are defined in the parent move() function, and not in the child frame() function.

```<code><script type="text/javascript">
            function move() {
                document.getElementById("headerTop").style.cursor = "wait";
                function frame() {
                    var elem = document.getElementById("myElement");
                    var width = 0;
                    var id = setInterval(frame, 1000);
                    if (width >= 99) {
                        var number = random(99, 100)
                        if(number = 99) {
                            clearInterval(id);
                            document.getElementById("myElement").className =
                            document.getElementById("myElement").className.replace
                            ( /(?:^|\s)bg-info(?!\S)/g , 'bg-danger' )
                            document.getElementById("header").title = "Oops looks like something has gone wrong reload the page to start over";
                        }else if (number = 100) {
                            clearInterval(id);
                            document.getElementById("myElement").className =
                            document.getElementById("myElement").className.replace
                            ( /(?:^|\s)bg-info(?!\S)/g , 'bg-success' )
                            document.getElementById("header").title = "download is ready";
                        }
                    } else {
                        width++;
                        elem.style.width = width + '%';
                        elem.innerHTML = width * 1 + '%';
                    }
                }
            }
    </script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im making a loading bar.

And now i got an error when i click on download

Uncaught TypeError: Cannot read property 'style' of null

I dont know what i am dong wrong please can someone help me here is my code

0%

            <button onclick="move()" type="button" class="btn btn-outline-primary btn-lg">download</button>

F.Y.I i am using bootstrap for the styling

Body:
After Jonathan's correction, another issue might be that elem, width and id are defined in the parent move() function, and not in the child frame() function.

<script type="text/javascript">
            function move() {
                document.getElementById("headerTop").style.cursor = "wait";
                function frame() {
                    var elem = document.getElementById("myElement");
                    var width = 0;
                    var id = setInterval(frame, 1000);
                    if (width >= 99) {
                        var number = random(99, 100)
                        if(number = 99) {
                            clearInterval(id);
                            document.getElementById("myElement").className =
                            document.getElementById("myElement").className.replace
                            ( /(?:^|\s)bg-info(?!\S)/g , 'bg-danger' )
                            document.getElementById("header").title = "Oops looks like something has gone wrong reload the page to start over";
                        }else if (number = 100) {
                            clearInterval(id);
                            document.getElementById("myElement").className =
                            document.getElementById("myElement").className.replace
                            ( /(?:^|\s)bg-info(?!\S)/g , 'bg-success' )
                            document.getElementById("header").title = "download is ready";
                        }
                    } else {
                        width++;
                        elem.style.width = width + '%';
                        elem.innerHTML = width * 1 + '%';
                    }
                }
            }
    </script>


问:
Find if video file has audio present in it
I'm trying to figure out if a video has audio present in it so as to extract the mp3 using ffmpeg. When the video contains no audio channels, ffmpeg creates an empty mp3 file which I'm using to figure out if audio was present in the video in the first place. I'm sure there is a better way to identify if audio is present in a video. Will avprobe help with this? Can anyone point me to a resource or probably a solution?

Edit: Surprisingly, the same command on my server running the latest build of ffprobe doesn't run. It throws an error saying

Unrecognized option 'select_stream'

Failed to set value 'a' for option 'select_stream'

Any ideas how to rectify this out?

答:
If you only want to know if there is audio and don't care about the stream details you can run the following command, which will extract the duration of the audio stream in the input file. If the response is null/whitespace the input file has no audio in it.

Command:

```<code>ffprobe -v error -of flat=s_ -select_streams 1 -show_entries stream=duration -of default=noprint_wrappers=1:nokey=1
</code>```

Body:
If you only want to know if there is audio and don't care about the stream details you can run the following command, which will extract the duration of the audio stream in the input file. If the response is null/whitespace the input file has no audio in it.

Command:

ffprobe -v error -of flat=s_ -select_streams 1 -show_entries stream=duration -of default=noprint_wrappers=1:nokey=1


问:
Is it necessary to wrap nHibernate futures in a transaction?
Is it necessary to wrap nHibernate futures in a transaction?

Such as:

```<code>using (var s = sf.OpenSession())
using (var tx = s.BeginTransaction())
{
    var blogs = s.CreateCriteria<Blog>()
        .SetMaxResults(30)
        .List<Blog>();
    var countOfBlogs = s.CreateCriteria<Blog>()
        .SetProjection(Projections.Count(Projections.Id()))
        .UniqueResult<int>();

    Console.WriteLine("Number of blogs: {0}", countOfBlogs);
    foreach (var blog in blogs)
    {
        Console.WriteLine(blog.Title);
    }

    tx.Commit();
}
</code>```

From here:

https://ayende.com/blog/3979/nhibernate-futures

I can't see a reason to do this. It's a select rather than an insert, or update etc.

答:
When an NHibernate query is not explicitly wrapped in a transaction it is called an "implicit transaction" which is discouraged, and has various implications including nullifying the second level cache. This is all explained here:

https://hibernatingrhinos.com/Products/nhprof/learn#DoNotUseImplicitTransactions

An excerpt:

Even if we are only reading data, we should use a transaction, because using transactions ensures that we get consistent results from the database. NHibernate assumes that all access to the database is done under a transaction, and strongly discourages any use of the session without a transaction.

Body:
Is it necessary to wrap nHibernate futures in a transaction?

Such as:

using (var s = sf.OpenSession())
using (var tx = s.BeginTransaction())
{
    var blogs = s.CreateCriteria<Blog>()
        .SetMaxResults(30)
        .List<Blog>();
    var countOfBlogs = s.CreateCriteria<Blog>()
        .SetProjection(Projections.Count(Projections.Id()))
        .UniqueResult<int>();

    Console.WriteLine("Number of blogs: {0}", countOfBlogs);
    foreach (var blog in blogs)
    {
        Console.WriteLine(blog.Title);
    }

    tx.Commit();
}

From here:

https://ayende.com/blog/3979/nhibernate-futures

I can't see a reason to do this. It's a select rather than an insert, or update etc.


问:
Which files? Which subroutines?
I have a Fortran project comprising around 100 files. All of them are compiled but not all of them are needed for a run. Also some files contain a mix of used / unused subroutines.

Is there a way to know the minimum set of files / subroutines / functions needed for a run?

答:
Yes.
Start with just the top-level main program.

Compile/Link it and get the list of unsatisfied references.

For each of the unsatisfied references, add the file containing it.

Repeat these two steps until there are no more unsatisfied references.

This removes all files not needed for a clean build.
Yes, it is a lot of work. Things are not always easy.

If you want to know what's not needed for a run with particular input,
for that you need a coverage tool such as gcov.
Routines that are not used will show a coverage count of 0.
Then if you really want to get rid of them,
extract them into separate source files so you can exclude them, and make sure they are not called.

Title: Which files? Which subroutines?


问:
epydoc and reStructuredText change link name
I'm using reStructuredText with epydoc. How can I have the text of an internal link different than the target of the link? I have:

```<code>:todo: Figure out the `Product.manufacturer` relationship in `Product`.
</code>```

The Product link looks fine and links to the Product object. The Product.manufacturer link goes to the proper member variable, but instead of the text being Product.manufacturer, I'd like to just be manufacturer.

I know this can be done if I use epytext, but we'd like to stick with reStructuredText so that we can switch documentation generators later if we want to.

答:
I'm not familiar with epydoc myself, but the normal reStructuredText way would be this:

```<code>`manufacturer <Product.manufacturer>`_
</code>```

Or, with Sphinx,

```<code>:attribute:`manufacturer <Product.manufacturer>`
</code>```

Considering that epydoc seems to have overridden the default role to provide links, it will be being left to it. However, this is the most likely to work:

```<code>:todo: Figure out the `manufacturer <Product.manufacturer>` relationship in `Product`.
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using reStructuredText with epydoc. How can I have the text of an internal link different than the target of the link? I have:

:todo: Figure out the `Product.manufacturer` relationship in `Product`.

The Product link looks fine and links to the Product object. The Product.manufacturer link goes to the proper member variable, but instead of the text being Product.manufacturer, I'd like to just be manufacturer.

I know this can be done if I use epytext, but we'd like to stick with reStructuredText so that we can switch documentation generators later if we want to.

Body:
I'm not familiar with epydoc myself, but the normal reStructuredText way would be this:

`manufacturer <Product.manufacturer>`_

Or, with Sphinx,

:attribute:`manufacturer <Product.manufacturer>`

Considering that epydoc seems to have overridden the default role to provide links, it will be being left to it. However, this is the most likely to work:

:todo: Figure out the `manufacturer <Product.manufacturer>` relationship in `Product`.


问:
Passing data from parent to child (Nested Form)
I'm creating a nested form in which I have the parent component that holds the form(s) and has the submit button. And there's the child component which is the form itself.

When I submit the form the property submitted became true, I need to inform my child component that submitted is now true when submitted.

This is the code from submit button in parent component:

```<code>      enviarDados(model: dadosAcordo, isValid: boolean, isJuridica:boolean) {
        this.servError = "";
        this.submitted = true;
        //more code
       }
</code>```

And this is how the child component look like so far:

```<code>export class TitularComponent implements OnChanges {
  @Input('group') // this is the input for the form
  @Input('submitted') // input for the status of submit
  public titularForm: FormGroup;
  @Output() modelChanged = new EventEmitter();

  constructor(private _fb: FormBuilder, private finalizaAcordo:FinalizaNegociacaoService) {}

  ngOnChanges(){

  }
// more code
</code>```

This is the html on the parent component:

```<code><div class="wrap-acordo">
  <form [formGroup]="formDadosBancarios" novalidate class="" (ngSubmit)="enviarDados(formDadosBancarios.value)">
      <div formArrayName="dados_titular">
        <div *ngFor="let dados_titular of formDadosBancarios.controls.dados_titular.controls; let i=index">
          <div [formGroupName]="i">
            <div class="col s12" *ngIf="formDadosBancarios.controls.dados_titular.length > 1">
              <span class="span-removeTitular right-align" (click)="removeTitular(i)"> Remover {{i+1}}º Titular </span>
            </div>
            <titular (modelChanged)="recebeValidators($event)" [group]="formDadosBancarios.controls.dados_titular.controls[i]"></titular>
          </div>
        </div>
      </div>
      <div class="col s12 m6">
        <input type="submit" class="botao-medio btn-aceita" value="Aceitar">
      </div>
      <div class="col s12 m6">
        <input type="button" class="botao-medio btn-recusa" value="Recusar">
      </div>
    </div>
  </form>
</div>
</code>```

Can someone help me? Thanks :)

答:
In your parent component, when the button is clicked, set this.formsubmitted = true . And in child cmponent set this form submitted as input using @Input. If you need to dp something once the formsubmitted becomes true, use ngonchanges for the input formsubmitted.
Ngonchanges(change: Simplechange) {
if(changes['submitted']&& changes['submitted'].currentvalue){
Do your stuff here
}
}

You can refer https://angular.io/docs/ts/latest/api/core/index/OnChanges-class.html

Body:
I'm creating a nested form in which I have the parent component that holds the form(s) and has the submit button. And there's the child component which is the form itself.

When I submit the form the property submitted became true, I need to inform my child component that submitted is now true when submitted.

This is the code from submit button in parent component:

      enviarDados(model: dadosAcordo, isValid: boolean, isJuridica:boolean) {
        this.servError = "";
        this.submitted = true;
        //more code
       }

And this is how the child component look like so far:

export class TitularComponent implements OnChanges {
  @Input('group') // this is the input for the form
  @Input('submitted') // input for the status of submit
  public titularForm: FormGroup;
  @Output() modelChanged = new EventEmitter();

  constructor(private _fb: FormBuilder, private finalizaAcordo:FinalizaNegociacaoService) {}

  ngOnChanges(){

  }
// more code

This is the html on the parent component:

  <form [formGroup]="formDadosBancarios" novalidate class="" (ngSubmit)="enviarDados(formDadosBancarios.value)">

 1">
               Remover {{i+1}}º Titular

            <titular (modelChanged)="recebeValidators($event)" [group]="formDadosBancarios.controls.dados_titular.controls[i]"></titular>

        <input type="submit" class="botao-medio btn-aceita" value="Aceitar">

        <input type="button" class="botao-medio btn-recusa" value="Recusar">

  </form>

Can someone help me? Thanks :)


问:
Postgres - Lateral join with random values on both sides
I am trying to generate the following table:

```<code>random person a | random utility 1
random person a | random utility 2
random person a | random utility 3
random person b | random utility 4
random person b | random utility 5
random person b | random utility 6
</code>```

So, I want to generate two random persons and for each person, 3 random utilities. Generated utilities are not shared between persons.

I came up with the following query:

```<code>select              gen_random_uuid() person, utility.utility
from                generate_series(1, 2) person
inner join lateral  (select person, gen_random_uuid() utility from generate_series(1, 3)) utility
on                  person.person = utility.person;
</code>```

But this generates the following:

```<code>64bf364b-ff74-4888-b2d9-0ffcf3147dd7 | f8455aa3-73ab-4432-9c49-2c940da28fa7
05f54217-0316-410d-83e8-2b5306eee143 | 68f7b48-2561-438c-a906-34b141c4adc5
07c23fc3-a6b9-4d74-a611-264c4de9a0bd | 5a597190-09f9-44ea-960d-f6657aa10a81
b5903b45-f96a-4eb4-8b67-95340131a29b | 742daba-de73-45c4-8b2b-758663c4af47
6ba75082-77e4-408b-9e19-92595121cf43 | 01635986-98e3-432e-9f4e-0a88edba3d67
48d7ab6f-4a32-4306-b060-f0019aef1d11 | 99f4e91f-c05f-496c-a4a3-7b62f64ed6e1
</code>```

So, as you can see, the result contains 6 random persons, with each person his/her own random utility.

As said, I need 2 random persons with each 3 random utlities. How can I fix this query?

Body:
I am trying to generate the following table:

random person a | random utility 1
random person a | random utility 2
random person a | random utility 3
random person b | random utility 4
random person b | random utility 5
random person b | random utility 6

So, I want to generate two random persons and for each person, 3 random utilities. Generated utilities are not shared between persons.

I came up with the following query:

select              gen_random_uuid() person, utility.utility
from                generate_series(1, 2) person
inner join lateral  (select person, gen_random_uuid() utility from generate_series(1, 3)) utility
on                  person.person = utility.person;

But this generates the following:

64bf364b-ff74-4888-b2d9-0ffcf3147dd7 | f8455aa3-73ab-4432-9c49-2c940da28fa7
05f54217-0316-410d-83e8-2b5306eee143 | 68f7b48-2561-438c-a906-34b141c4adc5
07c23fc3-a6b9-4d74-a611-264c4de9a0bd | 5a597190-09f9-44ea-960d-f6657aa10a81
b5903b45-f96a-4eb4-8b67-95340131a29b | 742daba-de73-45c4-8b2b-758663c4af47
6ba75082-77e4-408b-9e19-92595121cf43 | 01635986-98e3-432e-9f4e-0a88edba3d67
48d7ab6f-4a32-4306-b060-f0019aef1d11 | 99f4e91f-c05f-496c-a4a3-7b62f64ed6e1

So, as you can see, the result contains 6 random persons, with each person his/her own random utility.

As said, I need 2 random persons with each 3 random utlities. How can I fix this query?

Body:
Here is  example (I use md5 instead of gen_random_uuid, but same idea):

t=# with
  person as (select md5(random()::text) from generate_series(1,2,1))
, utility  as (select md5(random()::text) from generate_series(1,3,1))
select
  person.md5, utility.md5
from person
join utility on true
;
               md5                |               md5
----------------------------------+----------------------------------
 74df2447c58a1595e0a8458d1142e2e0 | 3703e2004a1494e6dd74cd51f4dd029e
 74df2447c58a1595e0a8458d1142e2e0 | a1f7d74adc1ff3a49533204071e00f82
 74df2447c58a1595e0a8458d1142e2e0 | 4f32029c29eee254d9c97045d06bcdf5
 48a56953721f04752b325c332e26a5ed | 3703e2004a1494e6dd74cd51f4dd029e
 48a56953721f04752b325c332e26a5ed | a1f7d74adc1ff3a49533204071e00f82
 48a56953721f04752b325c332e26a5ed | 4f32029c29eee254d9c97045d06bcdf5
(6 rows)

I made it based on

I need 2 random persons with each 3 random utlities

not on previous statements


问:
How to handle events on markup inserted through jQuery
I have the following markup:

```<code><div id="section">
    <input type="text" id="myInput">
</div>
</code>```

On click of a button, I'm cloning and inserting a copy of this markup with unique IDs using this script:

```<code>var newSection = $("#section").clone();
$(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
$(newSection).find("input").attr('id', "myInput" + ($("input[id^=myInput").length + 1));
$("div[id^=section").last().after(newSection);
</code>```

My resulting markup:

```<code><div id="section">
    <input type="text" id="myInput">
</div>
<div id="section2">
    <input type="text" id="myInput2">
</div>
</code>```

My question: is it possible to manipulate this new markup with jQuery? I assume since it has loaded dynamically after a click it's not part of the initial DOM and jQuery doesn't recognize it? I'm having trouble getting a click event to register on #myInput2. Thanks for any insight.

答:
Add classes to your markup:

```<code><div id="section" class="section">
    <input type="text" id="myInput" class="section-input">
</div>
</code>```

Simplify your code

```<code>var $newSection = $('#section').clone();
var $sections = $('.section');
var index = $sections.length +1;
$newSection.attr('id', 'section' + index);
$newSection.find('input').attr('id', 'myInput' + index);

$sections.last().after($newSection);
</code>```

Make sure click handlers are added to existing and new elements

```<code>$(document).on('click', '.section-input', function(){
    ... your code
})
</code>```

Body:
I have the following markup:

    <input type="text" id="myInput">

On click of a button, I'm cloning and inserting a copy of this markup with unique IDs using this script:

var newSection = $("#section").clone();
$(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
$(newSection).find("input").attr('id', "myInput" + ($("input[id^=myInput").length + 1));
$("div[id^=section").last().after(newSection);

My resulting markup:

    <input type="text" id="myInput">

    <input type="text" id="myInput2">

My question: is it possible to manipulate this new markup with jQuery? I assume since it has loaded dynamically after a click it's not part of the initial DOM and jQuery doesn't recognize it? I'm having trouble getting a click event to register on #myInput2. Thanks for any insight.

Body:
Add classes to your markup:

<div id="section" class="section">
    <input type="text" id="myInput" class="section-input">
</div>

Simplify your code

var $newSection = $('#section').clone();
var $sections = $('.section');
var index = $sections.length +1;
$newSection.attr('id', 'section' + index);
$newSection.find('input').attr('id', 'myInput' + index);

$sections.last().after($newSection);

Make sure click handlers are added to existing and new elements

$(document).on('click', '.section-input', function(){
    ... your code
})


问:
How can I find the normals for each vertex of an object so that I can apply smooth shading with OpenGL?
I'm loading an object from a .off file. This file format does not define the normals for an object's faces or vertices. I have found the face normals using a vector product. But I'm at a loss about finding the normals for each vertex, any ideas? </p>

答:
See example "Computing normals to achieve flat and smooth shading" (method ComputeVerticeNormal):

```<code>// Average all adjacent faces normals to get the vertex normal
GLpoint pn;
pn.x = pn.y = pn.z = 0;
for (int jx = 0; jx < nbAdjFaces; jx++)
{
   int ixFace= m_pStorage[jx];
   pn.x += m_pFaceNormals[ixFace].x;
   pn.y += m_pFaceNormals[ixFace].y;
   pn.z += m_pFaceNormals[ixFace].z;
}
pn.x /= nbAdjFaces;
pn.y /= nbAdjFaces;
pn.z /= nbAdjFaces;

// Normalize the vertex normal
VectorNormalize(&pn, &m_pVertNormals[ixVertice]);
</code>```

Body:
See example "Computing normals to achieve flat and smooth shading" (method ComputeVerticeNormal):

// Average all adjacent faces normals to get the vertex normal
GLpoint pn;
pn.x = pn.y = pn.z = 0;
for (int jx = 0; jx < nbAdjFaces; jx++)
{
   int ixFace= m_pStorage[jx];
   pn.x += m_pFaceNormals[ixFace].x;
   pn.y += m_pFaceNormals[ixFace].y;
   pn.z += m_pFaceNormals[ixFace].z;
}
pn.x /= nbAdjFaces;
pn.y /= nbAdjFaces;
pn.z /= nbAdjFaces;

// Normalize the vertex normal
VectorNormalize(&pn, &m_pVertNormals[ixVertice]);


问:
How to manually specify class labels in keras flow_from_directory?
Problem: I am training a model for multilabel image recognition. My images are therefore associated with multiple y labels. This is conflicting with the convenient keras method "flow_from_directory" of the ImageDataGenerator, where each image is supposed to be in the folder of the corresponding label (https://keras.io/preprocessing/image/).

Workaround: Currently, I am reading all images into a numpy array and use the "flow" function from there. But this results in heavy memory loads and a slow read-in process.

Question: Is there a way to use the "flow_from_directory" method and to supply manually the (multiple) class labels?

Update: I ended up extending the DirectoryIterator class for the multilabel case. You can now set the attribute "class_mode" to the value "multilabel" and provide a dictionary "multlabel_classes" which maps filenames to their labels. Code: https://github.com/tholor/keras/commit/29ceafca3c4792cb480829c5768510e4bdb489c5

答:
You could simply use the flow_from_directory and extend it to a multiclass in a following manner:

```<code>def multiclass_flow_from_directory(flow_from_directory_gen, multiclasses_getter):
    for x, y in flow_from_directory_gen:
        yield x, multiclasses_getter(x, y)
</code>```

Where multiclasses_getter is assigning a multiclass vector / your multiclass representation to your images. Note that x and y are not a single examples but batches of examples, so this should be included in your multiclasses_getter design.

Body:
You could simply use the flow_from_directory and extend it to a multiclass in a following manner:

def multiclass_flow_from_directory(flow_from_directory_gen, multiclasses_getter):
    for x, y in flow_from_directory_gen:
        yield x, multiclasses_getter(x, y)

Where multiclasses_getter is assigning a multiclass vector / your multiclass representation to your images. Note that x and y are not a single examples but batches of examples, so this should be included in your multiclasses_getter design.


问:
Currying in Typed Racket
In regular Racket, ((curry * 2) 3) works as expected, with 6 as a result.

However, in Typed Racket:

```<code>> ((curry * 2) 3)
; readline-input:3:0: Type Checker: could not apply function;
;  wrong number of arguments provided
;   expected: 0
;   given: 1
;   in: ((curry * 2) 3)
; [,bt for context]
</code>```

Why?

答:
I believe it has something to do with the fact that * can take only one argument, so when you curry it with a parameter, it is returning a procedure that takes no additional arguments. Type (curry * 2) at the command line in typed/racket and observe the result: (-> Number).

Note that there is only a return type and no parameter. I don't see a way around this in typed racket, but I hope that at least explains why it is happening. You should be safe to use currying with more complex procedures as long as they do not have an option to take only one parameter.

Title: Currying in Typed Racket

Body:
In regular Racket, ((curry * 2) 3) works as expected, with 6 as a result.

However, in Typed Racket:

> ((curry * 2) 3)
; readline-input:3:0: Type Checker: could not apply function;
;  wrong number of arguments provided
;   expected: 0
;   given: 1
;   in: ((curry * 2) 3)
; [,bt for context]

Why?


问:
Sybase Warning messages from perl DBI
I am connecting to sybase 12 from a perl script and calling storedprocs, I get the following warnings

```<code>DBD::Sybase::db prepare failed: Server message number=2401 severity=11 state=2 line=0 server=SERVER_NAME text=Character
set conversion is not available between client character set 'utf8' and server character set 'iso_1'.
Server message number=2411 severity=10 state=1 line=0 server=SERVER_NAME text=No conversions will be done.
at line 210.
</code>```

Now, I understand these are only warnings, and my process works perfectly fine, but I am calling my stored proc in a loop and throughout the day and hence it creates a lot of warning message in my log files which causes the entire process to run a bit slower than expected. Can someone help me how can i suppress these please?

答:
You can use a callback to handle the messages you want ignored.  See the DBD::Sybase docs.  The below is derived from the docs.  You specify the message numbers you would like to ignore.

```<code>%blocked_msgs = map { $_ => 1 }  ( 2401, 2411 );
sub err_handler {
  my($err, $sev, $state, $line, $server, $proc, $msg, $sql, $err_type) = @_;

   if ( exists $blocked_msgs{$err} ) { # it's a blocked message
     return 0;    # This is not an error
   }
   return 1;
}
</code>```

This is how you might use it:

```<code>$dbh = DBI->connect('dbi:Sybase:server=troll', 'sa', '');
$dbh->{syb_err_handler} = \&err_handler;
$dbh->do("exec someproc");
$dbh->disconnect;
</code>```

Title: Sybase Warning messages from perl DBI

Body:
I am connecting to sybase 12 from a perl script and calling storedprocs, I get the following warnings

DBD::Sybase::db prepare failed: Server message number=2401 severity=11 state=2 line=0 server=SERVER_NAME text=Character
set conversion is not available between client character set 'utf8' and server character set 'iso_1'.
Server message number=2411 severity=10 state=1 line=0 server=SERVER_NAME text=No conversions will be done.
at line 210.

Now, I understand these are only warnings, and my process works perfectly fine, but I am calling my stored proc in a loop and throughout the day and hence it creates a lot of warning message in my log files which causes the entire process to run a bit slower than expected. Can someone help me how can i suppress these please?

Body:
You can use a callback to handle the messages you want ignored.  See the DBD::Sybase docs.  The below is derived from the docs.  You specify the message numbers you would like to ignore.

%blocked_msgs = map { $_ => 1 }  ( 2401, 2411 );
sub err_handler {
  my($err, $sev, $state, $line, $server, $proc, $msg, $sql, $err_type) = @_;

   if ( exists $blocked_msgs{$err} ) { # it's a blocked message
     return 0;    # This is not an error
   }
   return 1;
}

This is how you might use it:

$dbh = DBI->connect('dbi:Sybase:server=troll', 'sa', '');
$dbh->{syb_err_handler} = \&err_handler;
$dbh->do("exec someproc");
$dbh->disconnect;


问:
Assign a particular ID to each item in a list and generate a new list with repeated IDs
I have 2 lists, each have 5 items in them. But the items in the 'start' list are lists:

```<code>start = [[3606,5599,6312,7897], [2394], [84,1046], [1046], [1]]

id = ['AB022430', 'AB024537', 'AB043103', 'AB051349', 'AB051628']
</code>```

I would like to created a new list with the format (I'm thinking via a pandas df or using 'zip'):

```<code>AB022430    3606
AB022430    5559
AB022430    6312
AB022430    7897
AB024537    2394
etc..
</code>```

I essentially want repeating IDs.

Body:
I have 2 lists, each have 5 items in them. But the items in the 'start' list are lists:

start = [[3606,5599,6312,7897], [2394], [84,1046], [1046], [1]]

id = ['AB022430', 'AB024537', 'AB043103', 'AB051349', 'AB051628']

I would like to created a new list with the format (I'm thinking via a pandas df or using 'zip'):

AB022430    3606
AB022430    5559
AB022430    6312
AB022430    7897
AB024537    2394
etc..

I essentially want repeating IDs.

Body:
You can use a list comprehension:

[(ID, v) for ID, val in zip(id, start) for v in val]

#[('AB022430', 3606),
# ('AB022430', 5599),
# ('AB022430', 6312),
# ('AB022430', 7897),
# ('AB024537', 2394),
# ('AB043103', 84),
# ('AB043103', 1046),
# ('AB051349', 1046),
# ('AB051628', 1)]


问:
Setup an MQTT Connection in Android
I am totally new to using MQTT with Android, I am trying this code :

```<code>public class MQTTActivity extends AppCompatActivity {
private HistoryAdapter mAdapter;
MqttAndroidClient mqttAndroidClient;

final String serverUri = "tcp://iot.eclipse.org:1883";

String clientId = "ExampleAndroidClient";
final String subscriptionTopic = "exampleAndroidTopic";
final String publishTopic = "exampleAndroidPublishTopic";
final String publishMessage = "Hello World!";

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

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            publishMessage();
        }
    });

    RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.history_recycler_view);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new HistoryAdapter(new ArrayList<String>());
    mRecyclerView.setAdapter(mAdapter);

    clientId = clientId + System.currentTimeMillis();

    mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), serverUri, clientId);
    mqttAndroidClient.setCallback(new MqttCallbackExtended() {
        @Override
        public void connectComplete(boolean reconnect, String serverURI) {

            if (reconnect) {
                addToHistory("Reconnected to : " + serverURI);
                // Because Clean Session is true, we need to re-subscribe
                subscribeToTopic();
            } else {
                addToHistory("Connected to: " + serverURI);
            }
        }

        @Override
        public void connectionLost(Throwable cause) {
            addToHistory("The Connection was lost.");
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            addToHistory("Incoming message: " + new String(message.getPayload()));
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    });

    MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
    mqttConnectOptions.setAutomaticReconnect(true);
    mqttConnectOptions.setCleanSession(false);

    try {
        //addToHistory("Connecting to " + serverUri);
        mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                disconnectedBufferOptions.setBufferEnabled(true);
                disconnectedBufferOptions.setBufferSize(100);
                disconnectedBufferOptions.setPersistBuffer(false);
                disconnectedBufferOptions.setDeleteOldestMessages(false);
                mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                subscribeToTopic();
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                addToHistory("Failed to connect to: " + serverUri);
            }
        });

    } catch (MqttException ex){
        ex.printStackTrace();
    }

}

private void addToHistory(String mainText){
    System.out.println("LOG: " + mainText);
    mAdapter.add(mainText);
    Snackbar.make(findViewById(android.R.id.content), mainText, Snackbar.LENGTH_LONG)
            .setAction("Action", null).show();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement

    return super.onOptionsItemSelected(item);
}

public void subscribeToTopic(){
    try {
        mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                addToHistory("Subscribed!");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                addToHistory("Failed to subscribe");
            }
        });

        // THIS DOES NOT WORK!
        mqttAndroidClient.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {
            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                // message Arrived!
                System.out.println("Message: " + topic + " : " + new String(message.getPayload()));
            }
        });

    } catch (MqttException ex){
        System.err.println("Exception whilst subscribing");
        ex.printStackTrace();
    }
}

public void publishMessage(){

    try {
        MqttMessage message = new MqttMessage();
        message.setPayload(publishMessage.getBytes());
        mqttAndroidClient.publish(publishTopic, message);
        addToHistory("Message Published");
        if(!mqttAndroidClient.isConnected()){
            addToHistory(mqttAndroidClient.getBufferedMessageCount() + " messages in buffer.");
        }
    } catch (MqttException e) {
        System.err.println("Error Publishing: " + e.getMessage());
        e.printStackTrace();
    }
}}
</code>```

I am getting this exception :

```<code>FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x8000010 (has extras) } in org.eclipse.paho.android.service.MqttService$NetworkConnectionIntentReceiver@41c79f18
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:810)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.SecurityException: Neither user 10083 nor current process has android.permission.WAKE_LOCK.
at android.os.Parcel.readException(Parcel.java:1428)
at android.os.Parcel.readException(Parcel.java:1382)
at android.os.IPowerManager$Stub$Proxy.acquireWakeLock(IPowerManager.java:301)
at android.os.PowerManager$WakeLock.acquireLocked(PowerManager.java:746)
at android.os.PowerManager$WakeLock.acquire(PowerManager.java:715)
at org.eclipse.paho.android.service.MqttService$NetworkConnectionIntentReceiver.onReceive(MqttService.java:821)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:800)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
at dalvik.system.NativeStart.main(Native Method)
</code>```

I already added the Network and the Internet Connection permessions.
I added the mqtt service to my manifest.

I can't seem to get where the code is going wrong ?

答:
The problem has nothing to do with MQTT protocol but with something else that the app is doing...

It looks like you are trying to notify the user about something(new msgs perhaps)

in order to do that you need to declare the use permisions in the manifest of the android, in your case something like:

```<code><uses-permission android:name="android.permission.WAKE_LOCK" />
</code>```

Title: Setup an MQTT Connection in Android

Body:
I am totally new to using MQTT with Android, I am trying this code :

public class MQTTActivity extends AppCompatActivity {
private HistoryAdapter mAdapter;
MqttAndroidClient mqttAndroidClient;

final String serverUri = "tcp://iot.eclipse.org:1883";

String clientId = "ExampleAndroidClient";
final String subscriptionTopic = "exampleAndroidTopic";
final String publishTopic = "exampleAndroidPublishTopic";
final String publishMessage = "Hello World!";

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

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            publishMessage();
        }
    });

    RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.history_recycler_view);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new HistoryAdapter(new ArrayList<String>());
    mRecyclerView.setAdapter(mAdapter);

    clientId = clientId + System.currentTimeMillis();

    mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), serverUri, clientId);
    mqttAndroidClient.setCallback(new MqttCallbackExtended() {
        @Override
        public void connectComplete(boolean reconnect, String serverURI) {

            if (reconnect) {
                addToHistory("Reconnected to : " + serverURI);
                // Because Clean Session is true, we need to re-subscribe
                subscribeToTopic();
            } else {
                addToHistory("Connected to: " + serverURI);
            }
        }

        @Override
        public void connectionLost(Throwable cause) {
            addToHistory("The Connection was lost.");
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            addToHistory("Incoming message: " + new String(message.getPayload()));
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    });

    MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
    mqttConnectOptions.setAutomaticReconnect(true);
    mqttConnectOptions.setCleanSession(false);

    try {
        //addToHistory("Connecting to " + serverUri);
        mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                disconnectedBufferOptions.setBufferEnabled(true);
                disconnectedBufferOptions.setBufferSize(100);
                disconnectedBufferOptions.setPersistBuffer(false);
                disconnectedBufferOptions.setDeleteOldestMessages(false);
                mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                subscribeToTopic();
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                addToHistory("Failed to connect to: " + serverUri);
            }
        });

    } catch (MqttException ex){
        ex.printStackTrace();
    }

}

private void addToHistory(String mainText){
    System.out.println("LOG: " + mainText);
    mAdapter.add(mainText);
    Snackbar.make(findViewById(android.R.id.content), mainText, Snackbar.LENGTH_LONG)
            .setAction("Action", null).show();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement

    return super.onOptionsItemSelected(item);
}

public void subscribeToTopic(){
    try {
        mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                addToHistory("Subscribed!");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                addToHistory("Failed to subscribe");
            }
        });

        // THIS DOES NOT WORK!
        mqttAndroidClient.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {
            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                // message Arrived!
                System.out.println("Message: " + topic + " : " + new String(message.getPayload()));
            }
        });

    } catch (MqttException ex){
        System.err.println("Exception whilst subscribing");
        ex.printStackTrace();
    }
}

public void publishMessage(){

    try {
        MqttMessage message = new MqttMessage();
        message.setPayload(publishMessage.getBytes());
        mqttAndroidClient.publish(publishTopic, message);
        addToHistory("Message Published");
        if(!mqttAndroidClient.isConnected()){
            addToHistory(mqttAndroidClient.getBufferedMessageCount() + " messages in buffer.");
        }
    } catch (MqttException e) {
        System.err.println("Error Publishing: " + e.getMessage());
        e.printStackTrace();
    }
}}

I am getting this exception :

FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x8000010 (has extras) } in org.eclipse.paho.android.service.MqttService$NetworkConnectionIntentReceiver@41c79f18
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:810)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.SecurityException: Neither user 10083 nor current process has android.permission.WAKE_LOCK.
at android.os.Parcel.readException(Parcel.java:1428)
at android.os.Parcel.readException(Parcel.java:1382)
at android.os.IPowerManager$Stub$Proxy.acquireWakeLock(IPowerManager.java:301)
at android.os.PowerManager$WakeLock.acquireLocked(PowerManager.java:746)
at android.os.PowerManager$WakeLock.acquire(PowerManager.java:715)
at org.eclipse.paho.android.service.MqttService$NetworkConnectionIntentReceiver.onReceive(MqttService.java:821)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:800)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
at dalvik.system.NativeStart.main(Native Method)

I already added the Network and the Internet Connection permessions.
I added the mqtt service to my manifest.

I can't seem to get where the code is going wrong ?

Body:
The problem has nothing to do with MQTT protocol but with something else that the app is doing...

It looks like you are trying to notify the user about something(new msgs perhaps)

in order to do that you need to declare the use permisions in the manifest of the android, in your case something like:

<uses-permission android:name="android.permission.WAKE_LOCK" />


问:
Python3 How to implement sliding window counts on Pandas Dataframe
I want to create a plot from a large Pandas dataframe. The data is in the following format

```<code>Type     Number    ...unimportant additional columns

Foo       13  ...
Foo       25  ...
Foo       56  ...
Foo       56  ...
Bar       10  ...
Bar       10  ...
Bar       11  ...
Bar       23  ...
</code>```

I need to count the number of elements from column 'Number' in a sliding window from x to x+i to determine the number of values falling in each sliding window bucket.

For example, if the window size is i=10, starting at x=0, and incrementing x by 1 each step, the sliding window bucket for 'Foo' a correct result for the above example would be:

```<code>      Foo    Bar

  0    0      2    #(0-10)
  1    0      3    #(1-11)
  2    0      3    #(2-12)
  3    1      3    #(3-13)
  4    1      3    #(4-14)
   .
   .
   .
  20   1      1    #(13-23)
  21   0      1    #(14-24)
  22   1      1    #(15-25)
   .
   .
   .
</code>```

The answer would have df.max().max - [Window Length] rows, and len(df.columns) columns.

Toy code to generate a similar dataframe might be the following:

```<code>import pandas as pd
import numpy as np

str_arr = ['Foo','Bar','Python','PleaseHelp']
data1 = np.matrix(np.random.choice(str_arr, 100, p=[0.5, 0.1, 0.1, 0.3])).T
data2 = np.random.randint(100, size=(100,1))
merge = np.concatenate((data1,data2), axis=1)

df = pd.DataFrame(merge, index=range(100), columns=['Type','Number'])
df.sort_values(['Type','Number'], ascending=[True,True], inplace=True)
df = df.reset_index(drop=True)
</code>```

How can I generate such a list efficiently?

Edit Note: Thanks to FLab who answered my question earlier before I clarified my question.

答:
Here is my proposed solution.

For convenience, let's force 'Number' column to be an int.

```<code>df['Number'] = df['Number'].astype(int)
</code>```

Define all possible ranges:

```<code>len_wdw = 10
all_ranges = [(i, i+len_wdw) for i in range(df['Number'].max()-len_wdw)]
</code>```

And now check how many observations there are for "Number" in each of this ranges:

```<code>def get_mask(df, rg):
    #rg is a range, e.g. (10-20)
    return (df['Number'] >= rg[0]) & (df['Number'] <= rg[1])

result = pd.concat({ rg[0] :
                        df[get_mask(df, rg)].groupby('Type').count()['Number']
                   for rg in all_ranges},
                 axis = 1).fillna(0).T
</code>```

For the randomly generated numbers, this gives:

```<code>    Bar   Foo  PleaseHelp  Python
0   1.0   4.0         3.0     1.0
1   1.0   5.0         2.0     1.0
2   1.0   5.0         3.0     1.0
3   1.0   4.0         3.0     0.0
4   1.0   3.0         3.0     1.0
.....
85  2.0   3.0         4.0     1.0
86  1.0   3.0         3.0     1.0
87  1.0   4.0         3.0     1.0
88  1.0   4.0         4.0     1.0
89  1.0   3.0         5.0     1.0
</code>```

Body:
I want to create a plot from a large Pandas dataframe. The data is in the following format

Type     Number    ...unimportant additional columns

Foo       13  ...
Foo       25  ...
Foo       56  ...
Foo       56  ...
Bar       10  ...
Bar       10  ...
Bar       11  ...
Bar       23  ...

I need to count the number of elements from column 'Number' in a sliding window from x to x+i to determine the number of values falling in each sliding window bucket.

For example, if the window size is i=10, starting at x=0, and incrementing x by 1 each step, the sliding window bucket for 'Foo' a correct result for the above example would be:

      Foo    Bar

  0    0      2    #(0-10)
  1    0      3    #(1-11)
  2    0      3    #(2-12)
  3    1      3    #(3-13)
  4    1      3    #(4-14)
   .
   .
   .
  20   1      1    #(13-23)
  21   0      1    #(14-24)
  22   1      1    #(15-25)
   .
   .
   .

The answer would have df.max().max - [Window Length] rows, and len(df.columns) columns.

Toy code to generate a similar dataframe might be the following:

import pandas as pd
import numpy as np

str_arr = ['Foo','Bar','Python','PleaseHelp']
data1 = np.matrix(np.random.choice(str_arr, 100, p=[0.5, 0.1, 0.1, 0.3])).T
data2 = np.random.randint(100, size=(100,1))
merge = np.concatenate((data1,data2), axis=1)

df = pd.DataFrame(merge, index=range(100), columns=['Type','Number'])
df.sort_values(['Type','Number'], ascending=[True,True], inplace=True)
df = df.reset_index(drop=True)

How can I generate such a list efficiently?

Edit Note: Thanks to FLab who answered my question earlier before I clarified my question.

Body:
Here is my proposed solution.

For convenience, let's force 'Number' column to be an int.

df['Number'] = df['Number'].astype(int)

Define all possible ranges:

len_wdw = 10
all_ranges = [(i, i+len_wdw) for i in range(df['Number'].max()-len_wdw)]

And now check how many observations there are for "Number" in each of this ranges:

def get_mask(df, rg):
    #rg is a range, e.g. (10-20)
    return (df['Number'] >= rg[0]) & (df['Number'] <= rg[1])

result = pd.concat({ rg[0] :
                        df[get_mask(df, rg)].groupby('Type').count()['Number']
                   for rg in all_ranges},
                 axis = 1).fillna(0).T

For the randomly generated numbers, this gives:

    Bar   Foo  PleaseHelp  Python
0   1.0   4.0         3.0     1.0
1   1.0   5.0         2.0     1.0
2   1.0   5.0         3.0     1.0
3   1.0   4.0         3.0     0.0
4   1.0   3.0         3.0     1.0
.....
85  2.0   3.0         4.0     1.0
86  1.0   3.0         3.0     1.0
87  1.0   4.0         3.0     1.0
88  1.0   4.0         4.0     1.0
89  1.0   3.0         5.0     1.0


问:
Ruby: Can I write multi-line string with no concatenation?
Is there a way to make this look a little better?

```<code>conn.exec 'select attr1, attr2, attr3, attr4, attr5, attr6, attr7 ' +
          'from table1, table2, table3, etc, etc, etc, etc, etc, ' +
          'where etc etc etc etc etc etc etc etc etc etc etc etc etc'
</code>```

Like, is there a way to imply concatenation?

答:
You can also use double quotes

```<code>x = """
this is
a multiline
string
"""

2.3.3 :012 > x
 => "\nthis is\na multiline\nstring\n"
</code>```

If needed to remove line breaks "\n" use backslash "\" at the end of each line

Body:
Is there a way to make this look a little better?

conn.exec 'select attr1, attr2, attr3, attr4, attr5, attr6, attr7 ' +
          'from table1, table2, table3, etc, etc, etc, etc, etc, ' +
          'where etc etc etc etc etc etc etc etc etc etc etc etc etc'

Like, is there a way to imply concatenation?

Body:
You can also use double quotes

x = """
this is
a multiline
string
"""

2.3.3 :012 > x
 => "\nthis is\na multiline\nstring\n"

If needed to remove line breaks "\n" use backslash "\" at the end of each line

ContentLicense: CC BY-SA 4.0


问:
Can't delete underlying VM for a node in Kubernetes
I'm running a three node cluster on GCE. I want to drain one node and delete the underlying VM.

Documentation for kubectl drain command says:

Once it returns (without giving an error), you can power down the node (or equivalently, if on a cloud platform, delete the virtual machine backing the node)

I execute the following commands:

Get the nodes

```<code>$ kl get nodes
NAME                                      STATUS    AGE
gke-jcluster-default-pool-9cc4e660-6q21   Ready     43m
gke-jcluster-default-pool-9cc4e660-rx9p   Ready     6m
gke-jcluster-default-pool-9cc4e660-xr4z   Ready     23h
</code>```

Drain node rx9p.

```<code>$ kl drain gke-jcluster-default-pool-9cc4e660-rx9p --force
node "gke-jcluster-default-pool-9cc4e660-rx9p" cordoned
WARNING: Deleting pods not managed by ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet: fluentd-cloud-logging-gke-jcluster-default-pool-9cc4e660-rx9p, kube-proxy-gke-jcluster-default-pool-9cc4e660-rx9p
node "gke-jcluster-default-pool-9cc4e660-rx9p" drained
</code>```

Delete gcloud VM.

```<code> $ gcloud compute instances delete gke-jcluster-default-pool-9cc4e660-rx9p
</code>```

List VMs.

```<code> $ gcloud compute instances list
</code>```

In the result, I'm seeing the VM I deleted above - rx9p. If I do kubectl get nodes, I'm seeing the rx9p node too.

What's going on? Something is restarting the VM I'm deleting? Do I have to wait for some timeout between the commands?

答:
You are on the right track with draining the node first.

The nodes (compute instances) are part of a managed instance group. If you delete just them with the gcloud compute instances delete command the managed instance group will recreate them.

To delete one properly use this command (after you have drained it!):

```<code>gcloud compute instance-groups managed delete-instances \
  gke-jcluster-default-pool-9cc4e660-grp \
  --instances=gke-jcluster-default-pool-9cc4e660-rx9p \
  --zone=...
</code>```

Body:
I'm running a three node cluster on GCE. I want to drain one node and delete the underlying VM.

Documentation for kubectl drain command says:

Once it returns (without giving an error), you can power down the node (or equivalently, if on a cloud platform, delete the virtual machine backing the node)

I execute the following commands:

Get the nodes

$ kl get nodes
NAME                                      STATUS    AGE
gke-jcluster-default-pool-9cc4e660-6q21   Ready     43m
gke-jcluster-default-pool-9cc4e660-rx9p   Ready     6m
gke-jcluster-default-pool-9cc4e660-xr4z   Ready     23h

Drain node rx9p.

$ kl drain gke-jcluster-default-pool-9cc4e660-rx9p --force
node "gke-jcluster-default-pool-9cc4e660-rx9p" cordoned
WARNING: Deleting pods not managed by ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet: fluentd-cloud-logging-gke-jcluster-default-pool-9cc4e660-rx9p, kube-proxy-gke-jcluster-default-pool-9cc4e660-rx9p
node "gke-jcluster-default-pool-9cc4e660-rx9p" drained

Delete gcloud VM.

 $ gcloud compute instances delete gke-jcluster-default-pool-9cc4e660-rx9p

List VMs.

 $ gcloud compute instances list

In the result, I'm seeing the VM I deleted above - rx9p. If I do kubectl get nodes, I'm seeing the rx9p node too.

What's going on? Something is restarting the VM I'm deleting? Do I have to wait for some timeout between the commands?

Body:
You are on the right track with draining the node first.

The nodes (compute instances) are part of a managed instance group. If you delete just them with the gcloud compute instances delete command the managed instance group will recreate them.

To delete one properly use this command (after you have drained it!):

gcloud compute instance-groups managed delete-instances \
  gke-jcluster-default-pool-9cc4e660-grp \
  --instances=gke-jcluster-default-pool-9cc4e660-rx9p \
  --zone=...


问:
PowerShell fails to call a simple function from an ASP.NET DLL
I'm trying to call this really simple .NET 4 function with PowerShell v2. Its definition look like:

Public Shared Function
  currentSchoolYear() As String
       Member of NM4.SiteAdmin.Logic.Subscription

Let's add the path to the DLL file containing that function. It's an ASP.NET MVC web application DLL file.

PS > Add-Type -Path C:\xxx\bin\xxxWebApp.dll

Let's try it (FAIL!):

PS >

  [NM4.SiteAdmin.Logic.Subscription]::currentSchoolYear()

  Exception calling "currentSchoolYear"

  with "0" argument(s): "The type

  initializer for

  'NM4.SiteAdmin.Logic.Subscription'

  threw an exception." At line:1 char:54

  + [NM4.SiteAdmin.Logic.Subscription]::currentSchoolYear

  <<<< ()

      + CategoryInfo          : NotSpecified: (:) [],

  MethodInvocationException

      + FullyQualifiedErrorId : DotNetMethodException

Let's observe the class from PowerShell:

PS >

  [NM4.SiteAdmin.Logic.Subscription]

  IsPublic IsSerial Name

  BaseType

  -------- -------- ---- --------  True     False    Subscription

  System.Object

Let's observe the function from PowerShell

PS >

  [NM4.SiteAdmin.Logic.Subscription]::currentSchoolYear

  MemberType          : Method

  OverloadDefinitions : {static string

  currentSchoolYear()} TypeNameOfValue

  :

  System.Management.Automation.PSMethod

  Value               : static string

  currentSchoolYear() Name

  : currentSchoolYear IsInstance

  : True

Why oh why? It seems like the doc to me.

答:
I used this command to get more details about the error:

$error | Format-List -force

Which then throwed this more precise example:

System.NullReferenceException: Object

  reference not set to an instance of an

  object.

                             at
NM4.SiteAdmin.GlobalFunctions.EstMachineProduction()

  in

  C:\xxx\Old_App_Code\DataModel\GlobalFunctions.vb:line

  17

And I discovered it was a call to the web.config that failed:

Return

  ConfigurationManager.ConnectionStrings.Item("test_DBNM4").ConnectionString

DLL files loaded by PowerShell are probably not in their usual web context. I hardcoded a ConnectionString to test it (temporary, not a good security practice), and it's working.


问:
Add marker to map from JSON, Android
I was trying to add markers to a map automatically after getting the data from JSON, with the position that is in the api, this is what I have:

```<code>@Override
    protected Void doInBackground(Void... params) {
        HttpHandler sh2 = new HttpHandler();
        final String jsonStrOportunidades = sh2.makeServiceCall(urlOportunidades);
        Log.e(TAG, "Response from URL: " + jsonStrOportunidades);
        if (jsonStrOportunidades != null) {
            try {
                JSONArray array = new JSONArray(jsonStrOportunidades);
                for (int i = 0; i < array.length(); i++) {
                    JSONObject jsonObject = array.getJSONObject(i);
                    String Designacao = jsonObject.getString("Designacao");
                    String Coord_LAT = jsonObject.getString("Coord_LAT");
                    String Coord_LONG = jsonObject.getString("Coord_LONG");

                    HashMap<String, String> oportunidades = new HashMap<>();

                    oportunidades.put("Designacao", Designacao);
                    oportunidades.put("Coord_LAT", Coord_LAT);
                    oportunidades.put("Coord_LONG", Coord_LONG);

                    double lat1 = Double.parseDouble(Coord_LAT);
                    double lng1 = Double.parseDouble(Coord_LONG);

                    mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));

                    listaOportunidades.add(oportunidades);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
        return null;
    }
</code>```

"mMap.addMarker" doesn't work, is it even possible creating markers from there?

答:
Try setting the marker from onPostExecute. doInBackground isn't the place to update UI components.

```<code>@Override
protected String doInBackground(Void... params) {
    HttpHandler sh2 = new HttpHandler();
    final String jsonStrOportunidades = sh2.makeServiceCall(urlOportunidades);
    Log.e(TAG, "Response from URL: " + jsonStrOportunidades);

    return jsonStrOportunidades;
}

@Override
protected void onPostExecute(String jsonStrOportunidades){

  if (jsonStrOportunidades != null) {
      try {
          JSONArray array = new JSONArray(jsonStrOportunidades);
          for (int i = 0; i < array.length(); i++) {
              JSONObject jsonObject = array.getJSONObject(i);
              String Designacao = jsonObject.getString("Designacao");
              String Coord_LAT = jsonObject.getString("Coord_LAT");
              String Coord_LONG = jsonObject.getString("Coord_LONG");

              HashMap<String, String> oportunidades = new HashMap<>();

              oportunidades.put("Designacao", Designacao);
              oportunidades.put("Coord_LAT", Coord_LAT);
              oportunidades.put("Coord_LONG", Coord_LONG);

              double lat1 = Double.parseDouble(Coord_LAT);
              double lng1 = Double.parseDouble(Coord_LONG);

              mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));

              listaOportunidades.add(oportunidades);
          }
      } catch (final JSONException e) {
          Log.e(TAG, "Json parsing error: " + e.getMessage());
          Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
      }
  }

}
</code>```

Also, you need to change the AsyncTask class like this

```<code>YourAsyncTaskClass extends AsyncTask<String, Void, String>
</code>```

Title: Add marker to map from JSON, Android

Body:
I was trying to add markers to a map automatically after getting the data from JSON, with the position that is in the api, this is what I have:

@Override
    protected Void doInBackground(Void... params) {
        HttpHandler sh2 = new HttpHandler();
        final String jsonStrOportunidades = sh2.makeServiceCall(urlOportunidades);
        Log.e(TAG, "Response from URL: " + jsonStrOportunidades);
        if (jsonStrOportunidades != null) {
            try {
                JSONArray array = new JSONArray(jsonStrOportunidades);
                for (int i = 0; i < array.length(); i++) {
                    JSONObject jsonObject = array.getJSONObject(i);
                    String Designacao = jsonObject.getString("Designacao");
                    String Coord_LAT = jsonObject.getString("Coord_LAT");
                    String Coord_LONG = jsonObject.getString("Coord_LONG");

                    HashMap<String, String> oportunidades = new HashMap<>();

                    oportunidades.put("Designacao", Designacao);
                    oportunidades.put("Coord_LAT", Coord_LAT);
                    oportunidades.put("Coord_LONG", Coord_LONG);

                    double lat1 = Double.parseDouble(Coord_LAT);
                    double lng1 = Double.parseDouble(Coord_LONG);

                    mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));

                    listaOportunidades.add(oportunidades);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
        return null;
    }

"mMap.addMarker" doesn't work, is it even possible creating markers from there?

Body:
Try setting the marker from onPostExecute. doInBackground isn't the place to update UI components.

@Override
protected String doInBackground(Void... params) {
    HttpHandler sh2 = new HttpHandler();
    final String jsonStrOportunidades = sh2.makeServiceCall(urlOportunidades);
    Log.e(TAG, "Response from URL: " + jsonStrOportunidades);

    return jsonStrOportunidades;
}

@Override
protected void onPostExecute(String jsonStrOportunidades){

  if (jsonStrOportunidades != null) {
      try {
          JSONArray array = new JSONArray(jsonStrOportunidades);
          for (int i = 0; i < array.length(); i++) {
              JSONObject jsonObject = array.getJSONObject(i);
              String Designacao = jsonObject.getString("Designacao");
              String Coord_LAT = jsonObject.getString("Coord_LAT");
              String Coord_LONG = jsonObject.getString("Coord_LONG");

              HashMap<String, String> oportunidades = new HashMap<>();

              oportunidades.put("Designacao", Designacao);
              oportunidades.put("Coord_LAT", Coord_LAT);
              oportunidades.put("Coord_LONG", Coord_LONG);

              double lat1 = Double.parseDouble(Coord_LAT);
              double lng1 = Double.parseDouble(Coord_LONG);

              mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));

              listaOportunidades.add(oportunidades);
          }
      } catch (final JSONException e) {
          Log.e(TAG, "Json parsing error: " + e.getMessage());
          Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
      }
  }

}

Also, you need to change the AsyncTask class like this

YourAsyncTaskClass extends AsyncTask<String, Void, String>


问:
How to create a json file using the rapidjson library from vector<string> data?
How can i create json file (string) from:

vector<string>m_paths

I have code:

```<code> rapidjson::Document jsonfile;
    jsonfile.SetObject();
    rapidjson::Document::AllocatorType& jsonallocator = jsonfile.GetAllocator();

    std::vector<String>::iterator itm;
    rapidjson::Value paths(rapidjson::kArrayType);

    for(itm = m_paths.begin(); itm != m_paths.end(); ++itm)
    {
        //rapidjson::Value jValueConverting;
       // jValueConverting.SetString(GetLogRpl().c_str(), (rapidjson::SizeType)GetLogRpl().size(), jsonallocator);
    }

    jsonfile.AddMember("paths", paths, jsonallocator);

    rapidjson::StringBuffer jsonstring;
    rapidjson::Writer<rapidjson::StringBuffer> jsonwriter(jsonstring);
    jsonfile.Accept(jsonwriter);

    String fullJsonString = jsonstring.GetString();

    return fullJsonString;
</code>```

I must use rapidjson library and don't know what i should do after creating allocator. Thanks for any help!

答:
```<code>        StringBuffer sb;
        PrettyWriter writer(sb);
        writer.StartObject();
        writer.String(_T("paths"));
        writer.StartArray();
        std::vector<String>::iterator itm;
        for(itm = m_paths.begin(); itm != m_paths.end(); ++itm)
        {
            writer.String(*itm);
        }
        writer.EndArray();
        writer.EndObject();

        std::string fullJsonString = sb.GetString();
</code>```

Body:
How can i create json file (string) from:

vector<string>m_paths

I have code:

 rapidjson::Document jsonfile;
    jsonfile.SetObject();
    rapidjson::Document::AllocatorType& jsonallocator = jsonfile.GetAllocator();

    std::vector<String>::iterator itm;
    rapidjson::Value paths(rapidjson::kArrayType);

    for(itm = m_paths.begin(); itm != m_paths.end(); ++itm)
    {
        //rapidjson::Value jValueConverting;
       // jValueConverting.SetString(GetLogRpl().c_str(), (rapidjson::SizeType)GetLogRpl().size(), jsonallocator);
    }

    jsonfile.AddMember("paths", paths, jsonallocator);

    rapidjson::StringBuffer jsonstring;
    rapidjson::Writer<rapidjson::StringBuffer> jsonwriter(jsonstring);
    jsonfile.Accept(jsonwriter);

    String fullJsonString = jsonstring.GetString();

    return fullJsonString;

I must use rapidjson library and don't know what i should do after creating allocator. Thanks for any help!


问:
How to use global scss files in angular-cli project
I am new to Angular 4 and to the Angular-CLI.
I cannot find any solution how to use root scss/css files for the whole application.
Thereby, my question, how to use global scss files in the project?</p>

答:
There is also the option to add your css/scss file to the "styles" array in the .angular-cli.json file. There may be a "best practice" that gets broken by doing this - I'm not really sure of the rules. But if you include a file in that array, it will be injected as though it were loaded at the top of index.html.

Here is an example from one of my projects: (/.angular-cli.json)
    ...
    "styles": [
      "styles.scss",
      "../node_modules/font-awesome/scss/font-awesome.scss",
      "../node_modules/mdi/scss/materialdesignicons.scss"
    ],
    ...