问:
How to restart one live node from a multi node cassandra cluster?
I have a production cassandra cluster of 6 nodes. I have made some changes to the cassandra.yaml file on one node and hence need to restart it.
How can I do it without losing any data or causing any cluster related issues?
Can I just kill the cassandra process on that particular node and start it again.
Cluster Info:
6 nodes. All active.
I am using AWS Ec2Snitch.

Thanks.

答:
Can I just kill the cassandra process on that particular node and start it again.

Essentially, yes.  I'm assuming you have a RF of 3 with 6 nodes, so it shouldn't be a big deal.  If you want, to do what I call a "clean shutdown" you could run the following commands first:

```<code>nodetool disablegossip
nodetool drain
</code>```

And then (depending on your install):

```<code>sudo service cassandra stop
</code>```

Or:

```<code>kill `cat cassandra.pid`
</code>```

Note that if you do not complete these steps, you should still be ok.  The drain just flushes the memtables to disk.  If that doesn't happen, the commit log is reconciled against what's on disk at boot-time anyway.  Those steps will just make your boot go faster.

Body:
Can I just kill the cassandra process on that particular node and start it again.

Essentially, yes.  I'm assuming you have a RF of 3 with 6 nodes, so it shouldn't be a big deal.  If you want, to do what I call a "clean shutdown" you could run the following commands first:

nodetool disablegossip
nodetool drain

And then (depending on your install):

sudo service cassandra stop

Or:

kill `cat cassandra.pid`

Note that if you do not complete these steps, you should still be ok.  The drain just flushes the memtables to disk.  If that doesn't happen, the commit log is reconciled against what's on disk at boot-time anyway.  Those steps will just make your boot go faster.


来源: stackexchange

问:
Use Perl module only when it is needed within a subroutine
Imagine my script has these two subs

```<code>sub with_json_mod{
    use JSON::Tiny;
    blah blah blah;
}

sub without_json_mod{
   blah blah blah;
}
</code>```

I only want to use without_json_mod when JSON::Tiny is not installed.

How can I make Perl not fail if JSON::Tiny is not installed and, instead, use the without_json_mod sub instead?

I tried to call require in the with_json_mod and it seems to work, but it doesn't work when I try to make it import the encode_json sub as in

```<code>sub with_json_mod{
    require JSON::Tiny qw/encode_json/;
    blah blah blah;
}
</code>```

答:
That's because you're calling require incorrectly.

What you need is:

```<code>require JSON::Tiny;
JSON::Tiny -> import ( 'encode_json' );
</code>```

You can wrap that in an 'eval' too, and test the value of $@:

```<code>eval { require JSON::Tiny; };
warn $@ if $@;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Imagine my script has these two subs

sub with_json_mod{
    use JSON::Tiny;
    blah blah blah;
}

sub without_json_mod{
   blah blah blah;
}

I only want to use without_json_mod when JSON::Tiny is not installed.

How can I make Perl not fail if JSON::Tiny is not installed and, instead, use the without_json_mod sub instead?

I tried to call require in the with_json_mod and it seems to work, but it doesn't work when I try to make it import the encode_json sub as in

sub with_json_mod{
    require JSON::Tiny qw/encode_json/;
    blah blah blah;
}

Body:
That's because you're calling require incorrectly.

What you need is:

require JSON::Tiny;
JSON::Tiny -> import ( 'encode_json' );

You can wrap that in an 'eval' too, and test the value of $@:

eval { require JSON::Tiny; };
warn $@ if $@;

ContentLicense: CC BY-SA 3.0


问:
SSIS, dtsx and deployment packages
I'm just trying to understand SSIS packages a bit better and how they are deployed. Correct me I'm wrong but for any deployment, I believe there needs to be at least two files a .SSISDeploymentManifest and a .dtsx. The .SSISDeploymentManifest  acts as the equivalent windows installer package which points to the .dtsx. The dtsx is the actual package of "stuff" that is referenced as an external file some how when you run the installer. When you install it, the package gets added to a list of ssis packages for that instance.

My further questions:

If i wanted to keep previous version of the same package, can I just copy the bin directories with the two above files and keep separately should I need to roll back to a previous package?

Where are these packages installed to? How does SSIS know where the packagess are?

答:
Correct me I'm wrong but for any deployment, I believe there needs to
  be at least two files a .SSISDeploymentManifest and a .dtsx. The
  .SSISDeploymentManifest acts as the equivalent windows installer
  package which points to the .dtsx. The dtsx is the actual package of
  "stuff" that is referenced as an external file some how when you run
  the installer. When you install it, the package gets added to a list
  of ssis packages for that instance.

Your assumptions are mostly correct. You don't need the deployment manifest, but it can be handy. Also, you don't need to deploy to the SQL Server instance. You have the option to deploy to the file system as well. I'll explain both below.

Regarding your 1st question:

Version Control:

Make sure you're developing and checking in your dtsx packages via visual studio.  Label your releases in sourcesafe or whatever version control you're using. If you are checking in and labeling, then you should be able to easily roll back to a previous version. As you mention, you also can just save a copy of your old bin directory but naturally put them in dated subfolders or something. However, this does not take the place of proper version control.

Regarding your 2nd question:

Deployment:

As the other poster states, you first have a decision to make:

a) Deploy packages to the file system
b) Deploy packages to MSDB

There are benefits to each, and everyone has their preference. I have used both, but I prefer the filesystem because it's more transparent, however there is more to maintain.

See this post for much more on this:  http://blogs.conchango.com/jamiethomson/archive/2006/01/05/SSIS_3A00_-Common-folder-structure.aspx

The code is in the dtsx package.  Generally,in order to make your packages portable you also abstract your connection strings and  other configurable information into a config file (.dtsconfig) or environment variable (no file needed). See BOL to learn more about configuration.

The manifest file contains metadata about which dtsx and config files to install.  If you open one, you'll see it's a simple readable xml file.

The manifest file makes it easy to hand over to a DBA to deploy (ask them to double-click the manifest file and follow directions, but they'll need instructions.

To me, the manifest file is more useful for deploying to SQL Server than to the file system. Really, all it does is make a copy of the dtsx and config files and puts them where you tell it. You could just as easily instruct the DBA to copy your dtsx files to a common folder on the server, and the config files to another folder on the same server.

Then when you schedule your jobs using SQL Agent, you specify that you're going to run an SSIS package that is stored on the file system and browse to where it's located. If you're using configurations, then there's a tab to specify where the config file is located.

There is so much to know about configuring/deployment/versioning of SSIS packages. But hopefully this will get you started on the right path.

ContentLicense: CC BY-SA 2.5

Title: SSIS, dtsx and deployment packages


问:
Add header(copyright) information to existing source files
I want to add our company's copyright information to all of our EXISTING source code files.

The project is developed in Eclipse. so, for new files I can modify the settings as suggested here. But for existing files, how am I supposed to do this. How can I modify hundreds of java files to add the copyright information. (And I'm unable to open the releng plugin mentioned in the above link.

Any windows based text maniputaion scripting language will also help.

答:
I think you can use Eclipse replace command using Regular Expression.

Imagine that your copyright is something like:

```<code>/* jQuery UI CSS Framework
*  Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
*  Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
*/
</code>```

then

```<code>1. Go to menu: Search -> File

2. in the Search dialog
2.1. check the "Regular Expression"
2.2. in the Containing text:
    \A[^(\Q/*\E\s+jQuery.*)]
2.3 click the Replace
    past your copyright
</code>```

Explanation of regex:

\A - Start of the file

\Q...\E - Here goes the regex keywords ( because / and * are keys in regex )

\s+ - whitespaces

[^(..)] - means except

Body:
I think you can use Eclipse replace command using Regular Expression.

Imagine that your copyright is something like:

/* jQuery UI CSS Framework
*  Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
*  Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
*/

then

1. Go to menu: Search -> File

2. in the Search dialog
2.1. check the "Regular Expression"
2.2. in the Containing text:
    \A[^(\Q/*\E\s+jQuery.*)]
2.3 click the Replace
    past your copyright

Explanation of regex:

\A - Start of the file

\Q...\E - Here goes the regex keywords ( because / and * are keys in regex )

\s+ - whitespaces

[^(..)] - means except


问:
Jekyll front matter output count
I'm working on jekyll theme design and I have .yml file stored the data (File name : games.yml) and has data as follows

```<code>---
- name: NFS
  year: 2015
  id: NFS15
  link: http://www.ecample.com/
  date: August 3-4, 2017
  categories: Racing

etc
</code>```

I'm trying to output the categories in sidebar with number of count in each category. e.g:

```<code>Racing (3)
Shooter (6)
Sports (5)
etc
</code>```

How can I achieve this?

My HTML output code:

```<code>      <a href="javascript:;" class="categories-list-item" cate="All">
        All<span class="my-badge"> {{site.data.games | size}}</span>
      </a>
      {% for cat in site.data.games %}
        <a href="javascript:;" class="categories-list-item" cate="{{ cat.categories}}">
          {{ cat.categories }} <span class="my-badge">{{ cat.categories | size }}</span>
        </a>
      {% endfor %}
</code>```

Now I get the result with entire category list e.g:

```<code>Racing
Racing
Racing
Shooter
Shooter
Shooter...
</code>```

and so on each count

答:
Create an array with the categories of each, then make a for loop with all items just to count how many times the current item category appears in each item, save that info into a counter and display it at the end:

```<code>{% assign cats = ''|split:"" %}
{% for game in site.data.games %}
{% unless cats contains game.categories %}
{% assign cats = cats | push: game.categories %}
{% endunless %}
{% endfor %}

{% for cat in cats %}
{% assign counter = 0 %}
{% for item in site.data.games %}
{% if cat == item.categories %}
{% assign counter = counter | plus: 1%}
{%endif%}
{% endfor %}

<a href="javascript:;" class="categories-list-item" cate="{{ cat }}">
    {{ cat }} <span class="my-badge">{{ counter }}</span>
</a>
{% endfor %}
</code>```

Or group them by game categories with group_by:

```<code>{% assign games = site.data.games | group_by:"categories" %}
{% for game in games %}
<a href="javascript:;" class="categories-list-item" cate="{{ cat.categories}}">
    {{ game.name }} <span class="my-badge">{{ game.size }}</span>
</a>
{% endfor %}
</code>```

First version will work in previous versions of Jekyll that do not have group_by.

Title: Jekyll front matter output count

Body:
I'm working on jekyll theme design and I have .yml file stored the data (File name : games.yml) and has data as follows

---
- name: NFS
  year: 2015
  id: NFS15
  link: http://www.ecample.com/
  date: August 3-4, 2017
  categories: Racing

etc

I'm trying to output the categories in sidebar with number of count in each category. e.g:

Racing (3)
Shooter (6)
Sports (5)
etc

How can I achieve this?

My HTML output code:

        All {{site.data.games | size}}

      {% for cat in site.data.games %}

          {{ cat.categories }} {{ cat.categories | size }}

      {% endfor %}

Now I get the result with entire category list e.g:

Racing
Racing
Racing
Shooter
Shooter
Shooter...

and so on each count

Body:
Create an array with the categories of each, then make a for loop with all items just to count how many times the current item category appears in each item, save that info into a counter and display it at the end:

{% assign cats = ''|split:"" %}
{% for game in site.data.games %}
{% unless cats contains game.categories %}
{% assign cats = cats | push: game.categories %}
{% endunless %}
{% endfor %}

{% for cat in cats %}
{% assign counter = 0 %}
{% for item in site.data.games %}
{% if cat == item.categories %}
{% assign counter = counter | plus: 1%}
{%endif%}
{% endfor %}

<a href="javascript:;" class="categories-list-item" cate="{{ cat }}">
    {{ cat }} <span class="my-badge">{{ counter }}</span>
</a>
{% endfor %}

Or group them by game categories with group_by:

{% assign games = site.data.games | group_by:"categories" %}
{% for game in games %}
<a href="javascript:;" class="categories-list-item" cate="{{ cat.categories}}">
    {{ game.name }} <span class="my-badge">{{ game.size }}</span>
</a>
{% endfor %}

First version will work in previous versions of Jekyll that do not have group_by.


问:
switch tabs from viewpager
I have implemented tab layout design and i want to switch to a different tab whenever someone clicks on an image in a viewpager. My research has concluded that a click event is registered on the viewpager adapter however i cannot find a way to grab the id of the tab layout from the adapter.Below is my view pager adapter code:

```<code>    public class BooksPagerAdapter extends PagerAdapter {
    private Context mContext;
    ViewPager viewPager;
    private ViewPager pager = null;
    ImageView image1;
    private int images[] = {R.drawable.lagers11, R.drawable.stout11, R.drawable.malts11, R.drawable.lagers11, R.drawable.stout11, R.drawable.malts11};
    public BooksPagerAdapter(Context context) {
        mContext = context;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        RelativeLayout relativeLayout = (RelativeLayout) ViewGroup.inflate(mContext, R.layout.tab_layout, null);
        View itemView = inflater.inflate(R.layout.shop_books, container, false);

        ImageView image1 = (ImageView) itemView.findViewById(R.id.image);
        image1.setImageResource(images[position]);
        itemView.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                //this will log the page number that was click
                Toast.makeText(mContext, position + " pagess", Toast.LENGTH_SHORT).show();

            }
        });
        ((ViewPager) container).addView(itemView);
        return itemView;

    }

    @Override
    public void destroyItem(ViewGroup container, int position,
                            Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return (6);
    }

    @Override
    public float getPageWidth(int position) {
        return (0.3f);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view == object);
    }}
</code>```

show_books layout

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:padding="2dp"
android:layout_height="100dp" />
</FrameLayout>
</code>```

tab layout

```<code><RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shattered"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/qb"
android:elevation="6dp"
app:tabGravity="fill"
app:tabIndicatorColor="#ffffff"
app:tabIndicatorHeight="3dp"
app:tabMode="scrollable"
app:tabSelectedTextColor="@color/tabSelectedTextColor"
app:tabTextColor="@color/tabTextColor">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpagertabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/tabs">
</android.support.v4.view.ViewPager>
</RelativeLayout>
</code>```

答:
You can use EventBus to comminicate between subviews of your Activity or Fragment. First define an Event:

```<code>public class ImageSelectedEvent {

    int index;

    public MessageEvent(int index) {
        this.index = index;
    }
}
</code>```

than register for this event like:

```<code>@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(ImageSelectedEvent event) {
    //TODO: make tab selected for event.index
}
</code>```

than add register/unregister codes for bus:

```<code>@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}
</code>```

Finally use someting like this when an image clicked:

```<code>itemView.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v){
        int index = //get image index
        EventBus.getDefault().post(new ImageSelectedEvent(index));
    }
});
</code>```

You can find more from here:

How to get started with EventBus in 3 steps

Title: switch tabs from viewpager

Body:
I have implemented tab layout design and i want to switch to a different tab whenever someone clicks on an image in a viewpager. My research has concluded that a click event is registered on the viewpager adapter however i cannot find a way to grab the id of the tab layout from the adapter.Below is my view pager adapter code:

    public class BooksPagerAdapter extends PagerAdapter {
    private Context mContext;
    ViewPager viewPager;
    private ViewPager pager = null;
    ImageView image1;
    private int images[] = {R.drawable.lagers11, R.drawable.stout11, R.drawable.malts11, R.drawable.lagers11, R.drawable.stout11, R.drawable.malts11};
    public BooksPagerAdapter(Context context) {
        mContext = context;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        RelativeLayout relativeLayout = (RelativeLayout) ViewGroup.inflate(mContext, R.layout.tab_layout, null);
        View itemView = inflater.inflate(R.layout.shop_books, container, false);

        ImageView image1 = (ImageView) itemView.findViewById(R.id.image);
        image1.setImageResource(images[position]);
        itemView.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                //this will log the page number that was click
                Toast.makeText(mContext, position + " pagess", Toast.LENGTH_SHORT).show();

            }
        });
        ((ViewPager) container).addView(itemView);
        return itemView;

    }

    @Override
    public void destroyItem(ViewGroup container, int position,
                            Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return (6);
    }

    @Override
    public float getPageWidth(int position) {
        return (0.3f);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view == object);
    }}

show_books layout

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:padding="2dp"
android:layout_height="100dp" />
</FrameLayout>

tab layout

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shattered"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/qb"
android:elevation="6dp"
app:tabGravity="fill"
app:tabIndicatorColor="#ffffff"
app:tabIndicatorHeight="3dp"
app:tabMode="scrollable"
app:tabSelectedTextColor="@color/tabSelectedTextColor"
app:tabTextColor="@color/tabTextColor">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpagertabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/tabs">
</android.support.v4.view.ViewPager>
</RelativeLayout>

Body:
You can use EventBus to comminicate between subviews of your Activity or Fragment. First define an Event:

public class ImageSelectedEvent {

    int index;

    public MessageEvent(int index) {
        this.index = index;
    }
}

than register for this event like:

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(ImageSelectedEvent event) {
    //TODO: make tab selected for event.index
}

than add register/unregister codes for bus:

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}

Finally use someting like this when an image clicked:

itemView.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v){
        int index = //get image index
        EventBus.getDefault().post(new ImageSelectedEvent(index));
    }
});

You can find more from here:

How to get started with EventBus in 3 steps


问:
Golang hierarchical routing
I want to make RESTful API which has multi layer route like :

```<code>/api/auhtorization/getUserdata
</code>```

where api stands for webservice name,
auhtorization stands for a function to check validation of token.
and getUserdata stands for a function that get specific user data ( if only request past authorization level )

```<code>func main(){
   http.HandleFunc("api/", func(rw, req){
      http.HandleFunc("authorization/", func(){

         if (auth passed)
         {
            http.HandleFunc("getUserdata", getUserFunction())
         }

      })

   })
}
</code>```

I know above code isn't a good example but I seek for best practice or framework for doing this.
Any answer will be highly appreciated!

答:
Your first (outmost) call to http.HandleFunc is correct - it maps a route to a handler function. The rest of the code implies a misunderstanding of how that works, though. The handler function will be called when a request matching that route comes in; when a handling a request is not the time to register additional routes, because route registration is not request-specific, and it's too late to modify the routing table for the current request. The last call makes even less sense: you can't register a route based on whether the current request is authorized. As soon as one authorized request comes in, that route will be registered for all future requests, regardless of whether those requests are authorized, and will not make any different for the current request.

What you want, most likely, is to replace both of the nested calls to http.HandleFunc with calls to handler methods, e.g.:

```<code>func main(){
    http.HandleFunc("/api/", func(rw, req){
        if strings.HasPrefix(req.URL.Path, "/api/authorization") {
            doAuthorization(rw,req)
        }
    }
}

func doAuthorization(rw http.ResponseWriter, req *http.Request) {
    if authPassed && strings.HasPrefix(req.URL.Path, "/api/authorization/getUserdata") {
        getUserFunction(rw,req)
    }
}
</code>```

Or, alternatively, use the router for all of it:

```<code>func main() {
    http.HandleFunc("/api", doApi)
    http.HandleFunc("/api/authorization", doAuthorization)
    http.HandleFunc("/api/authorization/getUserdata", getUserFunction)
}

func doApi(rw, req) {
    // Whatever you'd do for a call to "/api" itself
}

func doAuthorization(rw http.ResponseWriter, req *http.Request) {
    // Whatever you'd do for a call to "/api/authorization" itself
}
</code>```

Title: Golang hierarchical routing

Body:
I want to make RESTful API which has multi layer route like :

/api/auhtorization/getUserdata

where api stands for webservice name,
auhtorization stands for a function to check validation of token.
and getUserdata stands for a function that get specific user data ( if only request past authorization level )

func main(){
   http.HandleFunc("api/", func(rw, req){
      http.HandleFunc("authorization/", func(){

         if (auth passed)
         {
            http.HandleFunc("getUserdata", getUserFunction())
         }

      })

   })
}

I know above code isn't a good example but I seek for best practice or framework for doing this.
Any answer will be highly appreciated!

Body:
Your first (outmost) call to http.HandleFunc is correct - it maps a route to a handler function. The rest of the code implies a misunderstanding of how that works, though. The handler function will be called when a request matching that route comes in; when a handling a request is not the time to register additional routes, because route registration is not request-specific, and it's too late to modify the routing table for the current request. The last call makes even less sense: you can't register a route based on whether the current request is authorized. As soon as one authorized request comes in, that route will be registered for all future requests, regardless of whether those requests are authorized, and will not make any different for the current request.

What you want, most likely, is to replace both of the nested calls to http.HandleFunc with calls to handler methods, e.g.:

func main(){
    http.HandleFunc("/api/", func(rw, req){
        if strings.HasPrefix(req.URL.Path, "/api/authorization") {
            doAuthorization(rw,req)
        }
    }
}

func doAuthorization(rw http.ResponseWriter, req *http.Request) {
    if authPassed && strings.HasPrefix(req.URL.Path, "/api/authorization/getUserdata") {
        getUserFunction(rw,req)
    }
}

Or, alternatively, use the router for all of it:

func main() {
    http.HandleFunc("/api", doApi)
    http.HandleFunc("/api/authorization", doAuthorization)
    http.HandleFunc("/api/authorization/getUserdata", getUserFunction)
}

func doApi(rw, req) {
    // Whatever you'd do for a call to "/api" itself
}

func doAuthorization(rw http.ResponseWriter, req *http.Request) {
    // Whatever you'd do for a call to "/api/authorization" itself
}


问:
Angular2 cli hangs while creating a new app
I am trying to create a new Angular2 app using

```<code>ng new myAppName
</code>```

This hangs on the line

```<code>/ Installing packages for tooling via npm
</code>```

Its been sitting there for about an hour.

The previous time this happend I killed the process and tried re-running

```<code>ng new xxx
</code>```

That failed because angular cli had some reference to the app name somewhere and  thats whay I had to choose a new app name.

How do I get around this?

答: I had the same problem. Just waited a bit longer and finally it create the project. So, be patient!</p>

Body:
I am trying to create a new Angular2 app using

ng new myAppName

This hangs on the line

/ Installing packages for tooling via npm

Its been sitting there for about an hour.

The previous time this happend I killed the process and tried re-running

ng new xxx

That failed because angular cli had some reference to the app name somewhere and  thats whay I had to choose a new app name.

How do I get around this?


问:
How to set that all Lable foreground is White in Window?
Follow method is invalid,I dont want to set color by ergodic. How to set by style:</p>

```<code>Style styleLable = new System.Windows.Style(typeof(Label));
styleLable.Setters.Add(new Setter(Label.ForegroundProperty, "White"));
this.Resources.Add("", styleLable);
this.UpdateLayout();
</code>```

答:
There are two ways to do this:

I recommend using TextBlock instead of Label. It will be a lot easier:

```<code><StackPanel TextBlock.Foreground="White">
    <TextBlock Text="Some Text" />
    <TextBlock Text="Some Text" />
    <TextBlock Text="Some Text" />
    <TextBlock Text="Some Text" />
    <TextBlock Text="Some Text" />
</StackPanel>
</code>```

With Label, you can do it like following:

```<code><StackPanel>
    <StackPanel.Resources>
        <Style TargetType="Label">
            <Setter Property="Foreground"
                    Value="White" />
        </Style>
    </StackPanel.Resources>
    <Label Content="Some Text" />
    <Label Content="Some Text" />
    <Label Content="Some Text" />
    <Label Content="Some Text" />
    <Label Content="Some Text" />
</StackPanel>
</code>```

Body:
Follow method is invalid,I dont want to set color by ergodic. How to set by style:

Style styleLable = new System.Windows.Style(typeof(Label));
styleLable.Setters.Add(new Setter(Label.ForegroundProperty, "White"));
this.Resources.Add("", styleLable);
this.UpdateLayout();

Body:
There are two ways to do this:

I recommend using TextBlock instead of Label. It will be a lot easier:

<StackPanel TextBlock.Foreground="White">
    <TextBlock Text="Some Text" />
    <TextBlock Text="Some Text" />
    <TextBlock Text="Some Text" />
    <TextBlock Text="Some Text" />
    <TextBlock Text="Some Text" />
</StackPanel>

With Label, you can do it like following:

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="Label">
            <Setter Property="Foreground"
                    Value="White" />
        </Style>
    </StackPanel.Resources>
    <Label Content="Some Text" />
    <Label Content="Some Text" />
    <Label Content="Some Text" />
    <Label Content="Some Text" />
    <Label Content="Some Text" />
</StackPanel>


问:
Google Spreadsheet + Apps: Get max value of column, it gives me date format
I'm trying to use HTML and JS to write into a Spreadsheet and I found some useful code to do that. I had to add a column to insert an ID for each entry and I did it like this:

```<code>var sheet = SpreadsheetApp.openById("myKey").getSheetByName('Richieste');
var column = 1;
var colArray = sheet.getRange(2, column, sheet.getLastRow()).getValues();
var maxi = Math.max.apply(Math, colArray);
var id = maxi+1;

// set other params

var vals = [id, date, name, surname, serial, eMail, area, text, ans, flag];
var sheetObj = sheet.appendRow(vals);
</code>```

Now, if I have an empty sheet, it works for the first two entries: the third ID is set such as 02/01/1900 0.00.00 and you can see a screenshot here.

I cannot understand what's going on... do you know something about this?

Thanks a lot for your help!

S.

答: It is hard to tell from the information you provided, but it looks like your cell format is set to date time, not a number.</p>

Body:
I'm trying to use HTML and JS to write into a Spreadsheet and I found some useful code to do that. I had to add a column to insert an ID for each entry and I did it like this:

var sheet = SpreadsheetApp.openById("myKey").getSheetByName('Richieste');
var column = 1;
var colArray = sheet.getRange(2, column, sheet.getLastRow()).getValues();
var maxi = Math.max.apply(Math, colArray);
var id = maxi+1;

// set other params

var vals = [id, date, name, surname, serial, eMail, area, text, ans, flag];
var sheetObj = sheet.appendRow(vals);

Now, if I have an empty sheet, it works for the first two entries: the third ID is set such as 02/01/1900 0.00.00 and you can see a screenshot here.

I cannot understand what's going on... do you know something about this?

Thanks a lot for your help!

S.


问:
Google API: Not a valid origin for the client: url has not been whitelisted for client ID "ID"
I need help. I don't found an answer to my question. I tried googling and I tried asking on other sides but I never found an answer.

I'm working with the google API (Youtube data API) and I use the example code from the google side the code it works I'm pretty sure about that. I got an error when i try to start the Script:

details: "Not a valid origin for the client: "MyURL" has not been whitelisted for client ID "MyID". Please go to https://console.developers.google.com/ and whitelist this origin for your project's client ID."

error: "idpiframe_initialization_failed"

The problem i whitelisted my Website and it's accepted. i don't know what is wrong. What should i do to "whitelist" my Domain (It's whitelisted)

And another question. I did not search for an answer on this question before.

I think it's possible that I can use the code on Localhost, I think I must whitelist my localhost address or something like this. But whitelisting does not work.

DreamGamer

答:
Had the same problem and here's how I solved it:

Activate both Analytics and Google Plus APIs on your project

Create new OAUTH 2.0 client credentials

Add the Authorized Javascript Origins under Restrictions section

Use the new client id.

Enjoy.


问:
TypeScript "import { myVar }" syntax seems to be incorrectly compiling in a Node/CommonJS/ES5 app
In my Node application, I have a settings file that exports some settings as an object like this:

```<code>// settings.ts
export var settings = {
    port: 1234
}
</code>```

In another file, I import these settings and attempt to reference the port property:

```<code>// another-file.ts
import { settings } from './settings';
console.log(settings.port);
</code>```

This code compiles correctly, but at runtime I get the following error:

```<code>Cannot read property 'port' of undefined
</code>```

When I inspect the compiled code, I can see that this is happening because my second file above is compiling to this:

```<code>var settings_1 = require("./settings");
console.log(settings_1.settings.port);
</code>```

If I walk through the compiled code with my debugger, I can see that the settings_1 variable points to the exported value from settings.ts.  In other words, my port property lives at settings_1.port, not at settings_1.settings.port.  It seems the TypeScript compiler should instead generated this JavaScript code:

```<code>var settings = require("./settings");
console.log(settings.port);
</code>```

Am I doing something wrong?  Or is the TypeScript compiler incorrectly compiling my import?

I know that the TypeScript compiler is correctly type-checking my import; if I do something like this:

```<code>import { settings } from './settings';
console.log(settings.propertyThatDoesNotExist);
</code>```

I get compiler errors that propertyThatDoesNotExist doesn't exist.

I'm using TypeScript 2.3.2, targeting "es5" and outputting "commonjs" modules, running on Node 6.9.2.

答:
Figured it out.  It was a silly mistake on my part (isn't it always?).  I was working on converting an application from JavaScript to TypeScript, and I copied and renamed settings.js to settings.ts... but I didn't delete settings.js.  As a result, I was actually importing my old settings.js file which had its exports set up differently.

Once I deleted settings.js, my application started correctly using the .ts file instead, and my imports worked as expected.

Body:
In my Node application, I have a settings file that exports some settings as an object like this:

// settings.ts
export var settings = {
    port: 1234
}

In another file, I import these settings and attempt to reference the port property:

// another-file.ts
import { settings } from './settings';
console.log(settings.port);

This code compiles correctly, but at runtime I get the following error:

Cannot read property 'port' of undefined

When I inspect the compiled code, I can see that this is happening because my second file above is compiling to this:

var settings_1 = require("./settings");
console.log(settings_1.settings.port);

If I walk through the compiled code with my debugger, I can see that the settings_1 variable points to the exported value from settings.ts.  In other words, my port property lives at settings_1.port, not at settings_1.settings.port.  It seems the TypeScript compiler should instead generated this JavaScript code:

var settings = require("./settings");
console.log(settings.port);

Am I doing something wrong?  Or is the TypeScript compiler incorrectly compiling my import?

I know that the TypeScript compiler is correctly type-checking my import; if I do something like this:

import { settings } from './settings';
console.log(settings.propertyThatDoesNotExist);

I get compiler errors that propertyThatDoesNotExist doesn't exist.

I'm using TypeScript 2.3.2, targeting "es5" and outputting "commonjs" modules, running on Node 6.9.2.


问:
Two different variables getting same value
I am currently working on a small Java application and I ran into a problem. I create two different variables, but after I run the code, the first variable is getting the same value as the second one. They should be different.

Here is my custom file class:

```<code>public class MyFile {

    private static String path;
    private static String name;

    private static final String FILE_SEPARATOR = "/";

    public MyFile(String path) {
        System.out.println(path);
        this.path = "";
        this.name = "";
        this.path = /*FILE_SEPARATOR*/path;
        String[] dirs = path.split(FILE_SEPARATOR);
        this.name = dirs[dirs.length - 1];
    }

    public static String getPath() {
        return path;
    }

    public static String getName() {
        return name;
    }

    public String toString() {
        return "Path: " + path + ", Name: " + name;
    }
}
</code>```

Here I am using the variables:

```<code>MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());
</code>```

The output is the following: http://imgur.com/a/Nu3N6

答:
In MyFile class, you declare these fields as static fields :

```<code>private static String path;
private static String name;
</code>```

So you can assign to them a single value as a static field is shared among all instances of the class.

You should rather declare these fields as instance fields to have distinct values for each MyFile instance :

```<code>private String path;
private String name;
</code>```

Body:
I am currently working on a small Java application and I ran into a problem. I create two different variables, but after I run the code, the first variable is getting the same value as the second one. They should be different.

Here is my custom file class:

public class MyFile {

    private static String path;
    private static String name;

    private static final String FILE_SEPARATOR = "/";

    public MyFile(String path) {
        System.out.println(path);
        this.path = "";
        this.name = "";
        this.path = /*FILE_SEPARATOR*/path;
        String[] dirs = path.split(FILE_SEPARATOR);
        this.name = dirs[dirs.length - 1];
    }

    public static String getPath() {
        return path;
    }

    public static String getName() {
        return name;
    }

    public String toString() {
        return "Path: " + path + ", Name: " + name;
    }
}

Here I am using the variables:

MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());

The output is the following: http://imgur.com/a/Nu3N6

Body:
In MyFile class, you declare these fields as static fields :

private static String path;
private static String name;

So you can assign to them a single value as a static field is shared among all instances of the class.

You should rather declare these fields as instance fields to have distinct values for each MyFile instance :

private String path;
private String name;


问:
How to use (_ map op) from Z3-LIB in z3py
Z3-LIB supports the operators for the extended Array theory such as (_ map op). But, how can we use this operator in Z3py?</p>

答:
You can use

```<code>b = Map(f, a1, a2)
</code>```

with a1, a2 and b array variables. The first parameter f has to be a function declaration, so using, e.g., z3.And does not work for me. Instead, I introduced a custom function f and another axiom to make it equivalent to And. But maybe you don't need the predefined ones.

Body:
You can use

b = Map(f, a1, a2)

with a1, a2 and b array variables. The first parameter f has to be a function declaration, so using, e.g., z3.And does not work for me. Instead, I introduced a custom function f and another axiom to make it equivalent to And. But maybe you don't need the predefined ones.


问:
Composer Paysafe any version?
First time I try to add a package in the composer.json of my laravel application.

I trying to add this package paysafe https://github.com/paysafegroup/paysafe_sdk_php

I downloaded the repo and moved it under the folder "vendor" in laravel

It seem that I need to specific the version of the package I am trying to install , but I don't have this information ...

```<code>{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "laravel/framework": "4.2.*",
        "barryvdh/laravel-dompdf": "0.4.*",
        "mailgun/mailgun-php": "~1.7.2",
        "guzzlehttp/guzzle": "~4.0",
        "mikehaertl/phpwkhtmltopdf": "^2.0",
        "paysafe":"*"
    },
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "dev"
}
</code>```

When I run this command

```<code>php composer.phar require paysafe
</code>```

I get this error message:

```<code>  [InvalidArgumentException]
  Could not find package paysafe at any version for your minimum-stability (dev). Check the package spelli
  ng or your minimum-stability
</code>```

答:
We have recently updated the SDK which should have fixed the version conflict issue. Please use PHP SDK version 1.0.1 and give it another shot!

All the best!

Title: Composer Paysafe any version?

Body:
First time I try to add a package in the composer.json of my laravel application.

I trying to add this package paysafe https://github.com/paysafegroup/paysafe_sdk_php

I downloaded the repo and moved it under the folder "vendor" in laravel

It seem that I need to specific the version of the package I am trying to install , but I don't have this information ...

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "laravel/framework": "4.2.*",
        "barryvdh/laravel-dompdf": "0.4.*",
        "mailgun/mailgun-php": "~1.7.2",
        "guzzlehttp/guzzle": "~4.0",
        "mikehaertl/phpwkhtmltopdf": "^2.0",
        "paysafe":"*"
    },
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "dev"
}

When I run this command

php composer.phar require paysafe

I get this error message:

  [InvalidArgumentException]
  Could not find package paysafe at any version for your minimum-stability (dev). Check the package spelli
  ng or your minimum-stability


问:
How to swap keys and values in a Map elegantly
I already know how to do it the hard way and got it working - iterating over entries and swapping "manually". But i wonder if, like so many tasks,  this one can be solved in a more elegant way.

I have read this post, unfortunately it does not feature elegant solutions. I also have no possibility to use any fancy Guava BiMaps or anything outside the jdk (project stack is already defined).

I can assume that my map is bijective, btw :)

答:
The standard API / Java runtime doesn't offer a bi-directional map, so the only solution is to iterate over all entries and swap them manually.

What you can do is create a wrapper class which contains two maps and which does a dual put() internally so you have fast two views on the data.

[EDIT] Also, thanks to open source, you don't have to include a third party library, you can simply copy the classes you need into your own project.


Title: Python: How to change a date in pandas which set as index

Body:
I need to set the last date to today date. Example: 2016-05-18 to 2017-06-05.
However when I do df.index[-1] = today, it return this error
TypeError: Index does not support mutable operations

>>> today
0   2017-06-05
Name: trading_day, dtype: datetime64[ns]

           Stock      Open      High       Low     Close Adj Close  Volume
Date
2016-05-13   AAD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2016-05-16   AAD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2016-05-17   AAD  5.210000  5.260000  5.210000  5.260000  5.260000    2000
2016-05-18   AAD  5.200000  5.250000  5.200000  5.250000  5.250000    3000

>>> df.index[-1] = today
TypeError: Index does not support mutable operations

What I needed is

           Stock      Open      High       Low     Close Adj Close  Volume
Date
2016-05-13   AAD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2016-05-16   AAD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2016-05-17   AAD  5.210000  5.260000  5.210000  5.260000  5.260000    2000
2017-06-05   AAD  5.200000  5.250000  5.200000  5.250000  5.250000    3000

Only the last date is change.

Body:
You can use rename

df.rename({df.index[-1]: 'today'}, inplace = True)

You get

        Stock   Open    High    Low Close   Adj Close.1 Volume
Date
2016-05-13  AAD     5.23    5.26    5.20    5.26    5.26    5000
2016-05-16  AAD     5.22    5.26    5.22    5.26    5.26    6000
2016-05-17  AAD     5.21    5.26    5.21    5.26    5.26    2000
today       AAD     5.20    5.25    5.20    5.25    5.25    3000

Change the code to

import datetime as dt
df.rename({df.index[-1]: dt.date.today()}, inplace = True)

And you get

    Stock   Open    High    Low Close   Adj Close.1 Volume
Date
2016-05-13  AAD     5.23    5.26    5.20    5.26    5.26    5000
2016-05-16  AAD     5.22    5.26    5.22    5.26    5.26    6000
2016-05-17  AAD     5.21    5.26    5.21    5.26    5.26    2000
2016-06-05  AAD     5.20    5.25    5.20    5.25    5.25    3000


问:
dynamic query on entity field name in a generic
I'm using generics because I need a lot of reusability with different types of data. my main problem is querying data. I'm looking for a way to query something like this:

```<code>public void test<T>(int id, T type) where T : class
{
    using (var ctx = myDbContext())
    {
        var myTbl = ctx.Set<T>();
        //this line gets the primary key of the table
        string key = myTbl.GetPrimaryKey(ctx);

        //this is the query I want:
        var myResult = myTbl.FirstOrDefault(x => x.key == id);

        //let's say if key = "UserId", then (x => x.UserId == id) or something that translates to this.
    }
}
</code>```

also I have implemented following method:

```<code>public object GetPropertyValue(object src, string propertyName)
</code>```

that I can use to get value of a specific property.

but my problem is that I can't use it inside the .FirstOrDefault() call because of the LINQ to query issues with methods.

I currently use this code instead:

```<code>var myResult = myTbl.ToList().FirstOrDefault(x => (int)GetPropertyValue(x, key) == id);
</code>```

which is fine with a few number of rows in database, but when data grows in future it will have a lot of performance impact.

P.S: I'm using EF power tools for reverse engineering code first

答:
First -> Dont use myTbl.ToList().FirstOrDefault(x => (int)GetPropertyValue(x, key) == id) because it generates a select that brings all rows from that table, then filter by id in memory. You should translate your filter to an Expression> that will generare a select filtered by the Id column.

Build your linq expression like this:

```<code>var x = Expression.Parameter(typeof(T), "x");

string keyPropName = type.GetPrimaryKey(ctx);
var equalExp = Expression.Equal(
    Expression.Property(x, keyPropName),
    Expression.Constant(id)
    );

var lambda = Expression.Lambda<Func<T, bool>>(equalExp, x); //x => x.Id == idValue

var myResult = myTbl.FirstOrDefault(lambda);
</code>```

I used your GetPropertyValue and GetPrimaryKey methods.

Body:
I'm using generics because I need a lot of reusability with different types of data. my main problem is querying data. I'm looking for a way to query something like this:

public void test<T>(int id, T type) where T : class
{
    using (var ctx = myDbContext())
    {
        var myTbl = ctx.Set<T>();
        //this line gets the primary key of the table
        string key = myTbl.GetPrimaryKey(ctx);

        //this is the query I want:
        var myResult = myTbl.FirstOrDefault(x => x.key == id);

        //let's say if key = "UserId", then (x => x.UserId == id) or something that translates to this.
    }
}

also I have implemented following method:

public object GetPropertyValue(object src, string propertyName)

that I can use to get value of a specific property.

but my problem is that I can't use it inside the .FirstOrDefault() call because of the LINQ to query issues with methods.

I currently use this code instead:

var myResult = myTbl.ToList().FirstOrDefault(x => (int)GetPropertyValue(x, key) == id);

which is fine with a few number of rows in database, but when data grows in future it will have a lot of performance impact.

P.S: I'm using EF power tools for reverse engineering code first

Body:
First -> Dont use myTbl.ToList().FirstOrDefault(x => (int)GetPropertyValue(x, key) == id) because it generates a select that brings all rows from that table, then filter by id in memory. You should translate your filter to an Expression> that will generare a select filtered by the Id column.

Build your linq expression like this:

var x = Expression.Parameter(typeof(T), "x");

string keyPropName = type.GetPrimaryKey(ctx);
var equalExp = Expression.Equal(
    Expression.Property(x, keyPropName),
    Expression.Constant(id)
    );

var lambda = Expression.Lambda<Func<T, bool>>(equalExp, x); //x => x.Id == idValue

var myResult = myTbl.FirstOrDefault(lambda);

I used your GetPropertyValue and GetPrimaryKey methods.


问:
docker stack deploy do not remove services that are not declared in the current yaml compose file
I am currently using Docker Swarm Mode in pipeline and i use massively docker stack deploy -c compose-file.yml name-of-the-stack as a command to update the stack with the latest docker image. It perfectly works unless i do not remove a service from the yaml file. In this case the stack deploy command should remove the no more exisisting service on top of update the image of the other, but the behaviour is that it leaves the container running and this is not the expected behavior.
As consequence of this i changed it with a docker stack rm name-of-the-service and then docker stack deploy -c compose-file.yml name-of-stack. But this has another awful side effect that randomly affects the containers : the commands docker stack rm name-of-the-stack often makes the reliability of the nginx container proxypass totally unreliable (seems related to this issue https://github.com/docker/docker/issues/24244) .
As a matter of fact, the nginx container (that is in another stack but in the same overlay network) , that is in charge to handle all requests between containers and make proxypass between them using the routing mesh feature of the Docker Swarm Mode,  after the re-creation of the stack deployed, fails to proxy requests, like if it try to forward traffic to no more exisisting containers, and this make the integration and behavioral tests fail.
Is there a way to deploy consistently without using docker stack rm (that seems pretty buggy so far) but applying the latest state of the yml compose file?

答:
You need to include the --prune option in your docker stack deploy command:

```<code>$ docker stack deploy --help

Usage:  docker stack deploy [OPTIONS] STACK

Deploy a new stack or update an existing stack

Aliases:
  deploy, up

Options:
      --bundle-file string    Path to a Distributed Application Bundle file
  -c, --compose-file string   Path to a Compose file
      --help                  Print usage
      --prune                 Prune services that are no longer referenced
      --with-registry-auth    Send registry authentication details to Swarm agents
</code>```

Body:
You need to include the --prune option in your docker stack deploy command:

$ docker stack deploy --help

Usage:  docker stack deploy [OPTIONS] STACK

Deploy a new stack or update an existing stack

Aliases:
  deploy, up

Options:
      --bundle-file string    Path to a Distributed Application Bundle file
  -c, --compose-file string   Path to a Compose file
      --help                  Print usage
      --prune                 Prune services that are no longer referenced
      --with-registry-auth    Send registry authentication details to Swarm agents


问:
Uncaught Error: $injector:modulerr; works locally but not on server
The following code works fine in my local dev environment, but when I have the solution hosted on a server I get the following error, after using the unminified js I get the following error:

```<code>angular.js:66 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
    ReferenceError: shallowCopy is not defined
</code>```

Below is the relevant code, my index.php file including all of the file and the app.js file that is injecting my directives:

index.php:

```<code><!-- bootstrap/jquery -->
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">

<script src="js/jquery/jquery-3.1.1.min.js"></script>
<script src="js/jquery/jquery-ui.min.js"></script>
<link rel="stylesheet" href="styles/jquery/jquery-ui.min.css" />

<link rel="stylesheet" href="styles/bootstrap-3.3.7-dist/css/bootstrap.css" />
<script src="styles/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script src="plugins/Bootstrap-3-Typeahead-master/bootstrap3-typeahead.min.js"></script>
<!-- end bootstrap/jquery -->
<!-- custom css -->
<link rel="stylesheet" href="styles/styles.css" />
<!-- end custom css -->
<!-- favicon -->
<link rel='shortcut icon' type='image/x-icon' href='media/images/favicon.ico' />
<!-- end favicon -->

<!-- custom js -->
<script src="js/main.js"></script>
<!-- end custom js -->

<!-- angularjs -->
<script src="js/angularjs/angular.min.js"></script>
<script src="js/angularjs/angular-route.min.js"></script>
<script src="js/angularjs/angular-sanitize.js"></script>

<script src="js/app.js"></script>
<script src="js/login/login.js"></script>
<script src="js/questionnaire/questionnaire.js"></script>
<script src="js/study/study.js"></script>
<script src="js/result/result.js"></script>
<!-- end angularjs -->
<div class="row" ng-app="app" >
    <div ng-view>
    </div>
</div>
</code>```

app.js:

```<code>// app.js
(function () {

  "use strict";

  // Creating the Module
  angular.module("app", ["ngRoute", "ngSanitize"])
    .config(function ($routeProvider) {
        //$location.path('/questionnaire'); //logged in already, session still active

      $routeProvider.when("/", {
        controller: "loginController",
        controllerAs: "vm",
        templateUrl: "views/login.php"
      });

      $routeProvider.when("/questionnaire/", {
        controller: "questionnaireController",
        controllerAs: "vm",
        templateUrl: "views/questionnaire.php"
      });

      $routeProvider.when("/questionnaire/:survey", {
        controller: "questionnaireController",
        controllerAs: "vm",
        templateUrl: "views/questionnaire.php"
      });

      $routeProvider.when("/study/:studyid", {
        controller: "studyController",
        controllerAs: "vm",
        templateUrl: "views/study.php"
      });

      $routeProvider.when("/result/", {
        controller: "resultController",
        controllerAs: "vm",
        templateUrl: "views/result.php"
      });

      $routeProvider.otherwise({ redirectTo: "/" });

    });

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

答:
It's probably a problem of js minification, ref https://docs.angularjs.org/guide/di#implicit-annotation

Try the following, note the ['$routeProvider...:

replace your code with this

```<code>(function () {

  "use strict";

angular.module("app", ["ngRoute", "ngSanitize"])
    .config(['$routeProvider', function ($routeProvider) {
        //$location.path('/questionnaire'); //logged in already, session still active

  $routeProvider.when("/", {
    controller: "loginController",
    controllerAs: "vm",
    templateUrl: "views/login.php"
  });

  $routeProvider.when("/questionnaire/", {
    controller: "questionnaireController",
    controllerAs: "vm",
    templateUrl: "views/questionnaire.php"
  });

  $routeProvider.when("/questionnaire/:survey", {
    controller: "questionnaireController",
    controllerAs: "vm",
    templateUrl: "views/questionnaire.php"
  });

  $routeProvider.when("/study/:studyid", {
    controller: "studyController",
    controllerAs: "vm",
    templateUrl: "views/study.php"
  });

  $routeProvider.when("/result/", {
    controller: "resultController",
    controllerAs: "vm",
    templateUrl: "views/result.php"
  });

  $routeProvider.otherwise({ redirectTo: "/" });

}]);

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

Body:
The following code works fine in my local dev environment, but when I have the solution hosted on a server I get the following error, after using the unminified js I get the following error:

angular.js:66 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
    ReferenceError: shallowCopy is not defined

Below is the relevant code, my index.php file including all of the file and the app.js file that is injecting my directives:

index.php:

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">

<link rel="stylesheet" href="styles/jquery/jquery-ui.min.css" />

<link rel="stylesheet" href="styles/bootstrap-3.3.7-dist/css/bootstrap.css" />

<link rel="stylesheet" href="styles/styles.css" />

<link rel='shortcut icon' type='image/x-icon' href='media/images/favicon.ico' />

app.js:

// app.js
(function () {

  "use strict";

  // Creating the Module
  angular.module("app", ["ngRoute", "ngSanitize"])
    .config(function ($routeProvider) {
        //$location.path('/questionnaire'); //logged in already, session still active

      $routeProvider.when("/", {
        controller: "loginController",
        controllerAs: "vm",
        templateUrl: "views/login.php"
      });

      $routeProvider.when("/questionnaire/", {
        controller: "questionnaireController",
        controllerAs: "vm",
        templateUrl: "views/questionnaire.php"
      });

      $routeProvider.when("/questionnaire/:survey", {
        controller: "questionnaireController",
        controllerAs: "vm",
        templateUrl: "views/questionnaire.php"
      });

      $routeProvider.when("/study/:studyid", {
        controller: "studyController",
        controllerAs: "vm",
        templateUrl: "views/study.php"
      });

      $routeProvider.when("/result/", {
        controller: "resultController",
        controllerAs: "vm",
        templateUrl: "views/result.php"
      });

      $routeProvider.otherwise({ redirectTo: "/" });

    });

})();

Body:
It's probably a problem of js minification, ref https://docs.angularjs.org/guide/di#implicit-annotation

Try the following, note the ['$routeProvider...:

replace your code with this

(function () {

  "use strict";

angular.module("app", ["ngRoute", "ngSanitize"])
    .config(['$routeProvider', function ($routeProvider) {
        //$location.path('/questionnaire'); //logged in already, session still active

  $routeProvider.when("/", {
    controller: "loginController",
    controllerAs: "vm",
    templateUrl: "views/login.php"
  });

  $routeProvider.when("/questionnaire/", {
    controller: "questionnaireController",
    controllerAs: "vm",
    templateUrl: "views/questionnaire.php"
  });

  $routeProvider.when("/questionnaire/:survey", {
    controller: "questionnaireController",
    controllerAs: "vm",
    templateUrl: "views/questionnaire.php"
  });

  $routeProvider.when("/study/:studyid", {
    controller: "studyController",
    controllerAs: "vm",
    templateUrl: "views/study.php"
  });

  $routeProvider.when("/result/", {
    controller: "resultController",
    controllerAs: "vm",
    templateUrl: "views/result.php"
  });

  $routeProvider.otherwise({ redirectTo: "/" });

}]);

})();


问:
Using Unicode in google-apps menu item
I would like to use a unicode symbol for Power, &#x23FB, in my drop-down menu.  Here is a link saying it can be done; however, I can't figure how to code it.

how to make icons in google custom menu

```<code>var menu = DocumentApp.getUi().createAddonMenu();
    menu.addItem('&#9824', 'Run App');
    menu.addToUi();
</code>```

Thanks.

答:
Don't use the code. Cut and paste the character. Like '☢' The Apps Script IDE and all the apps support unicode.  </p>

```<code>var menu = DocumentApp.getUi().createAddonMenu();
    menu.addItem('☢', 'Run App');
    menu.addToUi();
</code>```

Title: Using Unicode in google-apps menu item

Body:
I would like to use a unicode symbol for Power, &#x23FB, in my drop-down menu.  Here is a link saying it can be done; however, I can't figure how to code it.

how to make icons in google custom menu

var menu = DocumentApp.getUi().createAddonMenu();
    menu.addItem('&#9824', 'Run App');
    menu.addToUi();

Thanks.

Body:
Don't use the code. Cut and paste the character. Like '☢' The Apps Script IDE and all the apps support unicode.

var menu = DocumentApp.getUi().createAddonMenu();
    menu.addItem('☢', 'Run App');
    menu.addToUi();


问:
How to hide browser errors provided by ZendFramework3?
How to hide framework errors that it display in browser?
I searcher in application.config, Application module.config tried to change flags and templates but no effect.

How to hide errors in browser but leave them in console?

As a server I'm using right now build in php5.6 server

```<code>  'view_manager' => [
    'display_not_found_reason' => true,
    'display_exceptions'       => false,
    'doctype'                  => 'HTML5',
    'not_found_template'       => 'error/404',
    'exception_template'       => 'error/index',
    'template_map' => [
        'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
        'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
        'error/404'               => __DIR__ . '/../view/error/custom_404.phtml',
        'error/index'             => __DIR__ . '/../view/error/index.phtml',
    ],
    'template_path_stack' => [
        __DIR__ . '/../view',
    ],
],
</code>```

答:
There two ways to do it because zend is a PHP framework so you can hide it with php code or with zend settings file.

1) Core PHP.

```<code>error_reporting(E_ALL);
ini_set('display_errors', true);
</code>```

PHP error settings

2) Zend change your settings as per your requirement false will hide your error.

```<code>/*in your module.config.php */
'view_manager' => array(
    'display_not_found_reason' => true,
    'display_exceptions' => true,
    'doctype' => 'HTML5',
    'not_found_template' => 'error/404',
    'exception_template' => 'error/index',
    'template_map' => array(
        'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
        '/index/index' => __DIR__ . '/../view/user/index/index.phtml',
        'error/404' => __DIR__ . '/../view/error/404.phtml',
        'error/index' => __DIR__ . '/../view/error/index.phtml',
    ),
    'template_path_stack' => array(
        __DIR__ . '/../view',
    ),
),
</code>```

Body:
How to hide framework errors that it display in browser?
I searcher in application.config, Application module.config tried to change flags and templates but no effect.

How to hide errors in browser but leave them in console?

As a server I'm using right now build in php5.6 server

  'view_manager' => [
    'display_not_found_reason' => true,
    'display_exceptions'       => false,
    'doctype'                  => 'HTML5',
    'not_found_template'       => 'error/404',
    'exception_template'       => 'error/index',
    'template_map' => [
        'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
        'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
        'error/404'               => __DIR__ . '/../view/error/custom_404.phtml',
        'error/index'             => __DIR__ . '/../view/error/index.phtml',
    ],
    'template_path_stack' => [
        __DIR__ . '/../view',
    ],
],

Body:
There two ways to do it because zend is a PHP framework so you can hide it with php code or with zend settings file.

1) Core PHP.

error_reporting(E_ALL);
ini_set('display_errors', true);

PHP error settings

2) Zend change your settings as per your requirement false will hide your error.

/*in your module.config.php */
'view_manager' => array(
    'display_not_found_reason' => true,
    'display_exceptions' => true,
    'doctype' => 'HTML5',
    'not_found_template' => 'error/404',
    'exception_template' => 'error/index',
    'template_map' => array(
        'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
        '/index/index' => __DIR__ . '/../view/user/index/index.phtml',
        'error/404' => __DIR__ . '/../view/error/404.phtml',
        'error/index' => __DIR__ . '/../view/error/index.phtml',
    ),
    'template_path_stack' => array(
        __DIR__ . '/../view',
    ),
),


问:
php script to dump the whole tables from a database and send it to a particular email
i am working on a project, and i will like to run a php script that will run as a backup. that is a script that will extract or export my database and send it to my mail. but what am confuse about is, can it be done using only php or sql or both?.

i will appreciate if you guys can help. Thanks

答:
You can do both.

```<code>$output = 'backupDir/myData.sql';
$sql = "SELECT * INTO OUTFILE '$file' FROM `someTable`";
$res = mysql_query($sql);
</code>```

You can execute the $sql separately on mysql client and get an output also.

Do check for permissions for backupDir directory. Sometimes they dont work with the webserver user www-data. Need to fix that also.

Body:
You can do both.

$output = 'backupDir/myData.sql';
$sql = "SELECT * INTO OUTFILE '$file' FROM `someTable`";
$res = mysql_query($sql);

You can execute the $sql separately on mysql client and get an output also.

Do check for permissions for backupDir directory. Sometimes they dont work with the webserver user www-data. Need to fix that also.


问:
Spring Cloud Sleuth with OpenTracing
Is there a way to use Spring Cloud Sleuth with OpenTracing? I want to connect Spring clients with Jaeger</p>

答: There's an ongoing discussion over here - https://github.com/spring-cloud/spring-cloud-sleuth/issues/599 . In general we don't explicitly use the OpenTracing API but we are Zipkin compatible in terms of header propagation. You can also manipulate the header names as you wish so if any sort of library you're using requires other header names for span / trace etc. then you can set it yourself as you want to.</p>

Title: Spring Cloud Sleuth with OpenTracing


问:
Using mRender with two data variables in jquery Datatables?
I have several columns defined using datatables. I assign "mData" which I manipulate mRender to display. However, I would like to display two data variables in one column in order to create a link, something like this:

```<code>    {"mData": "foo",
     "mData2": "bar",
     "mRender": function(data, data2){
          return '<a href="/data/' + data + '">bar</a>'; //
      }
    }
</code>```

Is there a way to do this?

答:
```<code>                'paging': true,
                'sort': true,
                'searching': true,
                'scrollY':70,
                "ajax": {
                    "url": '/Home/GetDept',
                    "type": "get",
                    "datatype" :"json"
                },
                "columns": [
                     { "data": "city", "autoWidth": true },
                     { "data": "postalcode", "autoWidth": true },
                     { "data": "adress", "autoWidth": true },

                     {
                         "data": "deptid",
                         "data": "namedept",
                         "width": "50px", "render": function (data, type, row, meta) {

                             return '<a  href="/Emp/Details?deptid=' + row.deptid + '">' + row.namedept + ' </a>';
                         }
                     }

                ]
            })
</code>```

Body:
I have several columns defined using datatables. I assign "mData" which I manipulate mRender to display. However, I would like to display two data variables in one column in order to create a link, something like this:

    {"mData": "foo",
     "mData2": "bar",
     "mRender": function(data, data2){
          return 'bar'; //
      }
    }

Is there a way to do this?


问:
How to add options that i read from sql using C# web service into select element?
i have a streets table in my sql database, what i'm trying to do is to push the name of each street into a select element in html page, so my code is :

```<code>[WebMethod]
public string FillStreetsIntoSelect()
{
    string streetsNames = "";
    command.Connection.Close();
    JavaScriptSerializer json = new JavaScriptSerializer();
    command.CommandText = "select Street_Name from Streets";
    command.Connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        streetsNames += reader.GetValue(0).ToString() + ",";
    }
    command.Connection.Close();
    return json.Serialize(streetsNames);
}
</code>```

and this is what this function returns:

```<code><string xmlns="http://tempuri.org/">"asd,fgh,qwe,ert,"</string>
</code>```

so this data i need to insert it into empty select element that i have in my html page by a javascript/jQuery function

```<code>function fillStreetLocationSelect() {
    $.ajax({
        async: true,
        url: web + "/FillStreetLocationSelect",
        dataType: "json",
        method: "POST",
        data: JSON.stringify(hazard),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            /*   */
        }
    });
}
</code>```

now, how to slipt the string that the function returns, and how to insert it into the select element

答:
Find below example , may be this is very helpful to you.</p>

```<code>   $.ajax({
        url: "WebService/WebService.asmx/GetAllCompany",
        data: "",
        type: 'POST',
        contentType: 'application/json;',
        dataType: 'json',
        success: function (result) {
            if (result != null) {
                var userlist = result;
                var t = JSON.parse(userlist.d);

                var ddl = document.getElementById('ddlCompany');
                $('#ddlCompany').html('');
                for (var i = 0; i < t.length; i++) {
                    ddl.options[i] = new Option(t[i].Name, t[i].Link);
                }

            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {

            alert(XMLHttpRequest.responseText);
            alert(textStatus);
            alert(errorThrown);
        }
    });
</code>```

Body:
i have a streets table in my sql database, what i'm trying to do is to push the name of each street into a select element in html page, so my code is :

[WebMethod]
public string FillStreetsIntoSelect()
{
    string streetsNames = "";
    command.Connection.Close();
    JavaScriptSerializer json = new JavaScriptSerializer();
    command.CommandText = "select Street_Name from Streets";
    command.Connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        streetsNames += reader.GetValue(0).ToString() + ",";
    }
    command.Connection.Close();
    return json.Serialize(streetsNames);
}

and this is what this function returns:

<string xmlns="http://tempuri.org/">"asd,fgh,qwe,ert,"</string>

so this data i need to insert it into empty select element that i have in my html page by a javascript/jQuery function

function fillStreetLocationSelect() {
    $.ajax({
        async: true,
        url: web + "/FillStreetLocationSelect",
        dataType: "json",
        method: "POST",
        data: JSON.stringify(hazard),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            /*   */
        }
    });
}

now, how to slipt the string that the function returns, and how to insert it into the select element

Body:
Find below example , may be this is very helpful to you.

   $.ajax({
        url: "WebService/WebService.asmx/GetAllCompany",
        data: "",
        type: 'POST',
        contentType: 'application/json;',
        dataType: 'json',
        success: function (result) {
            if (result != null) {
                var userlist = result;
                var t = JSON.parse(userlist.d);

                var ddl = document.getElementById('ddlCompany');
                $('#ddlCompany').html('');
                for (var i = 0; i < t.length; i++) {
                    ddl.options[i] = new Option(t[i].Name, t[i].Link);
                }

            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {

            alert(XMLHttpRequest.responseText);
            alert(textStatus);
            alert(errorThrown);
        }
    });


问:
how to pipe functions, when a promise in the promise in the middle checks authorization?
i'm trying to compose some functions together:

```<code>compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
</code>```

checkAuthorization returns a promise that check if a user is authorized.
buildParams receives someRequestData, and pipes the result to searchItem.

```<code>    checkAuthorization()
      .then(() => {
            compose(
                searchItem,
                buildParams
            )(someRequestData)
    }, (e) => {
       handleError(e)
    })
</code>```

I think it's OK, but I wish to have a more elegant look for readability, something like:

```<code>    compose(
      searchItem,
      checkAuthorization
      buildParams
    )(someRequestData)
</code>```

so what will happen is:
1) build params
2) checkAuth
3) search item

Any suggestions?

答:
No, that's not possible, since checkAuthorisation does not receive and pass through the params. And even if you would rewrite it to do that, it still would be weird and a reader would assume that you're building the params whose authorisation should be checked. So don't do that - you have a non-linear flow, and trying to force it into some linear composition is no good.

Btw, I would recommend to avoid compose when you're calling the function immediately anyway:

```<code>checkAuthorization().then(() =>
  searchItem(buildParams(someRequestData))
, e =>
   handleError(e)
);
</code>```

or maybe

```<code>checkAuthorization().then( compose(searchItem, buildParams, ()=>someRequestData)
                         , handleError ); //                ^^^^ "const"
</code>```

Body:
i'm trying to compose some functions together:

compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));

checkAuthorization returns a promise that check if a user is authorized.
buildParams receives someRequestData, and pipes the result to searchItem.

    checkAuthorization()
      .then(() => {
            compose(
                searchItem,
                buildParams
            )(someRequestData)
    }, (e) => {
       handleError(e)
    })

I think it's OK, but I wish to have a more elegant look for readability, something like:

    compose(
      searchItem,
      checkAuthorization
      buildParams
    )(someRequestData)

so what will happen is:
1) build params
2) checkAuth
3) search item

Any suggestions?

Body:
No, that's not possible, since checkAuthorisation does not receive and pass through the params. And even if you would rewrite it to do that, it still would be weird and a reader would assume that you're building the params whose authorisation should be checked. So don't do that - you have a non-linear flow, and trying to force it into some linear composition is no good.

Btw, I would recommend to avoid compose when you're calling the function immediately anyway:

checkAuthorization().then(() =>
  searchItem(buildParams(someRequestData))
, e =>
   handleError(e)
);

or maybe

checkAuthorization().then( compose(searchItem, buildParams, ()=>someRequestData)
                         , handleError ); //                ^^^^ "const"


问:
Use Perl module only when it is needed within a subroutine
Imagine my script has these two subs

```<code>sub with_json_mod{
    use JSON::Tiny;
    blah blah blah;
}

sub without_json_mod{
   blah blah blah;
}
</code>```

I only want to use without_json_mod when JSON::Tiny is not installed.

How can I make Perl not fail if JSON::Tiny is not installed and, instead, use the without_json_mod sub instead?

I tried to call require in the with_json_mod and it seems to work, but it doesn't work when I try to make it import the encode_json sub as in

```<code>sub with_json_mod{
    require JSON::Tiny qw/encode_json/;
    blah blah blah;
}
</code>```

答:
There are two main differences between use and require.

use happens at compile time and require happens at runtime.

use calls the import() method in the loaded package (if one exists) and require doesn't.

So you need to add a call to import().

```<code>sub with_json_mod{
    require JSON::Tiny;
    JSON::Tiny->import('encode_json');
    blah blah blah;
}
</code>```

Body:
Imagine my script has these two subs

sub with_json_mod{
    use JSON::Tiny;
    blah blah blah;
}

sub without_json_mod{
   blah blah blah;
}

I only want to use without_json_mod when JSON::Tiny is not installed.

How can I make Perl not fail if JSON::Tiny is not installed and, instead, use the without_json_mod sub instead?

I tried to call require in the with_json_mod and it seems to work, but it doesn't work when I try to make it import the encode_json sub as in

sub with_json_mod{
    require JSON::Tiny qw/encode_json/;
    blah blah blah;
}

Body:
There are two main differences between use and require.

use happens at compile time and require happens at runtime.

use calls the import() method in the loaded package (if one exists) and require doesn't.

So you need to add a call to import().

sub with_json_mod{
    require JSON::Tiny;
    JSON::Tiny->import('encode_json');
    blah blah blah;
}


问:
How to join 2 tables in codeigniter PHP?
I have 2 tables guest_info and guest_profile.two columns are there g_uid and company_id.Based on company_id(I have companyID), i have to take all g_uid.
In guest_info table,

g_uid | companyID

1        5

2        5

3        6

In guest_profile table,display all values from this table(only need to display first two datas)

g_uid | fname

1         xyz

2         fds

3         fsdf

答:
Go to folder "Models" That´s where you´ll do all your CRUD operations to the database.
For example, you can create a model file called "guest_profile_model.php"

Now you open that file and paste the code bellow:

```<code>       <?php

    class guest_profile_model extends CI_Model {

public function select($company_id) {

$this->db->query("select * from `guest_info` INNER JOIN `guest_profile` ON guest_info.g_uid = guest_profile.g_uid WHERE guest_info.company_id = ".$company_id." LIMIT 2");
 $result = $this->db->query($query);

 return $result->result_object();
}
    }
</code>```

That´s it, now from within your controller you just need to load and call it.
Example:

```<code>  $this-> load-> model('guest_profile_model ');
    $company_id = 1;
    $queryResult = $this -> guest_profile_model ->select(company_id);

    print_r($queryResult);
</code>```

Notice that the query return is going to be an object, that is because of the "result_object" in the model, you can change that to be an array if you want to.

Body:
Go to folder "Models" That´s where you´ll do all your CRUD operations to the database.
For example, you can create a model file called "guest_profile_model.php"

Now you open that file and paste the code bellow:

       <?php

    class guest_profile_model extends CI_Model {

public function select($company_id) {

$this->db->query("select * from `guest_info` INNER JOIN `guest_profile` ON guest_info.g_uid = guest_profile.g_uid WHERE guest_info.company_id = ".$company_id." LIMIT 2");
 $result = $this->db->query($query);

 return $result->result_object();
}
    }

That´s it, now from within your controller you just need to load and call it.
Example:

  $this-> load-> model('guest_profile_model ');
    $company_id = 1;
    $queryResult = $this -> guest_profile_model ->select(company_id);

    print_r($queryResult);

Notice that the query return is going to be an object, that is because of the "result_object" in the model, you can change that to be an array if you want to.


问:
the max function requires 1 argument(s)
I wrote this very simple SP in SQL 2008:

```<code>Create procedure dbo.GetNextID
(
    @TableName nvarchar(50),
    @FieldName nvarchar(50)
)
AS
    BEGIN
        exec('select isnull(max('+@FieldName+'),0)+1 as NewGeneratedID from '+ @TableName);
    END
</code>```

When I execute this procedure in Visual Studio SQL Express and pass a table name and a field name, it works fine. But when I try to add this SP as a query in a QueryTableAdapter in my ADO DataSet, I receive this error before clicking on Finish button:

```the max function requires 1 argument(s)```

can anyone help me with this?

答:
I guess that VS tries to determine a field list by executing the SP. But as it does not know what to pass to the SP, it uses empty parameters. Now, of course, your select statement fails.

You could try adding the following to your SP:

```<code>IF ISNULL(@TableName,'') = '' SET @TableName = '<Name of a test table>';
IF ISNULL(@FieldName,'') = '' SET @FieldName = '<Name of some field>';
</code>```

Use the names of some field and table that do exist here (for example names that you'd use from your application, too).

Alternatively you could add the following above the exec:

```<code>IF (ISNULL(@TableName, '') = '') OR (ISNULL(@FieldName, '') = '')
BEGIN
    SELECT -1 AS NewGeneratedId
    RETURN 0
END
</code>```

EDIT

On a side note, I'd like to warn you about concurrency issues that I see coming up from what your code does. If this code is supposed to return a unique ID for a new record in some table, I'd redesign this as follows:

Create a table NumberSeries where each row contains a unique name, a possible range for IDs and the current ID value.

Create a stored procedure that uses UPDATE ... OUTPUT to update the current ID for a number series and retrieve it in one step.

That way you can make sure that creating a new ID is a single operation that does not cause concurrency problems.

Title: the max function requires 1 argument(s)

Body:
I wrote this very simple SP in SQL 2008:

Create procedure dbo.GetNextID
(
    @TableName nvarchar(50),
    @FieldName nvarchar(50)
)
AS
    BEGIN
        exec('select isnull(max('+@FieldName+'),0)+1 as NewGeneratedID from '+ @TableName);
    END

When I execute this procedure in Visual Studio SQL Express and pass a table name and a field name, it works fine. But when I try to add this SP as a query in a QueryTableAdapter in my ADO DataSet, I receive this error before clicking on Finish button:

the max function requires 1 argument(s)

can anyone help me with this?

Body:
I guess that VS tries to determine a field list by executing the SP. But as it does not know what to pass to the SP, it uses empty parameters. Now, of course, your select statement fails.

You could try adding the following to your SP:

IF ISNULL(@TableName,'') = '' SET @TableName = '<Name of a test table>';
IF ISNULL(@FieldName,'') = '' SET @FieldName = '<Name of some field>';

Use the names of some field and table that do exist here (for example names that you'd use from your application, too).

Alternatively you could add the following above the exec:

IF (ISNULL(@TableName, '') = '') OR (ISNULL(@FieldName, '') = '')
BEGIN
    SELECT -1 AS NewGeneratedId
    RETURN 0
END

EDIT

On a side note, I'd like to warn you about concurrency issues that I see coming up from what your code does. If this code is supposed to return a unique ID for a new record in some table, I'd redesign this as follows:

Create a table NumberSeries where each row contains a unique name, a possible range for IDs and the current ID value.

Create a stored procedure that uses UPDATE ... OUTPUT to update the current ID for a number series and retrieve it in one step.

That way you can make sure that creating a new ID is a single operation that does not cause concurrency problems.


问:
python3 how to find the largest prefix of a string of bytes that is a substring of another
I need to find largest prefix (string of bytes starting from the beginning) of a bytes object s1 that is a substring of another bytes object s2 and return the start location in s2 and length. In this case s2 happens to be overlapping s1 as well.

The optimal result is the longest prefix that starts closest to the end of s2.

I have tried to implement this using bytes.rfind method as below.

Note: This is trying to find the largest prefix starting at index index in the bytes object  src that is present earlier in src within a maximum of maxOffset bytes before index. Therefore, s1 is src[index:] and s2 is src[index-maxOffset:index+maxLength-1]. maxLength is the maximum length of prefix that I am interested in searching for.

```<code>def crl(index, src, maxOffset, maxLength):
    """
    Returns starting position in source before index from where the max runlength is detected.
    """
    src_size = len(src)
    if index > src_size:
        return (-1, 0)
    if (index+maxLength) > src_size:
        maxLength = src_size - index
    startPos = max(0, index-maxOffset)
    endPos = index+maxLength-1
    l = maxLength

    while l>1:
        if src[index:index+l] in src[startPos:index+l-1]:
            p = src.rfind(src[index:index+l], startPos, index+l-1)
            return (p,l)
        l -= 1
    return (-1, 0)
</code>```

I have also tried to hand-code this as below since the previous implementation was very slow

```<code>def ocrl(index, src, maxOffset, maxLength):
    """
    Returns starting position in source before index from where the max runlength is detected.
    """
    size = len(src)
    if index>=size:
        return (-1, 0)
    startPos = index - 1 # max(0, index-maxOffset)
    stopPos = max(0, index-maxOffset)
    runs = {}
    while(startPos >= stopPos):
        currRun = 0
        pos = startPos
        while src[pos] == src[index+currRun]:
            currRun += 1
            pos += 1
            if currRun == maxLength:
                return (startPos, maxLength) #found best possible run
            if (pos >= size) or ((index+currRun) >= size):
                break
        if (currRun > 0) and (currRun not in runs.keys()):
            runs[currRun] = startPos
        startPos -= 1

    if not runs:
        return (-1, 0)
    else:
        # Return the index from where the longest run was found
        return (runs[max(runs.keys())], max(runs.keys()))
</code>```

While 2nd implementation is faster, it is still very slow and I believe inefficient. How can I make this more efficient and run faster ?

答:
In my opinion, you can use a modified Knuth-Morris-Pratt string searching agorithm that matches substrings as long as it can and reminds the longest match found.

I am not sure that there is a benefit work backwards over forward, as when you have found a match you need to continue the search for a longer one (except when you have matched the whole string).

Body:
I need to find largest prefix (string of bytes starting from the beginning) of a bytes object s1 that is a substring of another bytes object s2 and return the start location in s2 and length. In this case s2 happens to be overlapping s1 as well.

The optimal result is the longest prefix that starts closest to the end of s2.

I have tried to implement this using bytes.rfind method as below.

Note: This is trying to find the largest prefix starting at index index in the bytes object  src that is present earlier in src within a maximum of maxOffset bytes before index. Therefore, s1 is src[index:] and s2 is src[index-maxOffset:index+maxLength-1]. maxLength is the maximum length of prefix that I am interested in searching for.

def crl(index, src, maxOffset, maxLength):
    """
    Returns starting position in source before index from where the max runlength is detected.
    """
    src_size = len(src)
    if index > src_size:
        return (-1, 0)
    if (index+maxLength) > src_size:
        maxLength = src_size - index
    startPos = max(0, index-maxOffset)
    endPos = index+maxLength-1
    l = maxLength

    while l>1:
        if src[index:index+l] in src[startPos:index+l-1]:
            p = src.rfind(src[index:index+l], startPos, index+l-1)
            return (p,l)
        l -= 1
    return (-1, 0)

I have also tried to hand-code this as below since the previous implementation was very slow

def ocrl(index, src, maxOffset, maxLength):
    """
    Returns starting position in source before index from where the max runlength is detected.
    """
    size = len(src)
    if index>=size:
        return (-1, 0)
    startPos = index - 1 # max(0, index-maxOffset)
    stopPos = max(0, index-maxOffset)
    runs = {}
    while(startPos >= stopPos):
        currRun = 0
        pos = startPos
        while src[pos] == src[index+currRun]:
            currRun += 1
            pos += 1
            if currRun == maxLength:
                return (startPos, maxLength) #found best possible run
            if (pos >= size) or ((index+currRun) >= size):
                break
        if (currRun > 0) and (currRun not in runs.keys()):
            runs[currRun] = startPos
        startPos -= 1

    if not runs:
        return (-1, 0)
    else:
        # Return the index from where the longest run was found
        return (runs[max(runs.keys())], max(runs.keys()))

While 2nd implementation is faster, it is still very slow and I believe inefficient. How can I make this more efficient and run faster ?


问:
using dynamic linq to filter a list of objects
I have two class like this

```<code>public class Error{
   public string Code{get;set;}
   public string Description{get;set;}
}

public class Row{
   public List<Error> Errors {get;set;}
   ....
}
</code>```

So, for each row, can exists more errors.
It's possible using dynamic linq select the row that have an error code(for example Code1)?

So, if the row contains Code1 and Code2, i want select the row.

if in the example below query has a list of rows i want a query like this

```<code>query.Where("Errors != null && Errors.Code.contains('Code1')")
</code>```

答:
Use the where extension method of linq. and check if the code is equals to  Code1 or Code2 and convert the result into list of Error

```<code> List<Error> rows = row.Errors
            .Where(x => x.Code == "Code1" && x.Code == "Code2")
            .ToList();
</code>```

OR

```<code>var result = (from x in row.Errors
            where x.Code == "Code1" && x.Code == "Code2"
            select x).ToList();
</code>```

Body:
I have two class like this

public class Error{
   public string Code{get;set;}
   public string Description{get;set;}
}

public class Row{
   public List<Error> Errors {get;set;}
   ....
}

So, for each row, can exists more errors.
It's possible using dynamic linq select the row that have an error code(for example Code1)?

So, if the row contains Code1 and Code2, i want select the row.

if in the example below query has a list of rows i want a query like this

query.Where("Errors != null && Errors.Code.contains('Code1')")

Body:
Use the where extension method of linq. and check if the code is equals to  Code1 or Code2 and convert the result into list of Error

 List<Error> rows = row.Errors
            .Where(x => x.Code == "Code1" && x.Code == "Code2")
            .ToList();

OR

var result = (from x in row.Errors
            where x.Code == "Code1" && x.Code == "Code2"
            select x).ToList();


问:
multidimensional array initialized with array returned by function
I have a problem with the following example:

```<code>public static void main(String[] args) {

    // this works
    int[] test1DArray = returnArray();

    int[][] test2DArray = new int[][] {

        // this does not work
        new int[]= returnArray(),

        // yet this does
        new int[] {1, 2 ,3}
}

private static int[] returnArray() {

    int[] a = {1, 2, 3};
    return a;
}
</code>```

I am looking for a way to create a two-dimensional array, and have the second dimension be the array that is returned from a method. I do not understand why it does not work, as the error I am getting in Eclipse is

The left-hand side of an assignment must be a variable

From my understanding, I am creating a new int array and assigning the returned value to it. Populating the second dimension array immediately like this

```<code>new int[] {1, 2 ,3}
</code>```

works like a charm, and I am looking to do something similar with the array that's returned to me from returnArray()

Any help is greatly appreciated.

p/

答:
Just use:</p>

```<code>int[][] test2DArray = new int[][] {
    returnArray(),
    new int[] {1,2 ,3}
};
</code>```

Body:
I have a problem with the following example:

public static void main(String[] args) {

    // this works
    int[] test1DArray = returnArray();

    int[][] test2DArray = new int[][] {

        // this does not work
        new int[]= returnArray(),

        // yet this does
        new int[] {1, 2 ,3}
}

private static int[] returnArray() {

    int[] a = {1, 2, 3};
    return a;
}

I am looking for a way to create a two-dimensional array, and have the second dimension be the array that is returned from a method. I do not understand why it does not work, as the error I am getting in Eclipse is

The left-hand side of an assignment must be a variable

From my understanding, I am creating a new int array and assigning the returned value to it. Populating the second dimension array immediately like this

new int[] {1, 2 ,3}

works like a charm, and I am looking to do something similar with the array that's returned to me from returnArray()

Any help is greatly appreciated.

p/

Body:
Just use:

int[][] test2DArray = new int[][] {
    returnArray(),
    new int[] {1,2 ,3}
};


问:
How do you launch Safari browser from within an iPad app?

Possible Duplicate:

  launch safari from iphone app

How do you launch Safari browser from within an iPad app?

答:
Like this
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:yourURLHere]];

you can dial number too using this

[[UIApplication sharedApplication] openURL:@"tel://123245655];

enjoy..


问:
PHP url decoding or encoding help needed
Hey I'm trying to pass variables to my variation product page.

For example, im able to pass the keys and part numbers via

http://comugg.com/product/generallisting6/?attribute_pa_keys=yes&attribute_pa_part-number=0-261-204-591

however when i try to pass the engine size using the same format...for example,

http://comugg.com/product/generallisting6/?attribute_pa_engine-size=1.8L

it doesnt work. im assuming its becuase of the "." im wondering what i can do?

P.S. ive already tried using the slug 1-6L. it doesnt work:(

答:
Variables in the URL don't like dots I'm afraid.

Why not use the following when creating the variable and then reverse when reading?

```<code>$variablename = str_replace(".","_",$variablename;
</code>```

Body:
Variables in the URL don't like dots I'm afraid.

Why not use the following when creating the variable and then reverse when reading?

$variablename = str_replace(".","_",$variablename;