问:
Retreive data from server onClick View
I have a server that I get data from and display on a RecyclerView, When I click on the view, it is expected to open another activity that will display the full detail of the specific view, therefore the Id of the post is used to get the full content. I passed the id by intent to the new Activity, am getting an error:
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 34, size is 0
how do I make the Api call to get the content using id?

This is the full content for the item with id=34

```<code>{
  "blog_id": "34",
  "blog_title": "BLOG TITLE",
  "blog_subtitle": "Inspiration for Article Intro Effects",
  "blog_excerpt": "<p>Lorem ipsum dolor sit amet, veniam vidisse periculis ei mel, an nam malis nostrud euripidis. Ad invidunt explicari repudiandae qui, ut quo dolor sadipscing. Est laudem offendit ei. Id mentitum asse",
  "blog_content": "<p>We may define a food to be any substance which will repair the functional waste of the body, increase its growth, or maintain the heat, muscular, and nervous energy.</p>\r\n<p>In its most comprehensive sense, the oxygen of the air is a food; as although it is admitted by the lungs, it passes into the blood, and there re-acts upon the other food which has passed through the stomach. It is usual, however, to restrict the term food to such nutriment as enters the body by the intestinal canal. Water is often spoken of as being distinct from food, but for this there is no sufficient reason.</p>\r\n<p>Many popular writers have divided foods into flesh-formers, heat-givers, and bone-formers. Although attractive from its simplicity, this classification will not
  "blog_thumbnail": "https://watchnollywood.ml/app/templates/default/",
  "blog_medimg": "https://watchnollywood.ml/app/templates/default/images/medium_57d4789461f8b.jpg",
  "category_title": "General"
}
</code>```

BlogAdapter:

```<code>public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
List<BlogPost> postsList;
List<SingleBlogPost> singleBlogPosts;
Context context;
private LayoutInflater inflater;
static  String blog_Id;
static String blogID;

public MyBlogAdapter(Context context, List<BlogPost> postsList){
    this.context = context;
    this.inflater = LayoutInflater.from(context);
    this.postsList = postsList;
}
@Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.blog_post_item,parent, false);
    return new BlogViewHolder(view);
}

@Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
    BlogPost posts= postsList.get(position);
    holder.summary.setText(posts.getBlogExcerpt().trim().toString());
    holder.title.setText(posts.getBlogTitle().trim().toString());
    Glide.with(context).load(posts.getBlogThumbnail()).into(holder.cover);

    holder.blogHolder.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context, AnotherSingleView.class);
            blog_Id = posts.getBlogId();
            intent.putExtra(blogID,blog_Id);
            Log.d("MyblogAdapter","Please check blog Id: "+blog_Id);

            context.startActivity(intent);
        }
    });
   }

@Override
public int getItemCount() {
    Log.d("MyBlogAdapter,","getItemCount"+postsList.size());

    return postsList == null ? (0) : postsList.size();
}
}
</code>```

AnotherSingleView:

```<code>public class AnotherSingleView extends AppCompatActivity {
String postID;
int position = 0;
public TextView blogTitle,blogSub,blogContent;
public ImageView blogPic;
List<SingleBlogPost> singleBlogPosts;
 SingleBlogPost singleBlogPost;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_another_single_view);

    Intent intent  = getIntent();
    Bundle showBlogId = intent.getExtras();
    postID = showBlogId.getString(blogID);
    Log.d("AnotherSingleView","Please check blog Id: "+postID);

    singleBlogPosts = new ArrayList<>();

    blogContent = (TextView)findViewById(R.id.blog_content);
    blogSub = (TextView) findViewById(R.id.blog_subtitle);
    blogTitle =(TextView) findViewById(R.id.blog_title);
    blogPic =(ImageView) findViewById(R.id.blog_pix);
    singlePostDisplay();

}

private void singlePostDisplay() {
    singleBlogPost = singleBlogPosts.get(Interger.parseInt(postID));
    String post_id = singleBlogPost.getBlogId();
    if (postID.matches(post_id)){
        BlogaPI api = ApiClient.getBlogInterface();
      Call<List<SingleBlogPost>> call = api.postResponse();
        call.enqueue(new Callback<List<SingleBlogPost>>() {
            @Override
            public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
               singleBlogPosts = response.body();
                blogContent.setText(singleBlogPost.getBlogContent());
                blogSub.setText(singleBlogPost.getBlogSubtitle());
                blogTitle.setText(singleBlogPost.getBlogTitle());
                Glide.with(AnotherSingleView.this).load(singleBlogPost.getBlogMedimg()).into(blogPic);
            }

            @Override
            public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {

            }
        });

    }

}
}
</code>```

Interface:

```<code>public interface BlogRequestInterface {

  @GET("blog")
  Call<BlogApi> getMyBlog();
  @GET("post/{id}")
  Call<List<SingleBlogPost>> getSinglePost();
}
</code>```

Pojo class:

```<code>public class SingleBlogPost {

@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 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>```

答:
I do not recommend adding ClickListeners on onBindViewHolder. My onCreateViewHolder does something like this.

```<code>   @Override
   public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.blog_post_item,parent, false);
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //do stuff
        }
    });

    return new BlogViewHolder(view);
}
</code>```

And if you need position or list object for that you can refer to this link http://androidshenanigans.blogspot.com.tr/2015/02/viewholder-pattern-common-mistakes.html

Hope it helps.

Title: Retreive data from server onClick View

Body:
I have a server that I get data from and display on a RecyclerView, When I click on the view, it is expected to open another activity that will display the full detail of the specific view, therefore the Id of the post is used to get the full content. I passed the id by intent to the new Activity, am getting an error:
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 34, size is 0
how do I make the Api call to get the content using id?

This is the full content for the item with id=34

{
  "blog_id": "34",
  "blog_title": "BLOG TITLE",
  "blog_subtitle": "Inspiration for Article Intro Effects",
  "blog_excerpt": "
Lorem ipsum dolor sit amet, veniam vidisse periculis ei mel, an nam malis nostrud euripidis. Ad invidunt explicari repudiandae qui, ut quo dolor sadipscing. Est laudem offendit ei. Id mentitum asse",
  "blog_content": "
We may define a food to be any substance which will repair the functional waste of the body, increase its growth, or maintain the heat, muscular, and nervous energy.
\r\n
In its most comprehensive sense, the oxygen of the air is a food; as although it is admitted by the lungs, it passes into the blood, and there re-acts upon the other food which has passed through the stomach. It is usual, however, to restrict the term food to such nutriment as enters the body by the intestinal canal. Water is often spoken of as being distinct from food, but for this there is no sufficient reason.
\r\n
Many popular writers have divided foods into flesh-formers, heat-givers, and bone-formers. Although attractive from its simplicity, this classification will not
  "blog_thumbnail": "https://watchnollywood.ml/app/templates/default/",
  "blog_medimg": "https://watchnollywood.ml/app/templates/default/images/medium_57d4789461f8b.jpg",
  "category_title": "General"
}

BlogAdapter:

public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
List<BlogPost> postsList;
List<SingleBlogPost> singleBlogPosts;
Context context;
private LayoutInflater inflater;
static  String blog_Id;
static String blogID;

public MyBlogAdapter(Context context, List<BlogPost> postsList){
    this.context = context;
    this.inflater = LayoutInflater.from(context);
    this.postsList = postsList;
}
@Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.blog_post_item,parent, false);
    return new BlogViewHolder(view);
}

@Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
    BlogPost posts= postsList.get(position);
    holder.summary.setText(posts.getBlogExcerpt().trim().toString());
    holder.title.setText(posts.getBlogTitle().trim().toString());
    Glide.with(context).load(posts.getBlogThumbnail()).into(holder.cover);

    holder.blogHolder.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context, AnotherSingleView.class);
            blog_Id = posts.getBlogId();
            intent.putExtra(blogID,blog_Id);
            Log.d("MyblogAdapter","Please check blog Id: "+blog_Id);

            context.startActivity(intent);
        }
    });
   }

@Override
public int getItemCount() {
    Log.d("MyBlogAdapter,","getItemCount"+postsList.size());

    return postsList == null ? (0) : postsList.size();
}
}

AnotherSingleView:

public class AnotherSingleView extends AppCompatActivity {
String postID;
int position = 0;
public TextView blogTitle,blogSub,blogContent;
public ImageView blogPic;
List<SingleBlogPost> singleBlogPosts;
 SingleBlogPost singleBlogPost;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_another_single_view);

    Intent intent  = getIntent();
    Bundle showBlogId = intent.getExtras();
    postID = showBlogId.getString(blogID);
    Log.d("AnotherSingleView","Please check blog Id: "+postID);

    singleBlogPosts = new ArrayList<>();

    blogContent = (TextView)findViewById(R.id.blog_content);
    blogSub = (TextView) findViewById(R.id.blog_subtitle);
    blogTitle =(TextView) findViewById(R.id.blog_title);
    blogPic =(ImageView) findViewById(R.id.blog_pix);
    singlePostDisplay();

}

private void singlePostDisplay() {
    singleBlogPost = singleBlogPosts.get(Interger.parseInt(postID));
    String post_id = singleBlogPost.getBlogId();
    if (postID.matches(post_id)){
        BlogaPI api = ApiClient.getBlogInterface();
      Call<List<SingleBlogPost>> call = api.postResponse();
        call.enqueue(new Callback<List<SingleBlogPost>>() {
            @Override
            public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
               singleBlogPosts = response.body();
                blogContent.setText(singleBlogPost.getBlogContent());
                blogSub.setText(singleBlogPost.getBlogSubtitle());
                blogTitle.setText(singleBlogPost.getBlogTitle());
                Glide.with(AnotherSingleView.this).load(singleBlogPost.getBlogMedimg()).into(blogPic);
            }

            @Override
            public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {

            }
        });

    }

}
}

Interface:

public interface BlogRequestInterface {

  @GET("blog")
  Call<BlogApi> getMyBlog();
  @GET("post/{id}")
  Call<List<SingleBlogPost>> getSinglePost();
}

Pojo class:

public class SingleBlogPost {

@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 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;
}

Body:
I do not recommend adding ClickListeners on onBindViewHolder. My onCreateViewHolder does something like this.

   @Override
   public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.blog_post_item,parent, false);
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //do stuff
        }
    });

    return new BlogViewHolder(view);
}

And if you need position or list object for that you can refer to this link http://androidshenanigans.blogspot.com.tr/2015/02/viewholder-pattern-common-mistakes.html

Hope it helps.


来源: stackexchange

问:
Kivy PyInstaller on Appveyor
I would like to build the executables for my Kivy application using PyInstaller on Appveyor. I have the build working on my own computer, but on Appveyor build I get the following message:

```<code>OpenGL version detected: 1.1
Version: b'1.1.0'
Vendor: b'Microsoft Corporation'
Renderer: b'GDI Generic'
Try upgrading your graphics drivers and/or your graphics hardware in case of problems.
The application will leave now.
</code>```

I am using the default PyInstaller configuration as described in https://kivy.org/docs/guide/packaging-windows.html.

The appveyor.yml is as follows:

```<code>image: Visual Studio 2015

environment:
  matrix:
    - PYTHON: "C:\\Python34"
      PYTHON_VERSION: "3.4.x" # currently 3.4.3
      PYTHON_ARCH: "32"

    - PYTHON: "C:\\Python34-x64"
      PYTHON_VERSION: "3.4.x" # currently 3.4.3
      PYTHON_ARCH: "64"

install:
  # Install Python (from the official .msi of http://python.org) and pip when
  # not already installed.
  - ps: if (-not(Test-Path($env:PYTHON))) { & appveyor\install.ps1 }

  - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"

  # Check that we have the expected version and architecture for Python
  - "python --version"
  - "python -c \"import struct; print(struct.calcsize('P') * 8)\""

  - "pip install --disable-pip-version-check --user --upgrade pip"

  # Kivy and pyinstaller included
  - "%CMD_IN_ENV% pip install -r requirements.txt"

  # Saw somewhere on the internet, doesn't work with it nor without it.
  - ps: iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-desktop.ps1'))

build_script:
  - "%CMD_IN_ENV% python -m PyInstaller myapp.spec"

artifacts:
  - path: dist\*
</code>```

As far as I see it, it can go two ways:
* somehow prevent kivy pyinstaller hook from using OpenGL
* configure Appveyor to use OpenGL

Thanks for all your suggestions!

答: As @ilyaf said, but one thing might help you - try to install kivy.deps.angle and package it with that + make your app use the angle. I'm not quite sure if it'll help as there's no GPU, but angle translates OpenGL calls to DirectX, which Appveyor seems to have. It's worth trying, though I'm afraid it'll be no-go even with angle.

ContentLicense: CC BY-SA 3.0

Title: Kivy PyInstaller on Appveyor

Body:
I would like to build the executables for my Kivy application using PyInstaller on Appveyor. I have the build working on my own computer, but on Appveyor build I get the following message:

OpenGL version detected: 1.1
Version: b'1.1.0'
Vendor: b'Microsoft Corporation'
Renderer: b'GDI Generic'
Try upgrading your graphics drivers and/or your graphics hardware in case of problems.
The application will leave now.

I am using the default PyInstaller configuration as described in https://kivy.org/docs/guide/packaging-windows.html.

The appveyor.yml is as follows:

image: Visual Studio 2015

environment:
  matrix:
    - PYTHON: "C:\\Python34"
      PYTHON_VERSION: "3.4.x" # currently 3.4.3
      PYTHON_ARCH: "32"

    - PYTHON: "C:\\Python34-x64"
      PYTHON_VERSION: "3.4.x" # currently 3.4.3
      PYTHON_ARCH: "64"

install:
  # Install Python (from the official .msi of http://python.org) and pip when
  # not already installed.
  - ps: if (-not(Test-Path($env:PYTHON))) { & appveyor\install.ps1 }

  - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"

  # Check that we have the expected version and architecture for Python
  - "python --version"
  - "python -c \"import struct; print(struct.calcsize('P') * 8)\""

  - "pip install --disable-pip-version-check --user --upgrade pip"

  # Kivy and pyinstaller included
  - "%CMD_IN_ENV% pip install -r requirements.txt"

  # Saw somewhere on the internet, doesn't work with it nor without it.
  - ps: iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-desktop.ps1'))

build_script:
  - "%CMD_IN_ENV% python -m PyInstaller myapp.spec"

artifacts:
  - path: dist\*

As far as I see it, it can go two ways:
* somehow prevent kivy pyinstaller hook from using OpenGL
* configure Appveyor to use OpenGL

Thanks for all your suggestions!


问:
Portable recursive regex substitution within a string to resolve .. in path
In Bash, what is the most elegant and portable way to resolve all occurrences of .. within a string representing a path?

Example: path /aa/bb/cc/../dd/ee/../../ff/gg/hh/ii/jj/../../../kk becomes /aa/bb/ff/gg/kk

I wrote two functions that mostly accomplish this goal. (It was actually one, and it was longer, but I had a few ideas while writing this question…)

One uses repetition:

resolve_parents () {
  local previous result=$1
  local re="\/$re|$re\/" re='[^\/]{1,}\/\.\.'
  while [[ $result != $previous ]]; do
    previous=$result
    result=$(echo "$result" | awk '{sub(/\/'$re'/,"")} 1')
  done
  echo "$result"
}

resolve_parents '/aa/bb/cc/../dd/ee/../../ff/gg/hh/ii/jj/../../../kk'
```

<p>And one uses recursion:</p>

<pre class="lang-sh prettyprint-override"><code>resolve_parents_r () {
  local re="\/$re|$re\/" re='[^\/]{1,}\/\.\.'
  local result=$(echo "$1" | awk '{sub(/\/'$re'/,"")} 1')
  [[ $1 = $result ]] && echo "$1" || resolve_parents_r "$result"
}
</code>```

They do not remove a leading .., which would necessitate determining the base directory to get its parent. I am OK with that limitation. Also, it does not fully reduce aa/.. to an empty string. I suppose I would either need to separately apply a regex at the end without a leading or trailing slash, or add a slash to the string at the start and remove it at the end.

Background

I have a function that runs ln -s "$source" "$target". It needs to throw an error if $source does not exist. Confirming $source exists is straightforward if it is an absolute path, but relative paths must be normalized. I accomplish this by:

[[ -d $target ]] && target=$target/$(basename "$source")
local abs_source=$source
[[ $source = /* ]] || abs_source=$( cd "$target/../$source" && pwd -P )
```

The first line is necessary to ensure $target ends with the target name. Otherwise the ../ would need to be omitted if $target is a directory, but would be required if $target already ends with intended link name. cd works fine for resolving paths containing double dot parent references only if the directory exists. Since the test occurs before the link is created, $target unfortunately but necessarily does not exist.

Thus, I am left to determine whether $source exists by deleting matches of the regular expression [^/]+/\.\. either preceded or followed by a slash, but not both. (I considered deleting the matches and then deleting sequences of //, but that can result in a path that was relative becoming absolute or a path that ended in a target name becoming a directory, which would get another target name appended. Yikes!) I cannot use a global regex replace with that pattern, as that could delete sequences like ../... I am not aware of a command that does global replace by resetting the search cursor to the beginning of the string upon each match, so I wrote this into a while loop.

I hoped to use a pattern stored in $re for the sake of simplicity, but that soon became rather complicated when I tried to do the replace with sed and found the + requires extended regular expressions are sometimes turned on with sed -E (on OSX) and sometimes with sed -r. Upon replacing + with {1,}, I found the braces needed escaping for sed, but escaping them caused the Bash regex match to fail. I migrated to using awk and its sub command, which apparently requires the delimiter to be /, so I needed to escape those in my pattern as well.

To prevent infinite loops due to an interpretation mismatch between the regex in Bash and awk, I first added a counter variable with an arbitrary limit. I improved that to a difference test, so while [[ $result =~ $re ]] && (( count < 1000 )) became while [[ $result =~ $re && $result != $previous ]]. Then after experimenting with making an actually recursive function, I realized the $result =~ $re && was not necessary.

At this point I start to wonder whether I really care if my $sources are nonexistent!

答:
In 'configure' files which generated by 'autotools' used pretty simple, and looks like very portable approach :)</p>

```<code># expand $ac_aux_dir to an absolute path
am_aux_dir=`cd $ac_aux_dir && pwd`
</code>```

Body:
In Bash, what is the most elegant and portable way to resolve all occurrences of .. within a string representing a path?

Example: path /aa/bb/cc/../dd/ee/../../ff/gg/hh/ii/jj/../../../kk becomes /aa/bb/ff/gg/kk

I wrote two functions that mostly accomplish this goal. (It was actually one, and it was longer, but I had a few ideas while writing this question…)

One uses repetition:

resolve_parents () {
  local previous result=$1
  local re="\/$re|$re\/" re='[^\/]{1,}\/\.\.'
  while [[ $result != $previous ]]; do
    previous=$result
    result=$(echo "$result" | awk '{sub(/\/'$re'/,"")} 1')
  done
  echo "$result"
}

resolve_parents '/aa/bb/cc/../dd/ee/../../ff/gg/hh/ii/jj/../../../kk'

And one uses recursion:

resolve_parents_r () {
  local re="\/$re|$re\/" re='[^\/]{1,}\/\.\.'
  local result=$(echo "$1" | awk '{sub(/\/'$re'/,"")} 1')
  [[ $1 = $result ]] && echo "$1" || resolve_parents_r "$result"
}

They do not remove a leading .., which would necessitate determining the base directory to get its parent. I am OK with that limitation. Also, it does not fully reduce aa/.. to an empty string. I suppose I would either need to separately apply a regex at the end without a leading or trailing slash, or add a slash to the string at the start and remove it at the end.

Background

I have a function that runs ln -s "$source" "$target". It needs to throw an error if $source does not exist. Confirming $source exists is straightforward if it is an absolute path, but relative paths must be normalized. I accomplish this by:

[[ -d $target ]] && target=$target/$(basename "$source")
local abs_source=$source
[[ $source = /* ]] || abs_source=$( cd "$target/../$source" && pwd -P )

The first line is necessary to ensure $target ends with the target name. Otherwise the ../ would need to be omitted if $target is a directory, but would be required if $target already ends with intended link name. cd works fine for resolving paths containing double dot parent references only if the directory exists. Since the test occurs before the link is created, $target unfortunately but necessarily does not exist.

Thus, I am left to determine whether $source exists by deleting matches of the regular expression [^/]+/\.\. either preceded or followed by a slash, but not both. (I considered deleting the matches and then deleting sequences of //, but that can result in a path that was relative becoming absolute or a path that ended in a target name becoming a directory, which would get another target name appended. Yikes!) I cannot use a global regex replace with that pattern, as that could delete sequences like ../... I am not aware of a command that does global replace by resetting the search cursor to the beginning of the string upon each match, so I wrote this into a while loop.

I hoped to use a pattern stored in $re for the sake of simplicity, but that soon became rather complicated when I tried to do the replace with sed and found the + requires extended regular expressions are sometimes turned on with sed -E (on OSX) and sometimes with sed -r. Upon replacing + with {1,}, I found the braces needed escaping for sed, but escaping them caused the Bash regex match to fail. I migrated to using awk and its sub command, which apparently requires the delimiter to be /, so I needed to escape those in my pattern as well.

To prevent infinite loops due to an interpretation mismatch between the regex in Bash and awk, I first added a counter variable with an arbitrary limit. I improved that to a difference test, so while [[ $result =~ $re ]] && (( count < 1000 )) became while [[ $result =~ $re && $result != $previous ]]. Then after experimenting with making an actually recursive function, I realized the $result =~ $re && was not necessary.

At this point I start to wonder whether I really care if my $sources are nonexistent!

Body:
In 'configure' files which generated by 'autotools' used pretty simple, and looks like very portable approach :)

# expand $ac_aux_dir to an absolute path
am_aux_dir=`cd $ac_aux_dir && pwd`


问:
reverse vowels in string in c
I'm a beginner programmer. I was trying out the problem of reversing vowels in a string.

Ex: input: zabedfigu, output: zubidfega

When I run the following code, I get a runtime error. I've tried to change the conditions within incrementing the pointer pc1 upto only upto the middle index etc., but that either gives me a runtime error or doesn't give me the required output. I'd like some help on what to do to make my code work as well as any new way of solving the problem. TIA.

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

char* reverseVowels(char* str)
{
    char *pc1, *pc2;
    int i;
    pc1 = &str[0];
    for(i=0; str[i]!='\0';++i)
        ;
    pc2 = &str[i-1];

    while(pc1!=pc2)
    {
      if((*pc1=='a')||(*pc1=='e')||(*pc1=='i')||(*pc1=='o')||(*pc1=='u'))
      {
        while(pc2!=pc1)
        {
            if((*pc2=='a')||(*pc2=='e')||(*pc2=='i')||(*pc2=='o')||(*pc2=='u'))
            {
              char temp;
              temp = *pc1;
              *pc1 = *pc2;
              *pc2 = temp;
              ++pc2;
              break;
            }
            else
              ++pc2;
        }
        ++pc1;
      }
      else
        ++pc1;
    }
    //return str;
    return NULL;
}
int main()
{
    char string[20], *pstr;
    scanf("%s", string);
    //pstr = reverseVowels(string);
    //printf("%s", pstr);
    reverseVowels(string);
    printf("%s", string);
    return 0;
}
</code>```

答:
The problem is occurring when you are going to increment the pointer variable value of pc2, instead of decrementing the pointer variable pc2 value like this --pc.

Updated

According to cleblanc's comment, my previous answer was not working for an input like abade, so then I changed the code to fix that problem.

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

char* reverseVowels(char* str)
{
    char *pc1, *pc2;
    int i;
    pc1 = &str[0];
    for(i=0; str[i]!='\0';++i)
        ;
    pc2 = &str[i-1];

    while(pc1<pc2)
    {
      if((*pc1=='a')||(*pc1=='e')||(*pc1=='i')||(*pc1=='o')||(*pc1=='u'))
      {
        while(pc2!=pc1)
        {
            if((*pc2=='a')||(*pc2=='e')||(*pc2=='i')||(*pc2=='o')||(*pc2=='u'))
            {
              char temp;
              temp = *pc1;
              *pc1 = *pc2;
              *pc2 = temp;
              --pc2;
              break;
            }
            else
              --pc2;
        }
        ++pc1;
      }
      else
        ++pc1;
    }
    //return str;
    return NULL;
}
int main()
{
    char string[20], *pstr;
    scanf("%s", string);
    //pstr = reverseVowels(string);
    //printf("%s", pstr);
    reverseVowels(string);
    printf("%s\n", string);
    return 0;
}
</code>```

Title: reverse vowels in string in c

Body:
I'm a beginner programmer. I was trying out the problem of reversing vowels in a string.

Ex: input: zabedfigu, output: zubidfega

When I run the following code, I get a runtime error. I've tried to change the conditions within incrementing the pointer pc1 upto only upto the middle index etc., but that either gives me a runtime error or doesn't give me the required output. I'd like some help on what to do to make my code work as well as any new way of solving the problem. TIA.

#include<stdio.h>

char* reverseVowels(char* str)
{
    char *pc1, *pc2;
    int i;
    pc1 = &str[0];
    for(i=0; str[i]!='\0';++i)
        ;
    pc2 = &str[i-1];

    while(pc1!=pc2)
    {
      if((*pc1=='a')||(*pc1=='e')||(*pc1=='i')||(*pc1=='o')||(*pc1=='u'))
      {
        while(pc2!=pc1)
        {
            if((*pc2=='a')||(*pc2=='e')||(*pc2=='i')||(*pc2=='o')||(*pc2=='u'))
            {
              char temp;
              temp = *pc1;
              *pc1 = *pc2;
              *pc2 = temp;
              ++pc2;
              break;
            }
            else
              ++pc2;
        }
        ++pc1;
      }
      else
        ++pc1;
    }
    //return str;
    return NULL;
}
int main()
{
    char string[20], *pstr;
    scanf("%s", string);
    //pstr = reverseVowels(string);
    //printf("%s", pstr);
    reverseVowels(string);
    printf("%s", string);
    return 0;
}

Body:
The problem is occurring when you are going to increment the pointer variable value of pc2, instead of decrementing the pointer variable pc2 value like this --pc.

Updated

According to cleblanc's comment, my previous answer was not working for an input like abade, so then I changed the code to fix that problem.

#include <stdio.h>

char* reverseVowels(char* str)
{
    char *pc1, *pc2;
    int i;
    pc1 = &str[0];
    for(i=0; str[i]!='\0';++i)
        ;
    pc2 = &str[i-1];

    while(pc1<pc2)
    {
      if((*pc1=='a')||(*pc1=='e')||(*pc1=='i')||(*pc1=='o')||(*pc1=='u'))
      {
        while(pc2!=pc1)
        {
            if((*pc2=='a')||(*pc2=='e')||(*pc2=='i')||(*pc2=='o')||(*pc2=='u'))
            {
              char temp;
              temp = *pc1;
              *pc1 = *pc2;
              *pc2 = temp;
              --pc2;
              break;
            }
            else
              --pc2;
        }
        ++pc1;
      }
      else
        ++pc1;
    }
    //return str;
    return NULL;
}
int main()
{
    char string[20], *pstr;
    scanf("%s", string);
    //pstr = reverseVowels(string);
    //printf("%s", pstr);
    reverseVowels(string);
    printf("%s\n", string);
    return 0;
}


问:
Calling multiple JavaScript functions on a button click
How to call multiple functions on button click event?

Here is my button,

```<code><asp:LinkButton
    ID="LbSearch"
    runat="server"
    CssClass="regular"
    onclick="LbSearch_Click"
    OnClientClick="return validateView();ShowDiv1();">
</code>```

But my ShowDiv1 doesn't get called...

My JavaScript functions:

```<code>function ShowDiv1() {
    document.getElementById("ReportDiv").style.display = 'block';
    return false;
}

function validateView() {

    if (document.getElementById("ctl00_ContentPlaceHolder1_DLCategory").selectedIndex == 0) {
        document.getElementById("ctl00_ContentPlaceHolder1_ErrorMsg").innerHTML = "Please Select Your Category";
        document.getElementById("ctl00_ContentPlaceHolder1_DLCategory").focus();
        return false;
    }
    if (document.getElementById("ctl00_ContentPlaceHolder1_DLEmpName").selectedIndex == 0) {
        document.getElementById("ctl00_ContentPlaceHolder1_ErrorMsg").innerHTML = "Please Select Your Employee Name";
        document.getElementById("ctl00_ContentPlaceHolder1_DLEmpName").focus();
        return false;
    }
    return true;
}
</code>```

If the ValidateView() function returns true I should call ShowDiv1().

答:
Try this ....
I got it...
onClientClick="var b=validateView();if(b) var b=ShowDiv1();return b;"</p>

Body:
How to call multiple functions on button click event?

Here is my button,

<asp:LinkButton
    ID="LbSearch"
    runat="server"
    CssClass="regular"
    onclick="LbSearch_Click"
    OnClientClick="return validateView();ShowDiv1();">

But my ShowDiv1 doesn't get called...

My JavaScript functions:

function ShowDiv1() {
    document.getElementById("ReportDiv").style.display = 'block';
    return false;
}

function validateView() {

    if (document.getElementById("ctl00_ContentPlaceHolder1_DLCategory").selectedIndex == 0) {
        document.getElementById("ctl00_ContentPlaceHolder1_ErrorMsg").innerHTML = "Please Select Your Category";
        document.getElementById("ctl00_ContentPlaceHolder1_DLCategory").focus();
        return false;
    }
    if (document.getElementById("ctl00_ContentPlaceHolder1_DLEmpName").selectedIndex == 0) {
        document.getElementById("ctl00_ContentPlaceHolder1_ErrorMsg").innerHTML = "Please Select Your Employee Name";
        document.getElementById("ctl00_ContentPlaceHolder1_DLEmpName").focus();
        return false;
    }
    return true;
}

If the ValidateView() function returns true I should call ShowDiv1().

ContentLicense: CC BY-SA 2.5


问:
Python 3.6: Accumulate sklearn nGram by document instead of term
I am new with Python, but I could not find the answer to this anywhere (at least not in a form simple enough for me). How do I accumulate nGram frequencies by document instead of term?

I am creating nGrams based on a description field using sklearn.feature_extraction.text CountVectorizer. Here is the code:

```<code>df = pandas.read_sql('select unique_id, short_description')
from sklearn.feature_extraction.text import CountVectorizer
word_vectorizer = CountVectorizer(ngram_range=(3,3), analyzer='word')
X = word_vectorizer.fit_transform(df['short_description'])
frequencies = sum(X).toarray()[0]
results = pandas.DataFrame(frequencies, index=word_vectorizer.get_feature_names(), columns=['frequency'])
</code>```

This code provides a results dataframe that consists of one column of nGrams and one column of their frequencies across all records (documents) brought in during the first step.

```<code>"the quick brown"    4
"quick brown fox"    2
"brown fox jumped"   5
</code>```

Instead of this, I would like the frequency of each nGram for each record:

```<code>0001    "the quick brown"    2
0001    "quick brown fox"    2
0002    "the quick brown"    2
0002    "brown fox jumped"   5
</code>```

This would allow comparison of documents, as well as comparison of nGrams over time. Logically, this will require somehow mapping the frequencies back to the unique_id that was brought in. I have attempted various ways of appending the frequencies to the original dataframe with no success.

Thank you for any insight you all can provide, and please let me know if I can answer any questions.

EDIT:
Here is my latest attempt to accomplish my stated issue per the comments from JD Long below:

I have a dataframe (let's assume only one record for simplicity):

```<code>id    short_description
0001  the farmer plants grain
0002  the fisher catches tuna
0002  the police officer fights crime
</code>```

Here is the code I'm using to find the nGrams of the short_description field:

```<code>df = pandas.read_sql('select id, short_description')
df_grouped = df.groupby('id')

word_vectorizer = CountVectorizer(ngram_range=(3,3), analyzer='word')
for id, group in df_grouped:
   X = word_vectorizer.fit_transform(group['short_description'])
   frequencies = sum(X).toarray()[0]
   results = pd.DataFrame(frequencies, index=word_vectorizer.get_feature_names(), columns=['frequency'])
   dfinner = pd.DataFrame(word_vectorizer.get_feature_names())
</code>```

This results is the nGrams being assigned to a dataframe with the id no longer assigned to each nGram:

```<code>The farmer plants
farmer plants grain
the fisher catches
fisher catches tuna
the police officer
police officer fights
</code>```

How do I then get the id assigned to each nGram? Desired output:

```<code>id    nGram
0001  The farmer plants
0001  farmer plants grain
0002  The fisher catches
0002  fisher catches tuna
0002  The police officer
0002  police officer fights
0002  officer fights crime
</code>```

答:
there are a handful of ways to skin this cat. The ones that come to mind are the following:

first request a list of all the unique unique_id records from the db. Read that into a list then iterate over that list doing your DB request on a specific unique_id then do your ngrams and then push the results into a dataframe along with the unique_id... then iterate to the next unique_id

Read everything into a dataframe (like you are currently doing) then use the pandas group_by() function to group on unique_id and apply your ngram to each group.

Let your data volume be your guide. I think you are small enough volume that #2 should work just fine. Since I don't have your data I can't really test this, but it would look something like:

```<code>df_grouped = df.groupby('unique_id')

# iterate through the groups
for id, group in df_grouped:
  X = word_vectorizer.fit_transform(group['short_description'])
  frequencies = sum(X).toarray()[0]
  results = pandas.DataFrame(frequencies, index=word_vectorizer.get_feature_names(), columns=['frequency'])
  ## right here you need to pop your results into a collection of some kind
  ## you can likely put them in a pandas dataframe but I can't guess the
  ## format of the results... remember that id holds your unique_id for the
  ## group so you'll want that and the results in your output df
</code>```

Body:
I am new with Python, but I could not find the answer to this anywhere (at least not in a form simple enough for me). How do I accumulate nGram frequencies by document instead of term?

I am creating nGrams based on a description field using sklearn.feature_extraction.text CountVectorizer. Here is the code:

df = pandas.read_sql('select unique_id, short_description')
from sklearn.feature_extraction.text import CountVectorizer
word_vectorizer = CountVectorizer(ngram_range=(3,3), analyzer='word')
X = word_vectorizer.fit_transform(df['short_description'])
frequencies = sum(X).toarray()[0]
results = pandas.DataFrame(frequencies, index=word_vectorizer.get_feature_names(), columns=['frequency'])

This code provides a results dataframe that consists of one column of nGrams and one column of their frequencies across all records (documents) brought in during the first step.

"the quick brown"    4
"quick brown fox"    2
"brown fox jumped"   5

Instead of this, I would like the frequency of each nGram for each record:

0001    "the quick brown"    2
0001    "quick brown fox"    2
0002    "the quick brown"    2
0002    "brown fox jumped"   5

This would allow comparison of documents, as well as comparison of nGrams over time. Logically, this will require somehow mapping the frequencies back to the unique_id that was brought in. I have attempted various ways of appending the frequencies to the original dataframe with no success.

Thank you for any insight you all can provide, and please let me know if I can answer any questions.

EDIT:
Here is my latest attempt to accomplish my stated issue per the comments from JD Long below:

I have a dataframe (let's assume only one record for simplicity):

id    short_description
0001  the farmer plants grain
0002  the fisher catches tuna
0002  the police officer fights crime

Here is the code I'm using to find the nGrams of the short_description field:

df = pandas.read_sql('select id, short_description')
df_grouped = df.groupby('id')

word_vectorizer = CountVectorizer(ngram_range=(3,3), analyzer='word')
for id, group in df_grouped:
   X = word_vectorizer.fit_transform(group['short_description'])
   frequencies = sum(X).toarray()[0]
   results = pd.DataFrame(frequencies, index=word_vectorizer.get_feature_names(), columns=['frequency'])
   dfinner = pd.DataFrame(word_vectorizer.get_feature_names())

This results is the nGrams being assigned to a dataframe with the id no longer assigned to each nGram:

The farmer plants
farmer plants grain
the fisher catches
fisher catches tuna
the police officer
police officer fights

How do I then get the id assigned to each nGram? Desired output:

id    nGram
0001  The farmer plants
0001  farmer plants grain
0002  The fisher catches
0002  fisher catches tuna
0002  The police officer
0002  police officer fights
0002  officer fights crime

Body:
there are a handful of ways to skin this cat. The ones that come to mind are the following:

first request a list of all the unique unique_id records from the db. Read that into a list then iterate over that list doing your DB request on a specific unique_id then do your ngrams and then push the results into a dataframe along with the unique_id... then iterate to the next unique_id

Read everything into a dataframe (like you are currently doing) then use the pandas group_by() function to group on unique_id and apply your ngram to each group.

Let your data volume be your guide. I think you are small enough volume that #2 should work just fine. Since I don't have your data I can't really test this, but it would look something like:

df_grouped = df.groupby('unique_id')

# iterate through the groups
for id, group in df_grouped:
  X = word_vectorizer.fit_transform(group['short_description'])
  frequencies = sum(X).toarray()[0]
  results = pandas.DataFrame(frequencies, index=word_vectorizer.get_feature_names(), columns=['frequency'])
  ## right here you need to pop your results into a collection of some kind
  ## you can likely put them in a pandas dataframe but I can't guess the
  ## format of the results... remember that id holds your unique_id for the
  ## group so you'll want that and the results in your output df


问:
check number of unique values in each column of a matrix in spark
I have a csv file currently stored as a dataframe in spark

```<code>scala> df
res11: org.apache.spark.sql.DataFrame = [2013-03-25 12:49:36.000: string, OES_PSI603_EC1: string, 250.3315__SI: string, 250.7027__SI: string, 251.0738__SI: string, 251.4448__SI: string, 251.8159__SI: string, 252.1869__SI: string, 252.5579__SIF: string, 252.9288__SI: string, 253.2998__SIF: string, 253.6707__SIF: string, 254.0415__CI2: string, 254.4124__CI2: string, 254.7832__CI2: string, 255.154: string, 255.5248__NO: string, 255.8955__NO: string, 256.2662__NO: string, 256.6369: string, 257.0075: string, 257.3782: string, 257.7488: string, 258.1193: string, 258.4899: string, 258.8604__NO: string, 259.2309__NO: string, 259.6013__NO: string, 259.9717__N2: string, 260.3421__N2: string, 260.7125__N2: string, 261.4531: string, 261.8234: string, 262.1937: string, 262.5639: string, 262.9341: s...
scala>
</code>```

I want to count the number of unique elements in each columns. How can I do that?

Body:
I have a csv file currently stored as a dataframe in spark

scala> df
res11: org.apache.spark.sql.DataFrame = [2013-03-25 12:49:36.000: string, OES_PSI603_EC1: string, 250.3315__SI: string, 250.7027__SI: string, 251.0738__SI: string, 251.4448__SI: string, 251.8159__SI: string, 252.1869__SI: string, 252.5579__SIF: string, 252.9288__SI: string, 253.2998__SIF: string, 253.6707__SIF: string, 254.0415__CI2: string, 254.4124__CI2: string, 254.7832__CI2: string, 255.154: string, 255.5248__NO: string, 255.8955__NO: string, 256.2662__NO: string, 256.6369: string, 257.0075: string, 257.3782: string, 257.7488: string, 258.1193: string, 258.4899: string, 258.8604__NO: string, 259.2309__NO: string, 259.6013__NO: string, 259.9717__N2: string, 260.3421__N2: string, 260.7125__N2: string, 261.4531: string, 261.8234: string, 262.1937: string, 262.5639: string, 262.9341: s...
scala>

I want to count the number of unique elements in each columns. How can I do that?

Body:
You can use the countDistinct function on each column.

For example, in pyspark:

df = spark.createDataFrame([ (1, 1), (1, 3), (2, 1), (3, 2), (3, 3) ], ["user_id", "genre_id"])
>>> df.show()
+-------+--------+
|user_id|genre_id|
+-------+--------+
|      1|       1|
|      1|       3|
|      2|       1|
|      3|       2|
|      3|       3|
+-------+--------+

>>> import pyspark.sql.functions as F
>>> df.select( [ F.countDistinct(cn).alias("c_{0}".format(cn)) for cn in df.columns ] ).show()
+---------+----------+
|c_user_id|c_genre_id|
+---------+----------+
|        3|         3|
+---------+----------+


问:
Understanding Javascript scope with modules
I am trying to understand how scope works with node modules. I have an IIFE to initialize a LinkedList, which uses Node object for each element.

using IIFE to avoid polluting global scope

After IIFE, where does the Node go? Is there any way I can access Node in require object i.e. test class?

linkedList.js

(function LinkedListInit() {
    module.exports = new LinkedList();

    function LinkedList() {
        this.head;
    }

    // LinkedList Node
    function Node(data, next) {
        this.data = data;
        this.next = next;
    }

    LinkedList.prototype.insert = insert;

    function insert(data) {
        var curr = this.head,
            newNode = new Node(data);

        if (this.head == null) {
            this.head = newNode;
        } else {
            while (curr.next != null) {
                curr = curr.next;
            }
            curr.next = newNode;
        }
        return this;
    }
}());```
</div>
</div>
</p>

<h2>linkedListTest.js</h2>

```var linkedList = require('../../js/ds/linkedList');
// Test cases for linkedList.insert(val); works fine.

// Can I access Node here?
```

答:
The only things accessible outside of the Node module are those added to the module.exports variable.

When you do

```<code>var x = require('./some/path');
</code>```

x will be equal to the module.exports variable defined in ./some/path.js.

Unless Node is somehow made explicitly available in your module.exports object, you cannot access it from outside the module file.

The typical way to define modules with an IIFE in Node is to do:

```<code>module.exports = (function() {
    //...a lot of code...
    return {
      exportedValue1: somethingIWantToBeAvailable;
      exportedValue2: aDifferentThing;
      //... and so on ...
    };
})();
</code>```

But you don't really need the IIFE. Unlike a browser environment, stuff only gets added to the global scope in node if you explicitly request that by saying

```<code>global.variable = something;
</code>```

Otherwise, your variable is in module-local scope. As Node treats modules and files as being in one-to-one correspondence, this means any variables you create within a file are only accessible within that file - barring the use of global and module.exports.

Body:
I am trying to understand how scope works with node modules. I have an IIFE to initialize a LinkedList, which uses Node object for each element.

using IIFE to avoid polluting global scope

After IIFE, where does the Node go? Is there any way I can access Node in require object i.e. test class?

linkedList.js

(function LinkedListInit() {
    module.exports = new LinkedList();

    function LinkedList() {
        this.head;
    }

    // LinkedList Node
    function Node(data, next) {
        this.data = data;
        this.next = next;
    }

    LinkedList.prototype.insert = insert;

    function insert(data) {
        var curr = this.head,
            newNode = new Node(data);

        if (this.head == null) {
            this.head = newNode;
        } else {
            while (curr.next != null) {
                curr = curr.next;
            }
            curr.next = newNode;
        }
        return this;
    }
}());

linkedListTest.js

var linkedList = require('../../js/ds/linkedList');
// Test cases for linkedList.insert(val); works fine.

// Can I access Node here?

Body:
The only things accessible outside of the Node module are those added to the module.exports variable.

When you do

var x = require('./some/path');

x will be equal to the module.exports variable defined in ./some/path.js.

Unless Node is somehow made explicitly available in your module.exports object, you cannot access it from outside the module file.

The typical way to define modules with an IIFE in Node is to do:

module.exports = (function() {
    //...a lot of code...
    return {
      exportedValue1: somethingIWantToBeAvailable;
      exportedValue2: aDifferentThing;
      //... and so on ...
    };
})();

But you don't really need the IIFE. Unlike a browser environment, stuff only gets added to the global scope in node if you explicitly request that by saying

global.variable = something;

Otherwise, your variable is in module-local scope. As Node treats modules and files as being in one-to-one correspondence, this means any variables you create within a file are only accessible within that file - barring the use of global and module.exports.


问:
Any success stories for JSF, GWT, Wicket or Tapestry on the web?
I am searching for framework references. In other words I am looking for companies, which have successfully implemented a framework solution in java web application environment (success stories). Frameworks I am interested in are JSF, GWT, Wicket and Tapestry. I wasn't able to google any results, nor to find any references at the official sites. At the end I am a bit confused if there are any. Can someone help me out?</p>

答: Not aware of JSF, Wicket and Tapestry based apps, but Google Wave, Adwords, Adsense are built using GWT</p>


问:
Sending email with spring fails on service
I'am working on a project(using spring boot) in which i need to send real time email notification, the email service is invoked in other class not in controller.
I receive an error that my service mail is null but when i put it in controller(RestController) it's working.
Where is my mistake?
is it possible to call for mail service in other class(services)?
For the process using RestController i used this example and as i said it's working, here is the link:
http://therealdanvega.com/blog/2016/01/13/sending-async-emails-in-spring</p>

答:
@Autowire annotation will not work if you are calling the Service from another class, which is not manged by Spring Container. Below link is having the same problem like yours.

@Autowired and @Service working from controller but not from a different package

If you want to call this Service class from another class which is not managed by Spring, use a getter/setter method in Service class. If you share the code, it will be helpful to debug more.


问:
Task not serializable error - Spark Java
I have the following code in my Spark application. It is supposed to filter out genes from set csv files. I am loading the csv files into spark RDD. When I run the jar using spark-submit, I get Task not serializable exception.

```<code>public class AttributeSelector {

    public static final String path = System.getProperty("user.dir") + File.separator;
    public static Queue<Instances> result = new LinkedBlockingQueue<>();
    private static final Logger LOGGER = LoggerFactory.getLogger(AttributeSelector.class);

    int[] selectAttributes(Instances data) {

        int[] indexes = null;
        AttributeSelection filter = new AttributeSelection();
        CfsSubsetEval evaluator = new CfsSubsetEval();
        filter.setEvaluator(evaluator);
        BestFirst search = new BestFirst();
        filter.setSearch(search);
        try {
            filter.SelectAttributes(data);
            indexes = filter.selectedAttributes();
        } catch (Exception e) {
            System.out.println("Error when resampling input data with selected attributes!");
            e.printStackTrace();
        }
        return indexes;

    }

    public void selectData(Instances data, int[] indexes) {

        Instances newData = data;
        Remove remove = new Remove();
        remove.setAttributeIndicesArray(indexes);
        remove.setInvertSelection(true);

        try {
            remove.setInputFormat(data);
            newData = Filter.useFilter(data, remove);
            result.add(newData);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private Instances getInputInstance(File fileName) {
        CSVLoader loader = new CSVLoader();
        Instances instance = null;
        try {
            loader.setSource(fileName);
            instance = loader.getDataSet();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return instance;
    }

    private void writeMergedOutput() {

        LOGGER.info("Started merging results");
        Instances finalResult = result.poll();

        while (!result.isEmpty()) {
            finalResult = Instances.mergeInstances(finalResult, result.poll());
        }

        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(path + "Output" + ".arff"));
            writer.write(finalResult.toString());
            writer.flush();
            writer.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        LOGGER.info("Finished merging results");
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        try {
            LOGGER.info("Loading data");
            AttributeSelector attributeSelector = new AttributeSelector();
            attributeSelector.run(path + "Parts");

        } catch (Exception e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        LOGGER.info("Execution time: " + (end - start));
    }

    public void run(String sourceDir) {
        String master = "local[*]";

        SparkConf conf = new SparkConf()
                .setAppName(AttributeSelector.class.getName())
                .setMaster(master);

        JavaSparkContext context = new JavaSparkContext(conf);

        JavaFutureAction<Void> task = context.wholeTextFiles(sourceDir)
            .foreachAsync(new VoidFunction<Tuple2<String,String>>(){

                @Override
                public void call(Tuple2<String, String> fileInfo) throws Exception {
                    File file = new File(fileInfo._1);
                    Instances instance = getInputInstance(file);
                    instance.setClassIndex(instance.numAttributes() - 1);
                    int[] indices = selectAttributes(instance);
                    selectData(instance, indices);
                    LOGGER.info("Finished executing: " + fileInfo._1);
                }

        });

        while(!task.isDone()){

        }
        writeMergedOutput();

        context.close();
    }

}
</code>```

What causes this Exception and how do I resolve it?

The Exception I am getting is

```<code>org.apache.spark.SparkException: Task not serializable
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:298)
    at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:288)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:108)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2094)
    at org.apache.spark.rdd.AsyncRDDActions$$anonfun$foreachAsync$1.apply(AsyncRDDActions.scala:126)
    at org.apache.spark.rdd.AsyncRDDActions$$anonfun$foreachAsync$1.apply(AsyncRDDActions.scala:125)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
    at org.apache.spark.rdd.AsyncRDDActions.foreachAsync(AsyncRDDActions.scala:125)
    at org.apache.spark.api.java.JavaRDDLike$class.foreachAsync(JavaRDDLike.scala:732)
    at org.apache.spark.api.java.AbstractJavaRDDLike.foreachAsync(JavaRDDLike.scala:45)
    at geneselection.AttributeSelector.run(AttributeSelector.java:129)
    at geneselection.AttributeSelector.main(AttributeSelector.java:110)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:738)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.io.NotSerializableException: geneselection.AttributeSelector
Serialization stack:
    - object not serializable (class: geneselection.AttributeSelector, value: geneselection.AttributeSelector@5d43409a)
    - field (class: geneselection.AttributeSelector$1, name: this$0, type: class geneselection.AttributeSelector)
    - object (class geneselection.AttributeSelector$1, geneselection.AttributeSelector$1@210308d5)
    - field (class: org.apache.spark.api.java.JavaRDDLike$$anonfun$foreachAsync$1, name: f$15, type: interface org.apache.spark.api.java.function.VoidFunction)
    - object (class org.apache.spark.api.java.JavaRDDLike$$anonfun$foreachAsync$1, <function1>)
    at org.apache.spark.serializer.SerializationDebugger$.improveException(SerializationDebugger.scala:40)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:46)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:100)
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:295)
    ... 22 more
</code>```

答:
According to the java documentation for java.io.NotSerializableException:

Thrown when an instance is required to have a Serializable interface.

So you need to make geneselection.AttributeSelector implement java.io.Serializable (documentation)

Body:
I have the following code in my Spark application. It is supposed to filter out genes from set csv files. I am loading the csv files into spark RDD. When I run the jar using spark-submit, I get Task not serializable exception.

public class AttributeSelector {

    public static final String path = System.getProperty("user.dir") + File.separator;
    public static Queue<Instances> result = new LinkedBlockingQueue<>();
    private static final Logger LOGGER = LoggerFactory.getLogger(AttributeSelector.class);

    int[] selectAttributes(Instances data) {

        int[] indexes = null;
        AttributeSelection filter = new AttributeSelection();
        CfsSubsetEval evaluator = new CfsSubsetEval();
        filter.setEvaluator(evaluator);
        BestFirst search = new BestFirst();
        filter.setSearch(search);
        try {
            filter.SelectAttributes(data);
            indexes = filter.selectedAttributes();
        } catch (Exception e) {
            System.out.println("Error when resampling input data with selected attributes!");
            e.printStackTrace();
        }
        return indexes;

    }

    public void selectData(Instances data, int[] indexes) {

        Instances newData = data;
        Remove remove = new Remove();
        remove.setAttributeIndicesArray(indexes);
        remove.setInvertSelection(true);

        try {
            remove.setInputFormat(data);
            newData = Filter.useFilter(data, remove);
            result.add(newData);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private Instances getInputInstance(File fileName) {
        CSVLoader loader = new CSVLoader();
        Instances instance = null;
        try {
            loader.setSource(fileName);
            instance = loader.getDataSet();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return instance;
    }

    private void writeMergedOutput() {

        LOGGER.info("Started merging results");
        Instances finalResult = result.poll();

        while (!result.isEmpty()) {
            finalResult = Instances.mergeInstances(finalResult, result.poll());
        }

        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(path + "Output" + ".arff"));
            writer.write(finalResult.toString());
            writer.flush();
            writer.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        LOGGER.info("Finished merging results");
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        try {
            LOGGER.info("Loading data");
            AttributeSelector attributeSelector = new AttributeSelector();
            attributeSelector.run(path + "Parts");

        } catch (Exception e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        LOGGER.info("Execution time: " + (end - start));
    }

    public void run(String sourceDir) {
        String master = "local[*]";

        SparkConf conf = new SparkConf()
                .setAppName(AttributeSelector.class.getName())
                .setMaster(master);

        JavaSparkContext context = new JavaSparkContext(conf);

        JavaFutureAction<Void> task = context.wholeTextFiles(sourceDir)
            .foreachAsync(new VoidFunction<Tuple2<String,String>>(){

                @Override
                public void call(Tuple2<String, String> fileInfo) throws Exception {
                    File file = new File(fileInfo._1);
                    Instances instance = getInputInstance(file);
                    instance.setClassIndex(instance.numAttributes() - 1);
                    int[] indices = selectAttributes(instance);
                    selectData(instance, indices);
                    LOGGER.info("Finished executing: " + fileInfo._1);
                }

        });

        while(!task.isDone()){

        }
        writeMergedOutput();

        context.close();
    }

}

What causes this Exception and how do I resolve it?

The Exception I am getting is

org.apache.spark.SparkException: Task not serializable
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:298)
    at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:288)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:108)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2094)
    at org.apache.spark.rdd.AsyncRDDActions$$anonfun$foreachAsync$1.apply(AsyncRDDActions.scala:126)
    at org.apache.spark.rdd.AsyncRDDActions$$anonfun$foreachAsync$1.apply(AsyncRDDActions.scala:125)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
    at org.apache.spark.rdd.AsyncRDDActions.foreachAsync(AsyncRDDActions.scala:125)
    at org.apache.spark.api.java.JavaRDDLike$class.foreachAsync(JavaRDDLike.scala:732)
    at org.apache.spark.api.java.AbstractJavaRDDLike.foreachAsync(JavaRDDLike.scala:45)
    at geneselection.AttributeSelector.run(AttributeSelector.java:129)
    at geneselection.AttributeSelector.main(AttributeSelector.java:110)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:738)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.io.NotSerializableException: geneselection.AttributeSelector
Serialization stack:
    - object not serializable (class: geneselection.AttributeSelector, value: geneselection.AttributeSelector@5d43409a)
    - field (class: geneselection.AttributeSelector$1, name: this$0, type: class geneselection.AttributeSelector)
    - object (class geneselection.AttributeSelector$1, geneselection.AttributeSelector$1@210308d5)
    - field (class: org.apache.spark.api.java.JavaRDDLike$$anonfun$foreachAsync$1, name: f$15, type: interface org.apache.spark.api.java.function.VoidFunction)
    - object (class org.apache.spark.api.java.JavaRDDLike$$anonfun$foreachAsync$1, <function1>)
    at org.apache.spark.serializer.SerializationDebugger$.improveException(SerializationDebugger.scala:40)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:46)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:100)
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:295)
    ... 22 more


问:
"Open git bash here" and "Open command prompt here" disappeared from Windows explorer context menu
Short of re-installing git or editing the relevant registry key that adds context menus to the shell myself, I was wondering if there was another way to bring back the "Git Bash Here" and "Open command window here" menus?

I am using Windows 7 Home Premium 64-bit.

答:
Checkout this SO question:

Context menu for right click on folders in left panel of Windows

Explorer or on background of a directory in right panel:

HKEY_CLASSES_ROOT\Directory\Background\shell if you are administrator

HKEY_CURRENT_USER\Software\Classes\directory\Background\shell  if you are a normal user

Context menu for right click on folders in right panel of Windows

Explorer:

HKEY_CLASSES_ROOT\Directory\shell if you are administrator

HKEY_CURRENT_USER\Software\Classes\directory\shell  if you are a normal user

Context menu for any file:

HKEY_CLASSES_ROOT\*\shell if you are administrator

HKEY_CURRENT_USER\Software\Classes\*\shell if you are a normal user

In all cases:

add a new key under "shell", naming it as you want to name the
  context menu item

add a new key inside this key, named command (mandatory name)

edit    the "default" property in "command" to
  myprogrampath\path\path\executable.exe %1 to pass the file path and
  name of the selected file to your custom program

Update:

So I did a little more research into where the actual git bash and git gui context menu items were stored in the registry. I exported the keys that I had in my registry into a .reg file:

```<code>Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell\git_shell\command]
@="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%1\""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell\git_gui\command]
@="\"C:\\Program Files\\Git\\cmd\\git-gui.exe\" \"--working-dir\" \"%1\""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\Background\shell\git_shell\command]
@="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%v.\""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\Background\shell\git_gui\command]
@="\"C:\\Program Files\\Git\\cmd\\git-gui.exe\" \"--working-dir\" \"%v.\""
</code>```

Body:
Checkout this SO question:

Context menu for right click on folders in left panel of Windows

Explorer or on background of a directory in right panel:

HKEY_CLASSES_ROOT\Directory\Background\shell if you are administrator

HKEY_CURRENT_USER\Software\Classes\directory\Background\shell  if you are a normal user

Context menu for right click on folders in right panel of Windows

Explorer:

HKEY_CLASSES_ROOT\Directory\shell if you are administrator

HKEY_CURRENT_USER\Software\Classes\directory\shell  if you are a normal user

Context menu for any file:

HKEY_CLASSES_ROOT\*\shell if you are administrator

HKEY_CURRENT_USER\Software\Classes\*\shell if you are a normal user

In all cases:

add a new key under "shell", naming it as you want to name the
  context menu item

add a new key inside this key, named command (mandatory name)

edit    the "default" property in "command" to
  myprogrampath\path\path\executable.exe %1 to pass the file path and
  name of the selected file to your custom program

Update:

So I did a little more research into where the actual git bash and git gui context menu items were stored in the registry. I exported the keys that I had in my registry into a .reg file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell\git_shell\command]
@="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%1\""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell\git_gui\command]
@="\"C:\\Program Files\\Git\\cmd\\git-gui.exe\" \"--working-dir\" \"%1\""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\Background\shell\git_shell\command]
@="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%v.\""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\Background\shell\git_gui\command]
@="\"C:\\Program Files\\Git\\cmd\\git-gui.exe\" \"--working-dir\" \"%v.\""


问:
Best practices if your Build is taking too long in Visual Studio
I have moderate size solution in Visual Studio which takes around 5 minutes to build (It take that long because of FxCop and other post build steps).
My problem is, Visual Studio stops responding while it's building. You can't continue working as VS almost hangs. I tried using two VS instances, just using one for build, but it keeps crashing every now and then.

My question is, How to not waste time looking at Visual Studio building your large/moderate project. Are there any best practices for this?

答: Source.

Body: Source.

OwnerDisplayName: tvanfosson


问:
win32 resource file help
on this website, under the "Edit Control" title, there are a couple of lines of code like this..

```<code>case WM_CREATE:
    hwndEdit = CreateWindow(TEXT("Edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
                50, 50, 150, 20, hwnd, (HMENU) ID_EDIT,
                NULL, NULL);

    hwndButton = CreateWindow(
        TEXT("button"), TEXT("Set Title"),
        WS_VISIBLE | WS_CHILD,
        50, 100, 80, 25,
        hwnd, (HMENU) ID_BUTTON, NULL, NULL);

    break;
</code>```

I know that this method of creating buttons and such are done on the fly, But I was wondering how you would do it without doing it like this, instead using a resource file?.
In the Forgers Win32 tutorial it shows how to make a menu using a resource file, and how to describe a dialog box etc, But I cant seem to put any controls on the main(parent) window using a resource file??.

for example I have the following .rc file

```<code>#include "resource.h"
ID_MENU MENU
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "E&xit", ID_FILE_EXIT
    END
    POPUP "&About"
    BEGIN
        MENUITEM "&Information", ID_ABOUT_INFO
    END
END

ID_ABOUT_INFO DIALOG DISCARDABLE  0,0,250,250
CAPTION "Information"
BEGIN
    CTEXT "some text",ID_BLA,15,15,144,33
END

//this is all fine but how do I decribe the main window?, instead of the menu and dialog boxes?.
</code>```

How do I describe the main window instead of creating things on the fly?. Is there some kind of keyword?

答:
At the API-level, consider functions like CreateDialog.

It's not more complicated than that.

Although a dialog as main window has some problems, especially in MFC (which treats it specially).

Cheers & hth.,

Title: win32 resource file help

Body:
on this website, under the "Edit Control" title, there are a couple of lines of code like this..

case WM_CREATE:
    hwndEdit = CreateWindow(TEXT("Edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
                50, 50, 150, 20, hwnd, (HMENU) ID_EDIT,
                NULL, NULL);

    hwndButton = CreateWindow(
        TEXT("button"), TEXT("Set Title"),
        WS_VISIBLE | WS_CHILD,
        50, 100, 80, 25,
        hwnd, (HMENU) ID_BUTTON, NULL, NULL);

    break;

I know that this method of creating buttons and such are done on the fly, But I was wondering how you would do it without doing it like this, instead using a resource file?.
In the Forgers Win32 tutorial it shows how to make a menu using a resource file, and how to describe a dialog box etc, But I cant seem to put any controls on the main(parent) window using a resource file??.

for example I have the following .rc file

#include "resource.h"
ID_MENU MENU
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "E&xit", ID_FILE_EXIT
    END
    POPUP "&About"
    BEGIN
        MENUITEM "&Information", ID_ABOUT_INFO
    END
END

ID_ABOUT_INFO DIALOG DISCARDABLE  0,0,250,250
CAPTION "Information"
BEGIN
    CTEXT "some text",ID_BLA,15,15,144,33
END

//this is all fine but how do I decribe the main window?, instead of the menu and dialog boxes?.

How do I describe the main window instead of creating things on the fly?. Is there some kind of keyword?


问:
make bootstrap column non-responsive and add horizontal scool bar to it
i have done responsive webdesign a-lot that i cant simply remember how to make a div non-resposnive.

here is what my design looks like

when i take it to mobile it resizes, i don't want it to resize i want it to have a long width with an horizontal scroll bar.

here is my code sample.

```<code><?php function acardio_big_grid_3() {
?>
<div class="row"><div class="clearfix eight-small-grid-contoler">
<div class="the-content-cat-bt" style="padding-bottom: 10px;">  <a class="tiptipBlog" title="Latest Post">Best Smartphone 2017</a> </div>

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array('post_type' => 'post', 'posts_per_page' => 8, 'paged' => $paged);
$query = new WP_Query($args);
if( $query->have_posts() ) :
while( $query->have_posts() ) : $query->the_post(); ?>
<?php $count++; ?>
<?php if ($count == 1) : ?>
<div class="all-eight-small-grid-thumbs">
<li class="the-big-list">
<div class="eight-small-grid-thumbs">
<div class="the-main-featured-image-responsive">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'the-featured-section-wordpress-thumbnail' ); } ?>
</div>

</div>
</li>

 <?php elseif ($count == 2) : ?>
 <li class="the-big-list">
 <div class="eight-small-grid-thumbs">
 <div class="the-main-featured-image-responsive">
 <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'the-featured-section-wordpress-thumbnail' ); } ?>
</div>

</div>
</li>

<?php elseif ($count == 3) : ?>
<li class="the-big-list">
<div class="eight-small-grid-thumbs">
<div class="the-main-featured-image-responsive">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'the-featured-section-wordpress-thumbnail' ); } ?>
</div>

</div>
</li>

<?php elseif ($count == 4) : ?>
<li class="the-big-list">
<div class="eight-small-grid-thumbs">
<div class="the-main-featured-image-responsive">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'the-featured-section-wordpress-thumbnail' ); } ?>
</div>

</div>
</li>

<?php elseif ($count == 5) : ?>
<li class="the-big-list">

<div class="eight-small-grid-thumbs">
<div class="the-main-featured-image-responsive">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'the-featured-section-wordpress-thumbnail' ); } ?>
</div>

</div>
</li>

<?php elseif ($count == 6) : ?>
<li class="the-big-list">

<div class="eight-small-grid-thumbs">
<div class="the-main-featured-image-responsive">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'the-featured-section-wordpress-thumbnail' ); } ?>
</div>

</div>
</li>
</div>
</div>
</div>

<?php else : ?>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
<?php
}
add_shortcode( 'acardio-big-grid-3', 'acardio_big_grid_3' );
?>
</code>```

please what do i do to make sure it doesn't break on mobile like this

instead to be long and have a scroll bar.
Like this

答:
To get the side scrolling, you can set overflow-y: auto so if the contents inside of the container are wider then the container, you'll get the side scrolling you're looking for.

#container {
  border: 1px solid red;
  width: 350px;
  overflow-y: auto;
}

#inner {
  width: 620px;
}

article {
  display: inline-block;
  background-color: #ccc;
  width: 200px;
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div id="inner">
    <article></article>
    <article></article>
    <article></article>
  </div>
</div></code>```

Body:
i have done responsive webdesign a-lot that i cant simply remember how to make a div non-resposnive.

here is what my design looks like

when i take it to mobile it resizes, i don't want it to resize i want it to have a long width with an horizontal scroll bar.

here is my code sample.

<?php function acardio_big_grid_3() {
?>

  Best Smartphone 2017

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array('post_type' => 'post', 'posts_per_page' => 8, 'paged' => $paged);
$query = new WP_Query($args);
if( $query->have_posts() ) :
while( $query->have_posts() ) : $query->the_post(); ?>
<?php $count++; ?>
<?php if ($count == 1) : ?>

<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'the-featured-section-wordpress-thumbnail' ); } ?>

 <?php elseif ($count == 2) : ?>

 <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'the-featured-section-wordpress-thumbnail' ); } ?>

<?php elseif ($count == 3) : ?>

<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'the-featured-section-wordpress-thumbnail' ); } ?>

<?php elseif ($count == 4) : ?>

<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'the-featured-section-wordpress-thumbnail' ); } ?>

<?php elseif ($count == 5) : ?>

<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'the-featured-section-wordpress-thumbnail' ); } ?>

<?php elseif ($count == 6) : ?>

<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'the-featured-section-wordpress-thumbnail' ); } ?>

<?php else : ?>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
<?php
}
add_shortcode( 'acardio-big-grid-3', 'acardio_big_grid_3' );
?>

please what do i do to make sure it doesn't break on mobile like this

instead to be long and have a scroll bar.
Like this

Body:
To get the side scrolling, you can set overflow-y: auto so if the contents inside of the container are wider then the container, you'll get the side scrolling you're looking for.

#container {
  border: 1px solid red;
  width: 350px;
  overflow-y: auto;
}

#inner {
  width: 620px;
}

article {
  display: inline-block;
  background-color: #ccc;
  width: 200px;
  height: 200px;
}

<div id="container">
  <div id="inner">
    <article></article>
    <article></article>
    <article></article>
  </div>
</div>


问:
C# Sql Command for Insering into a database
I am new to Visual C# programming language and recently i was trying to make a application that is supposed to insert into a local database of users some data but every times my code runs and the insertion works fine the database does not update.This is the code that i am using

```<code>try
{
    cn.Open();
    SqlCommand insert = new SqlCommand();
    insert.CommandText = "insert into Clienti (Nume,Prenume,Parola,Email) values(@Nume,@Prenume,@Parola,@Email)";
    insert.Connection = cn;
    insert.Parameters.AddWithValue("@Nume", register_nume.Text);
    insert.Parameters.AddWithValue("@Prenume", register_prenume.Text);
    insert.Parameters.AddWithValue("@Parola", register_password.Text);
    insert.Parameters.AddWithValue("@Email", register_email.Text);
    insert.ExecuteNonQuery();
    SqlDataReader reader = insert.ExecuteReader();
    while (reader.Read()) { }

    MessageBox.Show("Added succesfully");
}
catch (Exception ex)
{
    MessageBox.Show(""+ex);
}
</code>```

I already tried the property Copy to output and it doesn't seems to work.
I am sorry for any grammar mistakes that i made,I would be grateful for any help.

答:
```<code>       insert.ExecuteNonQuery();
        SqlDataReader reader = insert.ExecuteReader();
        while (reader.Read()) { }
</code>```

You only need the ExecuteNonQuery, it will run the INSERT. You need to use ExecuteReader instead only when you're running a statement that produces result sets (eg. SELECT). So it should be:

```<code> insert.ExecuteNonQuery();
</code>```

Body:
I am new to Visual C# programming language and recently i was trying to make a application that is supposed to insert into a local database of users some data but every times my code runs and the insertion works fine the database does not update.This is the code that i am using

try
{
    cn.Open();
    SqlCommand insert = new SqlCommand();
    insert.CommandText = "insert into Clienti (Nume,Prenume,Parola,Email) values(@Nume,@Prenume,@Parola,@Email)";
    insert.Connection = cn;
    insert.Parameters.AddWithValue("@Nume", register_nume.Text);
    insert.Parameters.AddWithValue("@Prenume", register_prenume.Text);
    insert.Parameters.AddWithValue("@Parola", register_password.Text);
    insert.Parameters.AddWithValue("@Email", register_email.Text);
    insert.ExecuteNonQuery();
    SqlDataReader reader = insert.ExecuteReader();
    while (reader.Read()) { }

    MessageBox.Show("Added succesfully");
}
catch (Exception ex)
{
    MessageBox.Show(""+ex);
}

I already tried the property Copy to output and it doesn't seems to work.
I am sorry for any grammar mistakes that i made,I would be grateful for any help.

Body:
       insert.ExecuteNonQuery();
        SqlDataReader reader = insert.ExecuteReader();
        while (reader.Read()) { }

You only need the ExecuteNonQuery, it will run the INSERT. You need to use ExecuteReader instead only when you're running a statement that produces result sets (eg. SELECT). So it should be:

 insert.ExecuteNonQuery();


问:
Lua string length (cyrillic in utf8)
How to get the REAL length of the string with cyrillic symbols in lua?

If i'm using string.len("HELLO.") - I will get 6

But with string.len("ПРИВЕТ") - I will get 12(Same with "#" operator)

So the number of symbols didn't changed, but we got different numbers...
It's because cyrillic symbols has two bytes, when english letters, numbers and etc has 1.
I want to know how to get the right and real length of string(Get 6 in both samples).
Everyone who can help?

答:
string.len and # count bytes, not chars.

In Lua 5.3+, use utf8.len.

Title: Lua string length (cyrillic in utf8)


问:
Calculating Cumulative values using MySQL
I have this table:

```<code>Month_Year              MV                    MI
----------------------------------------------------------
August 2016              3                    100
October 2016             2                    150
September 2016           1                    100
January 2017             4                    200
</code>```

I need to create the next output table

```<code>Month_Year               MV       AMV          MI     AMI
----------------------------------------------------------
January 2016             0        0            0      0
...
July 2016                0        0            0      0
August 2016              3        3           100    100
September 2016           1        4           100    200
October 2016             2        6           150    350
November 2016            0        6           0      350
December 2016            0        6           0      350
January 2017             4        10          200    550
</code>```

At month M, for column AMV, AMV is the ccumulative value of all the AV ones before that month and month M. For example, AMV is 4 on 'September 2016' because in 'August 16' AV is 3 and 1 for 'September 2016'. Similarly for AMI. How can this be done?. Notice that the Month_Year column is not necessarily ordered. Thanks

ADDITIONAL INFO
After using the DATE_FORMAT(original_Date, '%Y %m') I was able to convert the first table to:

```<code>Month_Year              MV                    MI
----------------------------------------------------------
2016 08                  3                    100
2016 10                  2                    150
2016 09                  1                    100
2017 01                  4                    200
</code>```

Could this simplify the problem? Why not to use DATE_FORMAT(original_Date, '%m %Y')?

答:
The month-year format is a big big NO, and you have to somehow overcome it. For this example I create a MEMORY table months, and I use several joins with this table.

```<code>create table months (month_year_int int, month_year varchar(30)) engine=memory;
insert months
select 201601 as month_year_int, 'January 2016' as month_year
      union all select 201602, 'February 2016'
      union all select 201603, 'March 2016'
      union all select 201604, 'April 2016'
      union all select 201605, 'May 2016'
      union all select 201606, 'June 2016'
      union all select 201607, 'July 2016'
      union all select 201608, 'August 2016'
      union all select 201609, 'September 2016'
      union all select 201610, 'October 2016'
      union all select 201611, 'November 2016'
      union all select 201612, 'December 2016'
      union all select 201701, 'January 2017'
;
</code>```

All these would have been avoided if you had used a proper model for your data. Anyway, this is a solution whis does not use the My-Sql proprietary variable pattern (a rextester demo here):

```<code>select
    x.month_year,
    coalesce(t.mv, 0) MV,
    sum(y.mv) as AMV,
    coalesce(t.mi, 0) AMV,
    sum(y.mi) as AMI from
(
    select
        m.month_year_int,
        m.month_year,
        coalesce(t.mv, 0) as mv,
        coalesce(t.mi) as mi
    from months m left join test t on m.month_year = t.month_year
) x
left join
(
    select
        m.month_year_int,
        m.month_year,
        coalesce(t.mv, 0) as mv,
        coalesce(t.mi) as mi
    from months m
        left join test t on m.month_year = t.month_year
) y on x.month_year_int > y.month_year_int - 1
left join test t on x.month_year = t.month_year
group by x.month_year_int
order by x.month_year_int
;
</code>```

Body:
I have this table:

Month_Year              MV                    MI
----------------------------------------------------------
August 2016              3                    100
October 2016             2                    150
September 2016           1                    100
January 2017             4                    200

I need to create the next output table

Month_Year               MV       AMV          MI     AMI
----------------------------------------------------------
January 2016             0        0            0      0
...
July 2016                0        0            0      0
August 2016              3        3           100    100
September 2016           1        4           100    200
October 2016             2        6           150    350
November 2016            0        6           0      350
December 2016            0        6           0      350
January 2017             4        10          200    550

At month M, for column AMV, AMV is the ccumulative value of all the AV ones before that month and month M. For example, AMV is 4 on 'September 2016' because in 'August 16' AV is 3 and 1 for 'September 2016'. Similarly for AMI. How can this be done?. Notice that the Month_Year column is not necessarily ordered. Thanks

ADDITIONAL INFO
After using the DATE_FORMAT(original_Date, '%Y %m') I was able to convert the first table to:

Month_Year              MV                    MI
----------------------------------------------------------
2016 08                  3                    100
2016 10                  2                    150
2016 09                  1                    100
2017 01                  4                    200

Could this simplify the problem? Why not to use DATE_FORMAT(original_Date, '%m %Y')?

Body:
The month-year format is a big big NO, and you have to somehow overcome it. For this example I create a MEMORY table months, and I use several joins with this table.

create table months (month_year_int int, month_year varchar(30)) engine=memory;
insert months
select 201601 as month_year_int, 'January 2016' as month_year
      union all select 201602, 'February 2016'
      union all select 201603, 'March 2016'
      union all select 201604, 'April 2016'
      union all select 201605, 'May 2016'
      union all select 201606, 'June 2016'
      union all select 201607, 'July 2016'
      union all select 201608, 'August 2016'
      union all select 201609, 'September 2016'
      union all select 201610, 'October 2016'
      union all select 201611, 'November 2016'
      union all select 201612, 'December 2016'
      union all select 201701, 'January 2017'
;

All these would have been avoided if you had used a proper model for your data. Anyway, this is a solution whis does not use the My-Sql proprietary variable pattern (a rextester demo here):

select
    x.month_year,
    coalesce(t.mv, 0) MV,
    sum(y.mv) as AMV,
    coalesce(t.mi, 0) AMV,
    sum(y.mi) as AMI from
(
    select
        m.month_year_int,
        m.month_year,
        coalesce(t.mv, 0) as mv,
        coalesce(t.mi) as mi
    from months m left join test t on m.month_year = t.month_year
) x
left join
(
    select
        m.month_year_int,
        m.month_year,
        coalesce(t.mv, 0) as mv,
        coalesce(t.mi) as mi
    from months m
        left join test t on m.month_year = t.month_year
) y on x.month_year_int > y.month_year_int - 1
left join test t on x.month_year = t.month_year
group by x.month_year_int
order by x.month_year_int
;


问:
Additional values in 2d array
I created the following code in Java (1.8.0.121) for parsing of iMatrix array into matrixOutput one.
Once I run it I noticed that appears additional values in cells 1,0 and 1,1.

Could someone advice me how should I change to avoid such additions for other arrays (I plan a generic code which will take different arrays in format like iMatrix array)

    public class Dbg {

```<code>private static int[][] matrixOutput = { { 0, 2, 0, 0, 0 },
                                        { 0, 0, 0, 4, 0 },
                                        { 1, 2, 0, 0, 5 },
                                        { 0, 0, 0, 0, 0 },
                                        { 0, 0, 0, 0, 0 } };
private static int[][] iMatrix = {
        {1, -1, 0, 0, 0},
        {0, 1, 0, -1, 0},
        {-1, 0, 1, 0, 0},
        {0, -1, 1, 0, 0},
        {0, 0, 1, 0, -1},
        {0, 0, 0, 2, 0}};
private static int i = 0;
private static int j = 0;
private static int val = 0;

public static void main(String[] args) {

    int[][] list = new int[5][5];

    for (int m = 0; m < iMatrix.length; m++) {
        for (int n = 0; n < iMatrix[m].length; n++) {
            if (iMatrix[m][n] == 1){
                i = n;
            }
            if (iMatrix[m][n] == -1){
                j = n;
                val = n + 1;

            }
            list[i][j] = val;
        }
    }

    for (i = 0; i < list.length; i++) {
        for (j = 0; j < list.length; j++) {
            System.out.print(list[i][j]);
        }
        System.out.println();
    }

}
}
</code>```

Insead of MatrixOutput it gives me the following result:

```<code>02000
12040
12005
00000
00000
</code>```

When I changed places for 3 and 4 rows viceverso I saw that value 1 from 1,0 disappears. All values from iMatrix are stored correctly.

Title: Additional values in 2d array

Body:
I created the following code in Java (1.8.0.121) for parsing of iMatrix array into matrixOutput one.
Once I run it I noticed that appears additional values in cells 1,0 and 1,1.

Could someone advice me how should I change to avoid such additions for other arrays (I plan a generic code which will take different arrays in format like iMatrix array)

    public class Dbg {

private static int[][] matrixOutput = { { 0, 2, 0, 0, 0 },
                                        { 0, 0, 0, 4, 0 },
                                        { 1, 2, 0, 0, 5 },
                                        { 0, 0, 0, 0, 0 },
                                        { 0, 0, 0, 0, 0 } };
private static int[][] iMatrix = {
        {1, -1, 0, 0, 0},
        {0, 1, 0, -1, 0},
        {-1, 0, 1, 0, 0},
        {0, -1, 1, 0, 0},
        {0, 0, 1, 0, -1},
        {0, 0, 0, 2, 0}};
private static int i = 0;
private static int j = 0;
private static int val = 0;

public static void main(String[] args) {

    int[][] list = new int[5][5];

    for (int m = 0; m < iMatrix.length; m++) {
        for (int n = 0; n < iMatrix[m].length; n++) {
            if (iMatrix[m][n] == 1){
                i = n;
            }
            if (iMatrix[m][n] == -1){
                j = n;
                val = n + 1;

            }
            list[i][j] = val;
        }
    }

    for (i = 0; i < list.length; i++) {
        for (j = 0; j < list.length; j++) {
            System.out.print(list[i][j]);
        }
        System.out.println();
    }

}
}

Insead of MatrixOutput it gives me the following result:

02000
12040
12005
00000
00000

When I changed places for 3 and 4 rows viceverso I saw that value 1 from 1,0 disappears. All values from iMatrix are stored correctly.

Body:
private static int[][] matrixOutput = {
        { 0, 2, 0, 0, 0 },
        { 0, 0, 0, 4, 0 },
        { 1, 2, 0, 0, 5 },
        { 0, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0 } };
private static int[][] iMatrix = {
    { 1, -1, 0, 0, 0 },
    { 0, 1, 0, -1, 0 },
    { -1, 0, 1, 0, 0 },
    { 0, -1, 1, 0, 0 },
    { 0, 0, 1, 0, -1 },
    { 0, 0, 0, 2, 0 } };

public static void main(String[] args) {

    int[][] list = new int[5][5];

    for (int m = 0; m < iMatrix.length; m++) {
        int i = 0;
        int j = 0;
        int val = 0;
        for (int n = 0; n < iMatrix[m].length; n++) {

            if (iMatrix[m][n] == 1) {
                i = n;
            }
            if (iMatrix[m][n] == -1) {
                j = n;
                val = n+1;

            }
            list[i][j] = val;
        }
    }

    for (int i = 0; i < list.length; i++) {
        for (int j = 0; j < list.length; j++) {
            System.out.print(list[i][j]);
        }
        System.out.println();
    }

}