问:
Passing target variables from pattern match to static
I'm writing a Makefile to wrap the deployment of an elastic beanstalk app to multiple environments. This is my first time writing an "advanced" makefile and I'm having a bit of trouble.

My goals are as follows:

make deploy by itself should deploy with ENVIRONMENT=$(USER) and ENV_TYPE=staging.

The environment to deploy to can be set via an environment variable. If ENVIRONMENT=production then ENV_TYPE=production, otherwise ENV_TYPE=staging.

As a shorthand for setting the environment variable, one can suffix the deploy target with a - and the name of the environment. For example: make deploy-production.

It's number 3 that is giving me the most trouble. Since any environment not named production is of type staging, I tried to use pattern matching to define the target for deploying to staging environments. Here's what I have currently:

```<code>ENVIRONMENT = $(USER)
ifeq ($ENVIRONMENT, production)
ENV_TYPE=production
else
ENV_TYPE=staging
endif
DOCKER_TAG ?= $(USER)
CONTAINER_PORT ?= 8000
ES_HOST = logging-ingest.$(ENV_TYPE).internal:80

.PHONY: deploy
deploy:
    -pip install --upgrade awsebcli
    sed "s/<<ES_HOST>>/$(ES_HOST)/" < 01-filebeat.template > .ebextensions/01-filebeat.config
    sed "s/<<DOCKER_TAG>>/$(DOCKER_TAG)/" < Dockerrun.template | sed "s/<<CONTAINER_PORT>>/$(CONTAINER_PORT)/" > Dockerrun.aws.json
    eb labs cleanup-versions --num-to-leave 10 --older-than 5 --force -v --region us-west-2
    eb deploy -v coolapp-$(ENVIRONMENT)

.PHONY: deploy-%
deploy-%: ENVIRONMENT=$*
deploy-%: deploy
    @echo  # Noop required

.PHONY: deploy-production
deploy-production: ENVIRONMENT=production
deploy-production: ENV_TYPE=production
deploy-production: deploy
    @echo  # Noop required
</code>```

The problem is in the last step of the deploy target. Namely, $(ENVIRONMENT) appears to be unset.

Example Output:

```<code>18:42 $ make -n deploy-staging
pip install --upgrade awsebcli
sed "s/<<ES_HOST>>/logging-ingest.staging.internal:80/" < 01-filebeat.template > .ebextensions/01-filebeat.config
sed "s/<<DOCKER_TAG>>/schultjo/" < Dockerrun.template | sed "s/<<CONTAINER_PORT>>/8000/" > Dockerrun.aws.json
eb labs cleanup-versions --num-to-leave 10 --older-than 5 --force -v --region us-west-2
eb deploy -v coolapp-
echo  # Noop required
</code>```

Desired Output:

```<code>18:42 $ make -n deploy-staging
pip install --upgrade awsebcli
sed "s/<<ES_HOST>>/logging-ingest.staging.internal:80/" < 01-filebeat.template > .ebextensions/01-filebeat.config
sed "s/<<DOCKER_TAG>>/schultjo/" < Dockerrun.template | sed "s/<<CONTAINER_PORT>>/8000/" > Dockerrun.aws.json
eb labs cleanup-versions --num-to-leave 10 --older-than 5 --force -v --region us-west-2
eb deploy -v coolapp-staging
echo  # Noop required
</code>```

So I have tried to implement Renaud's recursive Make solution, but have run into a minor hiccup. Here's a simplified Makefile that I'm using:

```<code>ENVIRONMENT ?= $(USER)
ifeq ($ENVIRONMENT, production)
ENV_TYPE = production
else
ENV_TYPE = staging
endif
ES_HOST = logging-ingest.$(ENV_TYPE).internal:80

.PHONY: deploy
deploy:
    @echo $(ENVIRONMENT)
    @echo $(ENV_TYPE)
    @echo $(ES_HOST)

.PHONY: deploy-%
deploy-%:
    @$(MAKE) --no-print-directory ENVIRONMENT=$* deploy
</code>```

When I run make production, it looks like the if statements surrounding the ENV_TYPE definition are not run again. Here's my actual output:

```<code>12:50 $ make -n deploy-production
/Applications/Xcode.app/Contents/Developer/usr/bin/make --no-print-directory ENVIRONMENT=production deploy
echo production
echo staging
echo logging-ingest.staging.internal:80
</code>```

The last two lines should say production rather than staging, implying there is something wrong with my conditional, but I haven't edited that conditional from earlier versions when it worked, so I'm a but confused. The same error happens if I invoke make with ENVIRONMENT set manually (e.g. ENVIRONMENT=production make deploy).

答:
Your problem comes from the way target-specific variable values are inherited by target pre-requisites. What you are trying to do works for explicit target-specific variables:

```<code>$ cat Makefile
ENVIRONMENT = default

deploy:
    @echo '$@: ENVIRONMENT = $(ENVIRONMENT)'

deploy-foo: ENVIRONMENT = foo
deploy-foo: deploy
    @echo '$@: ENVIRONMENT = $(ENVIRONMENT)'
$ make deploy
deploy: ENVIRONMENT = default
$ make deploy-foo
deploy: ENVIRONMENT = foo
deploy-foo: ENVIRONMENT = foo
</code>```

because the deploy-foo-specific ENVIRONMENT variable is assigned value foo during the first expansion phase (the one during which target-specific variable assignments, target lists and pre-requisite lists are expanded). So, deploy inherits this value.

But it does not work with your pattern-specific variables that use the $* automatic variable:

```<code>$ cat Makefile
ENVIRONMENT = default

deploy:
    @echo '$@: ENVIRONMENT = $(ENVIRONMENT)'

deploy-%: ENVIRONMENT = $*
deploy-%: deploy
    @echo '$@: ENVIRONMENT = $(ENVIRONMENT)'
$ make deploy
$ deploy: ENVIRONMENT = default
$ make deploy-foo
deploy: ENVIRONMENT =
deploy-foo: ENVIRONMENT = foo
</code>```

The reason is that the deploy-foo-specific ENVIRONMENT variable is what is called a recursively expanded variable in make dialect (because you use the = assignment operator). It is expanded, recursively, but only when make needs its value, not when it is assigned. So, in the context of deploy-foo, it is assigned $*, not the pattern stem. ENVIRONMENT is passed as is to the context of the deploy pre-requisite and, in this context, $(ENVIRONMENT) is recursively expanded to $* and then to the empty string because there is no pattern in the deploy rule. You could try the simply expanded (non-recursive) variable flavour:

```<code>deploy-%: ENVIRONMENT := $*
</code>```

that is immediately expanded, but the result would be the same because $* expands as the empty string during the first expansion. It is set only during the second expansion and can thus be used only in recipes (that make expands in a second phase).

A simple (but not super-efficient) solution consists in invoking make again:

```<code>deploy-%:
    @$(MAKE) ENVIRONMENT=$* deploy
</code>```

Example:

```<code>$ cat Makefile
ENVIRONMENT = default

deploy:
    @echo '$(ENVIRONMENT)'

deploy-%:
    @$(MAKE) --no-print-directory ENVIRONMENT=$* deploy
$ make
default
$ make deploy
default
$ make deploy-foo
foo
</code>```

Note: GNU make supports a secondary expansion and one could think that it can be used to solve this problem. Unfortunately not: the secondary expansion expands only the pre-requisites, not the target-specific variable definitions.

As mentioned above, this recursive make is not very efficient. If efficiency is critical one single make invocation is preferable. And this can be done if you move all your variables processing in the recipe of a single pattern rule. Example if the shell that make uses is bash:

```<code>$ cat Makefile
deplo%:
    @{ [[ "$*" == "y" ]] && ENVIRONMENT=$(USER); } || \
    { [[ "$*" =~ y-(.*) ]] && ENVIRONMENT=$${BASH_REMATCH[1]}; } || \
    { echo "$@: unknown target" && exit 1; }; \
    echo "$@: ENVIRONMENT = $$ENVIRONMENT" && \
    <do-whatever-else-is-needed>
$ USER=bar make deploy
deploy: ENVIRONMENT = bar
$ make deploy-foo
deploy-foo: ENVIRONMENT = foo
$ make deplorable
deplorable: unknown target
make: *** [Makefile:2: deplorable] Error 1
</code>```

Do not forget to escape the recipe expansion by make ($$ENVIRONMENT).

Body:
I'm writing a Makefile to wrap the deployment of an elastic beanstalk app to multiple environments. This is my first time writing an "advanced" makefile and I'm having a bit of trouble.

My goals are as follows:

make deploy by itself should deploy with ENVIRONMENT=$(USER) and ENV_TYPE=staging.

The environment to deploy to can be set via an environment variable. If ENVIRONMENT=production then ENV_TYPE=production, otherwise ENV_TYPE=staging.

As a shorthand for setting the environment variable, one can suffix the deploy target with a - and the name of the environment. For example: make deploy-production.

It's number 3 that is giving me the most trouble. Since any environment not named production is of type staging, I tried to use pattern matching to define the target for deploying to staging environments. Here's what I have currently:

ENVIRONMENT = $(USER)
ifeq ($ENVIRONMENT, production)
ENV_TYPE=production
else
ENV_TYPE=staging
endif
DOCKER_TAG ?= $(USER)
CONTAINER_PORT ?= 8000
ES_HOST = logging-ingest.$(ENV_TYPE).internal:80

.PHONY: deploy
deploy:
    -pip install --upgrade awsebcli
    sed "s/<<ES_HOST>>/$(ES_HOST)/" < 01-filebeat.template > .ebextensions/01-filebeat.config
    sed "s/<<DOCKER_TAG>>/$(DOCKER_TAG)/" < Dockerrun.template | sed "s/<<CONTAINER_PORT>>/$(CONTAINER_PORT)/" > Dockerrun.aws.json
    eb labs cleanup-versions --num-to-leave 10 --older-than 5 --force -v --region us-west-2
    eb deploy -v coolapp-$(ENVIRONMENT)

.PHONY: deploy-%
deploy-%: ENVIRONMENT=$*
deploy-%: deploy
    @echo  # Noop required

.PHONY: deploy-production
deploy-production: ENVIRONMENT=production
deploy-production: ENV_TYPE=production
deploy-production: deploy
    @echo  # Noop required

The problem is in the last step of the deploy target. Namely, $(ENVIRONMENT) appears to be unset.

Example Output:

18:42 $ make -n deploy-staging
pip install --upgrade awsebcli
sed "s/<<ES_HOST>>/logging-ingest.staging.internal:80/" < 01-filebeat.template > .ebextensions/01-filebeat.config
sed "s/<<DOCKER_TAG>>/schultjo/" < Dockerrun.template | sed "s/<<CONTAINER_PORT>>/8000/" > Dockerrun.aws.json
eb labs cleanup-versions --num-to-leave 10 --older-than 5 --force -v --region us-west-2
eb deploy -v coolapp-
echo  # Noop required

Desired Output:

18:42 $ make -n deploy-staging
pip install --upgrade awsebcli
sed "s/<<ES_HOST>>/logging-ingest.staging.internal:80/" < 01-filebeat.template > .ebextensions/01-filebeat.config
sed "s/<<DOCKER_TAG>>/schultjo/" < Dockerrun.template | sed "s/<<CONTAINER_PORT>>/8000/" > Dockerrun.aws.json
eb labs cleanup-versions --num-to-leave 10 --older-than 5 --force -v --region us-west-2
eb deploy -v coolapp-staging
echo  # Noop required

So I have tried to implement Renaud's recursive Make solution, but have run into a minor hiccup. Here's a simplified Makefile that I'm using:

ENVIRONMENT ?= $(USER)
ifeq ($ENVIRONMENT, production)
ENV_TYPE = production
else
ENV_TYPE = staging
endif
ES_HOST = logging-ingest.$(ENV_TYPE).internal:80

.PHONY: deploy
deploy:
    @echo $(ENVIRONMENT)
    @echo $(ENV_TYPE)
    @echo $(ES_HOST)

.PHONY: deploy-%
deploy-%:
    @$(MAKE) --no-print-directory ENVIRONMENT=$* deploy

When I run make production, it looks like the if statements surrounding the ENV_TYPE definition are not run again. Here's my actual output:

12:50 $ make -n deploy-production
/Applications/Xcode.app/Contents/Developer/usr/bin/make --no-print-directory ENVIRONMENT=production deploy
echo production
echo staging
echo logging-ingest.staging.internal:80

The last two lines should say production rather than staging, implying there is something wrong with my conditional, but I haven't edited that conditional from earlier versions when it worked, so I'm a but confused. The same error happens if I invoke make with ENVIRONMENT set manually (e.g. ENVIRONMENT=production make deploy).

Body:
Your problem comes from the way target-specific variable values are inherited by target pre-requisites. What you are trying to do works for explicit target-specific variables:

$ cat Makefile
ENVIRONMENT = default

deploy:
    @echo '$@: ENVIRONMENT = $(ENVIRONMENT)'

deploy-foo: ENVIRONMENT = foo
deploy-foo: deploy
    @echo '$@: ENVIRONMENT = $(ENVIRONMENT)'
$ make deploy
deploy: ENVIRONMENT = default
$ make deploy-foo
deploy: ENVIRONMENT = foo
deploy-foo: ENVIRONMENT = foo

because the deploy-foo-specific ENVIRONMENT variable is assigned value foo during the first expansion phase (the one during which target-specific variable assignments, target lists and pre-requisite lists are expanded). So, deploy inherits this value.

But it does not work with your pattern-specific variables that use the $* automatic variable:

$ cat Makefile
ENVIRONMENT = default

deploy:
    @echo '$@: ENVIRONMENT = $(ENVIRONMENT)'

deploy-%: ENVIRONMENT = $*
deploy-%: deploy
    @echo '$@: ENVIRONMENT = $(ENVIRONMENT)'
$ make deploy
$ deploy: ENVIRONMENT = default
$ make deploy-foo
deploy: ENVIRONMENT =
deploy-foo: ENVIRONMENT = foo

The reason is that the deploy-foo-specific ENVIRONMENT variable is what is called a recursively expanded variable in make dialect (because you use the = assignment operator). It is expanded, recursively, but only when make needs its value, not when it is assigned. So, in the context of deploy-foo, it is assigned $*, not the pattern stem. ENVIRONMENT is passed as is to the context of the deploy pre-requisite and, in this context, $(ENVIRONMENT) is recursively expanded to $* and then to the empty string because there is no pattern in the deploy rule. You could try the simply expanded (non-recursive) variable flavour:

deploy-%: ENVIRONMENT := $*

that is immediately expanded, but the result would be the same because $* expands as the empty string during the first expansion. It is set only during the second expansion and can thus be used only in recipes (that make expands in a second phase).

A simple (but not super-efficient) solution consists in invoking make again:

deploy-%:
    @$(MAKE) ENVIRONMENT=$* deploy

Example:

$ cat Makefile
ENVIRONMENT = default

deploy:
    @echo '$(ENVIRONMENT)'

deploy-%:
    @$(MAKE) --no-print-directory ENVIRONMENT=$* deploy
$ make
default
$ make deploy
default
$ make deploy-foo
foo

Note: GNU make supports a secondary expansion and one could think that it can be used to solve this problem. Unfortunately not: the secondary expansion expands only the pre-requisites, not the target-specific variable definitions.

As mentioned above, this recursive make is not very efficient. If efficiency is critical one single make invocation is preferable. And this can be done if you move all your variables processing in the recipe of a single pattern rule. Example if the shell that make uses is bash:

$ cat Makefile
deplo%:
    @{ [[ "$*" == "y" ]] && ENVIRONMENT=$(USER); } || \
    { [[ "$*" =~ y-(.*) ]] && ENVIRONMENT=$${BASH_REMATCH[1]}; } || \
    { echo "$@: unknown target" && exit 1; }; \
    echo "$@: ENVIRONMENT = $$ENVIRONMENT" && \
    <do-whatever-else-is-needed>
$ USER=bar make deploy
deploy: ENVIRONMENT = bar
$ make deploy-foo
deploy-foo: ENVIRONMENT = foo
$ make deplorable
deplorable: unknown target
make: *** [Makefile:2: deplorable] Error 1

Do not forget to escape the recipe expansion by make ($$ENVIRONMENT).


来源: stackexchange

问:
Export Highchart to Excel using PHPExcel
I'm using codeigniter and some highchart on one report. And I need to export that report to excel using PHPExcel, but right now I still can't find any solution for this case

Is there's any information How To Export multiple highcharts on one excel file ?

答:
You can export Highchart as images. Visit https://www.highcharts.com/docs/export-module/export-module-overview

Use : $("#highchartDiv").highcharts().exportChart();

There are multiple options available to export Chart. Can be one of 'image/png', 'image/jpeg', 'application/pdf', or 'image/svg+xml'

You can also easily export multiple charts in one excel file.

ContentLicense: CC BY-SA 3.0


问:
How does one align a single row to the top in JQGrid?
JQGrid is awesome for displaying data with jQuery, but it doesn't exactly have great documentation.

I'm having a problem with the grid when the grid has only one element to display.  For some reason, it's aligning the single row to the bottom rather than to the top.

Here's a picture of a single misaligned row:

Here are the jqgrid options I'm passing in:

```<code>jQGridOptions = {
            "recordtext": '{0} - {1} of {2}',
            "url": 'data.json',
            'datatype': 'json',
            'mtype': 'GET',
            'colModel': [
                { 'name': 'Rank', 'align': 'center', 'index': 'Rank', 'sortable': false, 'search': false },
                { 'name': 'Name', 'index': 'Name', 'sortable': false, 'search': true },
                { 'name': 'Score', 'index': 'Score', 'sortable': false, 'search': false }
            ],
            'pager': '#ranking-pager',
            'rowNum': 10,
            'altRows': true,
            'scrollOffset': 0,
            'colNames': ["Rank", "Name", "Score"],
            'width': 696,
            'height': 'auto', // '100%',  // 300,
            'page': 1,
            'sortname': 'Rank',
            'sortorder': "asc",
            'hoverrows': true,
            'viewrecords': true,
            'gridComplete': function () {
                $('.ui-jqgrid-bdiv').jScrollPane({ showArrows: true, scrollbarWidth: 17, arrowSize: 17, scrollbarMargin: 0 });

                if (selectedRank !== -1) {
                    selectRank(selectedRank);
                    selectedRank = -1;
                }
            },
            'jsonReader': {
               id : 'Rank',
               'repeatitems': false
        }
    };
</code>```

As requested, here's the result from data.json:

```<code>{
    "page":1,
    "total":1,
    "records":1,
    "rows":  [{
                  "Name":"Gil Agostini",
                  "Score":94,
                  "Rank":1
             }]
}
</code>```

Call to jQGrid:

```<code>$(document).ready(function () {
        $("#ranking-table").jqGrid(jQGridOptions);
});
</code>```

Html:

```<code> <div style="float: left;">
                <div class="hvy-border1">
                    <div class="hvy-border2">
                        <div class="hvy-top-left hvy-corner">
                            <div>
                                <!-- -->
                            </div>
                        </div>
                        <div class="hvy-top-right hvy-corner">
                            <div>
                                <!-- -->
                            </div>
                        </div>
                        <div class="clear">
                            <!-- -->
                        </div>
                        <div id="table-and-pager" style="margin: 3px;">
                            <table id="ranking-table" class="scroll" cellpadding="0" cellspacing="0" style="height: 300px">
                            </table>
                            <div id="ranking-pager" class="scroll" style="text-align: center;">
                            </div>
                        </div>
                        <div class="clear">
                            <!-- -->
                        </div>
                        <div class="hvy-bottom-left hvy-corner">
                            <div>
                                <!-- -->
                            </div>
                        </div>
                        <div class="hvy-bottom-right hvy-corner">
                            <div>
                                <!-- -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
</code>```

Can anyone give me any clue what I maybe doing wrong here?

How do I get the row to align to the top rather than the bottom?

答:
I can not reproduce the problem which you describes. I suppose that you use some additional setting for jqGrid: you don't post the whole JavaScript code of your example.

Nevertheless I can definitively say that you has some problems in the format of the JSON data returned from the server. Important is that every row of data must has an unique id. For example

```<code>{ "id":123, "Name":"Gil Agostini", "Score":94, "Rank":1 }
</code>```

instead of

```<code>{ "Name":"Gil Agostini", "Score":94, "Rank":1 }
</code>```

The id can has also string type and not be only numeric. Moreover you have to define jsonReader parameter of jqGrid, because your data has named elements instead of the standard array of strings (which is more compact and small data). In the case you should at least use jsonReader: {repeatitems: false}.

If some other grid column (like the Name column) can be interpret as the id, you can either include key:true in the corresponding column definition or use id:'Name' as a property of the jsonReader.

For example the following jsonReader

```<code>jsonReader: {
    repeatitems: false,
    id: 'Name'
}
</code>```

can be used to read your current JSON data (see live here). Using any tool which you prefer you can verify the id value of the
 element of the grid.

ContentLicense: CC BY-SA 2.5

Body:
JQGrid is awesome for displaying data with jQuery, but it doesn't exactly have great documentation.

I'm having a problem with the grid when the grid has only one element to display.  For some reason, it's aligning the single row to the bottom rather than to the top.

Here's a picture of a single misaligned row:

Here are the jqgrid options I'm passing in:

jQGridOptions = {
            "recordtext": '{0} - {1} of {2}',
            "url": 'data.json',
            'datatype': 'json',
            'mtype': 'GET',
            'colModel': [
                { 'name': 'Rank', 'align': 'center', 'index': 'Rank', 'sortable': false, 'search': false },
                { 'name': 'Name', 'index': 'Name', 'sortable': false, 'search': true },
                { 'name': 'Score', 'index': 'Score', 'sortable': false, 'search': false }
            ],
            'pager': '#ranking-pager',
            'rowNum': 10,
            'altRows': true,
            'scrollOffset': 0,
            'colNames': ["Rank", "Name", "Score"],
            'width': 696,
            'height': 'auto', // '100%',  // 300,
            'page': 1,
            'sortname': 'Rank',
            'sortorder': "asc",
            'hoverrows': true,
            'viewrecords': true,
            'gridComplete': function () {
                $('.ui-jqgrid-bdiv').jScrollPane({ showArrows: true, scrollbarWidth: 17, arrowSize: 17, scrollbarMargin: 0 });

                if (selectedRank !== -1) {
                    selectRank(selectedRank);
                    selectedRank = -1;
                }
            },
            'jsonReader': {
               id : 'Rank',
               'repeatitems': false
        }
    };

As requested, here's the result from data.json:

{
    "page":1,
    "total":1,
    "records":1,
    "rows":  [{
                  "Name":"Gil Agostini",
                  "Score":94,
                  "Rank":1
             }]
}

Call to jQGrid:

$(document).ready(function () {
        $("#ranking-table").jqGrid(jQGridOptions);
});

Html:

Can anyone give me any clue what I maybe doing wrong here?

How do I get the row to align to the top rather than the bottom?

Body:
I can not reproduce the problem which you describes. I suppose that you use some additional setting for jqGrid: you don't post the whole JavaScript code of your example.

Nevertheless I can definitively say that you has some problems in the format of the JSON data returned from the server. Important is that every row of data must has an unique id. For example

{ "id":123, "Name":"Gil Agostini", "Score":94, "Rank":1 }

instead of

{ "Name":"Gil Agostini", "Score":94, "Rank":1 }

The id can has also string type and not be only numeric. Moreover you have to define jsonReader parameter of jqGrid, because your data has named elements instead of the standard array of strings (which is more compact and small data). In the case you should at least use jsonReader: {repeatitems: false}.

If some other grid column (like the Name column) can be interpret as the id, you can either include key:true in the corresponding column definition or use id:'Name' as a property of the jsonReader.

For example the following jsonReader

jsonReader: {
    repeatitems: false,
    id: 'Name'
}

can be used to read your current JSON data (see live here). Using any tool which you prefer you can verify the id value of the <tr> element of the grid.


问:
Add left and right bar button item in category of navigation controller class
i have create a category of navigation controller and set title and left and right bar button in view did load of this navigation controller class (category of this class).

```<code>- (void)viewDidAppear:(BOOL)animated
{

        NSArray *ver = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
        if ([[ver objectAtIndex:0] intValue] >= 7) {
            self.navigationBar.barTintColor = [UIColor colorWithRed:229.0f/255.0f green:114.0f/255.0f blue:89.0f/255.0f alpha:1.0f];
            self.navigationBar.translucent = NO;
        }else{
            self.navigationBar.tintColor = [UIColor colorWithRed:229.0f/255.0f green:114.0f/255.0f blue:89.0f/255.0f alpha:1.0f];
        }

        UILabel *lblTitleView=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 170, 44)];
        [lblTitleView setTextColor:[UIColor whiteColor]];
        [lblTitleView setFont:[UIFont boldSystemFontOfSize:17]];
        [lblTitleView setText:[self SetnavigationTitle:self.navigationItem.title]];
        [lblTitleView setTextAlignment:NSTextAlignmentCenter];
        [lblTitleView setBackgroundColor:[UIColor clearColor]];
        [self.navigationItem setTitleView:lblTitleView];

       // UINavigationController*navCnt = [[UINavigationController alloc] init];

      UIButton *btnLeft=[UIButton buttonWithType:UIButtonTypeCustom];
        [btnLeft setFrame:CGRectMake(0, 5, 32, 32)];
        [btnLeft setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateNormal];
        [btnLeft setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateHighlighted];
         [btnLeft setTitle:[NSString stringWithFormat:@"%@",[self SetleftbarbuttonTitle:self.navigationItem.leftBarButtonItem.title]] forState:UIControlStateNormal];
        [btnLeft setTintColor:[UIColor grayColor]];
        [btnLeft setBackgroundColor:[UIColor greenColor]];

        [btnLeft setTag:101];
        [btnLeft addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftBarButton=[[UIBarButtonItem alloc]initWithCustomView:btnLeft];
        [self.navigationItem  setLeftBarButtonItem:leftBarButton];
        self.navigationItem.hidesBackButton=YES;

       UIButton *btnRight=[UIButton buttonWithType:UIButtonTypeCustom];
        [btnRight setFrame:CGRectMake(270, 5, 32, 32)];
        [btnRight setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateNormal];
        [btnRight setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateHighlighted];
        [btnRight setTitle:[NSString stringWithFormat:@"%@",[self SetRightbarbuttonTitle:self.navigationItem.rightBarButtonItem.title]] forState:UIControlStateNormal];
        [btnRight setTintColor:[UIColor clearColor]];
        [btnRight setBackgroundColor:[UIColor greenColor]];

         [btnRight setTag:102];
        [btnRight addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightBarButton=[[UIBarButtonItem alloc]initWithCustomView:btnRight];

        [self.navigationItem setRightBarButtonItem:rightBarButton];

        [super viewDidAppear:animated];

}
</code>```

when i just pass title from any view controller then its work fine for each view controller but
now i have code for set both left and right bar button item in navigation controller sub class.

but now on the view controller i am not getting the uibar button item of navigation controller on this view controller.
 thanks in advance.

答:
Swift 4.0

```<code>let btnBack = UIButton(type: .custom)
btnBack.bounds = CGRect(x: 0, y: 0, width: 44, height: 44)
btnBack.addTarget(self, action: #selector(self.backButtonAction(sender:)), for: .touchUpInside)
btnBack.setImage(#imageLiteral(resourceName: "back_image"), for: .normal)

let leftBarButton = UIBarButtonItem(customView: btnBack)
self.navigationItem.setLeftBarButton(leftBarButton, animated: true)
</code>```

// Back Button Action

```<code>@objc func backButtonAction(sender: UIButton) {
    self.navigationController?.popViewController(animated: true)
}
</code>```

Body:
i have create a category of navigation controller and set title and left and right bar button in view did load of this navigation controller class (category of this class).

- (void)viewDidAppear:(BOOL)animated
{

        NSArray *ver = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
        if ([[ver objectAtIndex:0] intValue] >= 7) {
            self.navigationBar.barTintColor = [UIColor colorWithRed:229.0f/255.0f green:114.0f/255.0f blue:89.0f/255.0f alpha:1.0f];
            self.navigationBar.translucent = NO;
        }else{
            self.navigationBar.tintColor = [UIColor colorWithRed:229.0f/255.0f green:114.0f/255.0f blue:89.0f/255.0f alpha:1.0f];
        }

        UILabel *lblTitleView=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 170, 44)];
        [lblTitleView setTextColor:[UIColor whiteColor]];
        [lblTitleView setFont:[UIFont boldSystemFontOfSize:17]];
        [lblTitleView setText:[self SetnavigationTitle:self.navigationItem.title]];
        [lblTitleView setTextAlignment:NSTextAlignmentCenter];
        [lblTitleView setBackgroundColor:[UIColor clearColor]];
        [self.navigationItem setTitleView:lblTitleView];

       // UINavigationController*navCnt = [[UINavigationController alloc] init];

      UIButton *btnLeft=[UIButton buttonWithType:UIButtonTypeCustom];
        [btnLeft setFrame:CGRectMake(0, 5, 32, 32)];
        [btnLeft setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateNormal];
        [btnLeft setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateHighlighted];
         [btnLeft setTitle:[NSString stringWithFormat:@"%@",[self SetleftbarbuttonTitle:self.navigationItem.leftBarButtonItem.title]] forState:UIControlStateNormal];
        [btnLeft setTintColor:[UIColor grayColor]];
        [btnLeft setBackgroundColor:[UIColor greenColor]];

        [btnLeft setTag:101];
        [btnLeft addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftBarButton=[[UIBarButtonItem alloc]initWithCustomView:btnLeft];
        [self.navigationItem  setLeftBarButtonItem:leftBarButton];
        self.navigationItem.hidesBackButton=YES;

       UIButton *btnRight=[UIButton buttonWithType:UIButtonTypeCustom];
        [btnRight setFrame:CGRectMake(270, 5, 32, 32)];
        [btnRight setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateNormal];
        [btnRight setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateHighlighted];
        [btnRight setTitle:[NSString stringWithFormat:@"%@",[self SetRightbarbuttonTitle:self.navigationItem.rightBarButtonItem.title]] forState:UIControlStateNormal];
        [btnRight setTintColor:[UIColor clearColor]];
        [btnRight setBackgroundColor:[UIColor greenColor]];

         [btnRight setTag:102];
        [btnRight addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightBarButton=[[UIBarButtonItem alloc]initWithCustomView:btnRight];

        [self.navigationItem setRightBarButtonItem:rightBarButton];

        [super viewDidAppear:animated];

}

when i just pass title from any view controller then its work fine for each view controller but
now i have code for set both left and right bar button item in navigation controller sub class.

but now on the view controller i am not getting the uibar button item of navigation controller on this view controller.
 thanks in advance.

Body:
Swift 4.0

let btnBack = UIButton(type: .custom)
btnBack.bounds = CGRect(x: 0, y: 0, width: 44, height: 44)
btnBack.addTarget(self, action: #selector(self.backButtonAction(sender:)), for: .touchUpInside)
btnBack.setImage(#imageLiteral(resourceName: "back_image"), for: .normal)

let leftBarButton = UIBarButtonItem(customView: btnBack)
self.navigationItem.setLeftBarButton(leftBarButton, animated: true)

// Back Button Action

@objc func backButtonAction(sender: UIButton) {
    self.navigationController?.popViewController(animated: true)
}


问:
SCWaveFormView does not show waveform
I am developing an iOS app, in objective c.

Where I am using SCWaveFormView, here is a github link

to draw a waveform from an audio file.

My problem is when I run the example code SCWaveFormView works. But when I include this library in my project waveform does not work

Steps I perform to include this library is

Copying the SCWaveFormView files, and add in my project

Initializing/allocating the waveform and set initial parameters

Load the asset/audio file

When I debug all SCWaveFormView code executes correctly, even I can see variable values seem correct.

In SCWaveFormView sample project It works, what should I need to check to work in my project. What could be the problem.

答:
Thanks,

I do have problem related to file import.

I changed

lineWidthRatio to 1

or other value and it works for me.

Title: SCWaveFormView does not show waveform


问:
Microsoft Authentication in ASP.NET Core 2 and Azure App Services
I have the following application at GitHub and have deployed it to https://stratml.services on an Azure App Service with Authentication defined as Microsoft Account with anymous requests requiring a Microsoft Account sign in. In "prod" this challenge occurs, however https://stratml.services/Home/IdentityName returns no content.

I have been following this and this however I do not want to use EntityFramework and from the latter's description it seems to imply if I configure my Authentication scheme correctly I do not have to.

This following code is in my Start class:

```<code>        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = MicrosoftAccountDefaults.AuthenticationScheme;
        }).AddMicrosoftAccount(microsoftOptions =>
        {
            microsoftOptions.ClientId = Configuration["Authentication:AppId"];
            microsoftOptions.ClientSecret = Configuration["Authentication:Key"];
            microsoftOptions.CallbackPath = new PathString("/.auth/login/microsoftaccount/callback");

        });
</code>```

Update: Thanks to the first answer I was able to get, it now authorizes to Microsoft and attempts to feedback to my application however I receive the following error:

```<code>InvalidOperationException: No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Cookies
</code>```

Please visit https://stratml.services/Home/IdentityName and the GitHub has been updated.

```<code>        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = MicrosoftAccountDefaults.AuthenticationScheme;
        }).AddCookie(option =>
        {
            option.Cookie.Name = ".myAuth"; //optional setting
        }).AddMicrosoftAccount(microsoftOptions =>
        {
            microsoftOptions.ClientId = Configuration["Authentication:AppId"];
            microsoftOptions.ClientSecret = Configuration["Authentication:Key"];

        });
</code>```

答:
I have checked this issue on my side, based on my test, you could confgure your settings as follows:

Under the ConfigureServices method, add the cookie and MSA authentication services.

```<code>services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = MicrosoftAccountDefaults.AuthenticationScheme;
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(option =>
{
    option.Cookie.Name = ".myAuth"; //optional setting
})
.AddMicrosoftAccount(microsoftOptions =>
{
    microsoftOptions.ClientId = Configuration["Authentication:AppId"];
    microsoftOptions.ClientSecret = Configuration["Authentication:Key"];
});
</code>```

Under the Configure method, add app.UseAuthentication().

TEST:

```<code>[Authorize]
public IActionResult Index()
{
    return Content(this.User.Identity.Name);
}
</code>```

When I checking your online website, I found that you are using the Authentication and authorization in Azure App Service and Authenticate with Microsoft account.

AFAIK, when using the app service authentication, the claims could not be attached to current user, you could retrieve the identity name via Request.Headers["X-MS-CLIENT-PRINCIPAL-NAME"] or you could follow this similar issue to manually attach all claims for current user.

In general, you could either manually enable authentication middle-ware in your application or just leverage the app service authentication provided by Azure without changing your code for enabling authentication. Moreover, you could Remote debugging web apps to troubleshoot with your application.

UPDATE:

For enable the MSA authentication in my code and test it when deployed to azure, I disabled the App Service Authentication, then deployed my application to azure web app. I opened a new incognito window and found that my web app could work as expected.

If you want to simulate the MSA login locally and use Easy Auth when deployed to azure, I assumed that you could set a setting value in appsettings.json and manually add the authentication middle-ware for dev and override the setting on azure, details you could follow here. And you could use the same application Id and configure the following redirect urls:

```<code>https://stratml.services/.auth/login/microsoftaccount/callback //for easy auth
https://localhost:44337/signin-microsoft //manually MSA authentication for dev locally
</code>```

Moreover, you could follow this issue to manually attach all claims for current user. Then you could retrieve the user claims in the same way for the manually MSA authentication and Easy Auth.

Body:
I have the following application at GitHub and have deployed it to https://stratml.services on an Azure App Service with Authentication defined as Microsoft Account with anymous requests requiring a Microsoft Account sign in. In "prod" this challenge occurs, however https://stratml.services/Home/IdentityName returns no content.

I have been following this and this however I do not want to use EntityFramework and from the latter's description it seems to imply if I configure my Authentication scheme correctly I do not have to.

This following code is in my Start class:

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = MicrosoftAccountDefaults.AuthenticationScheme;
        }).AddMicrosoftAccount(microsoftOptions =>
        {
            microsoftOptions.ClientId = Configuration["Authentication:AppId"];
            microsoftOptions.ClientSecret = Configuration["Authentication:Key"];
            microsoftOptions.CallbackPath = new PathString("/.auth/login/microsoftaccount/callback");

        });

Update: Thanks to the first answer I was able to get, it now authorizes to Microsoft and attempts to feedback to my application however I receive the following error:

InvalidOperationException: No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Cookies

Please visit https://stratml.services/Home/IdentityName and the GitHub has been updated.

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = MicrosoftAccountDefaults.AuthenticationScheme;
        }).AddCookie(option =>
        {
            option.Cookie.Name = ".myAuth"; //optional setting
        }).AddMicrosoftAccount(microsoftOptions =>
        {
            microsoftOptions.ClientId = Configuration["Authentication:AppId"];
            microsoftOptions.ClientSecret = Configuration["Authentication:Key"];

        });

Body:
I have checked this issue on my side, based on my test, you could confgure your settings as follows:

Under the ConfigureServices method, add the cookie and MSA authentication services.

services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = MicrosoftAccountDefaults.AuthenticationScheme;
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(option =>
{
    option.Cookie.Name = ".myAuth"; //optional setting
})
.AddMicrosoftAccount(microsoftOptions =>
{
    microsoftOptions.ClientId = Configuration["Authentication:AppId"];
    microsoftOptions.ClientSecret = Configuration["Authentication:Key"];
});

Under the Configure method, add app.UseAuthentication().

TEST:

[Authorize]
public IActionResult Index()
{
    return Content(this.User.Identity.Name);
}

When I checking your online website, I found that you are using the Authentication and authorization in Azure App Service and Authenticate with Microsoft account.

AFAIK, when using the app service authentication, the claims could not be attached to current user, you could retrieve the identity name via Request.Headers["X-MS-CLIENT-PRINCIPAL-NAME"] or you could follow this similar issue to manually attach all claims for current user.

In general, you could either manually enable authentication middle-ware in your application or just leverage the app service authentication provided by Azure without changing your code for enabling authentication. Moreover, you could Remote debugging web apps to troubleshoot with your application.

UPDATE:

For enable the MSA authentication in my code and test it when deployed to azure, I disabled the App Service Authentication, then deployed my application to azure web app. I opened a new incognito window and found that my web app could work as expected.

If you want to simulate the MSA login locally and use Easy Auth when deployed to azure, I assumed that you could set a setting value in appsettings.json and manually add the authentication middle-ware for dev and override the setting on azure, details you could follow here. And you could use the same application Id and configure the following redirect urls:

https://stratml.services/.auth/login/microsoftaccount/callback //for easy auth
https://localhost:44337/signin-microsoft //manually MSA authentication for dev locally

Moreover, you could follow this issue to manually attach all claims for current user. Then you could retrieve the user claims in the same way for the manually MSA authentication and Easy Auth.


问:
Remove sticky class while scrolling down?
Here is my jQuery code for removing sticky class while scrolling down.

```<code>$(window).scroll(function (e) {
    if ($('.main_form_wrapper').length != 0) {
        var window_scroll = $(window).scrollTop();
        console.log(window_scroll, "window scroll")
        var bottom_position = window_scroll + $('.main_form_wrapper').outerHeight(true);
        console.log(bottom_position, "form_position for footer")
        var form_top_offset = $('.main_form_wrapper').offset().top;
        console.log(form_top_offset, "form top offset")
        var footer_top_offset = $('.top_footer').offset().top;
        console.log(footer_top_offset,"footer top offset")
        if (window_scroll > form_top_offset &&  bottom_position < footer_top_offset) {
            $(".main_form_wrapper").addClass('sticky');
        } else {
            console.log('here')
            $(".main_form_wrapper").removeClass('sticky');
        }
    }
});
</code>```

please help anyone knows about it.

答:
It's for 95% a duplicate of Detecting scroll direction

I took the time to create an example for you. I think the main point you where missing is you need to store the last scroll position to know if user is scrolling up or down the page. As simple as this:

var lastScrollTop = 0;
var theWrap = $('.wrap');
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       // downscroll code
       theWrap.removeClass('sticky');
   } else {
      // upscroll code
       theWrap.addClass('sticky');
   }
   lastScrollTop = st;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrap {
  width: 100px;
  height: 2000px;
  background-color: orange;
}
.wrap.sticky {
  background-color: green;
}</code>```

```

Body:
Here is my jQuery code for removing sticky class while scrolling down.

$(window).scroll(function (e) {
    if ($('.main_form_wrapper').length != 0) {
        var window_scroll = $(window).scrollTop();
        console.log(window_scroll, "window scroll")
        var bottom_position = window_scroll + $('.main_form_wrapper').outerHeight(true);
        console.log(bottom_position, "form_position for footer")
        var form_top_offset = $('.main_form_wrapper').offset().top;
        console.log(form_top_offset, "form top offset")
        var footer_top_offset = $('.top_footer').offset().top;
        console.log(footer_top_offset,"footer top offset")
        if (window_scroll > form_top_offset &&  bottom_position < footer_top_offset) {
            $(".main_form_wrapper").addClass('sticky');
        } else {
            console.log('here')
            $(".main_form_wrapper").removeClass('sticky');
        }
    }
});

please help anyone knows about it.

Body:
It's for 95% a duplicate of Detecting scroll direction

I took the time to create an example for you. I think the main point you where missing is you need to store the last scroll position to know if user is scrolling up or down the page. As simple as this:

var lastScrollTop = 0;
var theWrap = $('.wrap');
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       // downscroll code
       theWrap.removeClass('sticky');
   } else {
      // upscroll code
       theWrap.addClass('sticky');
   }
   lastScrollTop = st;
});

.wrap {
  width: 100px;
  height: 2000px;
  background-color: orange;
}
.wrap.sticky {
  background-color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap sticky">

</div>


问:
Google Directions API
In the JSON output, there is a field "maneuver" within a "step".  In this "turn-left", "turn-right", "turn-slight-left", etc. Example is here

Where could I find the definition of the "maneuver" field, and the list of possible values?  There is no relevant description here

Thanks in advance

答:
Maneuver contains the action to take for the current step (turn left, merge, straight, etc.). This field is used to determine which icon to display, and can contain one of the following values: turn-slight-left, turn-sharp-left, uturn-left, turn-left, turn-slight-right, turn-sharp-right, uturn-right, turn-right, straight, ramp-left, ramp-right, merge, fork-left, fork-right, ferry, ferry-train, roundabout-left, roundabout-right. Values in this list are subject to change

Below link will help you to find all the images
https://github.com/opentripplanner/OpenTripPlanner/tree/master/src/client/images/directions

Title: Google Directions API


问:
How to make picker view to display from a particular row in swift 3?
How to make picker view to display from default country but it is displaying from first but I need it from default country that is united states but here it is showing from first country but I need it to display from United States can anyone help me how to implement this ?

here are the images shown below here picker view displaying from first country but I need it to display from United States because it is my default selected country

```<code>func countryListDownloadJsonwithURL(countryAPI: String) {
        let url = NSURL(string: countryAPI)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String:Any]] {
                for item in jsonObj! {
                    let dict = Country(dict: item)
                    self.countryArray.append(dict)
                }
                print(self.countryArray)
                OperationQueue.main.addOperation({
                     self.countryPickerView.selectRow(self.i, inComponent: 0, animated: true)
                     self.countryPickerView.reloadAllComponents()
                     self.statePickerView.reloadAllComponents()
                })
            }
        }).resume()
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int{
        if pickerView.tag == 1 {
            return 1
        }else {
            return 1
        }
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        if pickerView.tag == 1 {
            return countryArray.count
        }
        else {
            return countryArray[countrySelectedIndex!].state.count
        }
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 1 {
            return countryArray[row].country
        }
        else {
            return countryArray[countrySelectedIndex!].state[row].state
        }
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if pickerView.tag == 1 {
            countryTextField.text = countryArray[row].country
            for item in countryArray {
                print(item.country)
                print(countryArray[row].country)
                if item.country == countryArray[row].country {
                    self.countryId = item.countryId
                    if item.state.count == 0 {
                        self.stateTextfield.isHidden = false
                        self.stateLabel.isHidden = true
                        self.selectedCountryTextField.isHidden = true
                        self.imageArrow.isHidden = true
                        break
                    }
                    else {
                        if let i = countryArray.index(where: { $0.country == countryArray[row].country }) {
                            countrySelectedIndex = i
                        }
                        self.countryId = item.countryId
                        if self.countryId?.isEmpty == true {
                            self.countryId = countryTextField.text
                        }
                        UserDefaults.standard.set(self.countryId, forKey: "guestCountryId")
                        self.statePickerView.delegate = self
                        self.statePickerView.dataSource = self
                        selectedCountryTextField.inputView = statePickerView
                        self.statePickerView.reloadAllComponents()
                        selectedCountryTextField.text = "Select state/province"
                        self.stateLabel.isHidden = false
                        self.stateTextfield.isHidden = true
                        self.selectedCountryTextField.isHidden = false
                        self.imageArrow.isHidden = false
                        break
                    }
                }
                else {
                    self.stateTextfield.isHidden = false
                    self.stateLabel.isHidden = true
                    self.selectedCountryTextField.isHidden = true
                    self.imageArrow.isHidden = true
                }
            }
        }
        else {
            self.selectedCountryTextField.text = countryArray[countrySelectedIndex!].state[row].state
            self.stateCode = countryArray[countrySelectedIndex!].state[row].stateValue as! Int
            print(self.stateCode)
            UserDefaults.standard.set(self.stateCode, forKey: "statecode")
        }
    }
</code>```

答:
you can use ActionSheetPicker which in fact reduces the code of all picker methods & you can get your selected country as default in picker view using else condition

```<code>if txtCountry.text == ""
    {
        let countryPicker = ActionSheetStringPicker(title: "Select a country", rows: pickerData, initialSelection: 0, doneBlock: { (pickerSheet, selectedIndex, selectedValue) in
            self.txtCountry.text = selectedValue! as? String
            self.selectedCountry = selectedIndex
        }, cancel: {pickerSheet in return }, origin: (sender as AnyObject).superview!)
        countryPicker?.show();
    }
    else
    {
        let countryPicker = ActionSheetStringPicker(title: "Select a country", rows: pickerData, initialSelection: selectedCountry, doneBlock: { (pickerSheet, selectedIndex, selectedValue) in
            self.txtCountry.text = selectedValue! as? String
            self.selectedCountry = selectedIndex

        }, cancel: {pickerSheet in return }, origin: (sender as AnyObject).superview!)
        countryPicker?.show();
    }
</code>```

Here  self.selectedCountry = selectedIndex helps you to manage selectedCountry Index dynamically

Body:
How to make picker view to display from default country but it is displaying from first but I need it from default country that is united states but here it is showing from first country but I need it to display from United States can anyone help me how to implement this ?

here are the images shown below here picker view displaying from first country but I need it to display from United States because it is my default selected country

func countryListDownloadJsonwithURL(countryAPI: String) {
        let url = NSURL(string: countryAPI)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String:Any]] {
                for item in jsonObj! {
                    let dict = Country(dict: item)
                    self.countryArray.append(dict)
                }
                print(self.countryArray)
                OperationQueue.main.addOperation({
                     self.countryPickerView.selectRow(self.i, inComponent: 0, animated: true)
                     self.countryPickerView.reloadAllComponents()
                     self.statePickerView.reloadAllComponents()
                })
            }
        }).resume()
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int{
        if pickerView.tag == 1 {
            return 1
        }else {
            return 1
        }
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        if pickerView.tag == 1 {
            return countryArray.count
        }
        else {
            return countryArray[countrySelectedIndex!].state.count
        }
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 1 {
            return countryArray[row].country
        }
        else {
            return countryArray[countrySelectedIndex!].state[row].state
        }
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if pickerView.tag == 1 {
            countryTextField.text = countryArray[row].country
            for item in countryArray {
                print(item.country)
                print(countryArray[row].country)
                if item.country == countryArray[row].country {
                    self.countryId = item.countryId
                    if item.state.count == 0 {
                        self.stateTextfield.isHidden = false
                        self.stateLabel.isHidden = true
                        self.selectedCountryTextField.isHidden = true
                        self.imageArrow.isHidden = true
                        break
                    }
                    else {
                        if let i = countryArray.index(where: { $0.country == countryArray[row].country }) {
                            countrySelectedIndex = i
                        }
                        self.countryId = item.countryId
                        if self.countryId?.isEmpty == true {
                            self.countryId = countryTextField.text
                        }
                        UserDefaults.standard.set(self.countryId, forKey: "guestCountryId")
                        self.statePickerView.delegate = self
                        self.statePickerView.dataSource = self
                        selectedCountryTextField.inputView = statePickerView
                        self.statePickerView.reloadAllComponents()
                        selectedCountryTextField.text = "Select state/province"
                        self.stateLabel.isHidden = false
                        self.stateTextfield.isHidden = true
                        self.selectedCountryTextField.isHidden = false
                        self.imageArrow.isHidden = false
                        break
                    }
                }
                else {
                    self.stateTextfield.isHidden = false
                    self.stateLabel.isHidden = true
                    self.selectedCountryTextField.isHidden = true
                    self.imageArrow.isHidden = true
                }
            }
        }
        else {
            self.selectedCountryTextField.text = countryArray[countrySelectedIndex!].state[row].state
            self.stateCode = countryArray[countrySelectedIndex!].state[row].stateValue as! Int
            print(self.stateCode)
            UserDefaults.standard.set(self.stateCode, forKey: "statecode")
        }
    }

Body:
you can use ActionSheetPicker which in fact reduces the code of all picker methods & you can get your selected country as default in picker view using else condition

if txtCountry.text == ""
    {
        let countryPicker = ActionSheetStringPicker(title: "Select a country", rows: pickerData, initialSelection: 0, doneBlock: { (pickerSheet, selectedIndex, selectedValue) in
            self.txtCountry.text = selectedValue! as? String
            self.selectedCountry = selectedIndex
        }, cancel: {pickerSheet in return }, origin: (sender as AnyObject).superview!)
        countryPicker?.show();
    }
    else
    {
        let countryPicker = ActionSheetStringPicker(title: "Select a country", rows: pickerData, initialSelection: selectedCountry, doneBlock: { (pickerSheet, selectedIndex, selectedValue) in
            self.txtCountry.text = selectedValue! as? String
            self.selectedCountry = selectedIndex

        }, cancel: {pickerSheet in return }, origin: (sender as AnyObject).superview!)
        countryPicker?.show();
    }

Here  self.selectedCountry = selectedIndex helps you to manage selectedCountry Index dynamically


问:
How to remove part of file between two line delimiter values in Scala Spark?
I have text as below,

```<code>TIME STAMP1
   A1200 EVENT START
   EVENT NAME          = DOS
   EVENT_INS       = 1
   EVENT_ID       = 100
   BUFFER             = 233355
   FORMAT           = ATC
   LOC              = C:/User/data
;
TIME STAMP2
   A1201 EVENT START
   EVENT NAME          = DOS
   EVENT_INS       = 0
   EVENT_ID       = 87
   BUFFER             = 773355
   FORMAT           = ETC
   LOC              = C:/User/data
;
</code>```

how can I remove TIME STAMP2 based on A1201,need to remove from A1201 to ; using scala.A1201 sensor part will repeat at different location in the file. Wherever it comes, I need to remove from A1201 to ;..

How can I do with Scala Spark ?.

答:
You can use the following simple solution

```<code>val rdd = sparkContext.wholeTextFiles("path to the text file")
rdd.map(x => x._2.replace("\n", "|*|").split(";").filter(!_.contains("A1201")).mkString(";").replace("|*|", "\n")+";")
</code>```

where,
 wholeTextFiles would read the file in Tuple2 format with filename as first argument and text data as the second argument

x._2.replace("\n", "|*|") replaces the line feeds with special character which is to be used later

.split(";") splits the text at ; and forms array

.filter(!_.contains("A1201")) filters out all text from  A1201 to ;

.mkString(";").replace("|*|", "\n")+";" converts the array of string to original format.

I hope the answer is helpful

ContentLicense: CC BY-SA 4.0

Body:
I have text as below,

TIME STAMP1
   A1200 EVENT START
   EVENT NAME          = DOS
   EVENT_INS       = 1
   EVENT_ID       = 100
   BUFFER             = 233355
   FORMAT           = ATC
   LOC              = C:/User/data
;
TIME STAMP2
   A1201 EVENT START
   EVENT NAME          = DOS
   EVENT_INS       = 0
   EVENT_ID       = 87
   BUFFER             = 773355
   FORMAT           = ETC
   LOC              = C:/User/data
;

how can I remove TIME STAMP2 based on A1201,need to remove from A1201 to ; using scala.A1201 sensor part will repeat at different location in the file. Wherever it comes, I need to remove from A1201 to ;..

How can I do with Scala Spark ?.

Body:
You can use the following simple solution

val rdd = sparkContext.wholeTextFiles("path to the text file")
rdd.map(x => x._2.replace("\n", "|*|").split(";").filter(!_.contains("A1201")).mkString(";").replace("|*|", "\n")+";")

where,
 wholeTextFiles would read the file in Tuple2 format with filename as first argument and text data as the second argument

x._2.replace("\n", "|*|") replaces the line feeds with special character which is to be used later

.split(";") splits the text at ; and forms array

.filter(!_.contains("A1201")) filters out all text from  A1201 to ;

.mkString(";").replace("|*|", "\n")+";" converts the array of string to original format.

I hope the answer is helpful


问:
How to resize image without loosing image content
I want to resize an image to a smaller image like thumbnail. I have used following options

```<code>Bitmap imageBitmap = Bitmap.createScaledBitmap(mBitmap, 200, 700, false);
</code>```

and

```<code>ThumbnailUtils.extractThumbnail()
</code>```

Both of these options cut parts of images. So they don't look good. I just want to reduce image dimensions and don't want to loose image content.

答:
```<code>    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    Bitmap bitmap = BitmapFactory.decodeFile(filepath,bmOptions);

   //Part 1 :withcompression Sacle image 200 pixels x 700 pixels this size you can customize as per your requirement

   Bitmap withCompressed = Bitmap.createScaledBitmap(bitmap,200,700,true);
</code>```

Body:
I want to resize an image to a smaller image like thumbnail. I have used following options

Bitmap imageBitmap = Bitmap.createScaledBitmap(mBitmap, 200, 700, false);

and

ThumbnailUtils.extractThumbnail()

Both of these options cut parts of images. So they don't look good. I just want to reduce image dimensions and don't want to loose image content.


问:
I need to export a single WordPress post or page with images and attachments included, and import into a different site
I need to export a single WordPress post or page with images and attachments included, and import into a different site.

I have tried the standard WordPress Export/Import feature, but it outputs XML with no images or attachments.

The desired result is the page I need to Export/Import, will import to the new site, with all of the content intact, including images and attachments.

The WordPress built in tool will not allow this, and I cannot find a working plugin to do it either.

答:
Try to use this plugin it might help you perform the task you are trying to do, I think this only work between wordpress to wordpress

https://wordpress.org/plugins/wp-ultimate-exporter/


问:
Calling FQL Method to query facebook
I'm using the Facebook C# SDK V4.2.1 to creat a simple application in silverlight 4, i wanto to get the profile picture. for what i know is that the best way is to cal the FQL method, but i'm new to this and i don´t know how to call FQL method.

i've searched the net and not found anything
If you can help me, I would apreciate.

答:
Facebook profile pictures are publically availible. You can see picture at url http://graph.facebook.com/username/picture
For example, my profile picture: http://graph.facebook.com/pavel.surmenok/picture
And large one: http://graph.facebook.com/pavel.surmenok/picture?type=large</p>

Title: Calling FQL Method to query facebook


问:
how can my button open a new tab?
I have a basic jquery issue. Just trying to make this link open in a new tab/window. I have added _blank but it does not go to a new page. Any ideas?

   $('#link13').click(function() {

    window.location.href= 'https://www.google.com','_blank';

  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" class="btn btn-primary" id="link13">See the Resources</button></code>```

答:
In HTML you can use following:

<button class="btn btn-success" onclick=" window.open('http://google.com','_blank')"> Google</button>

Pure HTML Method:

Google

Title: how can my button open a new tab?

Body:
I have a basic jquery issue. Just trying to make this link open in a new tab/window. I have added _blank but it does not go to a new page. Any ideas?

   $('#link13').click(function() {

    window.location.href= 'https://www.google.com','_blank';

  });

<button type="button" class="btn btn-primary" id="link13">See the Resources</button>

Body:
In HTML you can use following:

<button class="btn btn-success" onclick=" window.open('http://google.com','_blank')"> Google</button>

Pure HTML Method:

<a href="https://google.com" target="_blank">Google</a>


问:
Only one expression can be specified in the select list when the sub-query is not introduced with EXISTS
```<code>SELECT
  ( Select
COUNT(t2.ID) as Total_HH_Memebers_Primary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID
) col1

  , (Select
COUNT(t2.ID) as Total_HH_Memebers_Secondary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
 WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 10
              HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID

) col2
</code>```

Here is my query, i want to get two different results based on "WHERE" condition from same table in the form of columns when i do this its giving this error .can somebody how to it correctly?

答:
Try With cte</p>

```<code>;with col1 as
(  Select
COUNT(t2.ID) as Total_HH_Memebers_Primary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID
),col2 as
(Select
COUNT(t2.ID) as Total_HH_Memebers_Secondary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
 WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 10
              HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID

)

select col1.SETTLEMENT_ID,col2.Total_HH_Memebers_Secondary, col1.Total_HH_Memebers_Primary from col1
join col2 on col1.SETTLEMENT_ID=col2.SETTLEMENT_ID
</code>```

Body:
SELECT
  ( Select
COUNT(t2.ID) as Total_HH_Memebers_Primary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID
) col1

  , (Select
COUNT(t2.ID) as Total_HH_Memebers_Secondary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
 WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 10
              HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID

) col2

Here is my query, i want to get two different results based on "WHERE" condition from same table in the form of columns when i do this its giving this error .can somebody how to it correctly?

Body:
Try With cte

;with col1 as
(  Select
COUNT(t2.ID) as Total_HH_Memebers_Primary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID
),col2 as
(Select
COUNT(t2.ID) as Total_HH_Memebers_Secondary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
 WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 10
              HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID

)

select col1.SETTLEMENT_ID,col2.Total_HH_Memebers_Secondary, col1.Total_HH_Memebers_Primary from col1
join col2 on col1.SETTLEMENT_ID=col2.SETTLEMENT_ID


问:
How to count the number of comparisons happening when organizing an array?
I have this java code that sorts a set of random scores. What I need to do is modify sortArray so that it returns the total number of comparisons that were made during its calls to findMinLoc and modify the main to call the modiﬁed sortArray correctly, capturing the number of comparisons total into a variable. I am very new to programming and I'm having a complete block on how to do this. I've attempted to use a counter however it always displays only the amount of scores not how many comparisons were made to put the array in order.

```<code>import java.util.Scanner;
public class Lab11
{
    public static void main(String[] args)
    {
        Scanner stdIn = new Scanner(System.in);
        final int Size = 10;
        double [] scores = new double[Size];
        // set all the scores to a random number [0 - 99]
        for (int s = 0; s < Size; ++s)
            scores[s] = (int)(Math.random() * 100);
        // print the scores - original order
        System.out.println("Scores - Original");
        System.out.println("------------------");
        printArray(scores, Size);
        System.out.println("\n");
        // sort the scores
        System.out.println("Sorting ...\n");
        // print the scores - sorted order
        sortArray(scores, Size);
        System.out.println("Size of array = " + Size);
        System.out.println("Comparisons needed =   \n");
        System.out.println("Scores - Sorted");
        System.out.println("----------------");
        printArray(scores, Size);
        System.out.println("\n");
        stdIn.close();
    }
    public static void printArray(double [] arr, int eSize)
    {
        for (int i = 0; i < eSize; ++i)
            System.out.println(arr[i]);
    }
    public static int findMinLoc(double [] arr, int startInd, int     endInd)
    {
        int minLoc = startInd;
        for (int i = startInd; i <= endInd; ++i)
        {
            if (arr[i] < arr[minLoc])
                minLoc = i;
        }
        return minLoc;
    }
    public static void swapInArray(double [] arr, int ind1, int ind2)
    {
        double tmp = arr[ind1];
        arr[ind1] = arr[ind2];
        arr[ind2] = tmp;
    }
    public static void sortArray(double [] arr, int eSize)
    {
        for (int i = 0; i < eSize; ++i)
        {
            int ind = findMinLoc(arr, i, eSize-1);
            swapInArray(arr, i, ind);
        }
    }
}
</code>```

It should look something like..
Scores - Original -----------------
69.0
56.0
19.0
70.0
88.0
86.0
56.0
19.0
79.0
20.0
Sorting ...

Size of array = 10
Comparisions needed = 55

Scores - Sorted

19.0
19.0
20.0
56.0
56.0
69.0
70.0
79.0
86.0
88.0

each method I tried always came up with the caparisons needed being 10 and I don't understand why. Any suggestions on how to solve this?

答:
If 55 was the amount of comparisons you were expecting.
Globally define

```<code>static int minLocComps = 0;
</code>```

and add an increment

```<code>for (int i = startInd; i <= endInd; ++i)
    {
        if (arr[i] < arr[minLoc])
            minLoc = i;
        minLocComps++; //<-- Here
    }
</code>```

And finally your print out.

```<code>System.out.println("Comparisons needed = " + minLocComps +"\n");
</code>```

Body:
I have this java code that sorts a set of random scores. What I need to do is modify sortArray so that it returns the total number of comparisons that were made during its calls to findMinLoc and modify the main to call the modiﬁed sortArray correctly, capturing the number of comparisons total into a variable. I am very new to programming and I'm having a complete block on how to do this. I've attempted to use a counter however it always displays only the amount of scores not how many comparisons were made to put the array in order.

import java.util.Scanner;
public class Lab11
{
    public static void main(String[] args)
    {
        Scanner stdIn = new Scanner(System.in);
        final int Size = 10;
        double [] scores = new double[Size];
        // set all the scores to a random number [0 - 99]
        for (int s = 0; s < Size; ++s)
            scores[s] = (int)(Math.random() * 100);
        // print the scores - original order
        System.out.println("Scores - Original");
        System.out.println("------------------");
        printArray(scores, Size);
        System.out.println("\n");
        // sort the scores
        System.out.println("Sorting ...\n");
        // print the scores - sorted order
        sortArray(scores, Size);
        System.out.println("Size of array = " + Size);
        System.out.println("Comparisons needed =   \n");
        System.out.println("Scores - Sorted");
        System.out.println("----------------");
        printArray(scores, Size);
        System.out.println("\n");
        stdIn.close();
    }
    public static void printArray(double [] arr, int eSize)
    {
        for (int i = 0; i < eSize; ++i)
            System.out.println(arr[i]);
    }
    public static int findMinLoc(double [] arr, int startInd, int     endInd)
    {
        int minLoc = startInd;
        for (int i = startInd; i <= endInd; ++i)
        {
            if (arr[i] < arr[minLoc])
                minLoc = i;
        }
        return minLoc;
    }
    public static void swapInArray(double [] arr, int ind1, int ind2)
    {
        double tmp = arr[ind1];
        arr[ind1] = arr[ind2];
        arr[ind2] = tmp;
    }
    public static void sortArray(double [] arr, int eSize)
    {
        for (int i = 0; i < eSize; ++i)
        {
            int ind = findMinLoc(arr, i, eSize-1);
            swapInArray(arr, i, ind);
        }
    }
}

It should look something like..
Scores - Original -----------------
69.0
56.0
19.0
70.0
88.0
86.0
56.0
19.0
79.0
20.0
Sorting ...

Size of array = 10
Comparisions needed = 55

Scores - Sorted

19.0
19.0
20.0
56.0
56.0
69.0
70.0
79.0
86.0
88.0

each method I tried always came up with the caparisons needed being 10 and I don't understand why. Any suggestions on how to solve this?

Body:
If 55 was the amount of comparisons you were expecting.
Globally define

static int minLocComps = 0;

and add an increment

for (int i = startInd; i <= endInd; ++i)
    {
        if (arr[i] < arr[minLoc])
            minLoc = i;
        minLocComps++; //<-- Here
    }

And finally your print out.

System.out.println("Comparisons needed = " + minLocComps +"\n");


答:
The error message is telling you that: A sub-query in the select list IS NOT ALLOWED TO return more than ONE VALUE, and this is true for EACH subquery.

You have 2 columns AND multiple rows returned from this query:

```
Select <b>COUNT(t2.ID) as Total_HH_Memebers_Primary, t1.SETTLEMENT_ID</b>
from PScData t1
INNER JOIN PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
<b>Group By t1.SETTLEMENT_ID </b>
```

So IT IS NOT ALLOWED as a "subquery" inside a select clause.

You need to use "conditional aggregates" instead, explained elsewhere.

Title: Only one expression can be specified in the select list when the sub-query is not introduced with EXISTS

Body:
The error message is telling you that: A sub-query in the select list IS NOT ALLOWED TO return more than ONE VALUE, and this is true for EACH subquery.

You have 2 columns AND multiple rows returned from this query:

Select COUNT(t2.ID) as Total_HH_Memebers_Primary, t1.SETTLEMENT_ID
from PScData t1
INNER JOIN PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
Group By t1.SETTLEMENT_ID

So IT IS NOT ALLOWED as a "subquery" inside a select clause.

You need to use "conditional aggregates" instead, explained elsewhere.


问:
VB.net: Why I can NOT get the return value from my own stored procedure?
Why I can NOT get the return value (Scope_Identity) by executing my own Stored procedure (SQL Server 2008) via this below code written in VB.NET 2008? The SP inserts the new record into Table1 but I have 0 as the return value!

What's wrong with it?

here is my vb.net code and my SP:

```<code>Public Function Insert(ByVal Obj As entity, connectionString As String) As Integer
    Dim ScopeIdentity As Integer
    Dim Connection As New SqlConnection(connectionString)
    Using Command As New SqlCommand
        With Command
            .Connection = Connection
            .CommandTimeout = 300
            .CommandType = CommandType.StoredProcedure
            .CommandText = "S_Test"
            If .Connection.State <> ConnectionState.Open Then
                .Connection.Open()
            End If
            SqlCommandBuilder.DeriveParameters(Command)
            With .Parameters
                 .Item("@Name").Value = Obj.Name
                .Item("@Age").Value = Obj.Age
            End With
            Dim ScopeIdentityParameter As New SqlParameter("ReturnValue", SqlDbType.Int)
            ScopeIdentityParameter.Direction = ParameterDirection.ReturnValue
            Command.Parameters.Add(ScopeIdentityParameter)
            Command.ExecuteNonQuery()
            ScopeIdentity = System.Convert.ToInt32(ScopeIdentityParameter.Value)
        End With
    End Using
    Return ScopeIdentity
End Function
</code>```

my own simple Stored Procedure body:

```<code> insert into dbo.Table1(Name, Age) values(@Name, @Age)
 return SCOPE_IDENTITY()
</code>```

答:
Either change your VB code to take an interest in the return value (eg: Command.ExecuteScalar() rather than Command.ExecuteNonQuery() and use SELECT SCOPE_IDENTITY() at the end of the proc) or change your stored procedure to set the OUT param eg: set @ReturnValue = SCOPE_IDENTITY() instead of return SCOPE_IDENTITY()

Your VB code currently expects the proc to set an output parameter but return SCOPE_IDENTITY() doesn't set the parameter.

See here for context on SCOPE_IDENTITY() as well: http://msdn.microsoft.com/en-us/library/ms190315.aspx

Body:
Why I can NOT get the return value (Scope_Identity) by executing my own Stored procedure (SQL Server 2008) via this below code written in VB.NET 2008? The SP inserts the new record into Table1 but I have 0 as the return value!

What's wrong with it?

here is my vb.net code and my SP:

Public Function Insert(ByVal Obj As entity, connectionString As String) As Integer
    Dim ScopeIdentity As Integer
    Dim Connection As New SqlConnection(connectionString)
    Using Command As New SqlCommand
        With Command
            .Connection = Connection
            .CommandTimeout = 300
            .CommandType = CommandType.StoredProcedure
            .CommandText = "S_Test"
            If .Connection.State <> ConnectionState.Open Then
                .Connection.Open()
            End If
            SqlCommandBuilder.DeriveParameters(Command)
            With .Parameters
                 .Item("@Name").Value = Obj.Name
                .Item("@Age").Value = Obj.Age
            End With
            Dim ScopeIdentityParameter As New SqlParameter("ReturnValue", SqlDbType.Int)
            ScopeIdentityParameter.Direction = ParameterDirection.ReturnValue
            Command.Parameters.Add(ScopeIdentityParameter)
            Command.ExecuteNonQuery()
            ScopeIdentity = System.Convert.ToInt32(ScopeIdentityParameter.Value)
        End With
    End Using
    Return ScopeIdentity
End Function

my own simple Stored Procedure body:

 insert into dbo.Table1(Name, Age) values(@Name, @Age)
 return SCOPE_IDENTITY()


答:
Use window.open():

```<code>var win = window.open('https://www.google.com','_blank');
if (win) {
    //Browser has allowed it to be opened
    win.focus();
} else {
    //Browser has blocked it
    alert('Please allow popups for this website');
}
</code>```

Depending on the browsers implementation this will work
see this if it helps..

Title: how can my button open a new tab?

Body:
Use window.open():

var win = window.open('https://www.google.com','_blank');
if (win) {
    //Browser has allowed it to be opened
    win.focus();
} else {
    //Browser has blocked it
    alert('Please allow popups for this website');
}

Depending on the browsers implementation this will work
see this if it helps..


问:
Razors Html Helpers
How do you make a Razors helper "Dropdownlist" or what arguments would have to pass to make it editable. For example if I want to scroll down it should let me or if I want type Instead it should let aswell.

```<code>@Html.DropDownList("CustomerId", null, htmlAttributes: new { @class = "form-control" } )
</code>```

Also, if you I choose to use twitter-typeahead with EF razors how do use the "Editfor" so that once the user click on the right item, it sends the ID of that item to the database. In-other words, how do use a navigation property with razors "Editfor" helper.

```<code>@Html.EditorFor(model => model.CustomerId,  null, "customer",new {htmlAttributes = new { @class = "form-control" } })
</code>```

答:
I will try to help you convert the basic example of the following page to a razor page equivalent.

http://twitter.github.io/typeahead.js/examples/

You must know that this jquery plugin displays just a list of strings and the user will select one of the values and then you will have to find the id using C# code. I will just show you how to implement the twitter typehead using razor pages but you will have to make some extra work in order to get the id.

First of all you will need the html part

```<code><div id="the-basics">
  <input class="typeahead" type="text" placeholder="States of USA">
</div>
</code>```

Next you need to declare your list using C#.

```<code>List<string> Values = new List<string> { "Value 1", "Value 2", "Value 3" };
</code>```

Now you will have the following HTML.

```<code>var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substringRegex;

    // an array that will be populated with substring matches
    matches = [];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        matches.push(str);
      }
    });

    cb(matches);
  };
};

var states = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Values));

$('#the-basics .typeahead').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  name: 'states',
  source: substringMatcher(states)
});
</code>```

I hope it helps.

Title: Razors Html Helpers

Body:
How do you make a Razors helper "Dropdownlist" or what arguments would have to pass to make it editable. For example if I want to scroll down it should let me or if I want type Instead it should let aswell.

@Html.DropDownList("CustomerId", null, htmlAttributes: new { @class = "form-control" } )

Also, if you I choose to use twitter-typeahead with EF razors how do use the "Editfor" so that once the user click on the right item, it sends the ID of that item to the database. In-other words, how do use a navigation property with razors "Editfor" helper.

@Html.EditorFor(model => model.CustomerId,  null, "customer",new {htmlAttributes = new { @class = "form-control" } })

Body:
I will try to help you convert the basic example of the following page to a razor page equivalent.

http://twitter.github.io/typeahead.js/examples/

You must know that this jquery plugin displays just a list of strings and the user will select one of the values and then you will have to find the id using C# code. I will just show you how to implement the twitter typehead using razor pages but you will have to make some extra work in order to get the id.

First of all you will need the html part

<div id="the-basics">
  <input class="typeahead" type="text" placeholder="States of USA">
</div>

Next you need to declare your list using C#.

List<string> Values = new List<string> { "Value 1", "Value 2", "Value 3" };

Now you will have the following HTML.

var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substringRegex;

    // an array that will be populated with substring matches
    matches = [];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        matches.push(str);
      }
    });

    cb(matches);
  };
};

var states = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Values));

$('#the-basics .typeahead').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  name: 'states',
  source: substringMatcher(states)
});

I hope it helps.


问:
What versions of Android are unsupported with Twitter4J?
Does the Twitter4J library for Android work for all Android versions?  I cannot find anything regarding this issue on twitter4j's website, or anywhere else.
twitter4j.org</p>

答:
Twitter4J should work on any version of Android SDK.
But make sure that you use the latest version of Twitter4J as there are several Android specific issues reported against older versions.
http://twitter4j.org/jira/secure/QuickSearch.jspa?searchString=android</p>


问:
Bit shifting in sequential block fails, in combinational not. Why?
I am debugging a piece of Verilog code for days, particularly sending and receiving bytes from an FX2LP (Cypress CY7C68016A) USB controller. Without going into many details, data is sent and transmitted byte-wise in each cycle. For my test, I use a 16 byte buffer which I first fill and then transmit back (echo test).

The significant part of my code looks like:

```<code>reg [127:0] dataBuf; // 16 byte buffer for USB data

reg [7:0] cntByte; // counter for number of bytes
reg [7:0] nextCntByte;

reg shiftBufRx, shiftBufTx; // flags whether buffer should be shifted
reg [7:0] currentByte; // current read byte

// in transmit cycle, byte is read from USB_DATAOUT
assign USB_DATAOUT = dataBuf[7:0];

always @(posedge FIFO_CLK) begin
    // update state variables
    CurrentState <= NextState;
    cntByte <= nextCntByte;

    if(shiftBufRx) begin // cycle was a receive
        dataBuf <= { currentByte , dataBuf[127:8] };
    end
    if(shiftBufTx) begin // cycle was a transmit
        dataBuf <= { dataBuf[127-8:0] , 8'h00 };
    end
end

always @(*) begin
    // avoid race conditions
    NextState = CurrentState;
    nextCntByte = cntByte;
    nextDataBuf = dataBuf;
    currentByte = 0;
    shiftBufRx = 0;
    shiftBufTx = 0;

    case(CurrentState)
        [...]
        STATE_USBRX: begin
            if(cntByte < 16) begin
                nextCntByte = cntByte + 1;
                currentByte = USB_DATAIN; // contains received byte in receive cycle
                shiftBufRx = 1; // shift buffer after this cycle
            end
            [...]
        end
        STATE_USBTX: begin
            if(cntByte < 15) begin
                shiftBufTx = 1; // shift buffer after this cycle
                nextCntByte = cntByte + 1;
            end
            [...]
        end
        [...]
    endcase
end
</code>```

This code works perfectly in simulation (iVerilog). But when synthesizing and executing on an Altera Cyclone, I get very strange errors. For example, most of the time the first byte transmitted to the FPGA is read for each byte. For example, sending 11 22 33 44 55 66 ... would receive 11 11 11 11 11 11 ....

Now when I instead introduce a new variable:

```<code>reg [127:0] nextDataBuf;
</code>```

and replace the part in the sequential always @(posedge FIFO_CLK) block with:

```<code>if(shiftBufRx) begin
    dataBuf <= nextDataBuf;
end
if(shiftBufTx) begin
    dataBuf <= nextDataBuf;
end
</code>```

and in the combinational part:

```<code>        STATE_USBRX: begin
            if(cntByte < 16) begin
                nextCntByte = cntByte + 1;
                //currentByte = FIFO_DATAIN;
                nextDataBuf = { dataBuf[127-8:0] , FIFO_DATAIN };
                shiftBufRx = 1;
            end
            [...]
        end
        STATE_USBTX: begin
            if(cntByte < 15) begin
                shiftBufTx = 1;
                nextCntByte = cntByte + 1;
                nextDataBuf = { 8'h00 , dataBuf[127:8] };
            end
            [...]
        end
</code>```

Then it works!

That means: All I am doing is to move the shifting of the register from the sequential block to the combinational block.

I do not see any race conditions in my code and in simulation (iVerilog) both versions are identical.

What could be the reason?

答:
First of all you should definitely post a MVCE. This is almost an MVCE, but it doesn't contain a testbench and the ellipsis [...] obscures things that could be relevant like the state transitions from RX to TX.

Never the less, as it was close, I built a small test bench and added some minimal code to get it running. In my case it did NOT work "perfectly in simulation". In fact, as @greg pointed out, there is a definite error in the shift register.

In your before code, you are shifting left out of register, but are transmitting the low bytes. The first cycle they will be 8'h11 and afterward will either be 8'h00 or stay the same, depending on when shiftBufTx is true, and this depends on logic that isn't posted. There is enough posted to see that it cannot possibly work correctly as is.

```<code>    assign USB_DATAOUT = dataBuf[7:0];
    ...
    if(shiftBufTx) begin // cycle was a transmit
        dataBuf <= { dataBuf[127-8:0] , 8'h00 };
    end
</code>```

In the after code, you are shifting right and this is why it works:

```<code>nextDataBuf = { 8'h00 , dataBuf[127:8] };
</code>```

It is possible that the sim does not match synthesis for a similar reason. The code looks fairly synthesizable. Some suggestions:

There is no reason to have independent flags for Tx and Rx

As @serge pointed out, what happens if they conflict? This may sim okay but will not work in hardware.

You could just use a single flag and set it in the output of each state.

If you need more than one condition, you must have an else that insures that only one path can modify each non-blocking assignment to a var is active at any clock edge:

```<code>if(shiftBufRx) begin // cycle was a receive
    dataBuf <= { currentByte , dataBuf[127:8] };
end
**else** if(shiftBufTx) begin // cycle was a transmit
    dataBuf <= **{ 8'h00 , dataBuf[127:8] }**;
end
</code>```

Why did it appear to work in sim? Beyond small typos or transpositions of supposedly identical code, the sim is very forgiving of multiple writes to the same var (the later will "win").

But the synthesis tool must intuit your intent into registers. Depending on how complex the logic is, it might not be able to know that both flags can't be true at the same time. Sometimes it will interpret things like this as two parallel "write enable" conditions for dataBuf and create two parallel registers. The 2nd copy probably just never shifted back out after being set to 8'h11 which matches the symptoms. You should examine the actual output circuit after elaboration to detect this kind of error. Unfortunately not all of them fail or even give obvious warnings. In Xilinx Vivado you can pull up the schematic.

Body:
I am debugging a piece of Verilog code for days, particularly sending and receiving bytes from an FX2LP (Cypress CY7C68016A) USB controller. Without going into many details, data is sent and transmitted byte-wise in each cycle. For my test, I use a 16 byte buffer which I first fill and then transmit back (echo test).

The significant part of my code looks like:

reg [127:0] dataBuf; // 16 byte buffer for USB data

reg [7:0] cntByte; // counter for number of bytes
reg [7:0] nextCntByte;

reg shiftBufRx, shiftBufTx; // flags whether buffer should be shifted
reg [7:0] currentByte; // current read byte

// in transmit cycle, byte is read from USB_DATAOUT
assign USB_DATAOUT = dataBuf[7:0];

always @(posedge FIFO_CLK) begin
    // update state variables
    CurrentState <= NextState;
    cntByte <= nextCntByte;

    if(shiftBufRx) begin // cycle was a receive
        dataBuf <= { currentByte , dataBuf[127:8] };
    end
    if(shiftBufTx) begin // cycle was a transmit
        dataBuf <= { dataBuf[127-8:0] , 8'h00 };
    end
end

always @(*) begin
    // avoid race conditions
    NextState = CurrentState;
    nextCntByte = cntByte;
    nextDataBuf = dataBuf;
    currentByte = 0;
    shiftBufRx = 0;
    shiftBufTx = 0;

    case(CurrentState)
        [...]
        STATE_USBRX: begin
            if(cntByte < 16) begin
                nextCntByte = cntByte + 1;
                currentByte = USB_DATAIN; // contains received byte in receive cycle
                shiftBufRx = 1; // shift buffer after this cycle
            end
            [...]
        end
        STATE_USBTX: begin
            if(cntByte < 15) begin
                shiftBufTx = 1; // shift buffer after this cycle
                nextCntByte = cntByte + 1;
            end
            [...]
        end
        [...]
    endcase
end

This code works perfectly in simulation (iVerilog). But when synthesizing and executing on an Altera Cyclone, I get very strange errors. For example, most of the time the first byte transmitted to the FPGA is read for each byte. For example, sending 11 22 33 44 55 66 ... would receive 11 11 11 11 11 11 ....

Now when I instead introduce a new variable:

reg [127:0] nextDataBuf;

and replace the part in the sequential always @(posedge FIFO_CLK) block with:

if(shiftBufRx) begin
    dataBuf <= nextDataBuf;
end
if(shiftBufTx) begin
    dataBuf <= nextDataBuf;
end

and in the combinational part:

        STATE_USBRX: begin
            if(cntByte < 16) begin
                nextCntByte = cntByte + 1;
                //currentByte = FIFO_DATAIN;
                nextDataBuf = { dataBuf[127-8:0] , FIFO_DATAIN };
                shiftBufRx = 1;
            end
            [...]
        end
        STATE_USBTX: begin
            if(cntByte < 15) begin
                shiftBufTx = 1;
                nextCntByte = cntByte + 1;
                nextDataBuf = { 8'h00 , dataBuf[127:8] };
            end
            [...]
        end

Then it works!

That means: All I am doing is to move the shifting of the register from the sequential block to the combinational block.

I do not see any race conditions in my code and in simulation (iVerilog) both versions are identical.

What could be the reason?

Body:
First of all you should definitely post a MVCE. This is almost an MVCE, but it doesn't contain a testbench and the ellipsis [...] obscures things that could be relevant like the state transitions from RX to TX.

Never the less, as it was close, I built a small test bench and added some minimal code to get it running. In my case it did NOT work "perfectly in simulation". In fact, as @greg pointed out, there is a definite error in the shift register.

In your before code, you are shifting left out of register, but are transmitting the low bytes. The first cycle they will be 8'h11 and afterward will either be 8'h00 or stay the same, depending on when shiftBufTx is true, and this depends on logic that isn't posted. There is enough posted to see that it cannot possibly work correctly as is.

    assign USB_DATAOUT = dataBuf[7:0];
    ...
    if(shiftBufTx) begin // cycle was a transmit
        dataBuf <= { dataBuf[127-8:0] , 8'h00 };
    end

In the after code, you are shifting right and this is why it works:

nextDataBuf = { 8'h00 , dataBuf[127:8] };

It is possible that the sim does not match synthesis for a similar reason. The code looks fairly synthesizable. Some suggestions:

There is no reason to have independent flags for Tx and Rx

As @serge pointed out, what happens if they conflict? This may sim okay but will not work in hardware.

You could just use a single flag and set it in the output of each state.

If you need more than one condition, you must have an else that insures that only one path can modify each non-blocking assignment to a var is active at any clock edge:

if(shiftBufRx) begin // cycle was a receive
    dataBuf <= { currentByte , dataBuf[127:8] };
end
**else** if(shiftBufTx) begin // cycle was a transmit
    dataBuf <= **{ 8'h00 , dataBuf[127:8] }**;
end

Why did it appear to work in sim? Beyond small typos or transpositions of supposedly identical code, the sim is very forgiving of multiple writes to the same var (the later will "win").

But the synthesis tool must intuit your intent into registers. Depending on how complex the logic is, it might not be able to know that both flags can't be true at the same time. Sometimes it will interpret things like this as two parallel "write enable" conditions for dataBuf and create two parallel registers. The 2nd copy probably just never shifted back out after being set to 8'h11 which matches the symptoms. You should examine the actual output circuit after elaboration to detect this kind of error. Unfortunately not all of them fail or even give obvious warnings. In Xilinx Vivado you can pull up the schematic.