问:
Visualising an individual 2d graph for all points on a plane
I have a M vs N curve (let's take it to be a sigmoid, for ease of understanding) for a given value of parameters P and Q. I need to visualise the M vs N curves for a range of values of P and Q (assume 10 values in 0 to 1, i.e. 0.1, 0.2, ..., 0.9 for both P and Q)

The only solution that I've found for this problem is a Trellis plot (essentially a matrix of plots). I'd like to know if there any other method to visualise this sort of a 4d(?) relationship besides the Trellis plots. Thanks.

答:
I'm not sure I understand what you're hoping for, so let me know if this is on the right track. Below are three examples using R.

The first is indeed a matrix of plots where each panel represents a different value of q and, within each panel, each curve represents a different value of p. The second is a 3D plot which looks at a surface based on three of the variables with the fourth fixed. The third is a Shiny app that creates the same interactive plot as in the second example but also provides a slider that allows you to change p and see how the plot changes. Unfortunately, I'm not sure how to embed the interactive plots in Stackoverflow so I've just provided the code.

I'm not sure if there's an elegant way to look at all four variables at the same time, but maybe someone will come along with additional options.

Matrix of plots for various values of p and q

```<code>library(tidyverse)
theme_set(theme_classic())

# Function to plot
my_fun = function(x, p, q) {
  1/(1 + exp(p + q*x))
}

# Parameters
params = expand.grid(p=seq(-2,2,length=6), q=seq(-1,1,length=11))

# x-values to feed to my_fun
x = seq(-10,10,0.1)

# Generate data frame for plotting
dat = map2_df(params$p, params$q, function(p, q) {
  data.frame(p=p, q=q, x, y=my_fun(x, p, q))
})

ggplot(dat, aes(x,y,colour=p, group=p)) +
  geom_line() +
  facet_grid(. ~ q, labeller=label_both) +
  labs(colour="p") +
  scale_colour_gradient(low="red", high="blue") +
  theme(legend.position="bottom")
</code>```

3D plot with one variable fixed

The code below will produce an interactive 3D plot that you can zoom and rotate. I've fixed the value of p and drawn a plot of the y surface for a grid of x and q values.

```<code>library(rgl)

x = seq(-10,10,0.1)
q = seq(-1,1,0.01)
y = outer(x, q, function(a, b) 1/(1 + exp(1 + b*a)))

persp3d(x, q, y, col=hcl(240,80,65), specular="grey20",
        xlab = "x", ylab = "q", zlab = "y")
</code>```

I'm not sure how to embed the interactive plot, but here's a static image of one viewing angle:

Shiny app

The code below will create the same plot as above, but with the added ability to vary p with a slider and see how the plot changes.

Open an R script file and paste in the code below. Save it as app.r in its own directory then run the code. Both an rgl window and the Shiny app page with the slider for controlling the value of p should open. Resize the windows as desired and then move the slider to see how the function surface changes for various values of p.

```<code>library(shiny)

# Define UI for application that draws an interactive plot
ui <- fluidPage(

   # Application title
   titlePanel("Plot the function 1/(1 + exp(p + q*x))"),

   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
         sliderInput("p",
                     "Vary the value of p and see how the plot changes",
                     min = -2,
                     max = 2,
                     value = 1,
                     step=0.2)
      ),

      # Show a plot of the generated distribution
      mainPanel(
         plotOutput("distPlot")
      )
   )
)

# Define server logic required to draw the plot
server <- function(input, output) {

   output$distPlot <- renderPlot({

     library(rgl)

     x = seq(-10,10,0.1)
     q = seq(-1,1,0.01)
     y = outer(x, q, function(a, b) 1/(1 + exp(input$p + b*a)))

     persp3d(x, q, y, col=hcl(240,50,65), specular="grey20",
             xlab = "x", ylab = "q", zlab = "y")

   })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

Body:
I'm not sure I understand what you're hoping for, so let me know if this is on the right track. Below are three examples using R.

The first is indeed a matrix of plots where each panel represents a different value of q and, within each panel, each curve represents a different value of p. The second is a 3D plot which looks at a surface based on three of the variables with the fourth fixed. The third is a Shiny app that creates the same interactive plot as in the second example but also provides a slider that allows you to change p and see how the plot changes. Unfortunately, I'm not sure how to embed the interactive plots in Stackoverflow so I've just provided the code.

I'm not sure if there's an elegant way to look at all four variables at the same time, but maybe someone will come along with additional options.

Matrix of plots for various values of p and q

library(tidyverse)
theme_set(theme_classic())

# Function to plot
my_fun = function(x, p, q) {
  1/(1 + exp(p + q*x))
}

# Parameters
params = expand.grid(p=seq(-2,2,length=6), q=seq(-1,1,length=11))

# x-values to feed to my_fun
x = seq(-10,10,0.1)

# Generate data frame for plotting
dat = map2_df(params$p, params$q, function(p, q) {
  data.frame(p=p, q=q, x, y=my_fun(x, p, q))
})

ggplot(dat, aes(x,y,colour=p, group=p)) +
  geom_line() +
  facet_grid(. ~ q, labeller=label_both) +
  labs(colour="p") +
  scale_colour_gradient(low="red", high="blue") +
  theme(legend.position="bottom")

3D plot with one variable fixed

The code below will produce an interactive 3D plot that you can zoom and rotate. I've fixed the value of p and drawn a plot of the y surface for a grid of x and q values.

library(rgl)

x = seq(-10,10,0.1)
q = seq(-1,1,0.01)
y = outer(x, q, function(a, b) 1/(1 + exp(1 + b*a)))

persp3d(x, q, y, col=hcl(240,80,65), specular="grey20",
        xlab = "x", ylab = "q", zlab = "y")

I'm not sure how to embed the interactive plot, but here's a static image of one viewing angle:

Shiny app

The code below will create the same plot as above, but with the added ability to vary p with a slider and see how the plot changes.

Open an R script file and paste in the code below. Save it as app.r in its own directory then run the code. Both an rgl window and the Shiny app page with the slider for controlling the value of p should open. Resize the windows as desired and then move the slider to see how the function surface changes for various values of p.

library(shiny)

# Define UI for application that draws an interactive plot
ui <- fluidPage(

   # Application title
   titlePanel("Plot the function 1/(1 + exp(p + q*x))"),

   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
         sliderInput("p",
                     "Vary the value of p and see how the plot changes",
                     min = -2,
                     max = 2,
                     value = 1,
                     step=0.2)
      ),

      # Show a plot of the generated distribution
      mainPanel(
         plotOutput("distPlot")
      )
   )
)

# Define server logic required to draw the plot
server <- function(input, output) {

   output$distPlot <- renderPlot({

     library(rgl)

     x = seq(-10,10,0.1)
     q = seq(-1,1,0.01)
     y = outer(x, q, function(a, b) 1/(1 + exp(input$p + b*a)))

     persp3d(x, q, y, col=hcl(240,50,65), specular="grey20",
             xlab = "x", ylab = "q", zlab = "y")

   })
}

# Run the application
shinyApp(ui = ui, server = server)


来源: stackexchange

问:
How do you import a CSV and convert from list into a string in Netlogo?
How do I import data from a CSV file and convert it line-by-line into a string? Whenever I try, I get error messages that it is still a list or a list of lists. I am trying to copy the example given in the Netlogo User Manual for reading a file one line per tick (see below). I created a simpler example. THANKS!!

My code:

```<code>extensions [CSV]
globals [date]

to setup
  clear-all
  file-close-all
  file-open "S&PDate.csv"
  set date current-date
  reset-ticks
end

to go
  if file-at-end? [stop]
  set date current-date
  tick
end

to-report current-date
  file-open "S&PDate.csv"
  let result csv:from-row file-read-line
  while [ not file-at-end? ] [
    let row csv:from-row file-read-line
    set result (map result row)
  ]
  file-close
  report result
end
</code>```

NetLogo example

答:
Saad is right, and you may want to have a look at the asking guidelines on making an MCVE. Are you wanting string output so that your monitors look nice? If so, would this do the trick?</p>

```<code>extensions [ csv ]
globals [ dates ]

to setup
  ca
  set dates csv:from-file "example_strings.csv"
  reset-ticks
end

to go
  if ticks < length dates [
    print current-date
    tick
  ]
end

to-report current-date
  report csv:to-string ( list item ticks dates )
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How do I import data from a CSV file and convert it line-by-line into a string? Whenever I try, I get error messages that it is still a list or a list of lists. I am trying to copy the example given in the Netlogo User Manual for reading a file one line per tick (see below). I created a simpler example. THANKS!!

My code:

extensions [CSV]
globals [date]

to setup
  clear-all
  file-close-all
  file-open "S&PDate.csv"
  set date current-date
  reset-ticks
end

to go
  if file-at-end? [stop]
  set date current-date
  tick
end

to-report current-date
  file-open "S&PDate.csv"
  let result csv:from-row file-read-line
  while [ not file-at-end? ] [
    let row csv:from-row file-read-line
    set result (map result row)
  ]
  file-close
  report result
end

NetLogo example

Body:
Saad is right, and you may want to have a look at the asking guidelines on making an MCVE. Are you wanting string output so that your monitors look nice? If so, would this do the trick?

extensions [ csv ]
globals [ dates ]

to setup
  ca
  set dates csv:from-file "example_strings.csv"
  reset-ticks
end

to go
  if ticks < length dates [
    print current-date
    tick
  ]
end

to-report current-date
  report csv:to-string ( list item ticks dates )
end


问:
Is it possible to nest media queries within media queries?
Is this possible? It seems like a neat solution to me, but I'm not sure if it will work.

@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {

    /* Code for both portrait and landscape */

    @media (orientation:portrait) {

        /* Code for just portrait */

    }

    @media (orientation:landscape) {

        /* Code for just landscape */

    }

}
```

答:
I think not possible but you can write this format If you are using SASS css pre-processor.

example , you can copy this code and paste to https://www.sassmeister.com/ -and watch the output

SASS

```<code>@media only screen and (max-width: 767px) {
  body{
    color:red;
  }
   @media (orientation:portrait) {
       body{
        color:green;
      }
   }
   @media (orientation:landscape) {
       body{
        color:orange;
      }
   }
}
</code>```

Output CSS

```<code>@media only screen and (max-width: 767px) {
  body {
    color: red;
  }
}
@media only screen and (max-width: 767px) and (orientation: portrait) {
  body {
    color: green;
  }
}
@media only screen and (max-width: 767px) and (orientation: landscape) {
  body {
    color: orange;
  }
}
</code>```

Body:
I think not possible but you can write this format If you are using SASS css pre-processor.

example , you can copy this code and paste to https://www.sassmeister.com/ -and watch the output

SASS

@media only screen and (max-width: 767px) {
  body{
    color:red;
  }
   @media (orientation:portrait) {
       body{
        color:green;
      }
   }
   @media (orientation:landscape) {
       body{
        color:orange;
      }
   }
}

Output CSS

@media only screen and (max-width: 767px) {
  body {
    color: red;
  }
}
@media only screen and (max-width: 767px) and (orientation: portrait) {
  body {
    color: green;
  }
}
@media only screen and (max-width: 767px) and (orientation: landscape) {
  body {
    color: orange;
  }
}


问:
How to sort items in node orm find
I want to get sorted items using find method in node orm. I know there is and 'order' param in find(), It will give me sorted items from 'a-z'. What will I do if I want to get items from 'z-a' order That means how the 'GROUP BY DESC' can be used in node-orm?</p>

答:
There is a method for group by

UserModel.find({id: id_value}).groupBy({column1, column2}).order('-name').

In the ORM library you can find the below function which will guide you more.

```<code>export interface SelectQuery {
select(fields: string): SelectQuery;
calculateFoundRows: SelectQuery;
as(alias: string): SelectQuery;
fun(fun: string, column: string, alias: string): SelectQuery;
from(table: string, from_id: string, to_id: string): SelectQuery;
from(table: string, from_id: string, to_table: string, to_id: string): SelectQuery;
where(...args: any[]): SelectQuery;
whereExists(table: string, table_link: string, link: string, conditions: { [column: string]: any }): SelectQuery;
groupBy(...columns: string[]): SelectQuery;
offset(offset: number): SelectQuery;
limit(limit: number): SelectQuery;
order(column: string, direction: string): SelectQuery;
build(): string;
}
</code>```

Title: How to sort items in node orm find

Body:
There is a method for group by

UserModel.find({id: id_value}).groupBy({column1, column2}).order('-name').

In the ORM library you can find the below function which will guide you more.

export interface SelectQuery {
select(fields: string): SelectQuery;
calculateFoundRows: SelectQuery;
as(alias: string): SelectQuery;
fun(fun: string, column: string, alias: string): SelectQuery;
from(table: string, from_id: string, to_id: string): SelectQuery;
from(table: string, from_id: string, to_table: string, to_id: string): SelectQuery;
where(...args: any[]): SelectQuery;
whereExists(table: string, table_link: string, link: string, conditions: { [column: string]: any }): SelectQuery;
groupBy(...columns: string[]): SelectQuery;
offset(offset: number): SelectQuery;
limit(limit: number): SelectQuery;
order(column: string, direction: string): SelectQuery;
build(): string;
}


问:
Distributing iOS Application to staff within an Organisation
Intro

My company has built an application and we are ready to move it into production. The application built must be private and should be available to staff only. So this rules out iTunes and leaves us with Apple Enterprise Developer Program and Apple B2B. Now when we export the application out using the Enterprise option in Xcode, after installation we get a pop up saying Untrusted Enterprise Developer. We can't distribute this application and have all of our users go through settings to trust this app, that is too much to ask.

With the B2B, we would have to collect UDIDS of every iOS user and add them to a list of approved users. Dealing with over 200 users, this could become frustrating.

Question

So what I would like to know is, is there a way for a company to distribute iOS applications via a private link that once shared with employees all they would have to do is download the app, install and enjoy it without being asked to Trust the app or without collecting their UDID.

Thanks in advance!

答:
If you send the iOS App File to a user and they manually install it on their device, then they must also manually trust your organization before launching the app. Instruct the user to follow these steps to trust your organization.

Tap Settings > General > Device Management.

Under Enterprise App, tap the organization name.

Tap Trust “[Organization Name]”.

In the dialog that appears, tap Trust.

SOURCE


问:
Navigation Issue while navigating using Android Hardware Back Press [react-native]
When I navigate to the first screen from the final screen of my App using hardware back press

It initially navigates to first screen and also bounces back to the final screen

Also the animation that I have given in the first screen becomes a stuck and play like experience while navigating and this case is same for both types of navigation ie.,

-navigating with the back button in App and also while using hardware back press

This is my final screen js file where I handle hardware back press:

constructor(props) {
  super(props);
  this.handleBack = (() => {
    Actions.FirstScreen();
  });
 }

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBack);
  }

  componentWillUnmount() {
   BackHandler.removeEventListener('hardwareBackPress', this.handleBack);
 }```
</div>
</div>
</p>

<p>and this is the first screen's js file where I have the animation:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>  componentWillMount() {
    this.slide1 = new Animated.Value(0);
    this.slide2 = new Animated.Value(0);
    this.bnt1();
    this.bnt2();
 }

 bnt1() {
       Animated.timing(
         this.slide1, {
           delay: 100,
           toValue: w / 1.33,
           duration: 700,
       }
       ).start();
     }

     bnt2() {
           Animated.timing(
             this.slide2, {
               delay: 700,
               toValue: -(w / 1.33),
               duration: 500,
           }
           ).start();
         }</code>```

答:
In your final screen js file add this:

constructor(props) {
     super(props);
      this.handleBack = (() => {
        Actions.FirstScreen();
        return true;
       });
      } ```

Body:
When I navigate to the first screen from the final screen of my App using hardware back press

It initially navigates to first screen and also bounces back to the final screen

Also the animation that I have given in the first screen becomes a stuck and play like experience while navigating and this case is same for both types of navigation ie.,

-navigating with the back button in App and also while using hardware back press

This is my final screen js file where I handle hardware back press:

constructor(props) {
  super(props);
  this.handleBack = (() => {
    Actions.FirstScreen();
  });
 }

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBack);
  }

  componentWillUnmount() {
   BackHandler.removeEventListener('hardwareBackPress', this.handleBack);
 }

and this is the first screen's js file where I have the animation:

  componentWillMount() {
    this.slide1 = new Animated.Value(0);
    this.slide2 = new Animated.Value(0);
    this.bnt1();
    this.bnt2();
 }

 bnt1() {
       Animated.timing(
         this.slide1, {
           delay: 100,
           toValue: w / 1.33,
           duration: 700,
       }
       ).start();
     }

     bnt2() {
           Animated.timing(
             this.slide2, {
               delay: 700,
               toValue: -(w / 1.33),
               duration: 500,
           }
           ).start();
         }


问:
How to make this javascript script work?
i'm quite new to javascript and coding. I was wondering if someone could put this random name generator from jsfiddle together into a single working file?
I just cant work out how to make it run, do i have to import some libraries or something?
I have a feeling if i get this working i might learn something, somehow.

Heres where i got the code:
https://jsfiddle.net/katowulf/3gtDf/

Heres the script:

```<code>$('button').click(function() {
    $('h2').text(randomEl(adjectives)+' '+randomEl(nouns));
    selectElementContents($('h2')[0]);
});

function randomEl(list) {
    var i = Math.floor(Math.random() *   . list.length);
    return list[i];
}

function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

var adjectives = ["adamant", "adroit", "amatory", "animistic", "antic", "arcadian", "baleful", "bellicose", "bilious", "boorish", "calamitous", "caustic", "cerulean", "comely", "concomitant", "contumacious", "corpulent", "crapulous", "defamatory", "didactic", "dilatory", "dowdy", "efficacious", "effulgent", "egregious", "endemic", "equanimous", "execrable", "fastidious", "feckless", "fecund", "friable", "fulsome", "garrulous", "guileless", "gustatory", "heuristic", "histrionic", "hubristic", "incendiary", "insidious", "insolent", "intransigent", "inveterate", "invidious", "irksome", "jejune", "jocular", "judicious", "lachrymose", "limpid", "loquacious", "luminous", "mannered", "mendacious", "meretricious", "minatory", "mordant", "munificent", "nefarious", "noxious", "obtuse", "parsimonious", "pendulous", "pernicious", "pervasive", "petulant", "platitudinous", "precipitate", "propitious", "puckish", "querulous", "quiescent", "rebarbative", "recalcitant", "redolent", "rhadamanthine", "risible", "ruminative", "sagacious", "salubrious", "sartorial", "sclerotic", "serpentine", "spasmodic", "strident", "taciturn", "tenacious", "tremulous", "trenchant", "turbulent", "turgid", "ubiquitous", "uxorious", "verdant", "voluble", "voracious", "wheedling", "withering", "zealous"];
var nouns = ["ninja", "chair", "pancake", "statue", "unicorn", "rainbows", "laser", "senor", "bunny", "captain", "nibblets", "cupcake", "carrot", "gnomes", "glitter", "potato", "salad", "toejam", "curtains", "beets", "toilet", "exorcism", "stick figures", "mermaid eggs", "sea barnacles", "dragons", "jellybeans", "snakes", "dolls", "bushes", "cookies", "apples", "ice cream", "ukulele", "kazoo", "banjo", "opera singer", "circus", "trampoline", "carousel", "carnival", "locomotive", "hot air balloon", "praying mantis", "animator", "artisan", "artist", "colorist", "inker", "coppersmith", "director", "designer", "flatter", "stylist", "leadman", "limner", "make-up artist", "model", "musician", "penciller", "producer", "scenographer", "set decorator", "silversmith", "teacher", "auto mechanic", "beader", "bobbin boy", "clerk of the chapel", "filling station attendant", "foreman", "maintenance engineering", "mechanic", "miller", "moldmaker", "panel beater", "patternmaker", "plant operator", "plumber", "sawfiler", "shop foreman", "soaper", "stationary engineer", "wheelwright", "woodworkers"];

$('button').click();
</code>```

And the html:

```<code><button>new name</button>
    <h2></h2>
</code>```

答: you need to include JQuery library in the single file you create</p>

Body:
i'm quite new to javascript and coding. I was wondering if someone could put this random name generator from jsfiddle together into a single working file?
I just cant work out how to make it run, do i have to import some libraries or something?
I have a feeling if i get this working i might learn something, somehow.

Heres where i got the code:
https://jsfiddle.net/katowulf/3gtDf/

Heres the script:

$('button').click(function() {
    $('h2').text(randomEl(adjectives)+' '+randomEl(nouns));
    selectElementContents($('h2')[0]);
});

function randomEl(list) {
    var i = Math.floor(Math.random() *   . list.length);
    return list[i];
}

function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

var adjectives = ["adamant", "adroit", "amatory", "animistic", "antic", "arcadian", "baleful", "bellicose", "bilious", "boorish", "calamitous", "caustic", "cerulean", "comely", "concomitant", "contumacious", "corpulent", "crapulous", "defamatory", "didactic", "dilatory", "dowdy", "efficacious", "effulgent", "egregious", "endemic", "equanimous", "execrable", "fastidious", "feckless", "fecund", "friable", "fulsome", "garrulous", "guileless", "gustatory", "heuristic", "histrionic", "hubristic", "incendiary", "insidious", "insolent", "intransigent", "inveterate", "invidious", "irksome", "jejune", "jocular", "judicious", "lachrymose", "limpid", "loquacious", "luminous", "mannered", "mendacious", "meretricious", "minatory", "mordant", "munificent", "nefarious", "noxious", "obtuse", "parsimonious", "pendulous", "pernicious", "pervasive", "petulant", "platitudinous", "precipitate", "propitious", "puckish", "querulous", "quiescent", "rebarbative", "recalcitant", "redolent", "rhadamanthine", "risible", "ruminative", "sagacious", "salubrious", "sartorial", "sclerotic", "serpentine", "spasmodic", "strident", "taciturn", "tenacious", "tremulous", "trenchant", "turbulent", "turgid", "ubiquitous", "uxorious", "verdant", "voluble", "voracious", "wheedling", "withering", "zealous"];
var nouns = ["ninja", "chair", "pancake", "statue", "unicorn", "rainbows", "laser", "senor", "bunny", "captain", "nibblets", "cupcake", "carrot", "gnomes", "glitter", "potato", "salad", "toejam", "curtains", "beets", "toilet", "exorcism", "stick figures", "mermaid eggs", "sea barnacles", "dragons", "jellybeans", "snakes", "dolls", "bushes", "cookies", "apples", "ice cream", "ukulele", "kazoo", "banjo", "opera singer", "circus", "trampoline", "carousel", "carnival", "locomotive", "hot air balloon", "praying mantis", "animator", "artisan", "artist", "colorist", "inker", "coppersmith", "director", "designer", "flatter", "stylist", "leadman", "limner", "make-up artist", "model", "musician", "penciller", "producer", "scenographer", "set decorator", "silversmith", "teacher", "auto mechanic", "beader", "bobbin boy", "clerk of the chapel", "filling station attendant", "foreman", "maintenance engineering", "mechanic", "miller", "moldmaker", "panel beater", "patternmaker", "plant operator", "plumber", "sawfiler", "shop foreman", "soaper", "stationary engineer", "wheelwright", "woodworkers"];

$('button').click();

And the html:

<button>new name</button>


问:
Can't paste text at a TFX-CLI console (NPM)
I'm unable to paste text at CLI prompts when running tfx-cli.

I've just installed Node v8.9.1 LTS. Unfortunately, the tfx-cli install hung the first time through. I pressed Ctrl+C to cancel it, ran it again, and the second time it completed. (In the text that flashed across my screen during the second run, I believe I saw something about 'failed' and 'rollback.')

I don't know whether the initial failure is contributing to my problem.

When I run tfx login, I get this prompt first:

> Service URL:

I can type at this prompt, but I can't paste. Once I type the URL and press Enter I get this:

> Personal access token:

I can neither paste nor type at this prompt (or at least the cursor doesn't advance when I type). The only keys that seem to work here are Enter and Ctrl+C. Pressing Enter without typing anything results in this:

error:   Invalid input for Personal access token:

Pressing Enter after typing a few random characters sends no output to the console and simply dumps me back at the C:\> prompt.

How to fix this? How can one determine whether it's a Node problem or a tfx-cli problem? I suspect the latter but I'm not sure.

--EDIT--

Are others able to paste text at these prompts?

答:
I tested on my side with Node v8.9.1 LTS installed. Everything works correctly.

Make sure you have activated the command line window before pasting the text.

For Personal access token or password, it's implicit (non-visible) in the command line. The token strings will not show there when pasting the PAT/password. But it works if you enter the correct token.

So, just make sure you activated the cmd window before paste action:

Copy PAT/password (Sometimes you need to try this several times to make sure the strings are copied)

Activate the command line window (click within the window to active
it)

Paste the PAT/password (It's implicit, just make sure you pasted the
correct token )

Enter

UPDATE:

Seems related to the OS or permission. Whatever, you can try running the cmd as Administrator, then check whether you can copy and paste now.

Besides, you can also try to enable "QuickEdit Mode" for CMD console. ( Right-click on the title-bar of your cmd window. --> [Properties] - Options - check "QuickEdit Mode"

Also try the ways mentioned in this article: How to Enable CTRL+C / Ctrl+V for Pasting in the Windows Command Prompt


问:
Joomla , Joomfish language translation for whole page not only content!
When i click the flag to change the language , the content of the page is changing but not the other modules listed in the page. Example If i'm in my profile page then everything should be in that language! How i can make like that???</p>

答: Look in your JOOMLA INSTALL/language/en-GB folder. You will see a bunch of language files for every component, module, plugin, and template that uses a language file. You will need to make a corresponding file for each language you support on your website.</p>

ContentLicense: CC BY-SA 2.5


问:
Trouble referencing API (React and Superagent)
So by using postman I've managed to call the url for yummly. I'd like to render my search results. Currently in the render from lines 29 - 36 I have a fake search just to make sure the Dom works, and it does. How do I get the api search from lines 52 - 60 to show in 29 - 36.

import React from 'react';
import Request from 'superagent';
import _ from 'lodash';

export class Yum extends React.Component {
    constructor(){
        super();
        this.state = {};
    }

    componentWillMount(){

        /*var url = "http://api.yummly.com/v1/api/recipes?_app_id=5129dd16&_app_key=9772f1db10ba433223ad4e765dc2b537&=q"
        Request.get(url).then((response) => {
            console.log(response.body);
            this.setState({
                recipes: response.body.matches,
                total: response.body.totalResults
            });
        });*/
        this.search();
    }

    updateSearch(){
        this.search(this.refs.query.value);
    }

    render(){

        const title = 'Onion Soup';
        const ingredients = ["onions", "beef stock"];
        const listItems = ingredients.map((ingredient) => {
          return (
{ingredient}
);
        });

        return(

                <input ref="query" onChange = { (e) => {this.updateSearch();} } type="text" />

{title}

{listItems}

        )
    }

    search(query = "onion") {
        var url = `http://api.yummly.com/v1/api/recipes?_app_id=5129dd16&_app_key=9772f1db10ba433223ad4e765dc2b537&=q${query}&maxResult=1`
        Request.get(url).then((response) => {
            console.log(response.body.matches[0]);
            console.log(query);
            this.setState({
                recipes: response.body.matches[0],
                //total: response.body.totalResults
            });
        });
    }
}

export default Yum;```

答:
Here you go I have cleaned up your code a bit, please give it a try

```<code>import React from 'react';
import Request from 'superagent';
import _ from 'lodash';

export class Yum extends React.Component {
    constructor(){
        super();
        this.state = {
            searchQuery: 'onion'
            recipe: {
                ingredients: []
            }
        };

        this.search = this.search.bind(this);
        this.queryUpdate = this.queryUpdate.bind(this);
    }

    componentWillMount(){
        this.search(this.state.searchQuery);
    }

    render(){
        const title = 'Onion Soup'; // Get this from somwhere else ?
        const {recipe, searchQuery} = this.state; // Get state properties

        const listItems = _.get(recipe, 'ingredients', []).map((ingredient) => {
            return (<h5>{ingredient}</h5>);
        });

        return(
            <div>
                <input onChange={this.queryUpdate} type="text" value={searchQuery} />

                <h4>{title}</h4>
                <ul>
                    <li>{listItems}</li>
                </ul>
            </div>
        )
    }

    queryUpdate(e) {
        const searchQuery = event.target.value; // Get new value from DOM event
        this.setState({searchQuery}); // Save to state
        this.search(searchQuery); // Search
    }

    search(searchQuery) {
        const url = `http://api.yummly.com/v1/api/recipes?_app_id=5129dd16&_app_key=9772f1db10ba433223ad4e765dc2b537&q=${searchQuery}&maxResult=1`
        Request.get(url).then((response) => {
            this.setState({
                recipe: response.body.matches[0]
            });
        });
    }
}

export default Yum;
</code>```

Here are some of the issues I noticed:

Typo in URL: =q instead of q=

You should save the state of the text input in a state variable instead of using refs

smaller details commented in code

Body:
Here you go I have cleaned up your code a bit, please give it a try

import React from 'react';
import Request from 'superagent';
import _ from 'lodash';

export class Yum extends React.Component {
    constructor(){
        super();
        this.state = {
            searchQuery: 'onion'
            recipe: {
                ingredients: []
            }
        };

        this.search = this.search.bind(this);
        this.queryUpdate = this.queryUpdate.bind(this);
    }

    componentWillMount(){
        this.search(this.state.searchQuery);
    }

    render(){
        const title = 'Onion Soup'; // Get this from somwhere else ?
        const {recipe, searchQuery} = this.state; // Get state properties

        const listItems = _.get(recipe, 'ingredients', []).map((ingredient) => {
            return (<h5>{ingredient}</h5>);
        });

        return(
            <div>
                <input onChange={this.queryUpdate} type="text" value={searchQuery} />

                <h4>{title}</h4>
                <ul>
                    <li>{listItems}</li>
                </ul>
            </div>
        )
    }

    queryUpdate(e) {
        const searchQuery = event.target.value; // Get new value from DOM event
        this.setState({searchQuery}); // Save to state
        this.search(searchQuery); // Search
    }

    search(searchQuery) {
        const url = `http://api.yummly.com/v1/api/recipes?_app_id=5129dd16&_app_key=9772f1db10ba433223ad4e765dc2b537&q=${searchQuery}&maxResult=1`
        Request.get(url).then((response) => {
            this.setState({
                recipe: response.body.matches[0]
            });
        });
    }
}

export default Yum;

Here are some of the issues I noticed:

Typo in URL: =q instead of q=

You should save the state of the text input in a state variable instead of using refs

smaller details commented in code


问:
extracting the attribute value and cut the string using perl
<Student>
<test subject="/school/class/twelve/maths.txt"/>
<test subject="/school/class/eleven/physics.txt"/>
</Student>

I want to take the values of "subject" attibute, and then cut the string starting from class.
for example, the output must be two strings as: twelve/maths.txt and eleven/physics.txt
Could anyone please help to do this using shell script or perl?

答:
I have tried in steps. First to get the attribute value, then taking the substring

```<code>INPUT=$(sed -n 's/.*subject="\([^"]*\).*/\1/p' *.xml)
echo "the value of subject attribute=" $INPUT
</code>```

But this result in the output:

the value of subject attribute=/school/class/twelve/maths.txt /school/class/eleven/physics.txt

after this I have taken the substring:

```<code>SubString1=$(echo $INPUT| cut -d'/' -f 5)
echo "SubString1=" $SubString1
nospaces=${SubString1## } # remove leading spaces
SubString1=${nospaces%% } # remove trailing spaces
SubString2=$(echo $INPUT| cut -d'/' -f 11)
echo "SubString2=" $SubString2
</code>```

and the output is
SubString1=maths.txt
SubString2=physics.txt

Body:
I have tried in steps. First to get the attribute value, then taking the substring

INPUT=$(sed -n 's/.*subject="\([^"]*\).*/\1/p' *.xml)
echo "the value of subject attribute=" $INPUT

But this result in the output:

the value of subject attribute=/school/class/twelve/maths.txt /school/class/eleven/physics.txt

after this I have taken the substring:

SubString1=$(echo $INPUT| cut -d'/' -f 5)
echo "SubString1=" $SubString1
nospaces=${SubString1## } # remove leading spaces
SubString1=${nospaces%% } # remove trailing spaces
SubString2=$(echo $INPUT| cut -d'/' -f 11)
echo "SubString2=" $SubString2

and the output is
SubString1=maths.txt
SubString2=physics.txt


问:
Android set permission inside list-view custom apdpater class
I am trying to set permission to make the phone call  inside custom list adapter class extends from BaseAdapter from getView method.

But when touching on icon image the application crash

```<code>public View getView(int position, View convertView, ViewGroup parent) {

        final TextView  phoneTxt  = (TextView)convertView.findViewById(R.id.phone);
        ImageView phoneImage = (ImageView)convertView.findViewById(R.id.phone_icon);
        phoneImage.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
               int permissionCheck = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE);
               if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CALL_PHONE}, REQUEST__PHONE_CALL);
               }
               else {
                 Intent intent = new Intent(Intent.ACTION_CALL);
                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                 intent.setData(Uri.parse("tel:" + phoneTxt.getText()));
                 context.startActivity(intent);
               }

        }
    });
    }

    return convertView;
}
</code>```

Here is the error log

```<code>11-13 11:54:05.297: E/AndroidRuntime(9530): FATAL EXCEPTION: main
11-13 11:54:05.297: E/AndroidRuntime(9530): Process: com.myapp.myApp, PID: 9530
11-13 11:54:05.297: E/AndroidRuntime(9530): java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
11-13 11:54:05.297: E/AndroidRuntime(9530):     at com.myapp.myApp.adapter.NavDrawerListAdapter$1.onClick(NavDrawerListAdapter.java:134)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.view.View.performClick(View.java:5269)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.view.View$PerformClick.run(View.java:21556)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.os.Handler.handleCallback(Handler.java:815)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.os.Handler.dispatchMessage(Handler.java:104)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.os.Looper.loop(Looper.java:207)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.app.ActivityThread.main(ActivityThread.java:5769)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at java.lang.reflect.Method.invoke(Native Method)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
</code>```

Why this happening, is there any bug in above code?.

答:
In your code, you are trying to cast the context to Activity but a Context is not necessarily the instance of Activity. You may have used getApplicationContext() or getApplication() as the parameter where Context is required. Consider using YourActivity.this so that it can be casted to Activity.

Or you can use my library to request permissions from any context easily.

Check the instructions at https://github.com/nabinbhandari/Android-Permissions

Eg.

```<code>Permissions.check(context, Manifest.permission.CALL_PHONE, null,
    new PermissionHandler() {
        @Override
        public void onGranted() {
            //do your task.
        }
    });
</code>```

Body:
I am trying to set permission to make the phone call  inside custom list adapter class extends from BaseAdapter from getView method.

But when touching on icon image the application crash

public View getView(int position, View convertView, ViewGroup parent) {

        final TextView  phoneTxt  = (TextView)convertView.findViewById(R.id.phone);
        ImageView phoneImage = (ImageView)convertView.findViewById(R.id.phone_icon);
        phoneImage.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
               int permissionCheck = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE);
               if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CALL_PHONE}, REQUEST__PHONE_CALL);
               }
               else {
                 Intent intent = new Intent(Intent.ACTION_CALL);
                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                 intent.setData(Uri.parse("tel:" + phoneTxt.getText()));
                 context.startActivity(intent);
               }

        }
    });
    }

    return convertView;
}

Here is the error log

11-13 11:54:05.297: E/AndroidRuntime(9530): FATAL EXCEPTION: main
11-13 11:54:05.297: E/AndroidRuntime(9530): Process: com.myapp.myApp, PID: 9530
11-13 11:54:05.297: E/AndroidRuntime(9530): java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
11-13 11:54:05.297: E/AndroidRuntime(9530):     at com.myapp.myApp.adapter.NavDrawerListAdapter$1.onClick(NavDrawerListAdapter.java:134)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.view.View.performClick(View.java:5269)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.view.View$PerformClick.run(View.java:21556)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.os.Handler.handleCallback(Handler.java:815)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.os.Handler.dispatchMessage(Handler.java:104)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.os.Looper.loop(Looper.java:207)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.app.ActivityThread.main(ActivityThread.java:5769)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at java.lang.reflect.Method.invoke(Native Method)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

Why this happening, is there any bug in above code?.

Body:
In your code, you are trying to cast the context to Activity but a Context is not necessarily the instance of Activity. You may have used getApplicationContext() or getApplication() as the parameter where Context is required. Consider using YourActivity.this so that it can be casted to Activity.

Or you can use my library to request permissions from any context easily.

Check the instructions at https://github.com/nabinbhandari/Android-Permissions

Eg.

Permissions.check(context, Manifest.permission.CALL_PHONE, null,
    new PermissionHandler() {
        @Override
        public void onGranted() {
            //do your task.
        }
    });


问:
TypeScript Factory Subclass is not Assignable to Type Superclass
I want to use the Factory Pattern using TypeScript to convert raw data into a User.  I have two different types of Users: Employee and Customer.  Both extend the base class and compile without problems.  Below is an extremely simplified version of these three classes.

```<code>abstract class User {
  constructor(data: any) { }

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

class Employee extends User {
  static '@type' = 'Employee';

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

class Customer extends User {
  static '@type' = 'Customer';

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}
</code>```

Simple enough.  Now for the Factory.  I want to create a Factory that will take raw data returned from the server and convert that data into something the rest of the system can use (i.e. an instance of User).  What I want to do is something like

```<code>class UserFactory {
  /**
   * Vends a User constructed from the raw data from the server.
   *
   * @param userData (Object) - the User definition, as obtained from the server
   *
   * @return (User) the User initialized from `userData`
   */
  static vend<T extends User>(userData: any): T {
    switch (userData['@type']) {
      case Employee['@type']:
        return Employee.createFromServer(userData);

      case Customer['@type']:
        return Customer.createFromServer(userData);

      default:
        throw new Error('Unknown User type.');
    }
  }
}
</code>```

As you can probably guess (since I'm here and not relaxing over the weekend), that doesn't work.  I get the following error:

Type 'Employee' is not assignable to type 'T'.

Since T extends User and Employee extends User without adding or removing anything (in this simplified version), it seems like the above should work.  What's more annoying is it seems the above will work in other languages (e.g. Java (tested), C++), I'm just not sure why it won't work in this situation.

Somebody on GitHub suggested that the problem might be with overloading the constructor, but clearly that's not occurring here.

So, why isn't Employee assignable to type T?  (How) can I get the above to work?  Is there a better way to handle this in TypeScript?  A correct answer will answer at least the first 2 questions.

Addendum

createFromServer() is redefined in subclasses for a reason.  This is a minimally reproducible example.  The constructors don't actually take the raw data from the server.  Instead the createFromServer() converts the raw data into arguments the constructors can understand.

答:
It's not working because you've written too much code. You should be leveraging polymorphism. What this means is simply removing the static factory methods from the two base classes.

That way will work as you expect and you will have less code to maintain. In fact, it's the very reason why the static method in the User class has a this type and news the containing class using the this reference. It enables derived classes to inherit a factory that intrinsically has their more derived type

Also this isn't Java. In fact I couldn't think of a language less like Java than TypeScript

Body:
I want to use the Factory Pattern using TypeScript to convert raw data into a User.  I have two different types of Users: Employee and Customer.  Both extend the base class and compile without problems.  Below is an extremely simplified version of these three classes.

abstract class User {
  constructor(data: any) { }

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

class Employee extends User {
  static '@type' = 'Employee';

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

class Customer extends User {
  static '@type' = 'Customer';

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

Simple enough.  Now for the Factory.  I want to create a Factory that will take raw data returned from the server and convert that data into something the rest of the system can use (i.e. an instance of User).  What I want to do is something like

class UserFactory {
  /**
   * Vends a User constructed from the raw data from the server.
   *
   * @param userData (Object) - the User definition, as obtained from the server
   *
   * @return (User) the User initialized from `userData`
   */
  static vend<T extends User>(userData: any): T {
    switch (userData['@type']) {
      case Employee['@type']:
        return Employee.createFromServer(userData);

      case Customer['@type']:
        return Customer.createFromServer(userData);

      default:
        throw new Error('Unknown User type.');
    }
  }
}

As you can probably guess (since I'm here and not relaxing over the weekend), that doesn't work.  I get the following error:

Type 'Employee' is not assignable to type 'T'.

Since T extends User and Employee extends User without adding or removing anything (in this simplified version), it seems like the above should work.  What's more annoying is it seems the above will work in other languages (e.g. Java (tested), C++), I'm just not sure why it won't work in this situation.

Somebody on GitHub suggested that the problem might be with overloading the constructor, but clearly that's not occurring here.

So, why isn't Employee assignable to type T?  (How) can I get the above to work?  Is there a better way to handle this in TypeScript?  A correct answer will answer at least the first 2 questions.

Addendum

createFromServer() is redefined in subclasses for a reason.  This is a minimally reproducible example.  The constructors don't actually take the raw data from the server.  Instead the createFromServer() converts the raw data into arguments the constructors can understand.


问:
Django Rest Serializers: Return data of related field
I created models which are Contracts and ContractItems. ContractItems table contains a foreign key attribute of Contracts table. I need to return Contracts with their relevant ContractItems.

I implemented a serializer like it.

```<code>class ContractSerializer(ModelSerializer):
    class Meta:
        model = Contract
        fields = ('id', 'name')
</code>```

I could not get ContractItems to relevant Contract.

Could anyone suggest any way to get Contracts with their relevant ContractItems? And also One Contract can have many ContractItems.

答:
```<code>class ContractItemSerializer(ModelSerializer):
    class Meta:
        model = ContractItems
        fields = '__all__'

class ContractSerializer(ModelSerializer):

    contract_items  =  serializers.SerializerMethodField()
    class Meta:
        model = Contract
        fields = ('id', 'name')

    def get_contract_items(self, obj):
        qs = obj.related_name.all()
        return  ContractItemSerializer(qs, many=True).data
</code>```

Body:
I created models which are Contracts and ContractItems. ContractItems table contains a foreign key attribute of Contracts table. I need to return Contracts with their relevant ContractItems.

I implemented a serializer like it.

class ContractSerializer(ModelSerializer):
    class Meta:
        model = Contract
        fields = ('id', 'name')

I could not get ContractItems to relevant Contract.

Could anyone suggest any way to get Contracts with their relevant ContractItems? And also One Contract can have many ContractItems.


问:
phpDocumentor on legacy code
Can phpDocumentor be used to generate HTML docs for some legacy code that does not necessarily conform to its standard?

I'd like to generate some preliminary documentation for an old code tree and later on start improving my comments and add the appropriate @ tags as I get fluent with phpDocumentor. I've never used this piece of software before and the examples I've found focus on how to write new code that conforms to its syntax and generate HTML file by file with the -f parameter.

I've installed latest phpDocumentor through the PEAR command line installer and tried this little *.bat file on Windows XP:

```<code>@echo off
phpdoc ^
    --directory "\\server\project\trunk" ^
    --target "C:\tests\project-doc"
</code>```

... but this is all I get:

```<code>PHP Version 5.3.5
phpDocumentor version 1.4.3

Parsing configuration file phpDocumentor.ini...
   (found in C:\Archivos de programa\PHP\pear\data/PhpDocumentor/)...

done
Maximum memory usage set at 256M after considering php.ini...
using tokenizer Parser
directory: ''  not found
</code>```

I've also tried mapping the UNC path to a drive letter:

```<code>@echo off
phpdoc ^
    --directory "I:\" ^
    --target "C:\tests\project-doc"
</code>```

... but:

```<code>PHP Version 5.3.5
phpDocumentor version 1.4.3

Parsing configuration file phpDocumentor.ini...
   (found in C:\Archivos de programa\PHP\pear\data/PhpDocumentor/)...

done
Maximum memory usage set at 256M after considering php.ini...
using tokenizer Parser
a target directory must be specified
 try phpdoc -h
</code>```

This error message is the same if I create "C:\tests\project-doc" before.

What's exactly wrong in my syntax?

答:
I think I've found what the issue is. The parameter parser is very picky and it doesn't like neither UNC paths nor bare root directories. If I replace this:

```<code>--directory "I:\"
</code>```

... with this:

```<code>--directory "I:\."
</code>```

... it finally starts running.

I suppose it's a bug. Their bug tracker doesn't seem to be public so I don't know if it's a known issue.

Title: phpDocumentor on legacy code

Body:
Can phpDocumentor be used to generate HTML docs for some legacy code that does not necessarily conform to its standard?

I'd like to generate some preliminary documentation for an old code tree and later on start improving my comments and add the appropriate @ tags as I get fluent with phpDocumentor. I've never used this piece of software before and the examples I've found focus on how to write new code that conforms to its syntax and generate HTML file by file with the -f parameter.

I've installed latest phpDocumentor through the PEAR command line installer and tried this little *.bat file on Windows XP:

@echo off
phpdoc ^
    --directory "\\server\project\trunk" ^
    --target "C:\tests\project-doc"

... but this is all I get:

PHP Version 5.3.5
phpDocumentor version 1.4.3

Parsing configuration file phpDocumentor.ini...
   (found in C:\Archivos de programa\PHP\pear\data/PhpDocumentor/)...

done
Maximum memory usage set at 256M after considering php.ini...
using tokenizer Parser
directory: ''  not found

I've also tried mapping the UNC path to a drive letter:

@echo off
phpdoc ^
    --directory "I:\" ^
    --target "C:\tests\project-doc"

... but:

PHP Version 5.3.5
phpDocumentor version 1.4.3

Parsing configuration file phpDocumentor.ini...
   (found in C:\Archivos de programa\PHP\pear\data/PhpDocumentor/)...

done
Maximum memory usage set at 256M after considering php.ini...
using tokenizer Parser
a target directory must be specified
 try phpdoc -h

This error message is the same if I create "C:\tests\project-doc" before.

What's exactly wrong in my syntax?

Body:
I think I've found what the issue is. The parameter parser is very picky and it doesn't like neither UNC paths nor bare root directories. If I replace this:

--directory "I:\"

... with this:

--directory "I:\."

... it finally starts running.

I suppose it's a bug. Their bug tracker doesn't seem to be public so I don't know if it's a known issue.


问:
I can't download Pod ParallaxHeader by Github
My question is about an Pod of Github.

I have a problem with a version. I can't download it! :(

https://github.com/romansorochak/ParallaxHeader (I want version of Swift3 -> 1.0.6)

I tried this: pod 'ParallaxHeader', '~> 1.0.6'

But Promt shows this error:

[!] Unable to find a specification for ParallaxHeader (~> 1.0.6)

Somebody knows whats happen??

Thank you so much!

答:
Replace below code in your pod file .I have checked it and I can able to download pod file</p>

```<code># Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target ‘your project name’ do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for your project name

    pod 'ParallaxHeader', '~> 2.0.0'

end
</code>```

Body:
Replace below code in your pod file .I have checked it and I can able to download pod file

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target ‘your project name’ do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for your project name

    pod 'ParallaxHeader', '~> 2.0.0'

end


问:
Android 3.0 error gradle imort error

Error:Cannot choose between the following configurations of project
  :ViewLib:
    - debugApiElements
    - debugRuntimeElements
    - releaseApiElements
    - releaseRuntimeElements All of them match the consumer attributes:
    - Configuration 'debugApiElements':
        - Found com.android.build.api.attributes.BuildTypeAttr 'debug' but wasn't required.
        - Found com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' but
  wasn't required.
        - Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required.
        - Found org.gradle.api.attributes.Usage 'java-api' but wasn't required.
    - Configuration 'debugRuntimeElements':
        - Found com.android.build.api.attributes.BuildTypeAttr 'debug' but wasn't required.
        - Found com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' but
  wasn't required.
        - Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required.
        - Found org.gradle.api.attributes.Usage 'java-runtime' but wasn't required.
    - Configuration 'releaseApiElements':
        - Found com.android.build.api.attributes.BuildTypeAttr 'release' but wasn't required.
        - Found com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' but
  wasn't required.
        - Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required.
        - Found org.gradle.api.attributes.Usage 'java-api' but wasn't required.
    - Configuration 'releaseRuntimeElements':
        - Found com.android.build.api.attributes.BuildTypeAttr 'release' but wasn't required.
        - Found com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' but
  wasn't required.
        - Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required.
        - Found org.gradle.api.attributes.Usage 'java-runtime' but wasn't required.

答:
You might have something like compile project(':ViewLib') in your build.gradle

Try changing it to

compile project(path: ':ViewLib', configuration: 'default')

Also, note

compile is deprecated Reference link

So, instead of compile use implementation

implementation project(path: ':ViewLib', configuration: 'default')

compile, provided, and apk are currently still available. However,
  they will be removed in the next major release of the Android plugin.

Title: Android 3.0 error gradle imort error


问:
Magento Product Flat Data will not reindex
I am having a problem with my Product Flat Index not reindexing, it only stays on processing. I went in and ran the reindex through the shell with indexer.php.

I get a error that I do not understand a bit of, can someone help me?

```<code>Product Flat Data index process unknown error:
exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`sprayfoa_store`.<result 2 when explaining filename '#sql-66c_ab044'>, CONSTRAINT `FK_CAT_PRD_FLAT_1_ENTT_ID_CAT_PRD_ENTT_ENTT_ID` FOREIGN KEY (`entity_id`) REFERENCES `catalog_product_entity`)' in /home/sprayfoa/public_html/store/lib/Zend/Db/Statement/Pdo.php:228
Stack trace:
#0 /home/sprayfoa/public_html/store/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array)
#1 /home/sprayfoa/public_html/store/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#2 /home/sprayfoa/public_html/store/lib/Zend/Db/Statement.php(300): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#3 /home/sprayfoa/public_html/store/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
#4 /home/sprayfoa/public_html/store/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('ALTER TABLE `ca...', Array)
#5 /home/sprayfoa/public_html/store/lib/Varien/Db/Adapter/Pdo/Mysql.php(389): Zend_Db_Adapter_Pdo_Abstract->query('ALTER TABLE `ca...', Array)
#6 /home/sprayfoa/public_html/store/lib/Varien/Db/Adapter/Pdo/Mysql.php(327): Varien_Db_Adapter_Pdo_Mysql->query('ALTER TABLE `ca...')
#7 /home/sprayfoa/public_html/store/lib/Varien/Db/Adapter/Pdo/Mysql.php(2548): Varien_Db_Adapter_Pdo_Mysql->raw_query('ALTER TABLE `ca...')
#8 /home/sprayfoa/public_html/store/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php(806): Varien_Db_Adapter_Pdo_Mysql->addForeignKey('FK_CAT_PRD_FLAT...', 'catalog_product...', 'entity_id', 'catalog_product...', 'entity_id', 'CASCADE', 'CASCADE')
#9 /home/sprayfoa/public_html/store/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php(125): Mage_Catalog_Model_Resource_Product_Flat_Indexer->prepareFlatTable(1)
#10 /home/sprayfoa/public_html/store/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php(115): Mage_Catalog_Model_Resource_Product_Flat_Indexer->rebuild('1')
#11 /home/sprayfoa/public_html/store/app/code/core/Mage/Catalog/Model/Product/Flat/Indexer.php(73): Mage_Catalog_Model_Resource_Product_Flat_Indexer->rebuild(NULL)
#12 /home/sprayfoa/public_html/store/app/code/core/Mage/Catalog/Model/Product/Indexer/Flat.php(303): Mage_Catalog_Model_Product_Flat_Indexer->rebuild()
#13 /home/sprayfoa/public_html/store/app/code/core/Mage/Index/Model/Process.php(159): Mage_Catalog_Model_Product_Indexer_Flat->reindexAll()
#14 /home/sprayfoa/public_html/store/app/code/core/Mage/Index/Model/Process.php(187): Mage_Index_Model_Process->reindexAll()
#15 /home/sprayfoa/public_html/store/shell/indexer.php(158): Mage_Index_Model_Process->reindexEverything()
#16 /home/sprayfoa/public_html/store/shell/indexer.php(198): Mage_Shell_Compiler->run()
#17 {main}
</code>```

答:
Fixing this

In order to fix this issue, you need to find what the corrupted entries are. This is easy. In this case, you’ll need to create a query to get the empty registers:

```<code>SELECT a.entity_id FROM catalog_product_flat_2 AS a LEFT JOIN catalog_product_entity AS b ON a.entity_id = b.entity_id WHERE ISNULL(b.entity_id);
</code>```

This will display the corrupted entities. You only need to delete them
  and that’s all.

```<code>+-----------+
| entity_id |
+-----------+
|     35427 |
|     35428 |
+-----------+
2 rows in set (0.04 sec)
</code>```

As example:

```<code>DELETE FROM catalog_product_flat_2 where entity_id = '35427';
</code>```

Body:
I am having a problem with my Product Flat Index not reindexing, it only stays on processing. I went in and ran the reindex through the shell with indexer.php.

I get a error that I do not understand a bit of, can someone help me?

Product Flat Data index process unknown error:
exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`sprayfoa_store`.<result 2 when explaining filename '#sql-66c_ab044'>, CONSTRAINT `FK_CAT_PRD_FLAT_1_ENTT_ID_CAT_PRD_ENTT_ENTT_ID` FOREIGN KEY (`entity_id`) REFERENCES `catalog_product_entity`)' in /home/sprayfoa/public_html/store/lib/Zend/Db/Statement/Pdo.php:228
Stack trace:
#0 /home/sprayfoa/public_html/store/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array)
#1 /home/sprayfoa/public_html/store/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#2 /home/sprayfoa/public_html/store/lib/Zend/Db/Statement.php(300): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#3 /home/sprayfoa/public_html/store/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
#4 /home/sprayfoa/public_html/store/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('ALTER TABLE `ca...', Array)
#5 /home/sprayfoa/public_html/store/lib/Varien/Db/Adapter/Pdo/Mysql.php(389): Zend_Db_Adapter_Pdo_Abstract->query('ALTER TABLE `ca...', Array)
#6 /home/sprayfoa/public_html/store/lib/Varien/Db/Adapter/Pdo/Mysql.php(327): Varien_Db_Adapter_Pdo_Mysql->query('ALTER TABLE `ca...')
#7 /home/sprayfoa/public_html/store/lib/Varien/Db/Adapter/Pdo/Mysql.php(2548): Varien_Db_Adapter_Pdo_Mysql->raw_query('ALTER TABLE `ca...')
#8 /home/sprayfoa/public_html/store/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php(806): Varien_Db_Adapter_Pdo_Mysql->addForeignKey('FK_CAT_PRD_FLAT...', 'catalog_product...', 'entity_id', 'catalog_product...', 'entity_id', 'CASCADE', 'CASCADE')
#9 /home/sprayfoa/public_html/store/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php(125): Mage_Catalog_Model_Resource_Product_Flat_Indexer->prepareFlatTable(1)
#10 /home/sprayfoa/public_html/store/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php(115): Mage_Catalog_Model_Resource_Product_Flat_Indexer->rebuild('1')
#11 /home/sprayfoa/public_html/store/app/code/core/Mage/Catalog/Model/Product/Flat/Indexer.php(73): Mage_Catalog_Model_Resource_Product_Flat_Indexer->rebuild(NULL)
#12 /home/sprayfoa/public_html/store/app/code/core/Mage/Catalog/Model/Product/Indexer/Flat.php(303): Mage_Catalog_Model_Product_Flat_Indexer->rebuild()
#13 /home/sprayfoa/public_html/store/app/code/core/Mage/Index/Model/Process.php(159): Mage_Catalog_Model_Product_Indexer_Flat->reindexAll()
#14 /home/sprayfoa/public_html/store/app/code/core/Mage/Index/Model/Process.php(187): Mage_Index_Model_Process->reindexAll()
#15 /home/sprayfoa/public_html/store/shell/indexer.php(158): Mage_Index_Model_Process->reindexEverything()
#16 /home/sprayfoa/public_html/store/shell/indexer.php(198): Mage_Shell_Compiler->run()
#17 {main}

Body:
Fixing this

In order to fix this issue, you need to find what the corrupted entries are. This is easy. In this case, you’ll need to create a query to get the empty registers:

SELECT a.entity_id FROM catalog_product_flat_2 AS a LEFT JOIN catalog_product_entity AS b ON a.entity_id = b.entity_id WHERE ISNULL(b.entity_id);

This will display the corrupted entities. You only need to delete them
  and that’s all.

+-----------+
| entity_id |
+-----------+
|     35427 |
|     35428 |
+-----------+
2 rows in set (0.04 sec)

As example:

DELETE FROM catalog_product_flat_2 where entity_id = '35427';


问:
How to search users folders while avoiding digging too deep using DIR?
How to search all users' folders and list the files found (with extensions) in an output text file using .bat (cmd) without including data from AppData folders?

Let's say I have user Jenny and user Tommy. And of course within those users there are folders such as desktop, documents, videos, etc.

How can I create a CMD (or PowerShell) script that will search through each users' folders like desktop, documents, videos, etc., BUT prevent the script from pulling results found in the AppData folder.

I was trying to use this code to search each user, but the results were being watered down by what was found in each users AppData folders.

I used %~dp0Files.txt to have the results exported to the desktop where I was executing the .bat from.

```<code>cd..
cd..
cd Users
dir /s /p /b >> %~dp0Files.txt
pause
</code>```

I appreciate any advice. Even if there is a different script file that is better to use for this task.

答:
Thanks to Mofi's help I was able to also add an exclusion for the All Users folder which was also watering down the results.

My final coded ended up being:

:ScanUsers
@echo off
cls
ECHO Searching users' files
dir "%USERPROFILE%\..\*" /A-D /B /S | %SystemRoot%\System32\findstr.exe /I /L /V /C:"\\AppData\\" >"%~dp0Output\FilesSearch.txt"
start "%~dp0Output\FilesSearch.txt"
wscript.exe "%~dp0Extra\Here is a list of files.vbs"
Timeout 2
goto start
```

%~dp0Output just directs the text document to be saved into a specific file on the desktop

Body:
How to search all users' folders and list the files found (with extensions) in an output text file using .bat (cmd) without including data from AppData folders?

Let's say I have user Jenny and user Tommy. And of course within those users there are folders such as desktop, documents, videos, etc.

How can I create a CMD (or PowerShell) script that will search through each users' folders like desktop, documents, videos, etc., BUT prevent the script from pulling results found in the AppData folder.

I was trying to use this code to search each user, but the results were being watered down by what was found in each users AppData folders.

I used %~dp0Files.txt to have the results exported to the desktop where I was executing the .bat from.

cd..
cd..
cd Users
dir /s /p /b >> %~dp0Files.txt
pause

I appreciate any advice. Even if there is a different script file that is better to use for this task.

Body:
Thanks to Mofi's help I was able to also add an exclusion for the All Users folder which was also watering down the results.

My final coded ended up being:

:ScanUsers
@echo off
cls
ECHO Searching users' files
dir "%USERPROFILE%\..\*" /A-D /B /S | %SystemRoot%\System32\findstr.exe /I /L /V /C:"\\AppData\\" >"%~dp0Output\FilesSearch.txt"
start "%~dp0Output\FilesSearch.txt"
wscript.exe "%~dp0Extra\Here is a list of files.vbs"
Timeout 2
goto start

%~dp0Output just directs the text document to be saved into a specific file on the desktop


问:
I want my table to display all record if no searches were found for a movie but am unsure how to do that
This is my code, tell me where to change because When I do search for a movie that is in a record it displays the result, but when it isn't I only get "Movie Not Found" as in the response.write.

enter image description hereSLNkq.png

答:
I would suggest to put question as text/code instead.

For your case, I suggest you to work with datatable instead of datareader.

== With Datatable approach ==

```<code>SqlConnection con = new SqlConnection(constring);

SqlCommand cmd = new SqlCommand("IF EXISTS(SELECT * FROM Content WHERE MovieTitle=@MovieTitle) SELECT * FROM Content WHERE MovieTitle=@MovieTitle ELSE SELECT * FROM Content");

cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@MovieTitle", MovieTitle.Text);
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Result");
da.Fill(dt);
con.Close();

MovieResults.DataSource = dt;
MovieResults.DataBind();
</code>```

Based on @Shai Cohen's comment, it would be better approach by using ExecuteDataReader if transaction is forward-only. Thanks @ShaiCohen for your comment.

== Without Datatable approach ==

```<code>SqlConnection con = new SqlConnection(constring);

SqlCommand cmd = new SqlCommand("IF EXISTS(SELECT * FROM Content WHERE MovieTitle=@MovieTitle) SELECT * FROM Content WHERE MovieTitle=@MovieTitle ELSE SELECT * FROM Content");

cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@MovieTitle", MovieTitle.Text);
cmd.Connection = con;
con.Open();

MovieResults.DataSource = cmd.ExecuteReader();
MovieResults.DataBind();

con.Close();
</code>```

Enjoy Coding (;

Body:
I would suggest to put question as text/code instead.

For your case, I suggest you to work with datatable instead of datareader.

== With Datatable approach ==

SqlConnection con = new SqlConnection(constring);

SqlCommand cmd = new SqlCommand("IF EXISTS(SELECT * FROM Content WHERE MovieTitle=@MovieTitle) SELECT * FROM Content WHERE MovieTitle=@MovieTitle ELSE SELECT * FROM Content");

cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@MovieTitle", MovieTitle.Text);
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Result");
da.Fill(dt);
con.Close();

MovieResults.DataSource = dt;
MovieResults.DataBind();

Based on @Shai Cohen's comment, it would be better approach by using ExecuteDataReader if transaction is forward-only. Thanks @ShaiCohen for your comment.

== Without Datatable approach ==

SqlConnection con = new SqlConnection(constring);

SqlCommand cmd = new SqlCommand("IF EXISTS(SELECT * FROM Content WHERE MovieTitle=@MovieTitle) SELECT * FROM Content WHERE MovieTitle=@MovieTitle ELSE SELECT * FROM Content");

cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@MovieTitle", MovieTitle.Text);
cmd.Connection = con;
con.Open();

MovieResults.DataSource = cmd.ExecuteReader();
MovieResults.DataBind();

con.Close();

Enjoy Coding (;


问:
Express server inside angular app files
I am trying to add express inside my angular app to handle the communication with my server. I searched online about how to do it, and found out how. But I didn't understand few things.

I added a new file called server.js:

```<code>const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

//Get our API routes

const api = require('./server/routes/api');
const app = express();

//Parsers for POST Data app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: false }))

//Point static path to dist

app.use(express.static(path.join(__dirname, 'dist')));

//Set our API routes

app.use('/api', api);

// Catch all other routes and return the index file

app.get('*', (req, res) => {   res.sendFile(path.join(__dirname, 'dist/index.html')); });

/**  * Get port from environment and store in Express.  */

const port = process.env.PORT || '3000'; app.set('port', port);

/**  * Create HTTP server.  */

const server = http.createServer(app);

/**  * Listen on provided port, on all network interfaces.  */

server.listen(port, () => console.log(`API running on localhost:${port}`));
</code>```

And then I should add new folder called server and inside of another folder called routes and then an api.js file:

```<code>const express = require('express');

const router = express.Router();

/* GET api listing. */
router.get('/', (req, res) => {
  res.send('api works');
});

module.exports = router;
</code>```

What the difference between these 2 files ? Can we combine them together ?

答:
There is no difference between these two, except that the second one should only be used to define your own API routes, and yes, these can be combined if you want, but that will result in server.js becoming bulky.

The main idea here is to separate the concerns. server.js can be used to configure server level things, i.e. error handling, CORS configuration etc. On the other hand, api.js should be used to define your API routes.

Ultimately, server.js is what will be used to boot up your Node server, and if you see closely, this file internally uses api.js.

```<code>const api = require('./server/routes/api');
...
...
app.use('/api', api);
</code>```

Title: Express server inside angular app files

Body:
I am trying to add express inside my angular app to handle the communication with my server. I searched online about how to do it, and found out how. But I didn't understand few things.

I added a new file called server.js:

const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

//Get our API routes

const api = require('./server/routes/api');
const app = express();

//Parsers for POST Data app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: false }))

//Point static path to dist

app.use(express.static(path.join(__dirname, 'dist')));

//Set our API routes

app.use('/api', api);

// Catch all other routes and return the index file

app.get('*', (req, res) => {   res.sendFile(path.join(__dirname, 'dist/index.html')); });

/**  * Get port from environment and store in Express.  */

const port = process.env.PORT || '3000'; app.set('port', port);

/**  * Create HTTP server.  */

const server = http.createServer(app);

/**  * Listen on provided port, on all network interfaces.  */

server.listen(port, () => console.log(`API running on localhost:${port}`));

And then I should add new folder called server and inside of another folder called routes and then an api.js file:

const express = require('express');

const router = express.Router();

/* GET api listing. */
router.get('/', (req, res) => {
  res.send('api works');
});

module.exports = router;

What the difference between these 2 files ? Can we combine them together ?

Body:
There is no difference between these two, except that the second one should only be used to define your own API routes, and yes, these can be combined if you want, but that will result in server.js becoming bulky.

The main idea here is to separate the concerns. server.js can be used to configure server level things, i.e. error handling, CORS configuration etc. On the other hand, api.js should be used to define your API routes.

Ultimately, server.js is what will be used to boot up your Node server, and if you see closely, this file internally uses api.js.

const api = require('./server/routes/api');
...
...
app.use('/api', api);


问:
A potentially dangerous Request.Form value was detected from the client
I am using CKEditor/CKFinder as wysiwyg editor on my MVC.NET site.

I have set [ValidateInput(false)] and it works when debugging it locally, but I receive the following error when I have published the site:

```<code>A potentially dangerous Request.Form value was detected from the client (message="<p>
<em>Testing</e...").
</code>```

can anyone explain why the published site is different from the locally site, especially when I have set [ValidateInput(false)]?

*Update:*I am using .Net 3.5 so shouldn't  [ValidateInput(false)] work out the box?

答:
Have you tried setting the htmlEncodeOutput property?

```<code>CKEDITOR.replace('editor1', {
    htmlEncodeOutput: true });
</code>```

This should encode the output and you should be able to avoid setting the requestValidationMode.

Documentation for it is here: ckEditor documentation

Body:
I am using CKEditor/CKFinder as wysiwyg editor on my MVC.NET site.

I have set [ValidateInput(false)] and it works when debugging it locally, but I receive the following error when I have published the site:

A potentially dangerous Request.Form value was detected from the client (message="

Testing</e...").

can anyone explain why the published site is different from the locally site, especially when I have set [ValidateInput(false)]?

*Update:*I am using .Net 3.5 so shouldn't  [ValidateInput(false)] work out the box?

Body:
Have you tried setting the htmlEncodeOutput property?

CKEDITOR.replace('editor1', {
    htmlEncodeOutput: true });

This should encode the output and you should be able to avoid setting the requestValidationMode.

Documentation for it is here: ckEditor documentation

ContentLicense: CC BY-SA 4.0


问:
Google Maps Android API Samples Key not working?
I'm an Android/Java noob trying to get Google Maps Android API Samples to work with an emulator (Nexus 5X API 26) and Android Studio on my Macbook.

I copied the github repo for the samples and loaded it into Android Studio. Now, the project compiles and I have the app on the emulator, but the map doesn't seem to be loading in the fragment.

I don't see any errors in the console.

I have created my unrestricted GMaps API Key and updated it in the manifest file and the resource/debug google_maps_api.xml files.

This is the Activity in question.

https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/BasicMapDemoActivity.java

I also set a breakpoint at onMapReady() and it does get hit. But the fragment is blank. How do I debug it further?

答:
I resolved it myself by switching from an emulator to a real phone.

Looks like some emulators don't come pre-loaded with Google Play services APK. That might have been the issue.


问:
Rails 5 if statement working on show but not working on index
I am creating a poll app. Users can vote, but if they have voted already they are not able to vote again.

This is the method voted_for that checks it:

user.rb

```<code>class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

has_many :votes, dependent: :destroy
has_many :vote_options, through: :votes

def voted_for?(poll)
  vote_options.any? {|v| v.poll == poll }
end
end
</code>```

This wworks in my voting form:

polls/_voting_form.html.erb

```<code><%= form_tag votes_path, method: :post, remote: true, id: 'voting_form' do %>
  <%= hidden_field_tag 'poll[id]', @poll.id %>

  <%= render partial: 'polls/vote_option', collection: @poll.vote_options, as: :option %>

  <% if current_user.voted_for?(@poll) %>
    <p>You have already voted!</p>
  <% else %>
    <%= submit_tag 'Vote', class: 'btn btn-lg btn-primary' %>
  <% end %>
<% end %>
</code>```

Now I want too do thee same on index page, which shows list  of polls and a button VOTE for each. I want to show a button VIEW if user already voted that poll.

polls/index.html.erb

```<code>        <div class="container">

<% content_for(:page_header) {"POLLS"} %>

  <%= render "filter_box" %>

  <% @polls.each do |poll| %>

    <div class="well">

      <div class="row">
        <h4><%= poll.question %>
          <small>(voted:
            <%= poll.votes_summary %>)</small>
        </h4>
      </div>

      <div class="row">
        <div class="col-sm-2"><%= 'OPEN' %>
          <p><%= poll.open_date %></p>
        </div>
        <div class="col-sm-2"><%= 'CLOSE' %>
          <p><%= poll.close_date %></p>
        </div>
        <div class="col-sm-2"><%= 'DIVISION' %>
          <p><%= poll.division.try(:name) %></p>
        </div>
        <div class="col-sm-2">
          <p>
            <% if  current_user.voted_for?(@poll) %>
              <%= link_to 'VIEW', poll_path(poll), class: 'btn btn-primary btn-lg block' %>

            <% else %>
                <%= link_to 'VOTE', poll_path(poll), class: 'btn btn-primary btn-lg block' %>
            <% end %>
          </p>
        </div>

        <div class="col-sm-3">
          <div class="btn-group">

            <%= link_to 'Edit', edit_poll_path(poll), class: 'btn btn-default' %>
            <%= link_to 'Delete', poll_path(poll), method: :delete, class: 'btn btn-danger', data: {confirm: 'Are you sure?'} %>

          </div>

        </div>

      </div>
        </div>
    <% end %>
</code>```

polls_controller

```<code>class PollsController < ApplicationController

  before_action :authenticate_user!

  def index
    @q = Poll.ransack(params[:q])
  @polls = @q.result.order('id ASC')
    respond_to do |format|
      format.html
  end
  end

  def new
    @poll = Poll.new
      @poll.vote_options.build
  end

  def create
      @poll = Poll.new(poll_params)
      if @poll.save
        flash[:success] = 'Poll was created!'
        redirect_to polls_path
      else
        render 'new'
      end
    end

  def edit
  @poll = Poll.find_by_id(params[:id])
end

def update
  @poll = Poll.find_by_id(params[:id])
  if @poll.update_attributes(poll_params)
    flash[:success] = 'Poll was updated!'
    redirect_to polls_path
  else
    render 'edit'
  end
end

def destroy
  @poll = Poll.find_by_id(params[:id])
  if @poll.destroy
    flash[:success] = 'Poll was destroyed!'
  else
    flash[:warning] = 'Error destroying poll...'
  end
  redirect_to polls_path
end

def show
  @poll = Poll.includes(:vote_options).find_by_id(params[:id])
  @vote = Vote.find_by_id(params[:id])

end

  private

  def poll_params
    params.require(:poll).permit(:question, :description, :division_id, :open_date, :close_date, vote_options_attributes: [:id, :title, :_destroy])
  end
end
</code>```

But if I use this it ignores the first condition and shows VOTE button for all. Even polls I voted already.

How cnn I fix it?

答:
@poll is not a defined variable and will be null when used in if statement.

You have poll variable. So use poll variable in if statement in index.html.erb instead of @poll.

Body:
I am creating a poll app. Users can vote, but if they have voted already they are not able to vote again.

This is the method voted_for that checks it:

user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

has_many :votes, dependent: :destroy
has_many :vote_options, through: :votes

def voted_for?(poll)
  vote_options.any? {|v| v.poll == poll }
end
end

This wworks in my voting form:

polls/_voting_form.html.erb

<%= form_tag votes_path, method: :post, remote: true, id: 'voting_form' do %>
  <%= hidden_field_tag 'poll[id]', @poll.id %>

  <%= render partial: 'polls/vote_option', collection: @poll.vote_options, as: :option %>

  <% if current_user.voted_for?(@poll) %>

You have already voted!

  <% else %>
    <%= submit_tag 'Vote', class: 'btn btn-lg btn-primary' %>
  <% end %>
<% end %>

Now I want too do thee same on index page, which shows list  of polls and a button VOTE for each. I want to show a button VIEW if user already voted that poll.

polls/index.html.erb

<% content_for(:page_header) {"POLLS"} %>

  <%= render "filter_box" %>

  <% @polls.each do |poll| %>

<%= poll.question %>
          (voted:
            <%= poll.votes_summary %>)

<%= 'OPEN' %>

<%= poll.open_date %>

<%= 'CLOSE' %>

<%= poll.close_date %>

<%= 'DIVISION' %>

<%= poll.division.try(:name) %>

            <% if  current_user.voted_for?(@poll) %>
              <%= link_to 'VIEW', poll_path(poll), class: 'btn btn-primary btn-lg block' %>

            <% else %>
                <%= link_to 'VOTE', poll_path(poll), class: 'btn btn-primary btn-lg block' %>
            <% end %>

            <%= link_to 'Edit', edit_poll_path(poll), class: 'btn btn-default' %>
            <%= link_to 'Delete', poll_path(poll), method: :delete, class: 'btn btn-danger', data: {confirm: 'Are you sure?'} %>

    <% end %>

polls_controller

class PollsController < ApplicationController

  before_action :authenticate_user!

  def index
    @q = Poll.ransack(params[:q])
  @polls = @q.result.order('id ASC')
    respond_to do |format|
      format.html
  end
  end

  def new
    @poll = Poll.new
      @poll.vote_options.build
  end

  def create
      @poll = Poll.new(poll_params)
      if @poll.save
        flash[:success] = 'Poll was created!'
        redirect_to polls_path
      else
        render 'new'
      end
    end

  def edit
  @poll = Poll.find_by_id(params[:id])
end

def update
  @poll = Poll.find_by_id(params[:id])
  if @poll.update_attributes(poll_params)
    flash[:success] = 'Poll was updated!'
    redirect_to polls_path
  else
    render 'edit'
  end
end

def destroy
  @poll = Poll.find_by_id(params[:id])
  if @poll.destroy
    flash[:success] = 'Poll was destroyed!'
  else
    flash[:warning] = 'Error destroying poll...'
  end
  redirect_to polls_path
end

def show
  @poll = Poll.includes(:vote_options).find_by_id(params[:id])
  @vote = Vote.find_by_id(params[:id])

end

  private

  def poll_params
    params.require(:poll).permit(:question, :description, :division_id, :open_date, :close_date, vote_options_attributes: [:id, :title, :_destroy])
  end
end

But if I use this it ignores the first condition and shows VOTE button for all. Even polls I voted already.

How cnn I fix it?


问:
Css Pseudo-class :first-letter
Can it be used inside an a tag?

```<code>a.x:first-letter
{
   color:red;
}
</code>```

My name is Lionel

I can't seem to make it work.

答: According to css2.1 :first-letter applies only to block container elements.

Title: Css Pseudo-class :first-letter

Body:
Can it be used inside an a tag?

a.x:first-letter
{
   color:red;
}

My name is Lionel

I can't seem to make it work.


问:
Java JDBC thows com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException for \'Test1\' value
I have below table:
dummy_tbl

```<code>  |id |Name |
  ----------
  |1  |Test1|
  |2  |Test2|
</code>```

When I try to execute below query in SQlyog - MySql(5.6.80) it's working fine:

```<code> select * from dummy_tbl where name like \'Test1\';
</code>```

But same query when I tried from code using JDBC statement it's throwing below error:

```<code> com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'Test1\'' at line 1
</code>```

Code snipped from code:

```<code>  String sql = "SELECT * from dummy_tbl where name like \'Test1\'";
  Statement stmt= conn.createStatement();
  ResultSet rs = stmt.executeQuery(sql);
</code>```

答:
Changing the query to:
select * from dummy_tbl where name like 'Test%';

should fix your issue.

Body:
I have below table:
dummy_tbl

  |id |Name |
  ----------
  |1  |Test1|
  |2  |Test2|

When I try to execute below query in SQlyog - MySql(5.6.80) it's working fine:

 select * from dummy_tbl where name like \'Test1\';

But same query when I tried from code using JDBC statement it's throwing below error:

 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'Test1\'' at line 1

Code snipped from code:

  String sql = "SELECT * from dummy_tbl where name like \'Test1\'";
  Statement stmt= conn.createStatement();
  ResultSet rs = stmt.executeQuery(sql);


问:
linux shell script sed css structure
how do I write the following sed command so that I can use the line breaks and code structure when I write the sed command as well as output the same
code structure? As you can see I'm trying to modify CSS without making it one line.</p>

```<code>sed -i 's/#para3{
font-size:21pt;
position:absolute;
width:500px;
left:15px;
top:445px;
text-align:left;
  }/#para3{
font-size:testpt;
position:absolute;
width:500px;
left:15px;
top:445px;
text-align:left;
  }/g' $file0
</code>```

答:
If you just want to replace font-size value between #para3 { and next }:

```<code>sed '/#para3 *{/,/}/{s/\(font-size: *\)21pt;/\1testpt;/}' file
</code>```

To replace all block, you can try the c(change) command:

```<code>sed '/#para3 *{/,/}/c \
#para3 { \
  font-size: 3em; \
  width: 100%; \
}' file
</code>```

NB: after the c command, all lines except last one must ends with a  newline character (\)

Title: linux shell script sed css structure

Body:
how do I write the following sed command so that I can use the line breaks and code structure when I write the sed command as well as output the same
code structure? As you can see I'm trying to modify CSS without making it one line.

sed -i 's/#para3{
font-size:21pt;
position:absolute;
width:500px;
left:15px;
top:445px;
text-align:left;
  }/#para3{
font-size:testpt;
position:absolute;
width:500px;
left:15px;
top:445px;
text-align:left;
  }/g' $file0

Body:
If you just want to replace font-size value between #para3 { and next }:

sed '/#para3 *{/,/}/{s/\(font-size: *\)21pt;/\1testpt;/}' file

To replace all block, you can try the c(change) command:

sed '/#para3 *{/,/}/c \
#para3 { \
  font-size: 3em; \
  width: 100%; \
}' file

NB: after the c command, all lines except last one must ends with a  newline character (\)


问:
Trouble in Controller Query foreach loop in laravel
Hello Again everyone,

can anyone help me with this code.

```<code>public function submitranking(Request $req){
    $dataCandidate = Candidate::all();

    foreach($dataCandidate as $Candidate){
        $judgeRate = Score::where('canId',$Candidate->id )
        ->where('catId',$req->catId )
        ->where('judgeId',$req->judgeId)
        ->sum('score');
        dd($judgeRate);
    }

}
</code>```

It is supposed to display all the scores of the candidates when I dd($judgeRate) it only display one record? How can I make it loop and display all the total sum scores of the candidates... Please help

答:
You should try this:

```<code>public function submitranking(Request $req){

    $dataCandidate = Candidate::get();

    foreach($dataCandidate as $Candidate){
        $judgeRate = Score::where('canId',$Candidate->id )
        ->where('catId',$req->catId )
        ->where('judgeId',$req->judgeId)
        ->sum('score');

        print('<pre style="color:red;">');
        print_r($judgeRate);
        print('```');
    }
    exit;
}
```

<p><strong>OR</strong> You should try this:</p>

```public function submitranking(Request $req){

    $dataCandidate = Candidate::get();

    foreach($dataCandidate as $Candidate){
        $judgeRate = Score::select('score_id',DB::raw("SUM(score) as score"))
        ->where('canId',$Candidate->id )
        ->where('catId',$req->catId )
        ->where('judgeId',$req->judgeId)
        ->get();

        print('
');
        print_r($judgeRate);
        print('```');
    }
    exit;
}
</code>```

Body:
Hello Again everyone,

can anyone help me with this code.

public function submitranking(Request $req){
    $dataCandidate = Candidate::all();

    foreach($dataCandidate as $Candidate){
        $judgeRate = Score::where('canId',$Candidate->id )
        ->where('catId',$req->catId )
        ->where('judgeId',$req->judgeId)
        ->sum('score');
        dd($judgeRate);
    }

}

It is supposed to display all the scores of the candidates when I dd($judgeRate) it only display one record? How can I make it loop and display all the total sum scores of the candidates... Please help

Body:
You should try this:

public function submitranking(Request $req){

    $dataCandidate = Candidate::get();

    foreach($dataCandidate as $Candidate){
        $judgeRate = Score::where('canId',$Candidate->id )
        ->where('catId',$req->catId )
        ->where('judgeId',$req->judgeId)
        ->sum('score');

        print('<pre style="color:red;">');
        print_r($judgeRate);
        print('</pre>');
    }
    exit;
}

OR You should try this:

public function submitranking(Request $req){

    $dataCandidate = Candidate::get();

    foreach($dataCandidate as $Candidate){
        $judgeRate = Score::select('score_id',DB::raw("SUM(score) as score"))
        ->where('canId',$Candidate->id )
        ->where('catId',$req->catId )
        ->where('judgeId',$req->judgeId)
        ->get();

        print('<pre style="color:red;">');
        print_r($judgeRate);
        print('</pre>');
    }
    exit;
}


问:
How to create a table in rails by running a migration
I have created a migration file for creating a table UserDetails in my db.. and it was working fine b4...

Unknowingly I deleted that table to do some modification .. But now when i gave

rake db:migrate .. its not creating the table ..

I have the migration file .. BUt when i give rake db:migrate its not creating.. How to do so ??

答:
Could you just run that specific migration as stated in the Guides. http://guides.rubyonrails.org/migrations.html#being-specific

I have run specific migrations by their timestamp before. It seems like it would work in this situation also.


问:
How to check issues by version instead of build on crashlytics?
We have lot of builds for each version after we integrated the CI system.
However, if we want to check the issues of one specified version, we have to select all builds of this version, which is very inconvenient.

How to resolve this problem?

答:
You can filter Version on the dashboard.
 Check the image dropdown.


问:
Java if- else strings .contains not working error
If I put entity.about = "phone" and test = "phone" then the search list is updated but if I put entity.about = "this is phone" and test = "phone" then the search list is not updated.

```<code>public void onSearchConfirmed(final CharSequence text) {
    productsRef = FirebaseDatabase.getInstance().getReference("products");
    searchList.clear();
    final String test = text.toString();
    productsRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                ProductEntity entity = postSnapshot.getValue(ProductEntity.class);
                if(entity.about.contains(test) || entity.vendor_address.contains(test)) {
                    searchList.add(entity) ;
                }
            }
        }
    }
}
</code>```

答: Replace code:entity.about.contains(test) with entity.about.toLowerCase.contains(test)

Body:
If I put entity.about = "phone" and test = "phone" then the search list is updated but if I put entity.about = "this is phone" and test = "phone" then the search list is not updated.

public void onSearchConfirmed(final CharSequence text) {
    productsRef = FirebaseDatabase.getInstance().getReference("products");
    searchList.clear();
    final String test = text.toString();
    productsRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                ProductEntity entity = postSnapshot.getValue(ProductEntity.class);
                if(entity.about.contains(test) || entity.vendor_address.contains(test)) {
                    searchList.add(entity) ;
                }
            }
        }
    }
}


问:
php curl access unknown url ,Why curl_exec no return false,echo should output failed

curl access unknown url,Why curl_exec return true.It should output failed.

答:
```<code>$url = 'http://fvsfdfsdfsdfsfse';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
$result = curl_exec($curl);
print_r($result);
echo curl_error($curl);
curl_close($curl);

if($result == false) {
    echo 'failed';
    return;
}
echo 'succeed';
return;
</code>```