问:
List most recent mercurial hashes
Does hg have a nice way to list just the hashes of the most recent commits in the repo on separate lines? hg id -i only gives me the current commit.

Something equivalent to the -l parameter in hg log such that I could do something like:

```<code>$ hg id -i -l 3
1eb0c5a3002e  <--- youngest commit
321c6693361e  <--- 2nd youngest commit
647724838c03  <--- 3rd youngest commit
</code>```

To give some context, I have a bash script which I pass a mercurial hash to and it builds a docker image,

```<code>./build_image.sh 647724838c03
</code>```

I am trying to get command line completion for the hash argument so I need a command to generate all the hashes which I can drop into compgen:

```<code>local HASHES=$(cd $REPO && hg id -i -l 10)
COMPREPLY=( $(compgen -W "$HASHES" -- $cur) )
</code>```

Most of the time the hash I'm wanting to build will be the checked out commit so hg id -i will work okay, but getting a full list of the last 10 hashes would be nice!

Thanks in advance for any help!

EDIT

I got a work around using grep and awk:

```<code>$ hg log -l 5 | grep changeset | awk -vn=12 '{print substr($0,length($0)-n+1)}'
1eb0c5a3002e
ec0db890a6c3
321c6693361e
4a1e2ca2df06
2d1ef7d57485
</code>```

This isn't great though:

makes assumptions about how hg log outputs (which might change in different versions)

that awk command is a bit too mystical for me :)

doesn't work for Windows (assuming you're trying to solve a different problem to bash tab completion)

答:
That's what you have log for. Template the output to your needs, e.g.

```<code>hg log -l10 --template="{node|short} {date} {author}\n"
</code>```

gives you output like

```<code>0c4520bbf388 2017-06-07 12:25 +0200 username <user@example.com>
</code>```

Checkout hg help template for more templating options. You can basically apply templating to all relevant commands which generate  these kind of outputs.

Mind: if you do not sort log explicitly by commit date, it will return you the 10 newest commits in your repository - which does not necessarily reflect order of commit time. You can do that by giving additionally a revset and sorting by it:

```<code>hg log --rev="sort(date('<now'))" --template="{node}\n" -l5
</code>```

Title: List most recent mercurial hashes

Body:
Does hg have a nice way to list just the hashes of the most recent commits in the repo on separate lines? hg id -i only gives me the current commit.

Something equivalent to the -l parameter in hg log such that I could do something like:

$ hg id -i -l 3
1eb0c5a3002e  <--- youngest commit
321c6693361e  <--- 2nd youngest commit
647724838c03  <--- 3rd youngest commit

To give some context, I have a bash script which I pass a mercurial hash to and it builds a docker image,

./build_image.sh 647724838c03

I am trying to get command line completion for the hash argument so I need a command to generate all the hashes which I can drop into compgen:

local HASHES=$(cd $REPO && hg id -i -l 10)
COMPREPLY=( $(compgen -W "$HASHES" -- $cur) )

Most of the time the hash I'm wanting to build will be the checked out commit so hg id -i will work okay, but getting a full list of the last 10 hashes would be nice!

Thanks in advance for any help!

EDIT

I got a work around using grep and awk:

$ hg log -l 5 | grep changeset | awk -vn=12 '{print substr($0,length($0)-n+1)}'
1eb0c5a3002e
ec0db890a6c3
321c6693361e
4a1e2ca2df06
2d1ef7d57485

This isn't great though:

makes assumptions about how hg log outputs (which might change in different versions)

that awk command is a bit too mystical for me :)

doesn't work for Windows (assuming you're trying to solve a different problem to bash tab completion)

Body:
That's what you have log for. Template the output to your needs, e.g.

hg log -l10 --template="{node|short} {date} {author}\n"

gives you output like

0c4520bbf388 2017-06-07 12:25 +0200 username <user@example.com>

Checkout hg help template for more templating options. You can basically apply templating to all relevant commands which generate  these kind of outputs.

Mind: if you do not sort log explicitly by commit date, it will return you the 10 newest commits in your repository - which does not necessarily reflect order of commit time. You can do that by giving additionally a revset and sorting by it:

hg log --rev="sort(date('<now'))" --template="{node}\n" -l5


来源: stackexchange

问:
Is it possible to reliably nest find -exec commands in linux?
I need to fix permissions on a large number of files from a subset of directories on a large nfs volume.

In building up a solution, I started by using find to get a list of the directories I want:

```<code>find . -type d -regex "^./[0-9]*"
</code>```

The directories all start with a number.

I can successfully use this to exec a 2nd find.  That find gets files that exclude a few filenames I don't want to process:

```<code>find . -type d -regex "^./[0-9]*" -exec find {} -type f \( ! -iname '.*' ! -name 'async.log' \) \;
</code>```

This all works great and returns the list of files I need to process.

Now to the problem:

What I really want is to use the 2nd find to -exec chmod 644.  I have found a way to do this using xargs that seems to work fine.  In the examples here I'm using echo just to verify the list of files being returned.

```<code>find . -type d -regex "^./[0-9]*" | xargs -I dirname find dirname -type f \( ! -iname '.*' ! -name 'async.log' \) -exec echo {} \;
</code>```

But what I'd like do is just use -exec with my chained find commands, as it is many times faster than piping the results to xargs, but something goes wrong with the results:

```<code>find . -type d -regex "^./[0-9]*" -exec find {} -type f \( ! -iname '.*' ! -name 'async.log' \) \; -exec echo {} \;
</code>```

When I send output to a file, there is a discrepancy and the nested find command seems to stop before full completion.

When comparing the 2 files, the xargs version has 173125 lines, whereas the nested find command only has 173060 lines.

The last line in the find version shows truncation:

```<code>./104/5734c420e70d8.pdf
./104
</code>```

I am at a loss to explain this, or come up with a way to debug or workaround the problem.  Any ideas on how I might get my find -only solution working?

答:
I think it should be simplier if you use find only one time.

The following solution will work as long all your directories you want to search are in the same directory.

```<code>find {0,1,2,3,4,5,6,7,8,9}* -type f \( ! -iname '.*' ! -name 'async.log' \) -exec chmod 644 {} \;
</code>```

Search in current directory all directories beginning by a number, exclude file beginning by a dot, exclude file named async.log and apply command chmod 644 to file found.

ContentLicense: CC BY-SA 3.0

Body:
I need to fix permissions on a large number of files from a subset of directories on a large nfs volume.

In building up a solution, I started by using find to get a list of the directories I want:

find . -type d -regex "^./[0-9]*"

The directories all start with a number.

I can successfully use this to exec a 2nd find.  That find gets files that exclude a few filenames I don't want to process:

find . -type d -regex "^./[0-9]*" -exec find {} -type f \( ! -iname '.*' ! -name 'async.log' \) \;

This all works great and returns the list of files I need to process.

Now to the problem:

What I really want is to use the 2nd find to -exec chmod 644.  I have found a way to do this using xargs that seems to work fine.  In the examples here I'm using echo just to verify the list of files being returned.

find . -type d -regex "^./[0-9]*" | xargs -I dirname find dirname -type f \( ! -iname '.*' ! -name 'async.log' \) -exec echo {} \;

But what I'd like do is just use -exec with my chained find commands, as it is many times faster than piping the results to xargs, but something goes wrong with the results:

find . -type d -regex "^./[0-9]*" -exec find {} -type f \( ! -iname '.*' ! -name 'async.log' \) \; -exec echo {} \;

When I send output to a file, there is a discrepancy and the nested find command seems to stop before full completion.

When comparing the 2 files, the xargs version has 173125 lines, whereas the nested find command only has 173060 lines.

The last line in the find version shows truncation:

./104/5734c420e70d8.pdf
./104

I am at a loss to explain this, or come up with a way to debug or workaround the problem.  Any ideas on how I might get my find -only solution working?

Body:
I think it should be simplier if you use find only one time.

The following solution will work as long all your directories you want to search are in the same directory.

find {0,1,2,3,4,5,6,7,8,9}* -type f \( ! -iname '.*' ! -name 'async.log' \) -exec chmod 644 {} \;

Search in current directory all directories beginning by a number, exclude file beginning by a dot, exclude file named async.log and apply command chmod 644 to file found.


问:
I want to implement checkbox within a toolbar menu, and Check box shows but does not tick, any ideas?
I am making an app, where the toolbar has a menu, and within has 2-3 checkboxes.I have code put down for xml and java, and checkbox displays. But nothing gets ticked when i press. Code below

action_bar xml which gets included in main activity :

```<code><item
    android:id="@+id/eleaf"
    app:actionViewClass="android.widget.CheckBox"
    android:checkable="true"
    android:checked="false"
    android:orderInCategory="5"
    app:showAsAction="never"
    android:buttonTint="@color/colorAccent"
    android:title="E-Leaf"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    android:onClick="itemClicked"/>
</code>```

Java for onOptionsItemsSelected :

```<code>public boolean onOptionsItemSelected(MenuItem item)
{
    boolean checked = item.isChecked();

    switch (item.getItemId())
    {
        case R.id.eleaf:
            if(checked){
                Toast.makeText(this, "E-Leaf Map shown", Toast.LENGTH_SHORT).show();
                item.setChecked(false);
            }
            break;
        case R.id.biomass:
            if (checked){
                Toast.makeText(this, "Biomass Map shown", Toast.LENGTH_SHORT).show();
                item.setChecked(false);
            }
            break;
        default:
            return super.onOptionsItemSelected(item);
    }
    return true;
}
</code>```

I had this line in oncreate but not really using it :

```<code>    CheckBox checkEleaf = (CheckBox) findViewById(R.id.eleaf);
</code>```

Any suggestions on how to go about this. Thanks

答: Within each case in your switch you have to return true.</p>

Body:
I am making an app, where the toolbar has a menu, and within has 2-3 checkboxes.I have code put down for xml and java, and checkbox displays. But nothing gets ticked when i press. Code below

action_bar xml which gets included in main activity :

<item
    android:id="@+id/eleaf"
    app:actionViewClass="android.widget.CheckBox"
    android:checkable="true"
    android:checked="false"
    android:orderInCategory="5"
    app:showAsAction="never"
    android:buttonTint="@color/colorAccent"
    android:title="E-Leaf"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    android:onClick="itemClicked"/>

Java for onOptionsItemsSelected :

public boolean onOptionsItemSelected(MenuItem item)
{
    boolean checked = item.isChecked();

    switch (item.getItemId())
    {
        case R.id.eleaf:
            if(checked){
                Toast.makeText(this, "E-Leaf Map shown", Toast.LENGTH_SHORT).show();
                item.setChecked(false);
            }
            break;
        case R.id.biomass:
            if (checked){
                Toast.makeText(this, "Biomass Map shown", Toast.LENGTH_SHORT).show();
                item.setChecked(false);
            }
            break;
        default:
            return super.onOptionsItemSelected(item);
    }
    return true;
}

I had this line in oncreate but not really using it :

    CheckBox checkEleaf = (CheckBox) findViewById(R.id.eleaf);

Any suggestions on how to go about this. Thanks


问:
Problem using Resque, Rails 3 and Active-Recored
I have this Class which response to perform to be run by "Resque", I have an error at this line recipient.response = response.body which is:

undefined method response=' for #Hash:0x00000003969da0

I think that because the worker and ActiveRecord can't work together.

P.S I already loaded my environment and this class placed in lib directory

Using:

Ruby 1.9.2

Rails 3

Resque 1.10.0

```<code>class Msg
  def self.perform(message,sender,host, path, recipient)
    message_logger ||= Logger.new("#{Rails.root}/log/message.log")
    response = Net::HTTP.get_response(host, path)
    begin
      recipient.response = response.body
      recipient.sent_at = Time.zone.now
      recipient.save
      # Logging
      log = "Message #{
      message.sent_at}\n\tRespone:\n\t\tBody: #{response.body}\n\t\tCode: #{response.code}\n"
      message_logger.info(log)
    rescue Exception => e
      message_logger.error(e.message + '/n' + e.backtrace.inspect)
    end
  end
end
</code>```

答:
Resque uses json serialization. JSON serialization would not allow you to deserialize an object with the method intact.

If you have an instance of Recipient (named "recipient") and want to use it in the method to perform/persist a response then you should enqueue the id of the recipient and fetch it from your persistence layer when perform is called.

https://github.com/defunkt/resque  (checkout the section on Persistence)

Resque is different from DelayedJob/Background Job and other in this way.  (which is why I like it.  the same queue can be shared by multiple ruby implementations, jruby, mri, ...)

ContentLicense: CC BY-SA 4.0

Body:
I have this Class which response to perform to be run by "Resque", I have an error at this line recipient.response = response.body which is:

undefined method response=' for #Hash:0x00000003969da0

I think that because the worker and ActiveRecord can't work together.

P.S I already loaded my environment and this class placed in lib directory

Using:

Ruby 1.9.2

Rails 3

Resque 1.10.0

class Msg
  def self.perform(message,sender,host, path, recipient)
    message_logger ||= Logger.new("#{Rails.root}/log/message.log")
    response = Net::HTTP.get_response(host, path)
    begin
      recipient.response = response.body
      recipient.sent_at = Time.zone.now
      recipient.save
      # Logging
      log = "Message #{
      message.sent_at}\n\tRespone:\n\t\tBody: #{response.body}\n\t\tCode: #{response.code}\n"
      message_logger.info(log)
    rescue Exception => e
      message_logger.error(e.message + '/n' + e.backtrace.inspect)
    end
  end
end

ContentLicense: CC BY-SA 2.5


问:
Spring security - Disable logout redirect
I'm using spring security with REST, and I'm using the URL (/logout) as an endpoint for my logout method. But after calling this method, it redirect me to (/login?logout), I know this is the spring logOutSuccessUrl. And I want to get rid of the redirection. This is my code:

```<code>protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
         .antMatchers("/login").permitAll()
         .anyRequest().fullyAuthenticated()
         .and().requiresChannel().anyRequest().requiresSecure()
         .and().httpBasic().disable().logout()
         .disable()
       //  .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))
          .csrf().disable();

}
</code>```

I tried to use HttpStatusReturningLogoutSuccessHandler but it didn't work, and even setting logoutSuccessUrl() doesn't change anything.

Do you know how can I disable this redirection?

答:
So since there is no accepted answer yet, i post my solution, which worked for me:

```<code>.logout()
.logoutUrl("/api/user/logout")
.permitAll()
.logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> {
    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
})
.and()
</code>```

Just return a clean HTTP_OK (200) after successful logout - spring won't redirect you in this case

Body:
I'm using spring security with REST, and I'm using the URL (/logout) as an endpoint for my logout method. But after calling this method, it redirect me to (/login?logout), I know this is the spring logOutSuccessUrl. And I want to get rid of the redirection. This is my code:

protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
         .antMatchers("/login").permitAll()
         .anyRequest().fullyAuthenticated()
         .and().requiresChannel().anyRequest().requiresSecure()
         .and().httpBasic().disable().logout()
         .disable()
       //  .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))
          .csrf().disable();

}

I tried to use HttpStatusReturningLogoutSuccessHandler but it didn't work, and even setting logoutSuccessUrl() doesn't change anything.

Do you know how can I disable this redirection?

Body:
So since there is no accepted answer yet, i post my solution, which worked for me:

.logout()
.logoutUrl("/api/user/logout")
.permitAll()
.logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> {
    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
})
.and()

Just return a clean HTTP_OK (200) after successful logout - spring won't redirect you in this case


问:
Random shuffling of an array
I need to randomly shuffle the following Array:

```<code>int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};
</code>```

Is there any function to do that?

答:
The most simple solution for this Random Shuffling in an Array.</p>

```<code>String location[] = {"delhi","banglore","mathura","lucknow","chandigarh","mumbai"};
int index;
String temp;
Random random = new Random();
for(int i=1;i<location.length;i++)
{
    index = random.nextInt(i+1);
    temp = location[index];
    location[index] = location[i];
    location[i] = temp;
    System.out.println("Location Based On Random Values :"+location[i]);
}
</code>```

Title: Random shuffling of an array

Body:
I need to randomly shuffle the following Array:

int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};

Is there any function to do that?

Body:
The most simple solution for this Random Shuffling in an Array.

String location[] = {"delhi","banglore","mathura","lucknow","chandigarh","mumbai"};
int index;
String temp;
Random random = new Random();
for(int i=1;i<location.length;i++)
{
    index = random.nextInt(i+1);
    temp = location[index];
    location[index] = location[i];
    location[i] = temp;
    System.out.println("Location Based On Random Values :"+location[i]);
}


问:
How can i visit my angular cli website with routes?
I have a website which I made with the angular cli. And I'm using routes to switch the content.
My problem is, when i type e.g: www.website.de/login it give me an error: 404 Not Found. I run this website with http-server . -p 80. I have all ng build --prog files (dist) on the server. But if i try that local with ng serve and i type: localhost:4200/login it works.

Here are my files that are importent:

index.html

```<code><body>
    <script type="text/javascript" src="https://code.jquery.com/jquery2.1.4.min.js"></script>
    <script src="assets/materialize/js/materialize.js"></script>
    <home></home>
    <script src="assets/script.js"></script>
</body>
</code>```

home.component.html

```<code><header>
    <navbar></navbar>
</header>
<main>
    <router-outlet></router-outlet>
</main>
<footer *ngIf="router.url != '/dashboard'" class="page-footer">
    <footer-footer></footer-footer>
</footer>
</code>```

app-routing.module.ts

```<code>import {NgModule} from "@angular/core";
import {RouterModule, Routes} from "@angular/router";

import {DashboardComponent} from "./Dashboard/dashboard.component";
import {ImprintComponent} from "./Imprint/imprint.component";
import {ContactUsComponent} from "./ContactUs/contactus.component";
import {LoginComponent} from "./Login/login.component";
import {StartComponent} from "./start/start.component";
import {ImpressumComponent} from "./Impressum/impressum.component";

const routes: Routes = [
    { path: '', redirectTo: '/', pathMatch: 'full' },
    { path: '', component: StartComponent },
    { path: 'imprint', component: ImprintComponent },
    { path: 'impressum', component: ImpressumComponent },
    { path: 'contact_us', component: ContactUsComponent },
    { path: 'login', component: LoginComponent },
    { path: 'dashboard', component: DashboardComponent }
];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule{ }
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { DashboardComponent } from "./Dashboard/dashboard.component";
import { AppRoutingModule } from "./app-routing.module";
import {NavbarComponent} from "./Navbar/navbar.component";
import {ImprintComponent} from "./Imprint/imprint.component";
import {HomeComponent} from "./Home/home.component";
import {ContactUsComponent} from "./ContactUs/contactus.component";
import {LoginComponent} from "./Login/login.component";
import {FooterFooter} from "./Footer/footer.component";
import {HttpModule} from "@angular/http";
import { StartComponent } from './start/start.component';
import {ImpressumComponent} from "./Impressum/impressum.component";

@NgModule({
  declarations: [
      DashboardComponent,
      NavbarComponent,
      ImprintComponent,
      HomeComponent,
      ContactUsComponent,
      LoginComponent,
      FooterFooter,
      StartComponent,
      ImpressumComponent
  ],
  imports: [
      BrowserModule,
      AppRoutingModule,
      HttpModule
  ],
  providers: [],
  bootstrap: [HomeComponent]
})
export class AppModule { }
</code>```

Regards

答:
When you use ng serve angular-cli uses under the hood webpack-dev-server which is pre-configured to redirect every request to the index.html file. That's why it works when you type www.website.de/login. It does redirect and returns index.html, then Angular starts and pick ups the current URL and performs routing.

Now, when you use your custom server, like http-server, it doesn't do that. You have to configure the redirect yourself. Unfortunately, there is no easy way to do that for http-server.

I suggest you use json-server for static files instead of http-server. It has a simple API for configuring redirects using middleware.

Body:
I have a website which I made with the angular cli. And I'm using routes to switch the content.
My problem is, when i type e.g: www.website.de/login it give me an error: 404 Not Found. I run this website with http-server . -p 80. I have all ng build --prog files (dist) on the server. But if i try that local with ng serve and i type: localhost:4200/login it works.

Here are my files that are importent:

index.html

    <home></home>

home.component.html

    <navbar></navbar>

    <router-outlet></router-outlet>

app-routing.module.ts

import {NgModule} from "@angular/core";
import {RouterModule, Routes} from "@angular/router";

import {DashboardComponent} from "./Dashboard/dashboard.component";
import {ImprintComponent} from "./Imprint/imprint.component";
import {ContactUsComponent} from "./ContactUs/contactus.component";
import {LoginComponent} from "./Login/login.component";
import {StartComponent} from "./start/start.component";
import {ImpressumComponent} from "./Impressum/impressum.component";

const routes: Routes = [
    { path: '', redirectTo: '/', pathMatch: 'full' },
    { path: '', component: StartComponent },
    { path: 'imprint', component: ImprintComponent },
    { path: 'impressum', component: ImpressumComponent },
    { path: 'contact_us', component: ContactUsComponent },
    { path: 'login', component: LoginComponent },
    { path: 'dashboard', component: DashboardComponent }
];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule{ }

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { DashboardComponent } from "./Dashboard/dashboard.component";
import { AppRoutingModule } from "./app-routing.module";
import {NavbarComponent} from "./Navbar/navbar.component";
import {ImprintComponent} from "./Imprint/imprint.component";
import {HomeComponent} from "./Home/home.component";
import {ContactUsComponent} from "./ContactUs/contactus.component";
import {LoginComponent} from "./Login/login.component";
import {FooterFooter} from "./Footer/footer.component";
import {HttpModule} from "@angular/http";
import { StartComponent } from './start/start.component';
import {ImpressumComponent} from "./Impressum/impressum.component";

@NgModule({
  declarations: [
      DashboardComponent,
      NavbarComponent,
      ImprintComponent,
      HomeComponent,
      ContactUsComponent,
      LoginComponent,
      FooterFooter,
      StartComponent,
      ImpressumComponent
  ],
  imports: [
      BrowserModule,
      AppRoutingModule,
      HttpModule
  ],
  providers: [],
  bootstrap: [HomeComponent]
})
export class AppModule { }

Regards


问:
stream reduction incompatible types
I'm trying to create a finder which takes several predicates and reduces them:

```<code>public static <T extends BusinessInterface> Collection<T> findOr(
    Context pContext, Class<T> pClass, Predicate<? super T>... pPredicates) {
  Predicate<? super T> lReducedPredicate =
      Arrays.asList(pPredicates).stream().reduce(Predicate::or).orElse(r -> false);
  return find(pContext, pClass, lReducedPredicate);
}
</code>```

Unfortunately I get following compiler error:

Predicate lReducedPredicate = Arrays.asList(pPredicates).stream().reduce(Predicate::or).orElse(r -> false);
  incompatible types: Predicate cannot be converted to Predicate
  where T is a type-variable:
  T extends BusinessInterface declared in method findOr(Context,Class,Predicate...)
  where CAP#1,CAP#2 are fresh type-variables:
  CAP#1 extends Object super: T from capture of ? super T
  CAP#2 extends Object super: T from capture of ? super T

I get not errors in Eclipse and I have no idea what is going wrong.

Any help is really appreciated :).

答:
Your code works for me in intellij, but not in ideone, which is strange.

The reason for the compiler error is that you're effectively trying to do this:

```<code>Predicate<? super T> a = null;
Predicate<? super T> b = null;
a.or(b);  // Compiler error!
</code>```

Because of the separate wildcards on both a and b, the compiler can't guarantee that the type bounds are compatible, because those wildcards are not necessarily the same.

Anyway, try this one weird trick:

```<code>Arrays.asList(pPredicates)
    .stream()
    .map(a -> a)  // Here!
    .reduce(Predicate::or)
    .orElse(r -> false);
</code>```

Inserting this line allows it to cast to the type which matches the type constraints.

Title: stream reduction incompatible types

Body:
I'm trying to create a finder which takes several predicates and reduces them:

public static <T extends BusinessInterface> Collection<T> findOr(
    Context pContext, Class<T> pClass, Predicate<? super T>... pPredicates) {
  Predicate<? super T> lReducedPredicate =
      Arrays.asList(pPredicates).stream().reduce(Predicate::or).orElse(r -> false);
  return find(pContext, pClass, lReducedPredicate);
}

Unfortunately I get following compiler error:

Predicate lReducedPredicate = Arrays.asList(pPredicates).stream().reduce(Predicate::or).orElse(r -> false);
  incompatible types: Predicate cannot be converted to Predicate
  where T is a type-variable:
  T extends BusinessInterface declared in method findOr(Context,Class,Predicate...)
  where CAP#1,CAP#2 are fresh type-variables:
  CAP#1 extends Object super: T from capture of ? super T
  CAP#2 extends Object super: T from capture of ? super T

I get not errors in Eclipse and I have no idea what is going wrong.

Any help is really appreciated :).

Body:
Your code works for me in intellij, but not in ideone, which is strange.

The reason for the compiler error is that you're effectively trying to do this:

Predicate<? super T> a = null;
Predicate<? super T> b = null;
a.or(b);  // Compiler error!

Because of the separate wildcards on both a and b, the compiler can't guarantee that the type bounds are compatible, because those wildcards are not necessarily the same.

Anyway, try this one weird trick:

Arrays.asList(pPredicates)
    .stream()
    .map(a -> a)  // Here!
    .reduce(Predicate::or)
    .orElse(r -> false);

Inserting this line allows it to cast to the type which matches the type constraints.


问:
Cannot find namespace System.IdentityModel.Services
I'm trying to provide user authentication by implementing UserNamePasswordValidator. I have added Microsoft.IdentityModel and System.IdentityModel.Tokens.ValidatingIssuerNameRegistry nuget packages.

I'm getting and error when I implement UserNamePasswordValidator in my class UserAuthentication saying

The type or namespace name Selectors does not exist in namespace
System.IdentityModel (are you missing some reference).

Why is this failing?

```<code>public class UserAuthentication : System.IdentityModel.Selectors.UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {
        try
        {
            if (userName == "test" && password == "test123")
            {
                Console.WriteLine("Authentic User");
            }
        }
        catch (Exception ex)
        {
            throw new FaultException("Unknown Username or Incorrect Password");
        }
    }
}
</code>```

答:
Adding the nuget package is not enough (and also in your case, unnecessary), you need to reference the dll in your project. Look for the References list in the solution explorer.

Right click -> Add Reference -> type System.IdentityModel to search box -> select the right dll -> click OK -> Good to go

Body:
I'm trying to provide user authentication by implementing UserNamePasswordValidator. I have added Microsoft.IdentityModel and System.IdentityModel.Tokens.ValidatingIssuerNameRegistry nuget packages.

I'm getting and error when I implement UserNamePasswordValidator in my class UserAuthentication saying

The type or namespace name Selectors does not exist in namespace
System.IdentityModel (are you missing some reference).

Why is this failing?

public class UserAuthentication : System.IdentityModel.Selectors.UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {
        try
        {
            if (userName == "test" && password == "test123")
            {
                Console.WriteLine("Authentic User");
            }
        }
        catch (Exception ex)
        {
            throw new FaultException("Unknown Username or Incorrect Password");
        }
    }
}


问:
why / what is a true / false plot?
I got along via summary(object) works but plot(object) not to plot a subset of a data frame (lots of devices and each with Amplification against Voltage). Now I almost have the wanted result but why is the subset provided with two plots respectively divided into a false and true plot? Is the one plot the one I restricted (true) and the other plot all other subsets (false)?

I plotted it via lattice: xyplot(Amplification ~ Voltage | Serial_number==912009913, data=before, grid=TRUE)

(A "true / false plot lattice r" searching or something similar didn't provide me with a(ny) result)

答:
The | in lattice xyplot means conditional on, so FALSE corresponds to devices that do not have the serial number 912009913, and TRUE corresponds to the device with serial number 912009913. If you only want a plot for your device, I think the syntax you need is

```<code>xyplot(Amplification~Voltage, data=before[before$Serial_number==912009913,],
    grid=TRUE)
</code>```

Title: why / what is a true / false plot?

Body:
The | in lattice xyplot means conditional on, so FALSE corresponds to devices that do not have the serial number 912009913, and TRUE corresponds to the device with serial number 912009913. If you only want a plot for your device, I think the syntax you need is

xyplot(Amplification~Voltage, data=before[before$Serial_number==912009913,],
    grid=TRUE)


问:
TelecomManager Android
I am using this to get the phone no from sim,

```<code>TelecomManager tm = (TelecomManager) getSystemService(TELEPHONY_SERVICE);
String simphonenumber = tm.getLine1Number();
</code>```

but I get an error as :

```<code>'getLine1Number(PhoneAccountHandle) in TelecomManager cannot be applied to     0'
</code>```

Also I am not able to access :

```<code>tm.getDeviceId();
tm.getSimSerialNumber();
</code>```

答:
You need to pass a PhoneAccountHandle as argument of tm.getLine1Number();

There is many way to have a phoneAccountHandle :

PhoneAccountHandle phoneAccountHandle =  tm.getSimCallManager();

or

```<code>ComponentName componentName = new ComponentName("package name here", "your connection service class here");
PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(componentName, "just a label");`
</code>```

Then you can call tm.getLine1Number(phoneAccountHandle); but be aware of null pointer exception (if it doesn't find any number, it returns null).

Title: TelecomManager Android

Body:
I am using this to get the phone no from sim,

TelecomManager tm = (TelecomManager) getSystemService(TELEPHONY_SERVICE);
String simphonenumber = tm.getLine1Number();

but I get an error as :

'getLine1Number(PhoneAccountHandle) in TelecomManager cannot be applied to     0'

Also I am not able to access :

tm.getDeviceId();
tm.getSimSerialNumber();

Body:
You need to pass a PhoneAccountHandle as argument of tm.getLine1Number();

There is many way to have a phoneAccountHandle :

PhoneAccountHandle phoneAccountHandle =  tm.getSimCallManager();

or

ComponentName componentName = new ComponentName("package name here", "your connection service class here");
PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(componentName, "just a label");`

Then you can call tm.getLine1Number(phoneAccountHandle); but be aware of null pointer exception (if it doesn't find any number, it returns null).


问:
Major difference between Angular 1.2.x vs Angular 1.6.x version
I want to know the major difference between these versions like angular 1.6 supports UI router for routing and in angular 1.2 we have to use ng-route for routing</p>

答:
I would advise you to look at the post from Todd Motto :
https://toddmotto.com/angular-1-6-is-here

He is an Expert Developer at Google and covers every changes that happens in the Angular Stack.
Actually, you shouldn't only look at the changes from AngularJs 1.2 to 1.6 because between every minor version brings a slight change/approach to the framework.

FYI, the versionning notation correspond to : Major.Minor.Revision.

However, here is a list of notable changes between 1.2 and 1.6 :

angular.component() + lifecycle hooks

ngAnimate (ngAnimateSwap..)

Service / Factory

ngRoute

Also, Here is the official documentation that list every changes between minor version migration : https://docs.angularjs.org/guide/migration


问:
Dynamic update of Spinner2 based on choice in Spinner 1
In using this code (adapted from here) I get the following error:

The constructor ArrayAdapter(new
  AdapterView.OnItemSelectedListener(){},
  int, String[]) is undefined

Can anyone help correct this? Thanks

```<code>private void setDynamicSpinnerBE() {
    beSpinner = (Spinner) findViewById(R.id.spBE);
    final String[] itemsSpinner2;
    lensSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
            Integer focalLength = (Integer) parent.getAdapter().getItem(
                    position);
            itemsSpinner2 = getBellowsExtension(focalLength, maxBellows,
                    precision);

            ArrayAdapter<CharSequence> beAdapter = new ArrayAdapter<CharSequence>(
                    this, android.R.layout.simple_spinner_item,
                    itemsSpinner2);
            beAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            beSpinner.setAdapter(beAdapter);

        }

        public void onNothingSelected(AdapterView<?> parent) {
            beSpinner.setAdapter(null);
        }
    }

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

答:
In the constructor to your new ArrayAdapter on the following line:

```<code>ArrayAdapter<CharSequence> beAdapter = new ArrayAdapter<CharSequence>(this,
</code>```

this points to the current instance of the OnItemSelectedListener class you are in and not the parent view, this is where the problem occurs because ArrayAdapter does not have a matching constructor.  You should try using MyParentView.this (where MyParentView is the name of the view you are in) instead to pass the appropriate instance.

Body:
In using this code (adapted from here) I get the following error:

The constructor ArrayAdapter(new
  AdapterView.OnItemSelectedListener(){},
  int, String[]) is undefined

Can anyone help correct this? Thanks

private void setDynamicSpinnerBE() {
    beSpinner = (Spinner) findViewById(R.id.spBE);
    final String[] itemsSpinner2;
    lensSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
            Integer focalLength = (Integer) parent.getAdapter().getItem(
                    position);
            itemsSpinner2 = getBellowsExtension(focalLength, maxBellows,
                    precision);

            ArrayAdapter<CharSequence> beAdapter = new ArrayAdapter<CharSequence>(
                    this, android.R.layout.simple_spinner_item,
                    itemsSpinner2);
            beAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            beSpinner.setAdapter(beAdapter);

        }

        public void onNothingSelected(AdapterView<?> parent) {
            beSpinner.setAdapter(null);
        }
    }

    );
    ...
}

Body:
In the constructor to your new ArrayAdapter on the following line:

ArrayAdapter<CharSequence> beAdapter = new ArrayAdapter<CharSequence>(this,

this points to the current instance of the OnItemSelectedListener class you are in and not the parent view, this is where the problem occurs because ArrayAdapter does not have a matching constructor.  You should try using MyParentView.this (where MyParentView is the name of the view you are in) instead to pass the appropriate instance.


问:
Using Tqdm to add a Progress Bar when Downloading Files
I have been trying to set up a progress bar using the Tqdm module in python 3.6 but seems i am halfway there.

My code is the following:

```<code>from tqdm import tqdm
import requests
import time

url = 'http://alpha.chem.umb.edu/chemistry/ch115/Mridula/CHEM%20116/documents/chapter_20au.pdf'

# Streaming, so we can iterate over the response.
r = requests.get(url, stream=True)
#Using The Url as a filename
local_filename = url.split('/')[-1]
# Total size in bytes.
total_size = int(r.headers.get('content-length', 0))
#Printing Total size in Bytes
print(total_size)

#TQDM
with open(local_filename, 'wb') as f:
    for data in tqdm(r.iter_content(chunk_size = 512), total=total_size, unit='B', unit_scale=True):
        f.write(data)
</code>```

The Issue is that, when i insert the chunk_size = 512 in r.iter_content the progress bar does not load at all while showing the downloading data, but when i remove chunk_size = 512 completely and leave the parentheses blank the bar loads up exactly as it should but the download speed is horrible.

What am i doing wrong here?

答:
You're not far off but simply missing pretty much all the code to make the progress bar work accordingly. Assuming you have already created your interface, here is a method I used for my progress bar. It downloads the file and saves it on the desktop (but you can specify where you want to save it). It simply takes how much of the file is downloaded and divides it by the total file size then uses that value to update the progress bar. Let me know if this code helps:

```<code>url = 'http://alpha.chem.umb.edu/chemistry/ch115/Mridula/CHEM%20116/documents/chapter_20au.pdf'
save = 'C:/Users/' + username + "/Desktop/"
r = requests.get(url, stream=True)
total_size = int(r.headers["Content-Length"])
downloaded = 0  # keep track of size downloaded so far
chunkSize = 1024
bars = int(total_size / chunkSize)
print(dict(num_bars=bars))
with open(filename, "wb") as f:
    for chunk in tqdm(r.iter_content(chunk_size=chunkSize), total=bars, unit="KB",
                                  desc=filename, leave=True):
        f.write(chunk)
        downloaded += chunkSize  # increment the downloaded
        prog = ((downloaded * 100 / total_size))
        progress["value"] = (prog)  # *100 #Default max value of tkinter progress is 100

return
</code>```

progress = the progress bar

Body:
I have been trying to set up a progress bar using the Tqdm module in python 3.6 but seems i am halfway there.

My code is the following:

from tqdm import tqdm
import requests
import time

url = 'http://alpha.chem.umb.edu/chemistry/ch115/Mridula/CHEM%20116/documents/chapter_20au.pdf'

# Streaming, so we can iterate over the response.
r = requests.get(url, stream=True)
#Using The Url as a filename
local_filename = url.split('/')[-1]
# Total size in bytes.
total_size = int(r.headers.get('content-length', 0))
#Printing Total size in Bytes
print(total_size)

#TQDM
with open(local_filename, 'wb') as f:
    for data in tqdm(r.iter_content(chunk_size = 512), total=total_size, unit='B', unit_scale=True):
        f.write(data)

The Issue is that, when i insert the chunk_size = 512 in r.iter_content the progress bar does not load at all while showing the downloading data, but when i remove chunk_size = 512 completely and leave the parentheses blank the bar loads up exactly as it should but the download speed is horrible.

What am i doing wrong here?

Body:
You're not far off but simply missing pretty much all the code to make the progress bar work accordingly. Assuming you have already created your interface, here is a method I used for my progress bar. It downloads the file and saves it on the desktop (but you can specify where you want to save it). It simply takes how much of the file is downloaded and divides it by the total file size then uses that value to update the progress bar. Let me know if this code helps:

url = 'http://alpha.chem.umb.edu/chemistry/ch115/Mridula/CHEM%20116/documents/chapter_20au.pdf'
save = 'C:/Users/' + username + "/Desktop/"
r = requests.get(url, stream=True)
total_size = int(r.headers["Content-Length"])
downloaded = 0  # keep track of size downloaded so far
chunkSize = 1024
bars = int(total_size / chunkSize)
print(dict(num_bars=bars))
with open(filename, "wb") as f:
    for chunk in tqdm(r.iter_content(chunk_size=chunkSize), total=bars, unit="KB",
                                  desc=filename, leave=True):
        f.write(chunk)
        downloaded += chunkSize  # increment the downloaded
        prog = ((downloaded * 100 / total_size))
        progress["value"] = (prog)  # *100 #Default max value of tkinter progress is 100

return

progress = the progress bar


问:
Phoenix 1.3 problems adding custom action "No function clause ... "
Few day ago, I started using Phoenix 1.3, and everything was fine until I started adding a new action in the controller.

Router.ex

```<code> resources "/users", UserController, only: [:show] do
    resources "/events", EventController do

      get "/:id", EventController, :join, as: :join
    end
  end
</code>```

Event_controller.ex

```<code>def join(conn, %{"event_id" => id}, current_user) do
#some stuff..
conn
  |> put_status(:ok)
  |> put_flash(:info, "You just joined Event")
  |> redirect(to: page_path(conn, :index, current_user))
end
</code>```

then in my show template: /event/show.html.eex

```<code><%= link "To list", to: user_event_path(@conn, :index, @event.user) %>
<%= if @current_user.id != @user.id do %>
  <h1> <%= @user.name %> Event ! </h1>
  <h3> <%= @event.title %></h3>
  <p><%= @event.description %></p>
  <p><%= @event.location %></p>
  <p><%= @event.price %></p>
  <%= link "Join", to: user_event_path(@conn, :join, @current_user.id,
  @event.id), class: "btn btn-default btn-xs" %>
</code>```

I tried to do something like that in other projects with Phoenix 1.2 and its work, but it wasn't exactly the same code.

Can someone help me to understand why it is not working...

Btw sorry for my English!

The Error saying :

```<code>No function clause for Eventoma.Web.Router.Helpers.user_event_path/4
and action :join. The following actions/clauses are supported:
user_event_path(conn_or_endpoint, :create, user_id, opts \\ [])
user_event_path(conn_or_endpoint, :delete, user_id, id, opts \\ [])
user_event_path(conn_or_endpoint, :edit, user_id, id, opts \\ [])
user_event_path(conn_or_endpoint, :index, user_id, opts \\ [])
user_event_path(conn_or_endpoint, :new, user_id, opts \\ [])
user_event_path(conn_or_endpoint, :show, user_id, id, opts \\ [])
user_event_path(conn_or_endpoint, :update, user_id, id, opts \\ [])
    (phoenix) lib/phoenix/router/helpers.ex:299: Phoenix.Router.Helpers.raise_route_error/5
</code>```

答:
You can run mix phx.routes to see which routes are available.

If you run this on the router you provided, you will see:

```<code>$ mix phx.routes
           user_path  GET     /users/:id                            MyApp.Web.UserController :show
     user_event_path  GET     /users/:user_id/events                MyApp.Web.EventController :index
     user_event_path  GET     /users/:user_id/events/:id/edit       MyApp.Web.EventController :edit
     user_event_path  GET     /users/:user_id/events/new            MyApp.Web.EventController :new
     user_event_path  GET     /users/:user_id/events/:id            MyApp.Web.EventController :show
     user_event_path  POST    /users/:user_id/events                MyApp.Web.EventController :create
     user_event_path  PATCH   /users/:user_id/events/:id            MyApp.Web.EventController :update
                      PUT     /users/:user_id/events/:id            MyApp.Web.EventController :update
     user_event_path  DELETE  /users/:user_id/events/:id            MyApp.Web.EventController :delete
user_event_join_path  GET     /users/:user_id/events/:event_id/:id  MyApp.Web.EventController :join
</code>```

The bottom one is the join route:

```<code>user_event_join_path  GET     /users/:user_id/events/:event_id/:id  MyApp.Web.EventController :join
</code>```

There are :user_id, :event_id and id all present.

What you actually want for the this to work:

```<code><%= link "Join", to: user_event_path(@conn, :join, @current_user.id, @event.id), class: "btn btn-default btn-xs" %>
</code>```

Is the following router:

```<code>resources "/users", UserController, only: [:show] do
  resources "/events", EventController
  get "/events/:id", EventController, :join
end
</code>```

Which results in the following:

```<code>user_event_path  GET     /users/:user_id/events/:id        MyApp.Web.EventController :join
</code>```

As an aside, if you are making any changes to your data (which the verb :join suggests) then you should perhaps use a PUT request (based on this answer https://stackoverflow.com/a/630475/219743)

Body:
Few day ago, I started using Phoenix 1.3, and everything was fine until I started adding a new action in the controller.

Router.ex

 resources "/users", UserController, only: [:show] do
    resources "/events", EventController do

      get "/:id", EventController, :join, as: :join
    end
  end

Event_controller.ex

def join(conn, %{"event_id" => id}, current_user) do
#some stuff..
conn
  |> put_status(:ok)
  |> put_flash(:info, "You just joined Event")
  |> redirect(to: page_path(conn, :index, current_user))
end

then in my show template: /event/show.html.eex

<%= link "To list", to: user_event_path(@conn, :index, @event.user) %>
<%= if @current_user.id != @user.id do %>

 <%= @user.name %> Event !

 <%= @event.title %>

<%= @event.description %>

<%= @event.location %>

<%= @event.price %>

  <%= link "Join", to: user_event_path(@conn, :join, @current_user.id,
  @event.id), class: "btn btn-default btn-xs" %>

I tried to do something like that in other projects with Phoenix 1.2 and its work, but it wasn't exactly the same code.

Can someone help me to understand why it is not working...

Btw sorry for my English!

The Error saying :

No function clause for Eventoma.Web.Router.Helpers.user_event_path/4
and action :join. The following actions/clauses are supported:
user_event_path(conn_or_endpoint, :create, user_id, opts \\ [])
user_event_path(conn_or_endpoint, :delete, user_id, id, opts \\ [])
user_event_path(conn_or_endpoint, :edit, user_id, id, opts \\ [])
user_event_path(conn_or_endpoint, :index, user_id, opts \\ [])
user_event_path(conn_or_endpoint, :new, user_id, opts \\ [])
user_event_path(conn_or_endpoint, :show, user_id, id, opts \\ [])
user_event_path(conn_or_endpoint, :update, user_id, id, opts \\ [])
    (phoenix) lib/phoenix/router/helpers.ex:299: Phoenix.Router.Helpers.raise_route_error/5

Body:
You can run mix phx.routes to see which routes are available.

If you run this on the router you provided, you will see:

$ mix phx.routes
           user_path  GET     /users/:id                            MyApp.Web.UserController :show
     user_event_path  GET     /users/:user_id/events                MyApp.Web.EventController :index
     user_event_path  GET     /users/:user_id/events/:id/edit       MyApp.Web.EventController :edit
     user_event_path  GET     /users/:user_id/events/new            MyApp.Web.EventController :new
     user_event_path  GET     /users/:user_id/events/:id            MyApp.Web.EventController :show
     user_event_path  POST    /users/:user_id/events                MyApp.Web.EventController :create
     user_event_path  PATCH   /users/:user_id/events/:id            MyApp.Web.EventController :update
                      PUT     /users/:user_id/events/:id            MyApp.Web.EventController :update
     user_event_path  DELETE  /users/:user_id/events/:id            MyApp.Web.EventController :delete
user_event_join_path  GET     /users/:user_id/events/:event_id/:id  MyApp.Web.EventController :join

The bottom one is the join route:

user_event_join_path  GET     /users/:user_id/events/:event_id/:id  MyApp.Web.EventController :join

There are :user_id, :event_id and id all present.

What you actually want for the this to work:

<%= link "Join", to: user_event_path(@conn, :join, @current_user.id, @event.id), class: "btn btn-default btn-xs" %>

Is the following router:

resources "/users", UserController, only: [:show] do
  resources "/events", EventController
  get "/events/:id", EventController, :join
end

Which results in the following:

user_event_path  GET     /users/:user_id/events/:id        MyApp.Web.EventController :join

As an aside, if you are making any changes to your data (which the verb :join suggests) then you should perhaps use a PUT request (based on this answer https://stackoverflow.com/a/630475/219743)


问:
What's the difference between a "script" and an "application"?
I'm referring to distinctions such as in this answer:

...bash isn't for writing applications it's for, well, scripting. So sure, your application might have some housekeeping scripts but don't go writing critical-business-logic.sh because another language is probably better for stuff like that.

As programmer who's worked in many languages, this seems to be C, Java and other compiled language snobbery.  I'm not looking for reenforcement of my opinion or hand-wavy answers.  Rather, I genuinely want to know what technical differences are being referred to.

(And I use C in my day job, so I'm not just being defensive.)

答:
An application is big and will be used over and over by people and maybe sold to a customer.

A script starts out small, stays small if you're lucky, is rarely sold to a customer, and might either be run automatically or fall into disuse.

OwnerDisplayName: Jon Ericson

OwnerDisplayName: Norman Ramsey


问:
ScrollView Inside ScrollView
I Know people from Google have asked us not to put Scrollable view inside another Scrollable view but is there any official statement from them directing us not to do so?</p>

答:
Is this close enough?

You should never use a
  HorizontalScrollView with a ListView,
  since ListView takes care of its own
  scrolling. Most importantly, doing
  this defeats all of the important
  optimizations in ListView for dealing
  with large lists, since it effectively
  forces the ListView to display its
  entire list of items to fill up the
  infinite container supplied by
  HorizontalScrollView.

http://developer.android.com/reference/android/widget/HorizontalScrollView.html

UPDATE:

Since you may be forced to use a two dimensional scrollview, you may consider using this:
Internet archive of blog.gorges.us/2010/06/android-two-dimensional-scrollview/

I haven't used this but it may be a reasonable approach.

Title: ScrollView Inside ScrollView


问:
iOS AppDelegate crashes when adding didReceiveRemoteNotification
I have the following App delegate for an iOS app in Xcode 8.3:

```<code>@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?

  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  }
}
</code>```

When I start my app in either the simulator or on a device, it crashes with the following message:

```<code>2017-07-04 21:26:04.284336+0200 MyApp[352:25788] -[NSTaggedPointerString containsObject:]: unrecognized selector sent to instance 0xa00000070696f764
2017-07-04 21:26:04.284569+0200 MyApp[352:25788] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-    [NSTaggedPointerString containsObject:]: unrecognized selector sent to  instance 0xa00000070696f764'
*** First throw call stack:
(0x188baefe0 0x187610538 0x188bb5ef4 0x188bb2f54 0x188aaed4c 0x18ef7d030 0x18ef630f4 0x18ef77d18 0x18ef60474 0x18a757884 0x18a7576f0 0x18a757aa0 0x188b5d42c 0x188b5cd9c 0x188b5a9a8 0x188a8ada4 0x18ed4a384 0x18ed45058 0x100106fc8 0x187a9959c)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

In the simulator, it's a slightly different error message:

```<code>2017-07-04 21:30:10.379 MyApp[55965:1127208] -[__NSCFString containsObject:]: unrecognized selector sent to instance 0x608000028d60
2017-07-04 21:30:10.383 MyApp[55965:1127208] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString containsObject:]: unrecognized selector sent to instance 0x608000028d60'
</code>```

Removing the application(:didReceiveRemoteNotification) method makes the crash disappear.

Does anyone have any clue what's going on?

答: Figured out the problem: my Info.plist had 'Background Modes' set to a string instead of an array of modes. Fixing that fixes the crash.

Body:
I have the following App delegate for an iOS app in Xcode 8.3:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?

  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  }
}

When I start my app in either the simulator or on a device, it crashes with the following message:

2017-07-04 21:26:04.284336+0200 MyApp[352:25788] -[NSTaggedPointerString containsObject:]: unrecognized selector sent to instance 0xa00000070696f764
2017-07-04 21:26:04.284569+0200 MyApp[352:25788] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-    [NSTaggedPointerString containsObject:]: unrecognized selector sent to  instance 0xa00000070696f764'
*** First throw call stack:
(0x188baefe0 0x187610538 0x188bb5ef4 0x188bb2f54 0x188aaed4c 0x18ef7d030 0x18ef630f4 0x18ef77d18 0x18ef60474 0x18a757884 0x18a7576f0 0x18a757aa0 0x188b5d42c 0x188b5cd9c 0x188b5a9a8 0x188a8ada4 0x18ed4a384 0x18ed45058 0x100106fc8 0x187a9959c)
libc++abi.dylib: terminating with uncaught exception of type NSException

In the simulator, it's a slightly different error message:

2017-07-04 21:30:10.379 MyApp[55965:1127208] -[__NSCFString containsObject:]: unrecognized selector sent to instance 0x608000028d60
2017-07-04 21:30:10.383 MyApp[55965:1127208] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString containsObject:]: unrecognized selector sent to instance 0x608000028d60'

Removing the application(:didReceiveRemoteNotification) method makes the crash disappear.

Does anyone have any clue what's going on?


问:
Is it possible to use two context entities from two different database
Is it possible to use two context entities from two different database

Code connectiong to one entity:

```<code> Using one FoodSupplyEntities
 using (var contextFood = new FoodSupplyEntities())
        {
        var _result = (from _FoodSupplyStatus in contextFood.FoodSupplyStatus
                      join _FoodQualityStatus in contextFood.FoodQualityStatus
</code>```

But is it possible to join for example another table from a different entities from another server.?

Sample (Dont know but  it might gosomething like this.)

```<code>  using (var contextFood = new FoodSupplyEntities() and contextKitchenware = new KitchenwareEntities() )
        {
        var _result = (from _FoodSupplyStatus in contextFood.FoodSupplyStatus
                      join _KitchenwareSupplyStatus in contextKitchenware.KitchenwareSupplyStatus
</code>```

答:
Suppose you have 2 tables in 2 different databases:

User in Database1

Orders in Database2 where UserId of User table in database 1 is referring OrderedBy in Orders table.

I have Created 2 different context.
now i will create 2 queries for 2 different context and will make join on these queries on UserId and OrderedBy like:

```<code>List<OrderDetails> GetOrderDetails()
    {
        var users = this.TestDb1ModelUnit.GetRepository<User_Login>().GetAll();
        var orders = this.TestDb2ModelUnit.GetRepository<OrderDetail>().GetAll();

        var orderDetails = users.Join(orders,
            usr => usr.User_Id,
            ord => ord.OrderedBy,
            (usr, ord) => new { usr, ord }
            ).ToList();
    }
</code>```

Body:
Is it possible to use two context entities from two different database

Code connectiong to one entity:

 Using one FoodSupplyEntities
 using (var contextFood = new FoodSupplyEntities())
        {
        var _result = (from _FoodSupplyStatus in contextFood.FoodSupplyStatus
                      join _FoodQualityStatus in contextFood.FoodQualityStatus

But is it possible to join for example another table from a different entities from another server.?

Sample (Dont know but  it might gosomething like this.)

  using (var contextFood = new FoodSupplyEntities() and contextKitchenware = new KitchenwareEntities() )
        {
        var _result = (from _FoodSupplyStatus in contextFood.FoodSupplyStatus
                      join _KitchenwareSupplyStatus in contextKitchenware.KitchenwareSupplyStatus

Body:
Suppose you have 2 tables in 2 different databases:

User in Database1

Orders in Database2 where UserId of User table in database 1 is referring OrderedBy in Orders table.

I have Created 2 different context.
now i will create 2 queries for 2 different context and will make join on these queries on UserId and OrderedBy like:

List<OrderDetails> GetOrderDetails()
    {
        var users = this.TestDb1ModelUnit.GetRepository<User_Login>().GetAll();
        var orders = this.TestDb2ModelUnit.GetRepository<OrderDetail>().GetAll();

        var orderDetails = users.Join(orders,
            usr => usr.User_Id,
            ord => ord.OrderedBy,
            (usr, ord) => new { usr, ord }
            ).ToList();
    }


问:
Reactjs Pops undefined in component
I have created react components for a form. I passed data as props from GetSteps component to PageHeader component. Then I will able to use that data from the PageHeader. Also I passed same data from the GetSteps component to YourDetails component. But the data didn't pass to the YourDetails component. I cannot find the error. any help will be appreciated. Thank You.

```<code>class GetSteps extends React.Component {
constructor(props) {
    super(props);
    this.state = {data: ''}
}
// componentWillMount() {
//     var lang = [];
//     $.each(this.props.value.Languages, function(k, v) {
//         return lang[k] = v;
//     }.bind(this));
//     this.setState({ data: this.props.value.Languages })
//
//     console.log(this.state)
// }
render()
{
    return (
        <div className="page-content">
            <div className="container">
                <PageHeader title={this.props.value.Title} subtitle={this.props.value.SubTitle} f={this.props.value.PreferredLanguage}/>
                <YourDetails title={this.props.value.Title} preferredlang={this.props.value.PreferredLanguage}></YourDetails>
            </div>
        </div>
    );
}
</code>```

}

this is where I pass data as props

```<code>function PageHeader(props){

return(
    <div className="page-header">
        <span className="page-header-icon icon-world"></span>
        <h3 className="title">{props.title}</h3>
        <h4 className="sub-title special">{props.subtitle}</h4>
    </div>
);
</code>```

}

this is where I get data from GetSteps component

```<code>class YourDetails extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        havePartner: 'yes',
        UserFirstName: "",
        TravelPartnerName: "",
        AmwayLocation: "",
        Title: this.props.title
    };
    console.log(this.props);

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleOptionChange = this.handleOptionChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event){
    console.log(this.state);
    event.preventDefault();
}
handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'radio' ? target.checked : target.value;
    const name = target.name;

    this.setState({
        [name]: value
    });
}
handleOptionChange(event){
    this.setState({
        havePartner: event.target.value
    });
}
render() {
    return (
        <div className="main-content">
            <form onSubmit={this.handleSubmit}>
                <div className="field dropdown requiredField">
                    <label className="left">
                        Your prefered language
                    </label>
                    <div className="middleColumn">
                        <select name="language"
                                value={this.props.preferredlang}
                                onChange={this.handleInputChange}
                                className="dropdown requiredField align--left">
                            <option defaultValue value={this.props.preferredlang}>{this.props.preferredlang}</option>
                            <option value='g'></option>
                            <option value='fdg'></option>
                            <option value='df'></option>
                            <option value='dfg'></option>
                        </select>
                    </div>
                </div>
                <div className="field requiredField align--left">
                <label>
                    Your First Name
                </label>
                    <input
                        name="UserFirstName"
                        type="text"
                        onChange={this.handleInputChange} />

                </div>
                <div className="field optionset requiredField travel-partner align--left">
                    <label className="left">
                        Did you have a travel partner?
                    </label>
                    <ul className="optionset requiredField travel-partner align--left">
                        <li>
                            <input type="radio"  value="yes" checked={this.state.havePartner === 'yes'} onChange={this.handleOptionChange} className="radio"/>
                            <label>Yes</label>
                        </li>
                        <li>
                            <input type="radio" value="no"  checked={this.state.havePartner === 'no'} onChange={this.handleOptionChange } className="radio"/>
                            <label>No</label>
                        </li>
                    </ul>
                </div>
                <div className="field text requiredField align--left">
                <label className="left">
                    Your travel partner's first name
                </label>
                    <input className="text requiredField align--left"
                        name="TravelPartnerName"
                        type="text"
                        onChange={this.handleInputChange} />
                    </div>
                <div className="field text">
                    <label className="left requiredField">*Required Field</label>
                </div>
                <div className="Actions">
                <button type="submit" value="Submit" className="action nolabel " >
                    <span>Proceed to Day 1</span>
                    <span className="progress"></span>
                </button>
                </div>
            </form>
        </div>
    );
}
</code>```

}

this is where I didn't get data from GetSteps component

```<code>class Step extends React.Component {
constructor(props) {
    super(props);
    this.state = {data: ''}
}
componentWillMount() {
    var link = document.getElementById('step').getAttribute('link');
    $.getJSON( link+"VideoBuildForm", function( data, status ) {
        fieldValues.PreferredLanguage = data.compilation.PreferredLanguage;
        fieldValues.AmwayLocation = data.location;
        fieldValues.Languages =
            $.each(data.languages, function(k, v) {
                return data.languages[k] = v;
            });
        fieldValues.Title = data.title;
        fieldValues.SubTitle = data.subtitle;
        this.setState({ data: fieldValues });
    }.bind(this));

}

render() {
    return (
        <div>
            <GetSteps value={this.state.data}/>
        </div>
    );
}
</code>```

}

this is where I pass data to the GetSteps component

答: Try using props.title in your constructor instead of this.props.title.

Title: Reactjs Pops undefined in component

Body:
I have created react components for a form. I passed data as props from GetSteps component to PageHeader component. Then I will able to use that data from the PageHeader. Also I passed same data from the GetSteps component to YourDetails component. But the data didn't pass to the YourDetails component. I cannot find the error. any help will be appreciated. Thank You.

class GetSteps extends React.Component {
constructor(props) {
    super(props);
    this.state = {data: ''}
}
// componentWillMount() {
//     var lang = [];
//     $.each(this.props.value.Languages, function(k, v) {
//         return lang[k] = v;
//     }.bind(this));
//     this.setState({ data: this.props.value.Languages })
//
//     console.log(this.state)
// }
render()
{
    return (

                <PageHeader title={this.props.value.Title} subtitle={this.props.value.SubTitle} f={this.props.value.PreferredLanguage}/>
                <YourDetails title={this.props.value.Title} preferredlang={this.props.value.PreferredLanguage}></YourDetails>

    );
}

}

this is where I pass data as props

function PageHeader(props){

return(

{props.title}

{props.subtitle}

);

}

this is where I get data from GetSteps component

class YourDetails extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        havePartner: 'yes',
        UserFirstName: "",
        TravelPartnerName: "",
        AmwayLocation: "",
        Title: this.props.title
    };
    console.log(this.props);

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleOptionChange = this.handleOptionChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event){
    console.log(this.state);
    event.preventDefault();
}
handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'radio' ? target.checked : target.value;
    const name = target.name;

    this.setState({
        [name]: value
    });
}
handleOptionChange(event){
    this.setState({
        havePartner: event.target.value
    });
}
render() {
    return (

            <form onSubmit={this.handleSubmit}>

                        Your prefered language

                        <select name="language"
                                value={this.props.preferredlang}
                                onChange={this.handleInputChange}
                                className="dropdown requiredField align--left">
                            <option defaultValue value={this.props.preferredlang}>{this.props.preferredlang}</option>
                            <option value='g'></option>
                            <option value='fdg'></option>
                            <option value='df'></option>
                            <option value='dfg'></option>
                        </select>

                    Your First Name

                    <input
                        name="UserFirstName"
                        type="text"
                        onChange={this.handleInputChange} />

                        Did you have a travel partner?

                            <input type="radio"  value="yes" checked={this.state.havePartner === 'yes'} onChange={this.handleOptionChange} className="radio"/>
                            Yes

                            <input type="radio" value="no"  checked={this.state.havePartner === 'no'} onChange={this.handleOptionChange } className="radio"/>
                            No

                    Your travel partner's first name

                    <input className="text requiredField align--left"
                        name="TravelPartnerName"
                        type="text"
                        onChange={this.handleInputChange} />

                    *Required Field

                <button type="submit" value="Submit" className="action nolabel " >
                    Proceed to Day 1

                </button>

            </form>

    );
}

}

this is where I didn't get data from GetSteps component

class Step extends React.Component {
constructor(props) {
    super(props);
    this.state = {data: ''}
}
componentWillMount() {
    var link = document.getElementById('step').getAttribute('link');
    $.getJSON( link+"VideoBuildForm", function( data, status ) {
        fieldValues.PreferredLanguage = data.compilation.PreferredLanguage;
        fieldValues.AmwayLocation = data.location;
        fieldValues.Languages =
            $.each(data.languages, function(k, v) {
                return data.languages[k] = v;
            });
        fieldValues.Title = data.title;
        fieldValues.SubTitle = data.subtitle;
        this.setState({ data: fieldValues });
    }.bind(this));

}

render() {
    return (

            <GetSteps value={this.state.data}/>

    );
}

}

this is where I pass data to the GetSteps component


问:
how to reduce number of condition checks when I select one/two/three/four/five/six from the 6 select options?
Example: When I have only two select options

```<code>input_one = 'one';
input_two = 'two';
</code>```

when I select only input_one

```<code>if((isset($_POST['input_one']) && (!isset($_POST['input_two']) {
    //query
}
</code>```

When I select only input_two

```<code>elseif((!isset($_POST['input_one']) && (isset($_POST['input_two'])) {
    //query
}
</code>```

When I don't select any of those

```<code>elseif((!isset($_POST['input_one']) && (!isset($_POST['input_two'])) {
    //query
}
</code>```

When I select both of them

```<code>elsif((isset($_POST['input_one']) && (!isset($_POST['input_two'])) {
    //query
}
</code>```

but when I have 6 input options then I need to write a number of conditions. How do I reduce those, if there is any alternate method?

答:
an example for four conditions:

```<code><?php
$c = 0;
//basic conditions...............
if( isset($_POST['input_1'] ) $c += 1; //set 1st bit
if( isset($_POST['input_2'] ) $c += 2; //set 2nd bit
if( isset($_POST['input_3'] ) $c += 4; //set 3rd bit
if( isset($_POST['input_4'] ) $c += 8; //set 4th bit

//additional conditions...............
if($c < 8){ //0..7
    if($c < 4){ //0..3
        if($c < 2){ //0..1
            if($c == 0){        //nothing set
            }else{ // 1         //input_1
            }
        }else{ //2..3
            if($c == 2){        //input_2
            }else{ //3          //input_1 input_2
            }
        }
    }else{ //4..7
        if($c < 6){//4..5
            if($c == 4){        //input_3
            }else{ // 5         //input_1 input_3
            }
        }else{//6..7
            if($c == 6) {       //input_2 input_3
            }else{ // 7         //input_1 input_2 input_3
            }
        }
    }
}else{ //8..15
    if($c < 12){ //8..11
        if($c < 10){ //8..9
            if($c == 8){        //input_4
            }else{ // 9         //input_1 input_4
            }
        }else{ //10..11
            if($c == 10){       //input_2 input_4
            }else{ //11         //input_1 input_2 input_4
            }
        }
    }else{ //12..15
        if($c < 14){//12..13
            if($c == 12){       //input_3 input_4
            }else{ // 13        //input_1 input_3 input_4
            }
        }else{//14..15
            if($c == 14) {      //input_2 input_3 input_4
            }else{ // 15        //input_1 input_2 input_3 input_4
            }
        }
    }
}
?>
</code>```

In this case we have to check 8 condition to get all the issets states.
So it could not be the optimal solution when we have only 4 parameters what produces only 2^4=16 possibilities.

But if we take 6 arguments:
Then we have to check 6 basic onditions and 6 additionals.
So it gives 12 conditions to check when there is 2^6=64 possibilites.

Lets take 7 args:
Then we have 7 + 7 = 14 condition to check to get one of 2^7=128 possibilities.
And now we start to see advantages for bigger amount of arguments.

Body:
Example: When I have only two select options

input_one = 'one';
input_two = 'two';

when I select only input_one

if((isset($_POST['input_one']) && (!isset($_POST['input_two']) {
    //query
}

When I select only input_two

elseif((!isset($_POST['input_one']) && (isset($_POST['input_two'])) {
    //query
}

When I don't select any of those

elseif((!isset($_POST['input_one']) && (!isset($_POST['input_two'])) {
    //query
}

When I select both of them

elsif((isset($_POST['input_one']) && (!isset($_POST['input_two'])) {
    //query
}

but when I have 6 input options then I need to write a number of conditions. How do I reduce those, if there is any alternate method?

Body:
an example for four conditions:

<?php
$c = 0;
//basic conditions...............
if( isset($_POST['input_1'] ) $c += 1; //set 1st bit
if( isset($_POST['input_2'] ) $c += 2; //set 2nd bit
if( isset($_POST['input_3'] ) $c += 4; //set 3rd bit
if( isset($_POST['input_4'] ) $c += 8; //set 4th bit

//additional conditions...............
if($c < 8){ //0..7
    if($c < 4){ //0..3
        if($c < 2){ //0..1
            if($c == 0){        //nothing set
            }else{ // 1         //input_1
            }
        }else{ //2..3
            if($c == 2){        //input_2
            }else{ //3          //input_1 input_2
            }
        }
    }else{ //4..7
        if($c < 6){//4..5
            if($c == 4){        //input_3
            }else{ // 5         //input_1 input_3
            }
        }else{//6..7
            if($c == 6) {       //input_2 input_3
            }else{ // 7         //input_1 input_2 input_3
            }
        }
    }
}else{ //8..15
    if($c < 12){ //8..11
        if($c < 10){ //8..9
            if($c == 8){        //input_4
            }else{ // 9         //input_1 input_4
            }
        }else{ //10..11
            if($c == 10){       //input_2 input_4
            }else{ //11         //input_1 input_2 input_4
            }
        }
    }else{ //12..15
        if($c < 14){//12..13
            if($c == 12){       //input_3 input_4
            }else{ // 13        //input_1 input_3 input_4
            }
        }else{//14..15
            if($c == 14) {      //input_2 input_3 input_4
            }else{ // 15        //input_1 input_2 input_3 input_4
            }
        }
    }
}
?>

In this case we have to check 8 condition to get all the issets states.
So it could not be the optimal solution when we have only 4 parameters what produces only 2^4=16 possibilities.

But if we take 6 arguments:
Then we have to check 6 basic onditions and 6 additionals.
So it gives 12 conditions to check when there is 2^6=64 possibilites.

Lets take 7 args:
Then we have 7 + 7 = 14 condition to check to get one of 2^7=128 possibilities.
And now we start to see advantages for bigger amount of arguments.


问:
BDD naming: when does it stop being about the user experience?
I'm drawn to MSpec with the hopes of one day sharing my test reports with non-developers*, but that is most valuable (right?) if I discuss the business (the user experience) in the test/scenario names (instead of the individual C# objects/members actually under test).

But I'm struggling, with my low-level functionality, to cite non-developer concerns in my test/scenario names.  The farther the concern is from the UI, the more difficulty in naming the scenario such that it both a) is relevant to the non-developer and b) describes the low-level functionality being tested.

As you move farther and farther from the UI, is there a point at which test/scenario names just can't be shared with non-developers?  I feel like the answer should be "no", because I shouldn't be testing behavior unless it's something the non-developer cares about, but I'm failing regularly enough that I'm not sure what I'm missing.

If there are obvious answers somewhere, I'd appreciate some citations/references.

* e.g. end users or other stakeholders ("stakeholders" might include future developers -- or me in a year and a half -- using these specifications to gain insight into the why of the system)

答:
We normally use the word "scenario" to describe full-system, user-POV scenarios.

If you would like a word to describe class-level behaviour, try "example".

Your examples will be from the points of view of the users of your class. If those user classes want particularly developer-centric behaviour, then, yes, your examples will end up with developer-centric concerns in them.

Having said that, here are some vocabulary changes which I've found let me phrase the value I'm looking for in the most business-oriented way I can:

returns  -> tells me  or gives me

calls  -> delegates, asks

handles concurrency -> handles two things at once

extends -> is a

implements -> performs the role of

Basically, if you're using a developer-jargon word, imagine explaining it to someone in a few more words, then use that.

I wouldn't go overboard with it, though. The reason for using the stakeholders' domain specific terms in scenarios is because stakeholders are interested in reading and (hopefully) writing them. The audience for the class-level examples is technical, so it doesn't matter so much if we have technical concerns in them.


问:
Kerberos cache user how it works
I have a question regarding the kerberos sytem. I suceed installing on my linux machine in colaboration with apache but i don't understand a thing. If the user is still logged in, I mean he can access the secured application, if I write on terminal:

```<code>klist
</code>```

to see the ticket for that user it gives me nothing. But my client is already logged in. Only the first time I was supposed to enter the kinit command for that user and then to check with klist. How actually Kerberos works? If the first time when I created the user, I must initiate with kinit and klist the token, then what the heck?

答:
From my understanding, running kinit is to obtain the TGT ticket from the KDC. Only with TGT ticket, can you be able to request the Service Ticket.

For a TGT ticket, it has certain time duration of validity, meaning that client doesn't have to get the TGT ticket for every request after already getting a TGT ticket. Additionally, client can not only specify the location to put the TGT ticket for persistence, but also the memory cache. That's why you find the cache is empty by klist command but still you can access the service.

Title: Kerberos cache user how it works

Body:
I have a question regarding the kerberos sytem. I suceed installing on my linux machine in colaboration with apache but i don't understand a thing. If the user is still logged in, I mean he can access the secured application, if I write on terminal:

klist

to see the ticket for that user it gives me nothing. But my client is already logged in. Only the first time I was supposed to enter the kinit command for that user and then to check with klist. How actually Kerberos works? If the first time when I created the user, I must initiate with kinit and klist the token, then what the heck?


问:
What's Objective-C's equivalent of Swift's inout Parameters?
I'm back on writing Objective-C code again and is trying to find the equivalent of Swift's inout parameter notation in Objective-C.

```<code>func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}
</code>```

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID158

So far I've learned: 1.inout is not objc-compatible. 2.objc simply doesn't have language feature like this.

However, when I'm designing my API, I want it to be clear that this method is modifying its parameter. Is there any good way to accomplish this in Objective-C? Thank you!

答:
For bridging between obj-c and swift, you can put your params in a class and pass that in: https://stackoverflow.com/a/26288083/78496

You can sort of do inout in Obj-C, you just don't see it very often.

```<code>- (void) doThing: (int *) varA andAnother:(int *) varB
{
    int temp = *varA;
    *varA = *varB;
    *varB = temp;
}
</code>```

Then you'd call it using & to pass a reference

```<code>int i = 1;
int j = 2;
[self doThing:&i andAnother:&j]
</code>```

Body:
I'm back on writing Objective-C code again and is trying to find the equivalent of Swift's inout parameter notation in Objective-C.

func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID158

So far I've learned: 1.inout is not objc-compatible. 2.objc simply doesn't have language feature like this.

However, when I'm designing my API, I want it to be clear that this method is modifying its parameter. Is there any good way to accomplish this in Objective-C? Thank you!

Body:
For bridging between obj-c and swift, you can put your params in a class and pass that in: https://stackoverflow.com/a/26288083/78496

You can sort of do inout in Obj-C, you just don't see it very often.

- (void) doThing: (int *) varA andAnother:(int *) varB
{
    int temp = *varA;
    *varA = *varB;
    *varB = temp;
}

Then you'd call it using & to pass a reference

int i = 1;
int j = 2;
[self doThing:&i andAnother:&j]


问:
How to get rid of underlined links
I learn via Freecodecamp, one of our tasks was to create a Portfolio, but I cannot get rid of the underline links inside my navbar and footnote.

Text-decoration: none; does not help, any other ideas?

body {
  max-width: 100%;
  position: relative;
  overflow-x: hidden;
}

.container {
  z-index: 5;
  background-color: #8f8a01;
  position: fixed;
  top: 0;
  margin: auto;
  width: 100%;
  box-shadow: 2px 2px 2px #888;
  padding-bottom: 5px;
  text-decoration: none;
}

button {
  margin: 15px 0px 0px 15px;
  box-shadow: 2px 2px 2px #888;
  background-color: #ece2b4;
  font-family: 'Rajdhani', sans-serif;
  font-size: 17px;
  font-weight: 800;
  color: #8f8a01;
}

button:hover {
  background-color: #edce00;
}

a {
  text-decoration: none;
}

.about {
  min-height: 380px;
  margin: auto;
  width: 100%;
  padding: 50px 220px 70px 200px;
  background-color: #ece2b4;
  line-height: 50px;
  text-align: left;
  overflow: auto;
}

p {
  padding-left: 150px;
}

.photo {
  width: 200px;
  heihgt: 200px;
  float: right;
  margin-right: 0px;
  margin-left: 0px;
  border-radius: 120px;
  box-shadow: 2px 2px 2px #888;
}

#port {
  background-color: #bdb817;
  padding: 10px 10px 19px 10px;
  margin: auto;
  width: 100%;
}

.left-link {
  margin: 25px;
  padding: 5px 30px 15px 5px;
}

.right-link {
  margin: 25px;
  padding: 5px 30px 15px 5px;
}

#port {
  align: center;
}

img:hover {
  background-color: #edce00;
}

.small-img {
  padding: 5px;
  border: 1px solid gray;
  height: 250px;
  width: 300px;
  max-height: 350px;
  max-width: 400px;
  border-radius: 15px;
  box-shadow: 2px 2px 2px #888;
}

input {
  text-align: center;
}

.send-btn {
  margin: 10px 10px 50px 10px;
}

.ctcMe {
  z-index: 1;
  background-color: #ece2b4;
  line-height: 30px;
  margin: auto;
  width: 100%;
  padding-top: 2px;
}

input {
  border-radius: 0px;
  border-top: none;
  border-left: none;
  width: 200px;
}

textarea {
  border-radius: 0px;
  border-top: none;
  border-left: none;
  width: 200px;
}

.contact {
  text-align: center;
}

.send-btn {
  margin-left: 0%;
}

.web {
  background-color: #bdb817;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: auto;
  width: 100%;
}

.fc {
  width: 30px;
  height: 30px;
}

.coded {
  background-color: #edce00;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: auto;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <div class="container">
    <div class="row">
      <div class="col-xs-2">

          <button class="btn btn-block">
          About</button>
      </div>
      <div class="col-xs-2">

          <button class="btn btn-block">Portfolio</button>
      </div>

      <div class="col-xs-2">

          <button class="btn btn-block">Contact</button>
      </div>
    </div>
    <!-- close ROW -->
  </div>
  <!-- close HEAD -->

  <div class="about">
    <h2 style="text-align: center">

      ABOUT </h2>

      <img src="https://media.licdn.com/mpr/mpr/shrinknp_200_200/AAEAAQAAAAAAAAzEAAAAJDkwZTM5NmY4LWYwMzQtNDhmOS1hYzExLTM4YWI5NTZmMGI5ZA.jpg" alt="picture of me" class="img-responsive photo">
      <center>
        <p> I am a book-lover translator, and an excellent-organised personal assistant.
          <br> I help my team daily to get through the week from chaos to clarity,
          <br> and I provide my colleagues with comprehensive translations and proofreading.
          <br> Recently I am also a coding hobbyist and a Front-End Developer wannabe.
        </p>
      </center>
  </div>

  <div id="port">
    <h2 style="text-align: center"> PORTFOLIO</h2>
    <br>
    <div class="row img-center">
      <div class="col-xs-offset-2">
        <img class="small-img" src="http://www.drodd.com/images15/1-12.jpg">
        <img class="small-img" src="http://www.edu.xunta.gal/centros/ceipramoncajal/?q=system/files/u2/globo2fantasia.jpg">
        <img class="small-img" src="https://rfclipart.com/image/big/67-84-40/strawberry-style-font-number-3-Download-Royalty-free-Vector-File-EPS-71206.jpg">
      </div>
      <!-- close COL -->
    </div>
    <!--- close ROW -->
    <br>
    <div class="row img-center">
      <div class="col-xs-offset-2">

        <img class="small-img" src="http://3.bp.blogspot.com/-9cSZuRMO65M/UOYn20oxGUI/AAAAAAAALgg/zTyw-uLPkO8/s1600/number4.jpg">
        <img class="small-img" src="https://thebitterlemon.files.wordpress.com/2016/09/5.jpg?w=400">
        <img class="small-img" src="https://thumbs.dreamstime.com/z/liczby-kresk%C3%B3wki-%C5%9Bmieszny-r%C3%B3%C5%BCowy-flaming-31350873.jpg">
      </div>
      <!--close COL -->
    </div>
    <!--close ROW -->
  </div>
  <!-- close PORT -->
  <div class="ctcMe">
    <h2 style="text-align: center">

    CONTACT ME</h2>
      <br>
      <div class="row" style="margin-top: 10px;">
        <div class="col-xs-7">
          <p class="contact">If you have any requests or questions<br>I am very eager to answer them :) </p>
        </div>
        <!-- close COL -->

        <div class="col-xs-2">
          <form><input type="text" placeholder="name">
            <input type="text" placeholder="e-mail addres">
            <input type="text" placeholder="phone number">
            <textarea style="text-align: center" type="text" placeholder="message">
         </textarea>
          </form>
          <form><button class="btn send-btn" type="mailo">SEND</button></form>
          </form>
        </div>
        <!-- close COL -->
      </div>
      <!-- close ROW -->

  </div>
  <!-- close CtcMe -->

  <div class="web">
    <center>
      <p class="footnote">
        Around the web:
        <br>
        <img class="fc" src="https://yt3.ggpht.com/-bWUaHwGz7To/AAAAAAAAAAI/AAAAAAAAAAA/xEUD6X5iT2Y/s900-c-k-no-mo-rj-c0xffffff/photo.jpg">
        <img class="fc" src="http://www.blitzcleaned.com/wp-content/uploads/2014/07/LI-Logo-1.png">
        <img class="fc" src="http://www.freeiconspng.com/uploads/github-logo-icon-0.png">
        href="https://codepen.io/Broccolina/"><img class="fc" src="https://blog.codepen.io/wp-content/uploads/2012/06/Button-Black-Large.png">
      </p>
    </center>
  </div>

  <div class="coded">
    <center>
      <p class="footnote">
        Written and coded by
        href="https://www.facebook.com/broccolina19"> Agnieszka Kozub
      </p>
    </center>
  </div>
</body></code>```

答:
AFAK even a:link { text-decoration: none } should be enough.
Or even a { text-decoration: none }. But in this last case even anchors (other than href, e.g. Bla) will be affected.

Title: How to get rid of underlined links

Body:
I learn via Freecodecamp, one of our tasks was to create a Portfolio, but I cannot get rid of the underline links inside my navbar and footnote.

Text-decoration: none; does not help, any other ideas?

body {
  max-width: 100%;
  position: relative;
  overflow-x: hidden;
}

.container {
  z-index: 5;
  background-color: #8f8a01;
  position: fixed;
  top: 0;
  margin: auto;
  width: 100%;
  box-shadow: 2px 2px 2px #888;
  padding-bottom: 5px;
  text-decoration: none;
}

button {
  margin: 15px 0px 0px 15px;
  box-shadow: 2px 2px 2px #888;
  background-color: #ece2b4;
  font-family: 'Rajdhani', sans-serif;
  font-size: 17px;
  font-weight: 800;
  color: #8f8a01;
}

button:hover {
  background-color: #edce00;
}

a {
  text-decoration: none;
}

.about {
  min-height: 380px;
  margin: auto;
  width: 100%;
  padding: 50px 220px 70px 200px;
  background-color: #ece2b4;
  line-height: 50px;
  text-align: left;
  overflow: auto;
}

p {
  padding-left: 150px;
}

.photo {
  width: 200px;
  heihgt: 200px;
  float: right;
  margin-right: 0px;
  margin-left: 0px;
  border-radius: 120px;
  box-shadow: 2px 2px 2px #888;
}

#port {
  background-color: #bdb817;
  padding: 10px 10px 19px 10px;
  margin: auto;
  width: 100%;
}

.left-link {
  margin: 25px;
  padding: 5px 30px 15px 5px;
}

.right-link {
  margin: 25px;
  padding: 5px 30px 15px 5px;
}

#port {
  align: center;
}

img:hover {
  background-color: #edce00;
}

.small-img {
  padding: 5px;
  border: 1px solid gray;
  height: 250px;
  width: 300px;
  max-height: 350px;
  max-width: 400px;
  border-radius: 15px;
  box-shadow: 2px 2px 2px #888;
}

input {
  text-align: center;
}

.send-btn {
  margin: 10px 10px 50px 10px;
}

.ctcMe {
  z-index: 1;
  background-color: #ece2b4;
  line-height: 30px;
  margin: auto;
  width: 100%;
  padding-top: 2px;
}

input {
  border-radius: 0px;
  border-top: none;
  border-left: none;
  width: 200px;
}

textarea {
  border-radius: 0px;
  border-top: none;
  border-left: none;
  width: 200px;
}

.contact {
  text-align: center;
}

.send-btn {
  margin-left: 0%;
}

.web {
  background-color: #bdb817;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: auto;
  width: 100%;
}

.fc {
  width: 30px;
  height: 30px;
}

.coded {
  background-color: #edce00;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: auto;
  width: 100%;
}

  <meta name="viewport" content="width=device-width, initial-scale=1">

          <button class="btn btn-block">
          About</button>

          <button class="btn btn-block">Portfolio</button>

          <button class="btn btn-block">Contact</button>

      ABOUT

 I am a book-lover translator, and an excellent-organised personal assistant.

 I help my team daily to get through the week from chaos to clarity,

 and I provide my colleagues with comprehensive translations and proofreading.

 Recently I am also a coding hobbyist and a Front-End Developer wannabe.

 PORTFOLIO

    CONTACT ME

If you have any requests or questions
I am very eager to answer them :)

          <form><input type="text" placeholder="name">
            <input type="text" placeholder="e-mail addres">
            <input type="text" placeholder="phone number">
            <textarea style="text-align: center" type="text" placeholder="message">
         </textarea>
          </form>
          <form><button class="btn send-btn" type="mailo">SEND</button></form>
          </form>

        Around the web:

        Written and coded by
         Agnieszka Kozub

Body:
AFAK even a:link { text-decoration: none } should be enough.
Or even a { text-decoration: none }. But in this last case even anchors (other than href, e.g. <a name='bla'>Bla</a>) will be affected.


问:
VBA for aligning the pivot table
I am using an VBA to generate the Pivot Table.

I wanted to Center align my values in the Pivot table, I used the follwing line, in my code, I am getting object required error.

I researched in net, and everywhere it is the same, that we use

DataLabel.HorizontalAlignment = xlCenter

Below is the code, i am using to generate my Pivot table and trying to align the data values in the cell Center, Could someone suggest, where i am going wrong and how i could correct it.

```<code>Sub sum2017()
Dim ws9 As Worksheet
Dim pc9 As PivotCache
Dim pt9 As PivotTable
Dim ct9 As Integer
Set ws9 = Sheets("Sum2017")
Set pc9 = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'Result'!R1C1:R1048576C6")
Set pt9 = pc9.CreatePivotTable(ws9.Range("A3"))
pt9.AddDataField pt9.PivotFields("Overdue"), "Sum of Overdue", xlSum
pt9.AddDataField pt9.PivotFields("OK"), "Sum of OK", xlSum
pt9.AddDataField pt9.PivotFields("Total"), "Sum of Total", xlSum
pt9.AddDataField pt9.PivotFields("Overdue %"), "Sum of Overdue %", xlSum
pt9.AddDataField pt9.PivotFields("OK %"), "Sum of OK %", xlSum
ws.pt9.PivotSelect "Sum of overdue", xlDataOnly
DataLabel.HorizontalAlignment = xlCenter

End Sub
</code>```

答:
Pivot table fields can be centre aligned in the same way as regular cells.

For example if your pivot table is populating cells A3:C5 you would do as follows:

```<code>Range("A3:C5").HorizontalAlignment = xlCenter
</code>```

Title: VBA for aligning the pivot table

Body:
I am using an VBA to generate the Pivot Table.

I wanted to Center align my values in the Pivot table, I used the follwing line, in my code, I am getting object required error.

I researched in net, and everywhere it is the same, that we use

DataLabel.HorizontalAlignment = xlCenter

Below is the code, i am using to generate my Pivot table and trying to align the data values in the cell Center, Could someone suggest, where i am going wrong and how i could correct it.

Sub sum2017()
Dim ws9 As Worksheet
Dim pc9 As PivotCache
Dim pt9 As PivotTable
Dim ct9 As Integer
Set ws9 = Sheets("Sum2017")
Set pc9 = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'Result'!R1C1:R1048576C6")
Set pt9 = pc9.CreatePivotTable(ws9.Range("A3"))
pt9.AddDataField pt9.PivotFields("Overdue"), "Sum of Overdue", xlSum
pt9.AddDataField pt9.PivotFields("OK"), "Sum of OK", xlSum
pt9.AddDataField pt9.PivotFields("Total"), "Sum of Total", xlSum
pt9.AddDataField pt9.PivotFields("Overdue %"), "Sum of Overdue %", xlSum
pt9.AddDataField pt9.PivotFields("OK %"), "Sum of OK %", xlSum
ws.pt9.PivotSelect "Sum of overdue", xlDataOnly
DataLabel.HorizontalAlignment = xlCenter

End Sub

Body:
Pivot table fields can be centre aligned in the same way as regular cells.

For example if your pivot table is populating cells A3:C5 you would do as follows:

Range("A3:C5").HorizontalAlignment = xlCenter


问:
ES6 map array to string without comma
I am trying to map a list of errors into a list that I will show in a tooltip. The list added, but there's a , added between every li element.

I guess this is because this basically does errors.map(error => ...).toString() in the end. Any ideas how I can map the strings in errors array without having this comma added?

```<code>data-tip = {`
  Precisa de corrigir os seguintes problemas antes de publicar o anúncio:</br>
  <ul>
    ${errors.map(error => `<li>${error}</li>`)}
  </ul>
`}
</code>```

答:
In your code, you are using template literals which returns you a string and hence the code

```<code> ${errors.map(error => `<li>${error}</li>`)}
</code>```

is converted to a string using a toString() function which by default joins the returned array with a ,.

You can make use of join with anly other separator like

```<code>{`
  Precisa de corrigir os seguintes problemas antes de publicar o anúncio:</br>
  <ul>
    ${errors.map(error => `<li>${error}</li>`).join(' ')}
  </ul>
`}
</code>```

Title: ES6 map array to string without comma

Body:
I am trying to map a list of errors into a list that I will show in a tooltip. The list added, but there's a , added between every li element.

I guess this is because this basically does errors.map(error => ...).toString() in the end. Any ideas how I can map the strings in errors array without having this comma added?

data-tip = {`
  Precisa de corrigir os seguintes problemas antes de publicar o anúncio:

    ${errors.map(error => `<li>${error}</li>`)}

`}

Body:
In your code, you are using template literals which returns you a string and hence the code

 ${errors.map(error => `<li>${error}</li>`)}

is converted to a string using a toString() function which by default joins the returned array with a ,.

You can make use of join with anly other separator like

{`
  Precisa de corrigir os seguintes problemas antes de publicar o anúncio:</br>
  <ul>
    ${errors.map(error => `<li>${error}</li>`).join(' ')}
  </ul>
`}