问:
Spring Boot 2.0.0M2 Thymeleaf 3 failed to convert field
After upgrading to spring-boot-2-m2 (thymeleaf 3) I am getting failed conversion errors for fields that correspond to JPA relationships.

Failed to convert from type [@javax.persistence.ManyToOne @javax.persistence.JoinColumn com.pps2....entities.FormType] to type [java.lang.String] for value 'com.pps2.....FormType@819841af'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.util.Optional<?>] to type [java.lang.String]

JPA Entity

```<code>@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_form_type")
private FormType type;

public FormType getType() {
    return type;
}
</code>```

The code in the template is:

<select th:field="*{type}" class="col-xs-12">

Throws similar failed conversion error.

Of course when putting direct reference it works, but in that case it breaks a lot of templates in the project. And generates name as type.id and not type.

Working example
<select th:field="*{type.id}" class="col-xs-12">

Question - Why did they change the API? And is there a way to resolve it without rechecking all the templates (e.g. writing converter?)?

答:
The solution is to write your own Optional<T> to String converter. I do not know why it was excluded from Spring Boot 2 M2

Converter code

```<code>import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

@Component
final class OptionalToString implements Converter<Optional<?>, String> {

    public String convert(Optional<?> source) {
        return Objects.toString(source.get(),"");
    }
}
</code>```

Another option

Is to specify directly the column (like id)

Working example  <select th:field="*{type.id}" class="col-xs-12">

Body:
After upgrading to spring-boot-2-m2 (thymeleaf 3) I am getting failed conversion errors for fields that correspond to JPA relationships.

Failed to convert from type [@javax.persistence.ManyToOne @javax.persistence.JoinColumn com.pps2....entities.FormType] to type [java.lang.String] for value 'com.pps2.....FormType@819841af'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.util.Optional<?>] to type [java.lang.String]

JPA Entity

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_form_type")
private FormType type;

public FormType getType() {
    return type;
}

The code in the template is:

<select th:field="*{type}" class="col-xs-12">

Throws similar failed conversion error.

Of course when putting direct reference it works, but in that case it breaks a lot of templates in the project. And generates name as type.id and not type.

Working example
<select th:field="*{type.id}" class="col-xs-12">

Question - Why did they change the API? And is there a way to resolve it without rechecking all the templates (e.g. writing converter?)?

Body:
The solution is to write your own Optional<T> to String converter. I do not know why it was excluded from Spring Boot 2 M2

Converter code

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

@Component
final class OptionalToString implements Converter<Optional<?>, String> {

    public String convert(Optional<?> source) {
        return Objects.toString(source.get(),"");
    }
}

Another option

Is to specify directly the column (like id)

Working example  <select th:field="*{type.id}" class="col-xs-12">


来源: stackexchange

问:
Rmarkdown knitting YAML LaTeX error
I'm trying to have a script knit an Rmd file to a PDF document and faced some errors.

I must say, document knits fine if I click on the knit button in Rstudio but it fails to knit if I use the command:

```<code>rmarkdown::render('diagnostic.Rmd',output_format = "pdf_document",
                  output_file = "diag.pdf")
</code>```

The first error I get comes from this part of my code:

```<code>---
author: Zigo_datateam
date: "`r format(Sys.time(), '%d %B, %Y')`"
geometry: margin=1.6in
header-includes: "\\usepackage{fancyhdr} \\fancyfoot[CO,CE]{My footer}"
output:
  pdf_document:
    toc: false
title: "Graphic Layout(Report)"

---
</code>```

and is:

```<code>   Error in yaml::yaml.load(string, ...) :
  Scanner error: while scanning a simple key at line 4, column 1could
  not find expected ':' at line 5, column 1
</code>```

So, if I remove the hole header-includesexpression it seems to start knitting but then I get a second error from this part (which comes after the second "---"):

```<code>\addtolength{\headheight}{1.0cm}
\pagestyle{fancyplain}
\rhead{\includegraphics[height=1.2cm]{logo.png}}
\renewcommand{\headrulewidth}{0pt}
</code>```

ERROR:

```<code>! Undefined control sequence.
<argument> \undefinedpagestyle

l.130 ...headheight}{1.0cm} \pagestyle{fancyplain}
</code>```

How can I get rid of the first error without getting the second one?

Update: I decided to move all footer/header styles to a separate file and my code looks like this:

```<code>---
author: Zigo_datateam
date: "`r format(Sys.time(), '%d %B, %Y')`"
geometry: margin=1.6in
output:
  pdf_document:
    includes:
      in_header: mystyles.sty
title: "Graphic Layout(Report)"
---
</code>```

The errors I talked about earlier stoped showing but I still get this:

```<code>pandoc: Error producing PDF
Error: pandoc document conversion failed with error 43
</code>```

答:
In your YAML, use

```<code>header-includes:
  - \usepackage{fancyhdr}
  - \fancyfoot[CO,CE]{My footer}
</code>```

And it should work.

ContentLicense: CC BY-SA 3.0

Title: Rmarkdown knitting YAML LaTeX error

Body:
I'm trying to have a script knit an Rmd file to a PDF document and faced some errors.

I must say, document knits fine if I click on the knit button in Rstudio but it fails to knit if I use the command:

rmarkdown::render('diagnostic.Rmd',output_format = "pdf_document",
                  output_file = "diag.pdf")

The first error I get comes from this part of my code:

---
author: Zigo_datateam
date: "`r format(Sys.time(), '%d %B, %Y')`"
geometry: margin=1.6in
header-includes: "\\usepackage{fancyhdr} \\fancyfoot[CO,CE]{My footer}"
output:
  pdf_document:
    toc: false
title: "Graphic Layout(Report)"

---

and is:

   Error in yaml::yaml.load(string, ...) :
  Scanner error: while scanning a simple key at line 4, column 1could
  not find expected ':' at line 5, column 1

So, if I remove the hole header-includesexpression it seems to start knitting but then I get a second error from this part (which comes after the second "---"):

\addtolength{\headheight}{1.0cm}
\pagestyle{fancyplain}
\rhead{\includegraphics[height=1.2cm]{logo.png}}
\renewcommand{\headrulewidth}{0pt}

ERROR:

! Undefined control sequence.
<argument> \undefinedpagestyle

l.130 ...headheight}{1.0cm} \pagestyle{fancyplain}

How can I get rid of the first error without getting the second one?

Update: I decided to move all footer/header styles to a separate file and my code looks like this:

---
author: Zigo_datateam
date: "`r format(Sys.time(), '%d %B, %Y')`"
geometry: margin=1.6in
output:
  pdf_document:
    includes:
      in_header: mystyles.sty
title: "Graphic Layout(Report)"
---

The errors I talked about earlier stoped showing but I still get this:

pandoc: Error producing PDF
Error: pandoc document conversion failed with error 43

Body:
In your YAML, use

header-includes:
  - \usepackage{fancyhdr}
  - \fancyfoot[CO,CE]{My footer}

And it should work.


问:
Dynamic dropdown menu in a rails application?
Let's say I have a database table called Teachers.  Each row in the table has a name attribute and I want to display a dropdown menu in my webapp that displays all the names of the teachers in the database.  How can I do this?  I get how I would display a regular dropdown menu, but I don't get how to display one based off of the database.  </p>

答:
In your controller, you would get the teachers:

@teachers = Teacher.all

Then in your view, you can display them with:

select("teacher", "name", @teachers.collect {|p| [ p.name, p.id ] }, { include_blank: true })


问:
Android Game Keeps Getting Hacked
So we've been through this several times now, we release a game (for cheap) and someone hacks it and puts it up on a mirror.  We setup Google Alerts for all our apps, so we get told daily who's doing the hacking.  So far, we have implemented the licensing service as Google has suggested, our salt is randomly made each time the license is initiated with the unique device ID.  We run the check service once, when the application is started for the first time.  We then generate a 512 character hash for the key and the stored value that is compared against in SharedPreferences from there on out.

Now, I know that checking once is probably where the application is being blocked.  Our bytecode has most likely been looked at and recompiled without the line that initiates the check.

From here, I don't want to obfuscate our code as I have seen it broken before.  I want something a little more solid, and I also want to learn how to do this properly.  I am more interested in learning than making money at this point since only 2% of people will ever look for a hacked version.

So far, on my own, I have come up with a random number generator that is placed in several startup areas of the game.  When initiated (say, 1 out of 50 times) the license is checked.  I know this would make it harder to hack because the cracker would have to eliminate each case, compile, eliminate, compile. This method however, is still crackable...so what do you guys suggest?  Again, I am really interested in this process of security, so please educate, don't turn this into a discussion on obfuscation or checking periodically based on a timestamp.

Thanks

答:
It will be incredibly hard to inhibit this kind ov behavior. Anything that is handled on the client-side is hackable using APK decompilation and modding, memory editing with software such as Game Guardian ect.

The only way I can see how partially getting around it, would be to make an online game instead. Or have certain functions handled online. Or if anti-tamper encryption like denuvo ever is available for Android / iOS.

Title: Android Game Keeps Getting Hacked


问:
Datetime format in MSSQL
In my aplication I use a DateEdit control and show the date using this format dd/MM/yyyy so the date is save correctly when I use mssql-server 2014 (spanish) but whe I use mssql-server 2008 (english) the date is stored with this fomat MM/dd/yyyy so what I need to know is if there is a way to store the date with the format dd/MM/yyyy no matter the versión of mssql-server I use or the lenguage I use?

EDIT: to explain better this is the problem, this text 03/07/2017 is stored in the sqlserver 2014 as july 3 of 2017 and in the sqlserver 2008 is stored as march 7 of 2017.

答:
As others said: SQL doe not store dates as we humans do. But thats another matter.
I think what you need is to inform SQL the format your date has.
The best option is to use ISO 8601 format: yyyy-mm-ddThh:mi:ss.mmm.
So, if before saving the date you just format it with this format, SQL (no matter the version or the language) will recognize it as begining with a year, followed by a month and so on. The key of this subject is using first 4 digits.
This way, 2017-01-03 will always be January 03, 2017 and never March 01, 2017. Hope this help you.

Title: Datetime format in MSSQL


问:
Android: Creating a custom container-view
I'm trying to create a custom view (or better, layout) in android, that serves as a container for 2 child views (Think of it as a bar that separates 2 containers vertically, that can be swiped up and down).

I'd like to use it like a layout in xml, so that you can nest any views in it.
I thought of something like that:

```<code>            <view class="at.calista.quatscha.views.SwipebarLayout"
            android:id="@+id/sbl"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <!-- Top View -->
            <Button android:text="Top" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

            <!-- Bottom View -->
            <Button android:text="Bottom" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</view>
</code>```

This xml should give me the swipeable bar between the two buttons.

However, I don't know how to accomplish this, I'm extending LinearLayout atm, but how do I tell my children how to position themselves?

答:
instead of

```<code><view class="at.calista.quatscha.views.SwipebarLayout"
        android:id="@+id/sbl"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
</code>```

you can use

```<code><at.calista.quatscha.views.SwipebarLayout
        android:id="@+id/sbl"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
</code>```

If your SwipebarLayout class extends LinearLayout it will behave exactly same way as if you would have LinearLayout tag in your code instead and you can position the children exactly same way you would with LinearLayout. Of course if you have overridden some methods from LinearLayout then the functionality is different from that part.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to create a custom view (or better, layout) in android, that serves as a container for 2 child views (Think of it as a bar that separates 2 containers vertically, that can be swiped up and down).

I'd like to use it like a layout in xml, so that you can nest any views in it.
I thought of something like that:

            <view class="at.calista.quatscha.views.SwipebarLayout"
            android:id="@+id/sbl"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <Button android:text="Top" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

            <Button android:text="Bottom" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</view>

This xml should give me the swipeable bar between the two buttons.

However, I don't know how to accomplish this, I'm extending LinearLayout atm, but how do I tell my children how to position themselves?

Body:
instead of

<view class="at.calista.quatscha.views.SwipebarLayout"
        android:id="@+id/sbl"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

you can use

<at.calista.quatscha.views.SwipebarLayout
        android:id="@+id/sbl"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

If your SwipebarLayout class extends LinearLayout it will behave exactly same way as if you would have LinearLayout tag in your code instead and you can position the children exactly same way you would with LinearLayout. Of course if you have overridden some methods from LinearLayout then the functionality is different from that part.


问:
Getting all of the children Tag Helpers in a parent Tag Helper Asp.Net Core
I am trying to write two Tag helpers that are used to localize strings in razor views. The purpose of the parent tag is to gather all of the keys that are requested by the child tags and get them from the database in one batch and cache them.

Then the child tags will use the cached versions, this way I am hoping to lower the load on the database. I am looking for something like this:

```<code><parent-tag>
   <child-tag key="Hello" />
     some HTML here
   <child-tag key="Hi!" />
</parent-tag>
</code>```

I want to be able to get a list of  objects in the Parent tag's Invoke method.

I have also tried storing data in TagHelperContext to communicate with other tag helpers, but this will not work either, because I have to call output.GetChildContentAsync() inside the Parent's Invoke method, which defeats the whole purpose of the caching.

答:
@Encrypt0r you could have an in-memory static cache relation of the TagHelpers context.Items and your localized keys. This would involve using context.Items in your to execute GetChildContentAsync one time. All subsequent times would then be cached by looking up the key values based off of the context.Items (assuming the key values were not dynamic).

Think of it this way:

```<code>// Inside your TagHelper
if (_cache.TryGetValue(context.UniqueId, out var localizationKeys))
{
    ... You already have the keys, do whatever
}
else
{
    var myStatefulObject = new SomeStatefulObject();
    context.Items[typeof(SomeStatefulObject)] = myStatefulObject;
    await output.GetChildContentAsync();
    _cache[context.UniqueId] = new LocalizationKeyStuff(myStatefulObject);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write two Tag helpers that are used to localize strings in razor views. The purpose of the parent tag is to gather all of the keys that are requested by the child tags and get them from the database in one batch and cache them.

Then the child tags will use the cached versions, this way I am hoping to lower the load on the database. I am looking for something like this:

<parent-tag>
   <child-tag key="Hello" />
     some HTML here
   <child-tag key="Hi!" />
</parent-tag>

I want to be able to get a list of  objects in the Parent tag's Invoke method.

I have also tried storing data in TagHelperContext to communicate with other tag helpers, but this will not work either, because I have to call output.GetChildContentAsync() inside the Parent's Invoke method, which defeats the whole purpose of the caching.

Body:
@Encrypt0r you could have an in-memory static cache relation of the TagHelpers context.Items and your localized keys. This would involve using context.Items in your to execute GetChildContentAsync one time. All subsequent times would then be cached by looking up the key values based off of the context.Items (assuming the key values were not dynamic).

Think of it this way:

// Inside your TagHelper
if (_cache.TryGetValue(context.UniqueId, out var localizationKeys))
{
    ... You already have the keys, do whatever
}
else
{
    var myStatefulObject = new SomeStatefulObject();
    context.Items[typeof(SomeStatefulObject)] = myStatefulObject;
    await output.GetChildContentAsync();
    _cache[context.UniqueId] = new LocalizationKeyStuff(myStatefulObject);
}


问:
Windows Universal App Development Template Load error
it's quite annoying now just finished with the setup and when trying to build a "Hello World" Application with Visual Studio 2015 Enterprise

```<code>---------------------------
Microsoft Visual Studio
---------------------------
Error: this template attempted to load component assembly
'Microsoft.VisualStudio.Universal.TemplateWizards, Version=14.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. For more information
on this problem and how to enable this template, please see documentation
on Customizing Project Templates.
---------------------------
OK
---------------------------
</code>```

Now I don't understand what wrong with it.  I tried the comunity edition on Windows 8.1 and able to build the apps. but when trying with Enterprise Edition on Windows 10, nothing excepts Error.

Nor Information page list any tools for development.

```<code>Microsoft Visual Studio Enterprise 2015
Version 14.0.23107.0 D14REL
Microsoft .NET Framework
Version 4.6.00079

Installed Version: Enterprise

Architecture and Modeling Tools   00322-80000-00000-AA627
Microsoft Architecture and Modeling Tools

UML® and Unified Modeling Language™ are trademarks or registered trademarks of the Object Management Group, Inc. in the United States and other countries.

Visual Basic 2015   00322-80000-00000-AA627
Microsoft Visual Basic 2015

Visual C# 2015   00322-80000-00000-AA627
Microsoft Visual C# 2015

Visual C++ 2015   00322-80000-00000-AA627
Microsoft Visual C++ 2015

Application Insights Tools for Visual Studio Package   1.0
Application Insights Tools for Visual Studio

ASP.NET and Web Tools   14.0.20711.0
ASP.NET and Web Tools

ASP.NET Web Frameworks and Tools 2013   5.2.30624.0
For additional information, visit http://www.asp.net/

Common Azure Tools   1.5
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

GenerateUnitTest   1.0
Generates unit test code for methods in classes under test.

GitHub.VisualStudio   1.0
A Visual Studio Extension that brings the GitHub Flow into Visual Studio.

Indent Guides   14
Indent Guides

Adds visual guides at each indentation level.

Microsoft Azure HDInsight HQL Service   2.0.2200.0
Language service for Hive query

Microsoft Azure HDInsight Tools for Visual Studio   2.0.2200.0
An integrated development environment for HDInsight application development.

Microsoft Azure Mobile Services Tools   1.4
Microsoft Azure Mobile Services Tools

Microsoft Code Digger   0.9
Microsoft Code Digger

Microsoft.Pex.VisualStudio   1.0
Pex

NuGet Package Manager   3.0.0
NuGet Package Manager in Visual Studio. For more information about NuGet, visit http://docs.nuget.org/.

PreEmptive Analytics Visualizer   1.2
Microsoft Visual Studio extension to visualize aggregated summaries from the PreEmptive Analytics product.

SQL Server Data Tools   14.0.50616.0
Microsoft SQL Server Data Tools

Web Essentials 2015   0.5.144
Adds many useful features to Visual Studio for web developers.
</code>```

答:
you can find solution in here.

https://github.com/walbourn/directx-vs-templates/issues/7

above site said,

A workaround for this is to edit C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe.config and add to the  section:

```<code><dependentAssembly>
  <assemblyIdentity name="Microsoft.VisualStudio.Universal.TemplateWizards" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
  <bindingRedirect oldVersion="14.0.0.0" newVersion="15.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
  <assemblyIdentity name="Microsoft.VisualStudio.WinRT.TemplateWizards" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
  <bindingRedirect oldVersion="14.0.0.0" newVersion="15.0.0.0"/>
</dependentAssembly>
</code>```

Body:
it's quite annoying now just finished with the setup and when trying to build a "Hello World" Application with Visual Studio 2015 Enterprise

---------------------------
Microsoft Visual Studio
---------------------------
Error: this template attempted to load component assembly
'Microsoft.VisualStudio.Universal.TemplateWizards, Version=14.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. For more information
on this problem and how to enable this template, please see documentation
on Customizing Project Templates.
---------------------------
OK
---------------------------

Now I don't understand what wrong with it.  I tried the comunity edition on Windows 8.1 and able to build the apps. but when trying with Enterprise Edition on Windows 10, nothing excepts Error.

Nor Information page list any tools for development.

Microsoft Visual Studio Enterprise 2015
Version 14.0.23107.0 D14REL
Microsoft .NET Framework
Version 4.6.00079

Installed Version: Enterprise

Architecture and Modeling Tools   00322-80000-00000-AA627
Microsoft Architecture and Modeling Tools

UML® and Unified Modeling Language™ are trademarks or registered trademarks of the Object Management Group, Inc. in the United States and other countries.

Visual Basic 2015   00322-80000-00000-AA627
Microsoft Visual Basic 2015

Visual C# 2015   00322-80000-00000-AA627
Microsoft Visual C# 2015

Visual C++ 2015   00322-80000-00000-AA627
Microsoft Visual C++ 2015

Application Insights Tools for Visual Studio Package   1.0
Application Insights Tools for Visual Studio

ASP.NET and Web Tools   14.0.20711.0
ASP.NET and Web Tools

ASP.NET Web Frameworks and Tools 2013   5.2.30624.0
For additional information, visit http://www.asp.net/

Common Azure Tools   1.5
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

GenerateUnitTest   1.0
Generates unit test code for methods in classes under test.

GitHub.VisualStudio   1.0
A Visual Studio Extension that brings the GitHub Flow into Visual Studio.

Indent Guides   14
Indent Guides

Adds visual guides at each indentation level.

Microsoft Azure HDInsight HQL Service   2.0.2200.0
Language service for Hive query

Microsoft Azure HDInsight Tools for Visual Studio   2.0.2200.0
An integrated development environment for HDInsight application development.

Microsoft Azure Mobile Services Tools   1.4
Microsoft Azure Mobile Services Tools

Microsoft Code Digger   0.9
Microsoft Code Digger

Microsoft.Pex.VisualStudio   1.0
Pex

NuGet Package Manager   3.0.0
NuGet Package Manager in Visual Studio. For more information about NuGet, visit http://docs.nuget.org/.

PreEmptive Analytics Visualizer   1.2
Microsoft Visual Studio extension to visualize aggregated summaries from the PreEmptive Analytics product.

SQL Server Data Tools   14.0.50616.0
Microsoft SQL Server Data Tools

Web Essentials 2015   0.5.144
Adds many useful features to Visual Studio for web developers.

Body:
you can find solution in here.

https://github.com/walbourn/directx-vs-templates/issues/7

above site said,

A workaround for this is to edit C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe.config and add to the  section:

<dependentAssembly>
  <assemblyIdentity name="Microsoft.VisualStudio.Universal.TemplateWizards" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
  <bindingRedirect oldVersion="14.0.0.0" newVersion="15.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
  <assemblyIdentity name="Microsoft.VisualStudio.WinRT.TemplateWizards" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
  <bindingRedirect oldVersion="14.0.0.0" newVersion="15.0.0.0"/>
</dependentAssembly>


问:
reshaping k columns to 2 columns representing sequential pairs of the values of the k variables
I have a data frame like this:

```<code>id y1 y2 y3 y4
--+--+--+--+--
a |12|13|14|
b |12|18|  |
c |13|  |  |
d |13|14|15|16
</code>```

I want to reshape in such a way that I end with two columns. The above example would then become:

```<code>id from to
--+----+---
a |12  |13
a |13  |14
a |14  |
b |12  |18
b |18  |
c |13  |
d |13  |14
d |14  |15
d |15  |16
</code>```

Each id has a 'from' and a 'to' per pair of year values.

Does anybody know of an easy way to do this? I tried using reshape2. I also looked at Combine Multiple Columns Into Tidy Data but I think my case is different.

答:
In base R, stack and shift everything back one row in each group. Using @ycw's example data, dt:

```<code>tmp <- na.omit(cbind(dt[1], stack(dt[-1])[-2]))
names(tmp)[2] <- "from"
tmp$to <- with(tmp, ave(from, id, FUN=function(x) c(tail(x,-1),NA) ))
tmp[order(tmp$id),]

#   id from to
#1   a   12 13
#5   a   13 14
#9   a   14 NA
#2   b   12 18
#6   b   18 NA
#3   c   13 NA
#4   d   13 14
#8   d   14 15
#12  d   15 16
#16  d   16 NA
</code>```

In the world of data.table, the same logic applies. melt, then shift by= id:

```<code>library(data.table)
dt <- as.data.table(dt)

melt(dt, id.vars="id", value.name="from")[
  !is.na(from),-"variable"][, to := shift(from,1,type="lead"), by=id
][order(id)]
</code>```

Body:
I have a data frame like this:

id y1 y2 y3 y4
--+--+--+--+--
a |12|13|14|
b |12|18|  |
c |13|  |  |
d |13|14|15|16

I want to reshape in such a way that I end with two columns. The above example would then become:

id from to
--+----+---
a |12  |13
a |13  |14
a |14  |
b |12  |18
b |18  |
c |13  |
d |13  |14
d |14  |15
d |15  |16

Each id has a 'from' and a 'to' per pair of year values.

Does anybody know of an easy way to do this? I tried using reshape2. I also looked at Combine Multiple Columns Into Tidy Data but I think my case is different.

Body:
In base R, stack and shift everything back one row in each group. Using @ycw's example data, dt:

tmp <- na.omit(cbind(dt[1], stack(dt[-1])[-2]))
names(tmp)[2] <- "from"
tmp$to <- with(tmp, ave(from, id, FUN=function(x) c(tail(x,-1),NA) ))
tmp[order(tmp$id),]

#   id from to
#1   a   12 13
#5   a   13 14
#9   a   14 NA
#2   b   12 18
#6   b   18 NA
#3   c   13 NA
#4   d   13 14
#8   d   14 15
#12  d   15 16
#16  d   16 NA

In the world of data.table, the same logic applies. melt, then shift by= id:

library(data.table)
dt <- as.data.table(dt)

melt(dt, id.vars="id", value.name="from")[
  !is.na(from),-"variable"][, to := shift(from,1,type="lead"), by=id
][order(id)]


问:
Typescript - Calling function repeatedly from within ForEach() leads to undefined
I'm trying to iterate through an object that is made of objects, where one property of each object is used to make a service call.

This works fine when I try to do this just once and I can console log out the data returned from a successful service call, but when I try to use forEach() to repeat this process for every object within the parent object I get the error "Cannot read property 'host' of undefined".

Could someone explain what I am missing?

This is an example of what my code looks like right now:

```<code>getItemParametersCallback(data){
    ...
    // Parent Object made of Objects
    // data is returned by a service call
    this.parentObject = data.json();

    // Iterate through the objects of the parentObject
    const parentObjectItems = Object.keys(this.parentObject);

    parentObjectItems.forEach( key => {
        // I can add an if to limit this to being called once,
        // like if(key === 'apple')... and it works fine
        this.ItemService.getItem(this.getItemCallback.bind(this),
            this.parentObject[key]);
    });
}

// Console log out the data returned
getItemCallback(data){
    console.log(data);
}
</code>```

答:
From your code:

```<code>this.parentObject = data.json();

// Iterate through the objects of the parentObject
const parentObjectItems = Object.keys(this.parentObject);
</code>```

the data.json / .json method returns a promise. So Object.keys(this.parentObject) is wrong.

Solution

Use .then or async/await to unravel the continuation.

More

Promises : https://basarat.gitbooks.io/typescript/docs/promise.html

Async / Await : https://basarat.gitbooks.io/typescript/docs/async-await.html

Body:
I'm trying to iterate through an object that is made of objects, where one property of each object is used to make a service call.

This works fine when I try to do this just once and I can console log out the data returned from a successful service call, but when I try to use forEach() to repeat this process for every object within the parent object I get the error "Cannot read property 'host' of undefined".

Could someone explain what I am missing?

This is an example of what my code looks like right now:

getItemParametersCallback(data){
    ...
    // Parent Object made of Objects
    // data is returned by a service call
    this.parentObject = data.json();

    // Iterate through the objects of the parentObject
    const parentObjectItems = Object.keys(this.parentObject);

    parentObjectItems.forEach( key => {
        // I can add an if to limit this to being called once,
        // like if(key === 'apple')... and it works fine
        this.ItemService.getItem(this.getItemCallback.bind(this),
            this.parentObject[key]);
    });
}

// Console log out the data returned
getItemCallback(data){
    console.log(data);
}

Body:
From your code:

this.parentObject = data.json();

// Iterate through the objects of the parentObject
const parentObjectItems = Object.keys(this.parentObject);

the data.json / .json method returns a promise. So Object.keys(this.parentObject) is wrong.

Solution

Use .then or async/await to unravel the continuation.

More

Promises : https://basarat.gitbooks.io/typescript/docs/promise.html

Async / Await : https://basarat.gitbooks.io/typescript/docs/async-await.html


问:
Stopping table locks for MYISAM tables
I have a MYISAM table on which long-running SELECT statements are conducted. Do these statements cause locks on the tables that are being read? If so, how do you stop the locks from occurring?

According to https://dev.mysql.com/doc/refman/5.7/en/internal-locking.html:

MySQL uses table-level locking for MyISAM, MEMORY, and MERGE tables,
  permitting only one session to update those tables at a time. This
  locking level makes these storage engines more suitable for read-only,
  read-mostly, or single-user applications.

Does this also mean that SELECT statements create locks?

答:
Do these [long-running SELECT] statements cause locks on the tables that are being read?

Yes. A MyISAM table cannot be updated while it is being read from. If there is a long-running read (i.e, SELECT) query on the table, any UPDATE or DELETE queries will have to wait until the read query is complete.

(INSERT queries are sometimes an exception. So long as there are no internal holes in the table structure, a writer may be allowed to insert a row at the end of a table without obtaining a lock. However, if any rows are ever updated or deleted, this may create holes, which will require INSERT queries to obtain a write lock as well.)

For more information on the internals, read up on table-level locks. But the short and the long of matters is, you probably shouldn't use MyISAM if concurrency is a concern.

Title: Stopping table locks for MYISAM tables


问:
How to disable SSL for chef-manage?

TL:DR;

How does one disable SSL for the chef-manage addon of a chef-server?

Purpose

I'm working on a Vagrant setup which builds (among others) a chef server and chef node. The purpose is for an educational workshop (an introductory venture into using Chef server for enterprise applications). For this purpose, SSL on chef-server / chef-manage is an unnecessary complication and I'm looking to keep the curriculum lean and free of pitfalls.

chef-server

I've successfully disabled ssl on my chef-server via nginx['enable_non_ssl'] = true within the /etc/opscode/chef-server.rb file. Attempting curl http://chef.server.url/ returns the expected html content (rather than a redirect).

chef-manage

After adding chef-manage to chef-server (via chef-server-ctl install chef-manage && chef-server-ctl reconfigure && chef-manage-ctl reconfigure), attempting curl http://chef.server.url/ returns a 302 redirect. This stackoverflow answer to a different but related question seems to say that:

the chef-server webui is run via nginx

the chef-manage webui is run via unicorn

unicorn contains config.force_ssl=true unless ENV['NO_SSL'] (Found in /opt/chef-manage/embedded/service/chef-manage/config/environments/production.rb).

Performing export NO_SSL=true on the chef server and reconfiguring will disable ssl for chef-manage.

I've attempted this but a curl http://chef.server.url/ still returns a 302 redirect.

How can I disable ssl for the chef-manage webui?

Any tips, hints, or suggestions will be greatly appreciated!

答: For an intro workshop I wouldn't use Manage at all. It's just one more thing to learn for basically no benefit, and it's not quite deprecated but definitely in a similar orbit (Automate is where any major new development is going).</p>

Title: How to disable SSL for chef-manage?


问:
Cocoa Touch: can I add a non-integer tag to a UI element?
Is there an easy way for me to attach a property to a given UI element without subclassing it.

What I'd like is basically just like .tag but I'd want it to hold an NSString. the .tag only holds an integer.

Thanks

答:
You can use the functionality of associated objects introduced in the IA64 and ARM Objective-C runtimes. This works on on device for iOS, but not on the simulator since the simulator uses the old fragile 32-bit Objective-C run-time.

Here is a small example that allows you to set any kind of object as a context value on all UIView instances. The associated objects are released properly at dealloc, so no extra memory management needed.

```<code>// UIView+CWObjectContext.h
@interface UIView (CWObjectContext)

@property(nonatomic, retain) id objectContext;

@end

// UIView+CWobjectContext.m
#import "UIView+CWobjectContext.h"
#import <objc/runtime.h>
@implementation UIView (CWObjectContext)

static void* const objectContextKey = "objectContext";

-(id)objectContext;
{
   return objc_getAssociatedObject(self,
                                   objectContextKey);
}

-(void)setObjectContext:(id)object;
{
   objc_setAssociatedObject(self,
                            objectContextKey,
                            object,
                            OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
</code>```

Body:
You can use the functionality of associated objects introduced in the IA64 and ARM Objective-C runtimes. This works on on device for iOS, but not on the simulator since the simulator uses the old fragile 32-bit Objective-C run-time.

Here is a small example that allows you to set any kind of object as a context value on all UIView instances. The associated objects are released properly at dealloc, so no extra memory management needed.

// UIView+CWObjectContext.h
@interface UIView (CWObjectContext)

@property(nonatomic, retain) id objectContext;

@end

// UIView+CWobjectContext.m
#import "UIView+CWobjectContext.h"
#import <objc/runtime.h>
@implementation UIView (CWObjectContext)

static void* const objectContextKey = "objectContext";

-(id)objectContext;
{
   return objc_getAssociatedObject(self,
                                   objectContextKey);
}

-(void)setObjectContext:(id)object;
{
   objc_setAssociatedObject(self,
                            objectContextKey,
                            object,
                            OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end


问:
How to get user's roles, Discord, Python
I've been improving and improving my bot.
Now, I've figured out how to make the bot purge messages, but a purge message, shouldn't be allowed to any member, only to people with certain role.

I've done this code:

```<code>if author.roles.has("BotModerator"):
</code>```

I've looked for it, on this website(https://anidiotsguide.gitbooks.io/discord-js-bot-guide/information/understanding_roles.html), but seems that they're coding with Java, how can I do it in Python?

By the way, the error shown in the output is 'list' object has no atribute 'has'

答:
The roles a User has is a list of role objects, you'll need to access the name property of the role. You can use list comprehension.

```<code>if "botmoderator" in [y.name.lower() for y in author.roles]:
</code>```

But of course, this limits that command to only people with the specific role, BotModerators. It can't be used in another server unless they aswell have a role called BotModerator. I recommend you using the id instead. If you don't know how, tag the role then put a backslash in front of the name then send. Should show you the role's id. Then you can use that instead.

```<code>if "role_id" in [y.id for y in author.roles]:
</code>```

Body:
I've been improving and improving my bot.
Now, I've figured out how to make the bot purge messages, but a purge message, shouldn't be allowed to any member, only to people with certain role.

I've done this code:

if author.roles.has("BotModerator"):

I've looked for it, on this website(https://anidiotsguide.gitbooks.io/discord-js-bot-guide/information/understanding_roles.html), but seems that they're coding with Java, how can I do it in Python?

By the way, the error shown in the output is 'list' object has no atribute 'has'

Body:
The roles a User has is a list of role objects, you'll need to access the name property of the role. You can use list comprehension.

if "botmoderator" in [y.name.lower() for y in author.roles]:

But of course, this limits that command to only people with the specific role, BotModerators. It can't be used in another server unless they aswell have a role called BotModerator. I recommend you using the id instead. If you don't know how, tag the role then put a backslash in front of the name then send. Should show you the role's id. Then you can use that instead.

if "role_id" in [y.id for y in author.roles]:


问:
duplicate a collection into itself
How can I copy a mongodb collection into itself with clashes in _id resolved by a new _id?

Copying individual documents using the answer here is not feasible for large collections.

I want to do this to increase the size of the testing sample in a contrived manner, this is just for testing the scalability. So I thought, instead of adding new documents, I could duplicate the collection into itself a few times to achieve the purpose.

答:
If you want to generate plausible data for test purposes, here's a handy recipe using some command line tools:

mongodb-schema to infer a probablistic schema for an existing collection

morelikethis to convert that schema to a template

mgeneratejs to generate new documents according to a schema template

mongoimport to import the new documents into MongoDB

mongoimport is a part of the standard MongoDB command line tools; the first three tools are installable from npm:

```<code>npm install -g morelikethis mongodb-schema mgeneratejs
</code>```

Sample usage to generate 1,000 new documents based on an analysis of the existing documents:

mongodb-schema localhost:27017 mydb.mycollection | morelikethis | mgeneratejs -n 1000 | mongoimport -d mydb -c mycollection

If you don't have any test data yet (or prefer to describe the shape of new documents) you could always skip the schema analysis and start with mgeneratejs and mongoimport.

Title: duplicate a collection into itself

Body:
If you want to generate plausible data for test purposes, here's a handy recipe using some command line tools:

mongodb-schema to infer a probablistic schema for an existing collection

morelikethis to convert that schema to a template

mgeneratejs to generate new documents according to a schema template

mongoimport to import the new documents into MongoDB

mongoimport is a part of the standard MongoDB command line tools; the first three tools are installable from npm:

npm install -g morelikethis mongodb-schema mgeneratejs

Sample usage to generate 1,000 new documents based on an analysis of the existing documents:

mongodb-schema localhost:27017 mydb.mycollection | morelikethis | mgeneratejs -n 1000 | mongoimport -d mydb -c mycollection

If you don't have any test data yet (or prefer to describe the shape of new documents) you could always skip the schema analysis and start with mgeneratejs and mongoimport.


问:
Why does this code say that C::f overrides A::f but not B::f?
In the 3rd code example here the comment says that C::f overrides A::f. Why is this? My intuition says that it should override B::f.</p>

```<code>struct A { virtual void f(); };     // A::f is virtual
struct B : A { void f(); };         // B::f overrides A::f in B
struct C : virtual B { void f(); }; // C::f overrides A::f in C
struct D : virtual B {}; // D does not introduce an overrider, B::f is final in D
struct E : C, D  {       // E does not introduce an overrider, C::f is final in E
    using A::f; // not a function declaration, just makes A::f visible to lookup
};
int main() {
   E e;
   e.f();    // virtual call calls C::f, the final overrider in e
   e.E::f(); // non-virtual call calls A::f, which is visible in E
}
</code>```

答:
Virtual Base classes are relevant only to data members, not methods.

It doesn't matter whether C::f overrides A::f or B::f - it's the same thing.

That comment could be changed to C::f overrides B::f and it would still mean the same thing.

Consider the following hierarchy (no virtual base classes)

```<code>class A { virtual void foo(); }
class B : public A { void foo(); }
class C : public B { void foo(); }
</code>```

Here, B::foo overrides A::foo. C::foo overrides B::foo. So in effect, C::foo overrides A::foo.

Virtual base classes are used to avoid multiple base class instances - but that's relevant only to the data members in the base class not the methods. If a base class had only methods & no data members, there is no need to make it a virtual base class at all.

Body:
In the 3rd code example here the comment says that C::f overrides A::f. Why is this? My intuition says that it should override B::f.

struct A { virtual void f(); };     // A::f is virtual
struct B : A { void f(); };         // B::f overrides A::f in B
struct C : virtual B { void f(); }; // C::f overrides A::f in C
struct D : virtual B {}; // D does not introduce an overrider, B::f is final in D
struct E : C, D  {       // E does not introduce an overrider, C::f is final in E
    using A::f; // not a function declaration, just makes A::f visible to lookup
};
int main() {
   E e;
   e.f();    // virtual call calls C::f, the final overrider in e
   e.E::f(); // non-virtual call calls A::f, which is visible in E
}

Body:
Virtual Base classes are relevant only to data members, not methods.

It doesn't matter whether C::f overrides A::f or B::f - it's the same thing.

That comment could be changed to C::f overrides B::f and it would still mean the same thing.

Consider the following hierarchy (no virtual base classes)

class A { virtual void foo(); }
class B : public A { void foo(); }
class C : public B { void foo(); }

Here, B::foo overrides A::foo. C::foo overrides B::foo. So in effect, C::foo overrides A::foo.

Virtual base classes are used to avoid multiple base class instances - but that's relevant only to the data members in the base class not the methods. If a base class had only methods & no data members, there is no need to make it a virtual base class at all.


问:
Evolutionary Optimization Algorithms
I want to optimize following objective functionmax f = profit(x,y) - expense(x,y) subject to: 0<= x, y <=1 using strength pareto evolutionary algorithm (SPEA2). The objective function is non-linear and is not convex or concave function of decision variables. Can I break objective function into two that is maximize profit(x,y) and minimize expense(x,y) and then optimize them in combination at the end. I do not know if it make some sense, sorry I am completely new to the filed. I shall appreciate any help.

答:
Note: (in general) profit = income - expense; and what you've asked looks very dodgy (e.g. something = profit - expense = income - 2 * expense), so I'm going to assume you meant "income" everywhere you've said "profit".

No, you can't find max. income(x,y) and min. expense(x,y) and combine/optimise them at the end because your can expect a relationship between income and expense (e.g. as expense increases income increases).

Also; don't forget that the best way to approach this kind of problem is to expand and simplify the resulting function.

For a very simple example:

```<code>income = items * bonus + items * 0.9 * $123.45

expense = bonus * $1 + items * $99.00

profit = income - expense
       = (items * bonus + items * 0.9 * $123.45) - (bonus * $1 + items * $99.00)
       = items * bonus - bonus * $1 + items * 0.9 * $123.45 - items * $99.00
       = (items - 1) * bonus + items * (0.9 * 123.45 - 99.00)
       = (items - 1) * bonus + items * 12.105
</code>```

In other words; if you could find max. income(x,y) and min. expense(x,y) and combine/optimise them at the end, you still wouldn't want to because it's less efficient/slower, and better/faster to just find max. profit(x,y).

Title: Evolutionary Optimization Algorithms

Body:
Note: (in general) profit = income - expense; and what you've asked looks very dodgy (e.g. something = profit - expense = income - 2 * expense), so I'm going to assume you meant "income" everywhere you've said "profit".

No, you can't find max. income(x,y) and min. expense(x,y) and combine/optimise them at the end because your can expect a relationship between income and expense (e.g. as expense increases income increases).

Also; don't forget that the best way to approach this kind of problem is to expand and simplify the resulting function.

For a very simple example:

income = items * bonus + items * 0.9 * $123.45

expense = bonus * $1 + items * $99.00

profit = income - expense
       = (items * bonus + items * 0.9 * $123.45) - (bonus * $1 + items * $99.00)
       = items * bonus - bonus * $1 + items * 0.9 * $123.45 - items * $99.00
       = (items - 1) * bonus + items * (0.9 * 123.45 - 99.00)
       = (items - 1) * bonus + items * 12.105

In other words; if you could find max. income(x,y) and min. expense(x,y) and combine/optimise them at the end, you still wouldn't want to because it's less efficient/slower, and better/faster to just find max. profit(x,y).


问:
Angular 2 dependencies
Please consider this dependencies in package.json:

```<code>"dependencies": {
                  "@angular/common": "2.2.1",
                  "@angular/compiler": "2.2.1",
                  "@angular/core": "2.2.1",
                  "@angular/forms": "2.2.1",
                  "@angular/http": "2.2.1",
                  "@angular/platform-browser": "2.2.1",
                  "@angular/platform-browser-dynamic": "2.2.1",
                  "@angular/router": "3.2.1",
                  "@angular/upgrade": "2.2.1"
                }
</code>```

I want to use the bundle version of Angulajs and when I run this command:

npm install angular

It installs angular.min.js I want to know what is the difference between Those? Is there any way to bundle dependencies using npm and create a single file?

Another question is I know that Angular 4 has been released and when I run this command:

npm install angular

It installs angular.min.js with version v1.6.4 so what is this file? And why it outdated?

答:
I highly recommend you look into: https://github.com/angular/angular-cli

This is built by the angular team to help people get moving quickly in angular 4.  Many other frameworks do the same thing.  For example react has the same idea with this: https://facebook.github.io/react/blog/2016/07/22/create-apps-with-no-configuration.html

This isn't answering your questions directly but you can avoid the complexity involved in setting up angular 4.  In fact that's what the purpose of the angular-cli is, to help people not get stuck spending hours upon hours figuring out what dependencies to install.

Plus, not spend hours upon hours setting up webpack to build an angular project that does a production build.  With angular-cli it's just running the following command:

```<code>ng build --prod
</code>```

Title: Angular 2 dependencies

Body:
Please consider this dependencies in package.json:

"dependencies": {
                  "@angular/common": "2.2.1",
                  "@angular/compiler": "2.2.1",
                  "@angular/core": "2.2.1",
                  "@angular/forms": "2.2.1",
                  "@angular/http": "2.2.1",
                  "@angular/platform-browser": "2.2.1",
                  "@angular/platform-browser-dynamic": "2.2.1",
                  "@angular/router": "3.2.1",
                  "@angular/upgrade": "2.2.1"
                }

I want to use the bundle version of Angulajs and when I run this command:

npm install angular

It installs angular.min.js I want to know what is the difference between Those? Is there any way to bundle dependencies using npm and create a single file?

Another question is I know that Angular 4 has been released and when I run this command:

npm install angular

It installs angular.min.js with version v1.6.4 so what is this file? And why it outdated?

Body:
I highly recommend you look into: https://github.com/angular/angular-cli

This is built by the angular team to help people get moving quickly in angular 4.  Many other frameworks do the same thing.  For example react has the same idea with this: https://facebook.github.io/react/blog/2016/07/22/create-apps-with-no-configuration.html

This isn't answering your questions directly but you can avoid the complexity involved in setting up angular 4.  In fact that's what the purpose of the angular-cli is, to help people not get stuck spending hours upon hours figuring out what dependencies to install.

Plus, not spend hours upon hours setting up webpack to build an angular project that does a production build.  With angular-cli it's just running the following command:

ng build --prod


问:
Find remaining memory available to a process in 32 bit Linux using C++
My C++ program caches lots of objects, and in beginning of each major API call, I want to ensure that there is at least 500 MB available for the API call. I may either be running out of RAM+swap space (consider system with 1 GB RAM + 1 GB SWAP file), or I may be running out of Virtual Address in my process.(I may already be using 3.7 GB out of total 4GB address space). It's not easy for me to approximate how much data I have cached, but I can purge some of it if it is becoming an issue, and do so iteratively till I have 500 MB available in system or address space (whichever is becoming bottleneck). So my requirements are to find in C++ on 32 bit Linux:

A) Find how much RAM + SWAP space is free.

B) How much user space address space is available to my process.

C) How much Virtual Memory the process is already using. Consider it similar to 'Commit Size' or 'Working Set Size' of a process on Windows.

Any answers would be greatly appreciated.

答: Take a look at the source for the vmstat : here. Then search for domem() function, which gather all information about the memory (occupied and free).</p>


问:
Repeater - textbox content to database C#
I'm trying to insert content to my local database from a textbox inside a repeater element, in a post - comment way. So far I've tried looping on all the generated rows to find the specific textbox but I have had no luck, either the insert goes empty, or I get 1 insert per preexisting row, or I get the same value inserted over and over again through different posts.

I finally tried to pass the post id to the itemfinder and it's kind of working, but the "comm_contenido" inserts from the textbox are still going empty to the database.

My question is what it the correct and more direct way to handle these kind of inserts from within a Repeater?.

C#:

```<code>protected void Button1_Command(object sender, CommandEventArgs e)
{

    string postid = e.CommandArgument.ToString();
    string emailcc = Session["EMAIL"].ToString();
    string user_id = Session["ID"].ToString();
    string usrnom = Session["NOMBRE"].ToString();
    string usrfoto = Session["FOTO_URL"].ToString();
    //string COMM_CONTENIDO = lblcomm.Text.ToString();

    var COMM_fecha = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    TextBox txt2;

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBD"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {

                int m = Int32.Parse(postid);
                txt2 = (TextBox)Repeater_UsrPosts.Items[m].FindControl("txtcomentar");
                string txt1 = txt2.Text;

                cmd.CommandType = CommandType.Text;
                cmd.CommandText = (@"INSERT INTO MIEMBROS_Comments (COMM_USER_ID, COMM_CONTENIDO, COMM_FECHA, COMM_USER_NOMBRE, COMM_USER_FOTO, COMM_POST_ID) VALUES ('"
                + user_id + "','" + txt1 + "','" + COMM_fecha + "','" + usrnom + "','" + usrfoto + "','" + postid + "');");
                cmd.Connection = conn;
                conn.Open();
                int rowsAffected = cmd.ExecuteNonQuery();
            }
        }

        //txtpublica.Text = "";
        traerposts();

}
</code>```

ASP:

```<code><asp:Repeater ID="Repeater_UsrPosts" runat="server" >
    <ItemTemplate>

        <!-- Post -->
        <div class="post clearfix">
            <div class="user-block">

                <img alt="" src="<%#Eval("post_user_foto")%>" class="img-circle img-bordered-sm" />

                <span class="username">
                    <a href="#"><%#Eval("post_user_nombre") %></a>
                    <a href="#" class="pull-right btn-box-tool"><i class="fa fa-times"></i></a>
                </span>
                <span class="description"><%#Eval("post_fecha") %></span>
            </div>
            <!-- /.user-block -->

            <p>

                <%#Eval("post_contenido") %>
            </p>

            <ul class="list-inline">
                <li><a href="#" class="link-black text-sm"><i class="fa fa-share margin-r-5"></i>Share</a></li>
                <li><a href="#" class="link-black text-sm"><i class="fa fa-thumbs-o-up margin-r-5"></i>Like</a>
                </li>
                <li class="pull-right">
                    <asp:LinkButton ID="bttnabrircomentarios" runat="server" class="link-black text-sm">
                        <i class="fa fa-comments-o margin-r-5"></i>Comments</asp:LinkButton>
                </li>
            </ul>

            <asp:TextBox ID="txtcomentar" runat="server" class="form-control input-sm" placeholder="Escribe un comentario" EnableViewState="False"></asp:TextBox>

            <%# Eval("post_id") %> -

            <asp:Button ID="Button1" runat="server" Text="Button"
                OnCommand="Button1_Command" CommandName="myCommand"
                CommandArgument='<%# Eval("post_ID") %>' />
            <br />
        </div>
        <!-- /.post -->
    </ItemTemplate>
</asp:Repeater>
</code>```

答:
You can reach the TextBox Control by assigning OnTextChanged to it, and you can also assign its AutoPostBack to true if you wanted to reach the data immediately.

but you should use if(!IsPostBack) before you bind your data to your repeater, so it doesn't reset your Controls before you could reach the data.

OnTextChanged needs two parameter, one of them is the sender object which is calling it, That's your TextBox, something like..

ASP

```<code><asp:Repeater ID="RepeaterExample" runat="server"><ItemTemplate>
    <asp:TextBox runat="server" ID="TextBoxExample" AutoPostBack="True" OnTextChanged="TextBoxExample_OnTextChanged"/>
</ItemTemplate></asp:Repeater>
</code>```

Behind Code

```<code>protected void TextBoxExample_OnTextChanged(object sender, EventArgs e)
{
    TextBox txt = (TextBox) sender;
    //Response.Write(txt.Text);
    //or whatever you want to do with it.
}
</code>```

and if you wanted to use it with Button_OnClick, you should use like a global string you can call later, you can do something like this..

ASP

```<code><asp:Button runat="server" ID="ButtonExample" OnClick="ButtonExample_OnClick"/>
</code>```

Behind Code

```<code>private string text = "";

protected void TextBoxTest_OnTextChanged(object sender, EventArgs e)
{
    TextBox txt = (TextBox)sender;
    text = txt.Text;
}

protected void ButtonExample_OnClick(object sender, EventArgs e)
{
    //Response.Write(text);
}
</code>```

but the last method will take the value of the last TextBox whose text has changed, unless you add it together like..

```<code>text += txt.Text;
</code>```

Hope, I could help..

Body:
I'm trying to insert content to my local database from a textbox inside a repeater element, in a post - comment way. So far I've tried looping on all the generated rows to find the specific textbox but I have had no luck, either the insert goes empty, or I get 1 insert per preexisting row, or I get the same value inserted over and over again through different posts.

I finally tried to pass the post id to the itemfinder and it's kind of working, but the "comm_contenido" inserts from the textbox are still going empty to the database.

My question is what it the correct and more direct way to handle these kind of inserts from within a Repeater?.

C#:

protected void Button1_Command(object sender, CommandEventArgs e)
{

    string postid = e.CommandArgument.ToString();
    string emailcc = Session["EMAIL"].ToString();
    string user_id = Session["ID"].ToString();
    string usrnom = Session["NOMBRE"].ToString();
    string usrfoto = Session["FOTO_URL"].ToString();
    //string COMM_CONTENIDO = lblcomm.Text.ToString();

    var COMM_fecha = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    TextBox txt2;

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBD"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {

                int m = Int32.Parse(postid);
                txt2 = (TextBox)Repeater_UsrPosts.Items[m].FindControl("txtcomentar");
                string txt1 = txt2.Text;

                cmd.CommandType = CommandType.Text;
                cmd.CommandText = (@"INSERT INTO MIEMBROS_Comments (COMM_USER_ID, COMM_CONTENIDO, COMM_FECHA, COMM_USER_NOMBRE, COMM_USER_FOTO, COMM_POST_ID) VALUES ('"
                + user_id + "','" + txt1 + "','" + COMM_fecha + "','" + usrnom + "','" + usrfoto + "','" + postid + "');");
                cmd.Connection = conn;
                conn.Open();
                int rowsAffected = cmd.ExecuteNonQuery();
            }
        }

        //txtpublica.Text = "";
        traerposts();

}

ASP:

<asp:Repeater ID="Repeater_UsrPosts" runat="server" >
    <ItemTemplate>

                <img alt="" src="<%#Eval("post_user_foto")%>" class="img-circle img-bordered-sm" />

                    <%#Eval("post_user_nombre") %>

                <%#Eval("post_fecha") %>

                <%#Eval("post_contenido") %>

Share

Like

                    <asp:LinkButton ID="bttnabrircomentarios" runat="server" class="link-black text-sm">
                        Comments</asp:LinkButton>

            <asp:TextBox ID="txtcomentar" runat="server" class="form-control input-sm" placeholder="Escribe un comentario" EnableViewState="False"></asp:TextBox>

            <%# Eval("post_id") %> -

            <asp:Button ID="Button1" runat="server" Text="Button"
                OnCommand="Button1_Command" CommandName="myCommand"
                CommandArgument='<%# Eval("post_ID") %>' />

    </ItemTemplate>
</asp:Repeater>

Body:
You can reach the TextBox Control by assigning OnTextChanged to it, and you can also assign its AutoPostBack to true if you wanted to reach the data immediately.

but you should use if(!IsPostBack) before you bind your data to your repeater, so it doesn't reset your Controls before you could reach the data.

OnTextChanged needs two parameter, one of them is the sender object which is calling it, That's your TextBox, something like..

ASP

<asp:Repeater ID="RepeaterExample" runat="server"><ItemTemplate>
    <asp:TextBox runat="server" ID="TextBoxExample" AutoPostBack="True" OnTextChanged="TextBoxExample_OnTextChanged"/>
</ItemTemplate></asp:Repeater>

Behind Code

protected void TextBoxExample_OnTextChanged(object sender, EventArgs e)
{
    TextBox txt = (TextBox) sender;
    //Response.Write(txt.Text);
    //or whatever you want to do with it.
}

and if you wanted to use it with Button_OnClick, you should use like a global string you can call later, you can do something like this..

ASP

<asp:Button runat="server" ID="ButtonExample" OnClick="ButtonExample_OnClick"/>

Behind Code

private string text = "";

protected void TextBoxTest_OnTextChanged(object sender, EventArgs e)
{
    TextBox txt = (TextBox)sender;
    text = txt.Text;
}

protected void ButtonExample_OnClick(object sender, EventArgs e)
{
    //Response.Write(text);
}

but the last method will take the value of the last TextBox whose text has changed, unless you add it together like..

text += txt.Text;

Hope, I could help..


问:
The ViewBag content isn't being visualized
I'm brand new to ASP.NET MVC web development.
And I'm trying to build a website that basically has access to a database which can be filled by user.

Alright, all good, that part works fine. What I'm struggling with, is that whenever the user insert data into the database, I wanna show a message saying that his insertion has been done succesfully, or something like that. I wanna show that down in the form panel.

This is the code that I got so far:

This is the method being called when the user clicks the submit button:

```<code>[HttpPost]
public ActionResult Create(PersonModels person)
{
    try
    {
        // TODO: Add insert logic here
        //Adding to database and holding the response in the viewbag.
        string strInsertion = ConnectionModels.insertPerson(person);
        ViewBag.InsertionResult = strInsertion;

        return RedirectToAction("Index");
    }
    catch
    {
        return View("Index");
    }
}
</code>```

And this is my Index action:

```<code>public ActionResult Index()
{
    return View();
}
</code>```

And finally, this is what I'm trying to d in my index.cshtml:

```<code><div>
     <label>
         @ViewBag.InsertionResult
     </label>
</div>
</code>```

I'm not gonna post it completely 'cause it'd be quite extensive. But that's beneath the div of the form panel.

I hope you can give me a hand.

Thanks in advance! :)

答:
ViewBag and ViewData objects will return null values after a redirect. Their contents only survive for the duration of the current request.

There's another property, TempData, whose contents will endure the current and subsequent request, but only the subsequent request. However, this means that you can use it to pass data when you call RedirectToAction.

```<code>[HttpPost]
public ActionResult Create(PersonModels person)
{
    try
    {
        // TODO: Add insert logic here
        //Adding to database and holding the response in the viewbag.
        string strInsertion = ConnectionModels.insertPerson(person);
        TempData[InsertionResult] = strInsertion;

        return RedirectToAction("Index");
    }
    catch
    {
        return View("Index");
    }
}

[HttpGet]
public ActionResult Index()
{
    string strInsertion = TempData[InsertionResult];
    return View("Index", new { InsertionResult = strInsertion });
}

<label>
    @Model.InsertionResult
</label>
</code>```

A good explanation is given here: http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications/

An alternative approach would be for your Index view to take an optional view model containing the result of the HttpPost that created the Person in your database. You could use that model to populate the contents of your label. Strongly typed models FTW!

Body:
I'm brand new to ASP.NET MVC web development.
And I'm trying to build a website that basically has access to a database which can be filled by user.

Alright, all good, that part works fine. What I'm struggling with, is that whenever the user insert data into the database, I wanna show a message saying that his insertion has been done succesfully, or something like that. I wanna show that down in the form panel.

This is the code that I got so far:

This is the method being called when the user clicks the submit button:

[HttpPost]
public ActionResult Create(PersonModels person)
{
    try
    {
        // TODO: Add insert logic here
        //Adding to database and holding the response in the viewbag.
        string strInsertion = ConnectionModels.insertPerson(person);
        ViewBag.InsertionResult = strInsertion;

        return RedirectToAction("Index");
    }
    catch
    {
        return View("Index");
    }
}

And this is my Index action:

public ActionResult Index()
{
    return View();
}

And finally, this is what I'm trying to d in my index.cshtml:

         @ViewBag.InsertionResult

I'm not gonna post it completely 'cause it'd be quite extensive. But that's beneath the div of the form panel.

I hope you can give me a hand.

Thanks in advance! :)

Body:
ViewBag and ViewData objects will return null values after a redirect. Their contents only survive for the duration of the current request.

There's another property, TempData, whose contents will endure the current and subsequent request, but only the subsequent request. However, this means that you can use it to pass data when you call RedirectToAction.

[HttpPost]
public ActionResult Create(PersonModels person)
{
    try
    {
        // TODO: Add insert logic here
        //Adding to database and holding the response in the viewbag.
        string strInsertion = ConnectionModels.insertPerson(person);
        TempData[InsertionResult] = strInsertion;

        return RedirectToAction("Index");
    }
    catch
    {
        return View("Index");
    }
}

[HttpGet]
public ActionResult Index()
{
    string strInsertion = TempData[InsertionResult];
    return View("Index", new { InsertionResult = strInsertion });
}

<label>
    @Model.InsertionResult
</label>

A good explanation is given here: http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications/

An alternative approach would be for your Index view to take an optional view model containing the result of the HttpPost that created the Person in your database. You could use that model to populate the contents of your label. Strongly typed models FTW!


问:
vb.net How to Fire Click Event Dynamically
I'm trying to fire a click-event by clicking on another control
using this following code:

```<code>Private Sub GroupControl4_Click(sender As Object, e As EventArgs) Handles GroupControl4.Click
    For Each c As Control In XtraTabControl1.Controls
        For Each cs As Control In DirectCast(c, DevExpress.XtraTab.XtraTabPage).Controls
            If cs.Tag = sender.Tag Then
                cs.PerformClick()
            End If
        Next
    Next
End Sub
</code>```

And I got this error:

"'PerformClick' is not a member of 'System.Windows.Forms.Control'"

I also tried to DirectCast, which I didn't helper either.

答:
this is the solution

I'm creating a new Function

```<code>    Private Sub FireEvent(ByVal ctrl As Control, ByVal EventName As String)
    Dim flags As BindingFlags = BindingFlags.[Public] Or BindingFlags.NonPublic Or BindingFlags.[Static] Or BindingFlags.Instance Or BindingFlags.DeclaredOnly
    Dim EventP As PropertyInfo = Nothing
    Dim CtrlS As Object = ctrl.[GetType]
    Dim FoundEvents As Boolean = False
    While FoundEvents = False
        EventP = CtrlS.GetProperty("Events", flags)
        If EventP Is Nothing Then
            CtrlS = CtrlS.BaseType
        Else
            FoundEvents = True
        End If
    End While

    Dim EventF As FieldInfo = Nothing
    CtrlS = ctrl.[GetType]
    Dim FoundField As Boolean = False
    While FoundField = False
        EventF = CtrlS.GetField(EventName, flags)
        If EventF Is Nothing Then
            CtrlS = CtrlS.BaseType
        Else
            FoundField = True
        End If
    End While

    If Not EventP Is Nothing Then
        Dim eventH = DirectCast(EventP.GetValue(ctrl, Nothing), EventHandlerList)
        Dim eventFIeld As Object = EventF.GetValue(Nothing)
        Dim handlers As [Delegate] = eventH(eventFIeld)
        For Each handler As [Delegate] In handlers.GetInvocationList()
            handler.Method.Invoke(handler.Target, New Object() {ctrl, New EventArgs})
        Next
    End If

End Sub
</code>```

and this code work excellent

```<code>Private Sub GroupControl4_Click(sender As Object, e As EventArgs) Handles GroupControl4.Click, GroupControl5.Click
    For Each c As Control In XtraTabControl1.Controls
        For Each cs As Control In DirectCast(c, DevExpress.XtraTab.XtraTabPage).Controls
            If cs.Tag = sender.Tag Then
                FireEvent(cs, "EventClick")
            End If
        Next
    Next
End Sub
</code>```

thanks

Body:
I'm trying to fire a click-event by clicking on another control
using this following code:

Private Sub GroupControl4_Click(sender As Object, e As EventArgs) Handles GroupControl4.Click
    For Each c As Control In XtraTabControl1.Controls
        For Each cs As Control In DirectCast(c, DevExpress.XtraTab.XtraTabPage).Controls
            If cs.Tag = sender.Tag Then
                cs.PerformClick()
            End If
        Next
    Next
End Sub

And I got this error:

"'PerformClick' is not a member of 'System.Windows.Forms.Control'"

I also tried to DirectCast, which I didn't helper either.

Body:
this is the solution

I'm creating a new Function

    Private Sub FireEvent(ByVal ctrl As Control, ByVal EventName As String)
    Dim flags As BindingFlags = BindingFlags.[Public] Or BindingFlags.NonPublic Or BindingFlags.[Static] Or BindingFlags.Instance Or BindingFlags.DeclaredOnly
    Dim EventP As PropertyInfo = Nothing
    Dim CtrlS As Object = ctrl.[GetType]
    Dim FoundEvents As Boolean = False
    While FoundEvents = False
        EventP = CtrlS.GetProperty("Events", flags)
        If EventP Is Nothing Then
            CtrlS = CtrlS.BaseType
        Else
            FoundEvents = True
        End If
    End While

    Dim EventF As FieldInfo = Nothing
    CtrlS = ctrl.[GetType]
    Dim FoundField As Boolean = False
    While FoundField = False
        EventF = CtrlS.GetField(EventName, flags)
        If EventF Is Nothing Then
            CtrlS = CtrlS.BaseType
        Else
            FoundField = True
        End If
    End While

    If Not EventP Is Nothing Then
        Dim eventH = DirectCast(EventP.GetValue(ctrl, Nothing), EventHandlerList)
        Dim eventFIeld As Object = EventF.GetValue(Nothing)
        Dim handlers As [Delegate] = eventH(eventFIeld)
        For Each handler As [Delegate] In handlers.GetInvocationList()
            handler.Method.Invoke(handler.Target, New Object() {ctrl, New EventArgs})
        Next
    End If

End Sub

and this code work excellent

Private Sub GroupControl4_Click(sender As Object, e As EventArgs) Handles GroupControl4.Click, GroupControl5.Click
    For Each c As Control In XtraTabControl1.Controls
        For Each cs As Control In DirectCast(c, DevExpress.XtraTab.XtraTabPage).Controls
            If cs.Tag = sender.Tag Then
                FireEvent(cs, "EventClick")
            End If
        Next
    Next
End Sub

thanks


问:
Android sms bot
I am trying to make a simple android app. When I send sms hi to my mobile from some number, it should reply hi automatically to me in response. And when I send "How are you", it should reply me How are you.</p>

答:
Just a quick Google search on "How to read and send text messages Android" would really help in this situation as there are plenty of resources available.

Assuming you have the basics of the app already built, look at http://codetheory.in/android-sms/ for more information on how to register to deal with messages as well as receive and send them. There are some direct code examples that you could copy&paste into your code and extend. For instance instead of logging the message, you could simply call a function that you create, to send a message back to that number. Hope this helps!

Title: Android sms bot


问:
How can i go to my current location in Mapboxgl?
I want to navigate to users current location in the map. I am working with Mapboxgl, Ionic3 and Angular4.

I used the  following code map.addControl(new mapboxgl.GeolocateControl());

This works fine in development (ie web browser) but my target is a mobile application. My app will be used in both android and ios mobiles.

I guess it supports click event in web browser not in mobiles. It may work if I write touch event for this.

I prefer to write the custom code for this navigation. I mean place some icon and write the same functionality instead of mapboxgl.GeolocateControl()

答:
As MapBox-gl is touch-enabled, I would be surprised if the the GeolocateControl would not support touch events.

The GeolocateControl should work in Ionic on both Android and iOS. Make sure you tell your app to request permissions for geolocation


问:
How to have a bootstrap class button link to an external site
I m having problem with a button that i created and trying to link to an external website. my code is

```<code><div id="home-btn" class="animated zoomIn">
   <a class="btn btn-lg btn-general btn-white smooth-scroll"
   href="http://www.yumpu.com/fr/embed/view/OPR2Gbw5Ml83hkp4" target="_blank"
   role="button"  title="Magazine Carrefour Floride en ligne">Clicquez ici pour
   lire le Magazine en Ligne</a>
   </div>
</code>```

I tried to place the href else where but same thing will not work.
Thanks!

答:
I cleaned the code, and added btn-default.
If you want to change color just choose from these:

```<code>.btn
.btn-default
.btn-primary
.btn-success
.btn-info
.btn-warning
.btn-danger
.btn-link
</code>```

you code:

```<code><div id="home-btn" class="animated zoomIn">
  <a class="btn  btn-default btn-lg btn-general btn-white smooth-scroll"
    href="http://www.yumpu.com/fr/embed/view/OPR2Gbw5Ml83hkp4" target="_blank">
    Clicquez ici pour ire le Magazine en Ligne
  </a>
</div>
</code>```

Body:
I m having problem with a button that i created and trying to link to an external website. my code is

   Clicquez ici pour
   lire le Magazine en Ligne

I tried to place the href else where but same thing will not work.
Thanks!

Body:
I cleaned the code, and added btn-default.
If you want to change color just choose from these:

.btn
.btn-default
.btn-primary
.btn-success
.btn-info
.btn-warning
.btn-danger
.btn-link

you code:

<div id="home-btn" class="animated zoomIn">
  <a class="btn  btn-default btn-lg btn-general btn-white smooth-scroll"
    href="http://www.yumpu.com/fr/embed/view/OPR2Gbw5Ml83hkp4" target="_blank">
    Clicquez ici pour ire le Magazine en Ligne
  </a>
</div>


问:
JSSOR AUTO PLAY VIDEO
I have recently installed Jssor slider on my company website ena electronics and im trying to add an autoplay video onto the site.

Using the below code I can get it to play in a webpage but when put into the slider in a div it doesn't work... Am I missing something?

thanks

```<code><video width="320" height="240" controls autoplay>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support the video tag.
</video>
</code>```

答:
For now, jssor slider does not control video. You'd write manual code to play the video when the slider parks at the specific slide that your video stays in.</p>

```<code><!-- Jssor Slider Begin -->
<script type="text/javascript" src="../js/jssor.slider.min.js"></script>
<script>
    jssor_slider1_init = function () {
        var options = {
            $AutoPlay: 1
        };

        var jssor_slider1 = new $JssorSlider$('slider1_container', options);

        function SliderParkEventHandler(slideIndex, fromIndex)
        {
            if(slideIndex == 1)
            {
                //do something to play video when the slider parks at the second slide
            }
        }

        jssor_slider1.$On($JssorSlider$.$EVT_PARK,SliderParkEventHandler);
    };
</script>
<div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 600px;
    height: 300px;">
    <!-- Slides Container -->
    <div u="slides" style="position: absolute; left: 0px; top: 0px; width: 600px; height: 300px; overflow: hidden;">
        <div></div>
        <div>
            <!-- assuming that you placed video in the second slide -->
            <video id="myvideo" width="320" height="240" controls autoplay>
                <source src="movie.mp4" type="video/mp4">
                <source src="movie.ogg" type="video/ogg">
                Your browser does not support the video tag.
            </video>
        </div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>
    <!-- Trigger -->
    <script>
        jssor_slider1_init();
    </script>
</div>
<!-- Jssor Slider End -->
</code>```

Title: JSSOR AUTO PLAY VIDEO

Body:
I have recently installed Jssor slider on my company website ena electronics and im trying to add an autoplay video onto the site.

Using the below code I can get it to play in a webpage but when put into the slider in a div it doesn't work... Am I missing something?

thanks

<video width="320" height="240" controls autoplay>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support the video tag.
</video>

Body:
For now, jssor slider does not control video. You'd write manual code to play the video when the slider parks at the specific slide that your video stays in.

<!-- Jssor Slider Begin -->
<script type="text/javascript" src="../js/jssor.slider.min.js"></script>
<script>
    jssor_slider1_init = function () {
        var options = {
            $AutoPlay: 1
        };

        var jssor_slider1 = new $JssorSlider$('slider1_container', options);

        function SliderParkEventHandler(slideIndex, fromIndex)
        {
            if(slideIndex == 1)
            {
                //do something to play video when the slider parks at the second slide
            }
        }

        jssor_slider1.$On($JssorSlider$.$EVT_PARK,SliderParkEventHandler);
    };
</script>
<div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 600px;
    height: 300px;">
    <!-- Slides Container -->
    <div u="slides" style="position: absolute; left: 0px; top: 0px; width: 600px; height: 300px; overflow: hidden;">
        <div></div>
        <div>
            <!-- assuming that you placed video in the second slide -->
            <video id="myvideo" width="320" height="240" controls autoplay>
                <source src="movie.mp4" type="video/mp4">
                <source src="movie.ogg" type="video/ogg">
                Your browser does not support the video tag.
            </video>
        </div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>
    <!-- Trigger -->
    <script>
        jssor_slider1_init();
    </script>
</div>
<!-- Jssor Slider End -->


问:
Appium: getting device time (python, real, device ios)
Can somebody help me.I need to get current device time in runtime (there is some functionality which depends on device time).

I am using appium 1.6.3, iOS 10.2 (real device), python 2.7.10
I have tried following:

self.driver.device_time
=> 'Invalid Date'

from appium.webdriver.webdriver import WebDriver
a = WebDriver.device_time
=> a = <property object at 0x10b69f158>
             fdel ={NoneType} None
             fset ={NoneType} None

答:
Remember to import webdriver:

```<code>from appium import webdriver
</code>```

Then you have to create your webdriver object

```<code>self.driver = webdriver.Remote(
    command_executor='http://0.0.0.0:4723/wd/hub',
    desired_capabilities={
        'app': 'http://appium.s3.amazonaws.com/TestApp7.1.app.zip',
        'platformName': 'iOS',
        'platformVersion': '10.3',
        'deviceName': 'iPhone Simulator'
    })
</code>```

Once you have your webdriver object instantiated it is as simple as:

```<code>self.driver.device_time
</code>```

You do need to have libimobiledevice installed because that comes with a binary called idevicedate which is used for this call.

Body:
Remember to import webdriver:

from appium import webdriver

Then you have to create your webdriver object

self.driver = webdriver.Remote(
    command_executor='http://0.0.0.0:4723/wd/hub',
    desired_capabilities={
        'app': 'http://appium.s3.amazonaws.com/TestApp7.1.app.zip',
        'platformName': 'iOS',
        'platformVersion': '10.3',
        'deviceName': 'iPhone Simulator'
    })

Once you have your webdriver object instantiated it is as simple as:

self.driver.device_time

You do need to have libimobiledevice installed because that comes with a binary called idevicedate which is used for this call.


问:
Create an array that sums to a specific number?
I am using python.  I am trying to create an array that sums to a certain number, but I want the array to be of a length of my choosing.  Any idea on how to do this?
For example, I want a array that sums to 1.
So [.25,.25,.25,.25], but I want the numbers that are inside the array to be random, and I want my array to have a length of 98.
Can someone please help?</p>

答:
Here's a simple implementation that works by building an array of 98 random numbers, finding their sum, then dividing each of the numbers by the sum so that entire array is normalised to 1.

```<code>import random

# generate a random array of 98 numbers
numbers = [random.random() for _ in range(98)]
print(numbers)
# [0.2378205280188267, 0.08942239291741982, ...]
print(sum(numbers))
# 48.8051742287

# normalise the array to sum to 1
normalised = [r / sum(numbers) for r in numbers]
print(normalised)
# [0.004872854810521523, 0.0018322318141581963, ...]
print(sum(normalised))
# 1.0
</code>```

But you should probably consider using NumPy if you are doing a large number of calculations.

Edit: the equivalent code as above but easier to read and without list comprehension:

```<code># build a list/array of random numbers
numbers = []
for _ in range(98):
    numbers.append(random.random())

# get the sum of the array
print(sum(numbers))
# 48.8051742287

# normalise the original list using the sum
normalised = []
for n in numbers:
    normalised.append(n / sum(numbers))
print(sum(normalised))
# 1.0
</code>```

Body:
Here's a simple implementation that works by building an array of 98 random numbers, finding their sum, then dividing each of the numbers by the sum so that entire array is normalised to 1.

import random

# generate a random array of 98 numbers
numbers = [random.random() for _ in range(98)]
print(numbers)
# [0.2378205280188267, 0.08942239291741982, ...]
print(sum(numbers))
# 48.8051742287

# normalise the array to sum to 1
normalised = [r / sum(numbers) for r in numbers]
print(normalised)
# [0.004872854810521523, 0.0018322318141581963, ...]
print(sum(normalised))
# 1.0

But you should probably consider using NumPy if you are doing a large number of calculations.

Edit: the equivalent code as above but easier to read and without list comprehension:

# build a list/array of random numbers
numbers = []
for _ in range(98):
    numbers.append(random.random())

# get the sum of the array
print(sum(numbers))
# 48.8051742287

# normalise the original list using the sum
normalised = []
for n in numbers:
    normalised.append(n / sum(numbers))
print(sum(normalised))
# 1.0


问:
Get maximum from absolute values returning signed value
Supposing I have a class

```<code>Public Class Foo
    Property fooProp1 as Single
    Property fooProp2 as Single
    Property fooProp3 as Single
End Class
</code>```

to find the absolut maximum of a property (which contains positive or negative values) in a Collection(Of Foo) I can do:

```<code>Collection.Max(Function(x As foo) Math.Abs(x.fooProp1))
</code>```

and it returns the greater absolute value WITHOUT sign.

The question is how can I do to get the number WITH sign?

Thanks in advance.
RG

答:
Math.Abs will always return an unsigned value (the actual meaning of Absolute).

The get the value of a property you need only to READ it.

To get a MAX or MIN, you MUST compare values, like this:

```<code>        dim x as integer = foo.property
        dim y as integer = last_foo_property (or anything else)

        Minimum = Math.Min(x,y)
        Maximum = Math.Max(x,y)
</code>```

But, if are trying to get the lower and upper values of a collection, you may utilize:

```<code>      MaxValue = Collection.Find(Collection, Function(Z) (Z > BiggerValue))

      MinValue = Collection.Find(Collection, Function(Z) (Z < LowerValue))
</code>```

where these values are gotten before the call.

Another way is to make a SORT and get the first and the last values...

Body:
Supposing I have a class

Public Class Foo
    Property fooProp1 as Single
    Property fooProp2 as Single
    Property fooProp3 as Single
End Class

to find the absolut maximum of a property (which contains positive or negative values) in a Collection(Of Foo) I can do:

Collection.Max(Function(x As foo) Math.Abs(x.fooProp1))

and it returns the greater absolute value WITHOUT sign.

The question is how can I do to get the number WITH sign?

Thanks in advance.
RG

Body:
Math.Abs will always return an unsigned value (the actual meaning of Absolute).

The get the value of a property you need only to READ it.

To get a MAX or MIN, you MUST compare values, like this:

        dim x as integer = foo.property
        dim y as integer = last_foo_property (or anything else)

        Minimum = Math.Min(x,y)
        Maximum = Math.Max(x,y)

But, if are trying to get the lower and upper values of a collection, you may utilize:

      MaxValue = Collection.Find(Collection, Function(Z) (Z > BiggerValue))

      MinValue = Collection.Find(Collection, Function(Z) (Z < LowerValue))

where these values are gotten before the call.

Another way is to make a SORT and get the first and the last values...


问:
Java generics: multiple generic parameters?
I was wondering if it's possible to write a function that accepts multiple generic types as follows:

```<code>public int void myfunction(Set<T> a, Set<T> b) {
    return 5;
}

Set<Integer> setA = new HashSet<Integer>();
Set<String> setB = new HashSet<String>();
int result = myfunction(setA, setB);
</code>```

Will that work? Does the  generic in each parameter mean that each parameter must have the same type T that's generic?

答:
You can follow one of the below approaches:

1) Basic, single type :

```<code>//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}
</code>```

2) Multiple Types :

```<code>// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}
</code>```

3) Below will raise compiler error as 'T3 is not in the listing of generic types that are used in function declaration part.

```<code>//Raised compilation error
public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}
</code>```

Correct : Compiles fine

```<code>public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}
</code>```

Sample Class Code :

```<code>package generics.basics;

import java.util.ArrayList;
import java.util.List;

public class GenericMethods {

/*
 Declare the generic type parameter T in this method.

 After the qualifiers public and static, you put <T> and
 then followed it by return type, method name, and its parameters.

 Observe : type of val is 'T' and not '<T>'

 * */
//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

/*// Q: To audience -> will this compile ?
 *
 * public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return 0;

}*/

 public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return null;

}

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(10);
    list.add(20);
    System.out.println(list.toString());
    fill(list, 100);
    System.out.println(list.toString());

    List<String> Strlist = new ArrayList<>();
    Strlist.add("Chirag");
    Strlist.add("Nayak");
    System.out.println(Strlist.toString());
    fill(Strlist, "GOOD BOY");
    System.out.println(Strlist.toString());

    System.out.println(multipleTypeArgument("Chirag", 100));
    System.out.println(multipleTypeArgument(100,"Nayak"));

}

}
</code>```

// class definition ends

Sample Output:

```<code>[10, 20]
[100, 100]
[Chirag, Nayak]
[GOOD BOY, GOOD BOY]
Chirag 100
100 Nayak
</code>```

Body:
I was wondering if it's possible to write a function that accepts multiple generic types as follows:

public int void myfunction(Set<T> a, Set<T> b) {
    return 5;
}

Set<Integer> setA = new HashSet<Integer>();
Set<String> setB = new HashSet<String>();
int result = myfunction(setA, setB);

Will that work? Does the  generic in each parameter mean that each parameter must have the same type T that's generic?

Body:
You can follow one of the below approaches:

1) Basic, single type :

//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

2) Multiple Types :

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

3) Below will raise compiler error as 'T3 is not in the listing of generic types that are used in function declaration part.

//Raised compilation error
public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}

Correct : Compiles fine

public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}

Sample Class Code :

package generics.basics;

import java.util.ArrayList;
import java.util.List;

public class GenericMethods {

/*
 Declare the generic type parameter T in this method.

 After the qualifiers public and static, you put <T> and
 then followed it by return type, method name, and its parameters.

 Observe : type of val is 'T' and not '<T>'

 * */
//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

/*// Q: To audience -> will this compile ?
 *
 * public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return 0;

}*/

 public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return null;

}

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(10);
    list.add(20);
    System.out.println(list.toString());
    fill(list, 100);
    System.out.println(list.toString());

    List<String> Strlist = new ArrayList<>();
    Strlist.add("Chirag");
    Strlist.add("Nayak");
    System.out.println(Strlist.toString());
    fill(Strlist, "GOOD BOY");
    System.out.println(Strlist.toString());

    System.out.println(multipleTypeArgument("Chirag", 100));
    System.out.println(multipleTypeArgument(100,"Nayak"));

}

}

// class definition ends

Sample Output:

[10, 20]
[100, 100]
[Chirag, Nayak]
[GOOD BOY, GOOD BOY]
Chirag 100
100 Nayak


问:
Flask-WTF - validate_on_submit() is never executed
I'm using Flask-WTF:

Here is my form:

```<code>from flask.ext.wtf import Form, TextField

class BookNewForm(Form):
    name = TextField('Name')
</code>```

Here is the controller:

```<code>@book.route('/book/new', methods=['GET', 'POST'])
def customers_new():
    form = BookNewForm()
    if form.is_submitted():
        print "submitted"
    if form.validate():
        print "valid"
    if form.validate_on_submit():
        flash("Successfully created a new book")
        return redirect(url_for('.books_show'))
    return render_template('views/books_new.html', form=form)
</code>```

Now the problem is, if you look at my print statements, it always prints submitted, but it NEVER prints valid and validate_on_submit() is never executed. Why?

答:
I came across this when trying to render a FormField being iterated over my FieldList in my template. I had to embed two hidden_tag elements one for the FieldList form and one for the FieldForm form, search the template comments for keyword "HIDDEN TAG"

```<code>class ParamRangeForm( FlaskForm ):
    minX = FloatField( )
    maxX = FloatField( )

class ParamRangesForm( FlaskForm ):
    paramRanges = FieldList( FormField( ParamRangeForm ) )
    submit      = SubmitField( 'Submit' )

    def loadParams( self ) :
        for paramName in ["p1" , "p2" , "p3", "p4"] :
            prf = ParamRangeForm( )
            prf.minX = -100.9#float('-inf')
            prf.maxX = 100.5#float('-inf')
            self.paramRanges.append_entry( prf )

...

  <form action="" method="POST" enctype="multipart/form-data">
    {{ rangesForm.hidden_tag() }} <!--#### HIDDEN TAG #1 -->
    <table>
      <!--Print Column Headers-->
      <thead>
      <tr>
        <th class="ColumnHeader">Parameter</td>
        <th class="ColumnHeader">Min</td>
        <th class="ColumnHeader">Max</td>
      </tr>
      </thead>

      <!--Print Parameter Rows-->
      <tbody>
      {% for paramRange in rangesForm.paramRanges %}
        <tr>
          {{ paramRange.hidden_tag() }} <!--#### HIDDEN TAG #2 -->
          <td>p{{ loop.index }}</td>
          <td>{{ paramRange.minX }}</td>
          <td>{{ paramRange.maxX }}</td>
        </tr>
      {% endfor %}
      </tbody>
    </table>
    </div>
    {{ rangesForm.submit() }}
  </form>
</code>```

Body:
I'm using Flask-WTF:

Here is my form:

from flask.ext.wtf import Form, TextField

class BookNewForm(Form):
    name = TextField('Name')

Here is the controller:

@book.route('/book/new', methods=['GET', 'POST'])
def customers_new():
    form = BookNewForm()
    if form.is_submitted():
        print "submitted"
    if form.validate():
        print "valid"
    if form.validate_on_submit():
        flash("Successfully created a new book")
        return redirect(url_for('.books_show'))
    return render_template('views/books_new.html', form=form)

Now the problem is, if you look at my print statements, it always prints submitted, but it NEVER prints valid and validate_on_submit() is never executed. Why?

Body:
I came across this when trying to render a FormField being iterated over my FieldList in my template. I had to embed two hidden_tag elements one for the FieldList form and one for the FieldForm form, search the template comments for keyword "HIDDEN TAG"

class ParamRangeForm( FlaskForm ):
    minX = FloatField( )
    maxX = FloatField( )

class ParamRangesForm( FlaskForm ):
    paramRanges = FieldList( FormField( ParamRangeForm ) )
    submit      = SubmitField( 'Submit' )

    def loadParams( self ) :
        for paramName in ["p1" , "p2" , "p3", "p4"] :
            prf = ParamRangeForm( )
            prf.minX = -100.9#float('-inf')
            prf.maxX = 100.5#float('-inf')
            self.paramRanges.append_entry( prf )

...

  <form action="" method="POST" enctype="multipart/form-data">
    {{ rangesForm.hidden_tag() }} <!--#### HIDDEN TAG #1 -->
    <table>
      <!--Print Column Headers-->
      <thead>
      <tr>
        <th class="ColumnHeader">Parameter</td>
        <th class="ColumnHeader">Min</td>
        <th class="ColumnHeader">Max</td>
      </tr>
      </thead>

      <!--Print Parameter Rows-->
      <tbody>
      {% for paramRange in rangesForm.paramRanges %}
        <tr>
          {{ paramRange.hidden_tag() }} <!--#### HIDDEN TAG #2 -->
          <td>p{{ loop.index }}</td>
          <td>{{ paramRange.minX }}</td>
          <td>{{ paramRange.maxX }}</td>
        </tr>
      {% endfor %}
      </tbody>
    </table>
    </div>
    {{ rangesForm.submit() }}
  </form>