问:
Centering two divs in a wrapper
I am trying to center #left and #center inside #wrapper like this:

I am trying to get #center to be in the actual center of #wrapper both horizontally and vertically, and that #left will be in a slight margin to his left. How do I achieve that?

.c {
  border: 1px solid black;
  margin-left: auto;
  margin-right: auto;
  width: 60vw;
  height: 80vh;
  margin-top: 13vh;
}

#wrapper {
  height: 13vh;
  margin-top: 2vh;
  border: 1px solid blue;
}

#center {
  display: inline-block;
  width: 12vw;
  height: 10vh;
  border: 1px solid red;
}

#left {
  display: inline-block;
  width: 13vh;
  height: 13vh;
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="c">
  <div>content content content</div>
  <div>content content content</div>

  <div id="wrapper">
    <div id="left">left</div>
    <div id="center">center</div>

  </div>
  <div>content content content</div>
  <div>content content content</div></code>```

Jsfiddle: https://jsfiddle.net/y6r585jk/2/

答:
You know the width of #left. It's 13vh.

Add a pseudo-element on the right with the same width.

Then center all three elements in the container.

The pseudo is a counter-balance to #left. It enables #center to be perfectly centered.

You can hide the pseudo with visibility: hidden.

.c {
  border: 1px solid black;
  margin-left: auto;
  margin-right: auto;
  width: 60vw;
  height: 80vh;
  margin-top: 13vh;
}

#wrapper {
  height: 13vh;
  margin-top: 2vh;
  border: 1px solid blue;

  /* new */
  display: flex;
  justify-content: center; /* center children horizontally */
  align-items: center;     /* center children vertically */
}

/* new */
#wrapper::after {
  content: 'right';
  width: 13vh;
  border: 1px dashed black;
  /* visibility: hidden; */
}

#center {
  display: inline-block;
  width: 12vw;
  height: 10vh;
  border: 1px solid red;
  margin: 0 5px; /* new */
}

#left {
  display: inline-block;
  width: 13vh;
  height: 13vh;
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="c">
  <div>content content content</div>
  <div>content content content</div>
  <div id="wrapper">
    <div id="left">left</div>
    <div id="center">center</div>
  </div>
  <div>content content content</div>
  <div>content content content</div>
</div></code>```

https://jsfiddle.net/y6r585jk/4/

The layout can also be achieved using an actual (DOM) element or absolute positioning.

More details here: Center and right align flexbox elements

Title: Centering two divs in a wrapper

Body:
I am trying to center #left and #center inside #wrapper like this:

I am trying to get #center to be in the actual center of #wrapper both horizontally and vertically, and that #left will be in a slight margin to his left. How do I achieve that?

.c {
  border: 1px solid black;
  margin-left: auto;
  margin-right: auto;
  width: 60vw;
  height: 80vh;
  margin-top: 13vh;
}

#wrapper {
  height: 13vh;
  margin-top: 2vh;
  border: 1px solid blue;
}

#center {
  display: inline-block;
  width: 12vw;
  height: 10vh;
  border: 1px solid red;
}

#left {
  display: inline-block;
  width: 13vh;
  height: 13vh;
  border: 1px solid green;
}

content content content

content content content

left

center

content content content

content content content

Jsfiddle: https://jsfiddle.net/y6r585jk/2/

Body:
You know the width of #left. It's 13vh.

Add a pseudo-element on the right with the same width.

Then center all three elements in the container.

The pseudo is a counter-balance to #left. It enables #center to be perfectly centered.

You can hide the pseudo with visibility: hidden.

.c {
  border: 1px solid black;
  margin-left: auto;
  margin-right: auto;
  width: 60vw;
  height: 80vh;
  margin-top: 13vh;
}

#wrapper {
  height: 13vh;
  margin-top: 2vh;
  border: 1px solid blue;

  /* new */
  display: flex;
  justify-content: center; /* center children horizontally */
  align-items: center;     /* center children vertically */
}

/* new */
#wrapper::after {
  content: 'right';
  width: 13vh;
  border: 1px dashed black;
  /* visibility: hidden; */
}

#center {
  display: inline-block;
  width: 12vw;
  height: 10vh;
  border: 1px solid red;
  margin: 0 5px; /* new */
}

#left {
  display: inline-block;
  width: 13vh;
  height: 13vh;
  border: 1px solid green;
}

<div class="c">
  <div>content content content</div>
  <div>content content content</div>
  <div id="wrapper">
    <div id="left">left</div>
    <div id="center">center</div>
  </div>
  <div>content content content</div>
  <div>content content content</div>
</div>

https://jsfiddle.net/y6r585jk/4/

The layout can also be achieved using an actual (DOM) element or absolute positioning.

More details here: Center and right align flexbox elements


来源: stackexchange

问:
How do I get PHP errors to display?
I have checked my PHP ini file (php.ini) and display_errors is set and also error reporting is E_ALL. I have restarted my Apache webserver.

I have even put these lines at the top of my script, and it doesn't even catch simple parse errors. For example, I declare variables with a "$" and I don't close statements";". But all my scripts show a blank page on these errors, but I want to actually see the errors in my browser output.

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

What is left to do?

答:
You can add your own custom error handler, which can provide extra debug information. Furthermore, you can set it up to send you the information via email.</p>

```<code>function ERR_HANDLER($errno, $errstr, $errfile, $errline){
    $msg = "<b>Something bad happened.</b> [$errno] $errstr <br><br>
    <b>File:</b> $errfile <br>
    <b>Line:</b> $errline <br>
    ```".json_encode(debug_backtrace(), JSON_PRETTY_PRINT)."``` <br>";

    echo $msg;

    return false;
}

function EXC_HANDLER($exception){
    ERR_HANDLER(0, $exception->getMessage(), $exception->getFile(), $exception->getLine());
}

function shutDownFunction() {
    $error = error_get_last();
    if ($error["type"] == 1) {
        ERR_HANDLER($error["type"], $error["message"], $error["file"], $error["line"]);
    }
}

set_error_handler ("ERR_HANDLER", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
register_shutdown_function("shutdownFunction");
set_exception_handler("EXC_HANDLER");
</code>```

ContentLicense: CC BY-SA 4.0

Title: How do I get PHP errors to display?

Body:
I have checked my PHP ini file (php.ini) and display_errors is set and also error reporting is E_ALL. I have restarted my Apache webserver.

I have even put these lines at the top of my script, and it doesn't even catch simple parse errors. For example, I declare variables with a "$" and I don't close statements";". But all my scripts show a blank page on these errors, but I want to actually see the errors in my browser output.

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

What is left to do?

Body:
You can add your own custom error handler, which can provide extra debug information. Furthermore, you can set it up to send you the information via email.

function ERR_HANDLER($errno, $errstr, $errfile, $errline){
    $msg = "<b>Something bad happened.</b> [$errno] $errstr <br><br>
    <b>File:</b> $errfile <br>
    <b>Line:</b> $errline <br>
    <pre>".json_encode(debug_backtrace(), JSON_PRETTY_PRINT)."</pre> <br>";

    echo $msg;

    return false;
}

function EXC_HANDLER($exception){
    ERR_HANDLER(0, $exception->getMessage(), $exception->getFile(), $exception->getLine());
}

function shutDownFunction() {
    $error = error_get_last();
    if ($error["type"] == 1) {
        ERR_HANDLER($error["type"], $error["message"], $error["file"], $error["line"]);
    }
}

set_error_handler ("ERR_HANDLER", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
register_shutdown_function("shutdownFunction");
set_exception_handler("EXC_HANDLER");


问:
spring-security & jersey: no automatic redirection to the login site
I ran into the following problem using spring-security 3.0.3 with jersey 1.2:

when i annotate my Jersey Resources with the @Secured or @PreAuthorize Annotations, spring-security does not autoredirect the user-agent to the login page as i want it to. Only the AuthenticationCredentialsNotFoundException gets thrown and a HTTP 500 gets returned to the user-agent instead of a redirection to spring-security's form login page.
Does anyone know why this problem occurs?

Resource:

```<code>@Path("/event")
@Component
public class EventResource extends AbstractBaseResource {

     @Resource(name = "eventService")
     private EventService eventService;

     public void setEventService(EventService eventService) {
         this.eventService = eventService;
     }

 @GET
 @Path("/view/{id}")
 @Produces(MediaType.TEXT_HTML)
 @PreAuthorize("hasRole('ROLE_USER')")
 public Viewable viewEvent(@PathParam("id") long id) throws UnsupportedEncodingException, URISyntaxException{
            ...
        }
}
</code>```

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_3_0.xsd"
    version="3.0">
    <filter>
        <filter-name>jersey</filter-name>
        <filter-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</filter-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
            <param-value>/(static|images|js|css|(WEB-INF/views))/.*</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.config.property.JSPTemplatesBasePath</param-name>
            <param-value>/WEB-INF/views/</param-value>
        </init-param>
    </filter>

    <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

    <filter-mapping>
        <filter-name>jersey</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

    [...]
</web-app>
</code>```

context:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <context:annotation-config />
    <context:component-scan base-package="..." />
 <context:mbean-export/>

    <security:http auto-config="true" >
     <security:form-login/>
     <security:logout/>
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider ref="..." />
    </security:authentication-manager>

 <security:global-method-security pre-post-annotations="enabled" />

    [...]
</beans>
</code>```

Thank you!

答:
Could it be due to the login page itself getting filtered by spring security?   One way to check would be to try adding a line similar to</p>

```<code><intercept-url pattern="/login.jsp*" filters="none"/>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I ran into the following problem using spring-security 3.0.3 with jersey 1.2:

when i annotate my Jersey Resources with the @Secured or @PreAuthorize Annotations, spring-security does not autoredirect the user-agent to the login page as i want it to. Only the AuthenticationCredentialsNotFoundException gets thrown and a HTTP 500 gets returned to the user-agent instead of a redirection to spring-security's form login page.
Does anyone know why this problem occurs?

Resource:

@Path("/event")
@Component
public class EventResource extends AbstractBaseResource {

     @Resource(name = "eventService")
     private EventService eventService;

     public void setEventService(EventService eventService) {
         this.eventService = eventService;
     }

 @GET
 @Path("/view/{id}")
 @Produces(MediaType.TEXT_HTML)
 @PreAuthorize("hasRole('ROLE_USER')")
 public Viewable viewEvent(@PathParam("id") long id) throws UnsupportedEncodingException, URISyntaxException{
            ...
        }
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_3_0.xsd"
    version="3.0">
    <filter>
        <filter-name>jersey</filter-name>
        <filter-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</filter-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
            <param-value>/(static|images|js|css|(WEB-INF/views))/.*</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.config.property.JSPTemplatesBasePath</param-name>
            <param-value>/WEB-INF/views/</param-value>
        </init-param>
    </filter>

    <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

    <filter-mapping>
        <filter-name>jersey</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

    [...]
</web-app>

context:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <context:annotation-config />
    <context:component-scan base-package="..." />
 <context:mbean-export/>

    <security:http auto-config="true" >
     <security:form-login/>
     <security:logout/>
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider ref="..." />
    </security:authentication-manager>

 <security:global-method-security pre-post-annotations="enabled" />

    [...]
</beans>

Thank you!

Body:
Could it be due to the login page itself getting filtered by spring security?   One way to check would be to try adding a line similar to

<intercept-url pattern="/login.jsp*" filters="none"/>


问:
can not install apk after generate signed apk in Android studio
I want to publish my app to google play. So I follow this link.

I created a keystore, and built app-release.apk successfully. But when I install APK to my device, it take error:

```<code>~/Android/Sdk/platform-tools$ ./adb install ~/Downloads/libraries/LolliPin/app/app-release.apk
[100%] /data/local/tmp/app-release.apk
        pkg: /data/local/tmp/app-release.apk
Failure [INSTALL_PARSE_FAILED_NO_CERTIFICATES]
</code>```

When upload to Developer Console, the site say app has not signed.

I try again using manual steps: jarsigned --> zipalign --> apksigner but it is not run.

Please tell me the solution. Many thanks!

UPDATE: when I verified the apk (created by android studio --> generate apk signed) by apksigned, it show error:

```<code>~/Android/Sdk/build-tools/25.0.2$ ./apksigner verify /home/haitt22/test/app-release.apk
DOES NOT VERIFY
ERROR: No JAR signatures
</code>```

UPDATE 2: when i signed it using apksigner in build-tool, log:

```<code>/apksigner sign --ks /home/haitt22/test/test.jks /home/ubuntu/test/app-release-aligned.apk
Keystore password for signer #1:
Exception in thread "main" java.lang.IllegalAccessError: class com.android.apksig.internal.apk.v1.V1SchemeSigner (in unnamed module @0x646d64ab) cannot access class sun.security.x509.AlgorithmId (in module java.base) because module java.base does not export sun.security.x509 to unnamed module @0x646d64ab
    at com.android.apksig.internal.apk.v1.V1SchemeSigner.getSupportedAlgorithmId(V1SchemeSigner.java:625)
    at com.android.apksig.internal.apk.v1.V1SchemeSigner.<clinit>(V1SchemeSigner.java:541)
    at com.android.apksig.DefaultApkSignerEngine.<init>(DefaultApkSignerEngine.java:149)
    at com.android.apksig.DefaultApkSignerEngine.<init>(DefaultApkSignerEngine.java:52)
    at com.android.apksig.DefaultApkSignerEngine$Builder.build(DefaultApkSignerEngine.java:902)
    at com.android.apksig.ApkSigner.sign(ApkSigner.java:259)
    at com.android.apksig.ApkSigner.sign(ApkSigner.java:178)
    at com.android.apksigner.ApkSignerTool.sign(ApkSignerTool.java:277)
    at com.android.apksigner.ApkSignerTool.main(ApkSignerTool.java:89)
</code>```

答: Use OpenJDK 8. Java 9 is causing this problem</p>

ContentLicense: CC BY-SA 3.0

Body:
I want to publish my app to google play. So I follow this link.

I created a keystore, and built app-release.apk successfully. But when I install APK to my device, it take error:

~/Android/Sdk/platform-tools$ ./adb install ~/Downloads/libraries/LolliPin/app/app-release.apk
[100%] /data/local/tmp/app-release.apk
        pkg: /data/local/tmp/app-release.apk
Failure [INSTALL_PARSE_FAILED_NO_CERTIFICATES]

When upload to Developer Console, the site say app has not signed.

I try again using manual steps: jarsigned --> zipalign --> apksigner but it is not run.

Please tell me the solution. Many thanks!

UPDATE: when I verified the apk (created by android studio --> generate apk signed) by apksigned, it show error:

~/Android/Sdk/build-tools/25.0.2$ ./apksigner verify /home/haitt22/test/app-release.apk
DOES NOT VERIFY
ERROR: No JAR signatures

UPDATE 2: when i signed it using apksigner in build-tool, log:

/apksigner sign --ks /home/haitt22/test/test.jks /home/ubuntu/test/app-release-aligned.apk
Keystore password for signer #1:
Exception in thread "main" java.lang.IllegalAccessError: class com.android.apksig.internal.apk.v1.V1SchemeSigner (in unnamed module @0x646d64ab) cannot access class sun.security.x509.AlgorithmId (in module java.base) because module java.base does not export sun.security.x509 to unnamed module @0x646d64ab
    at com.android.apksig.internal.apk.v1.V1SchemeSigner.getSupportedAlgorithmId(V1SchemeSigner.java:625)
    at com.android.apksig.internal.apk.v1.V1SchemeSigner.<clinit>(V1SchemeSigner.java:541)
    at com.android.apksig.DefaultApkSignerEngine.<init>(DefaultApkSignerEngine.java:149)
    at com.android.apksig.DefaultApkSignerEngine.<init>(DefaultApkSignerEngine.java:52)
    at com.android.apksig.DefaultApkSignerEngine$Builder.build(DefaultApkSignerEngine.java:902)
    at com.android.apksig.ApkSigner.sign(ApkSigner.java:259)
    at com.android.apksig.ApkSigner.sign(ApkSigner.java:178)
    at com.android.apksigner.ApkSignerTool.sign(ApkSignerTool.java:277)
    at com.android.apksigner.ApkSignerTool.main(ApkSignerTool.java:89)


问:
Hangfire failes to load assembly
Context

I have two application in place, one is my main enterprise application and in other I have hangfire (hangfire server, client and dashboard) hosted. My main application also use hangfire for some long task and executes them asynchronously. Both using the same DB for HF storage. And there is only one HF server.

Issue

I am getting the following errors intermittently -

"Can not change the state to 'Processing': target method was not found."
  OR

"Can not change the state to 'Enqueued': target method was not found."

with following details -

System.IO.FileNotFoundException

Could not load file or assembly 'MyApp.Hangfire, Version=1.0.0.0,
  Culture=neutral, PublicKeyToken=null' or one of its dependencies. The
  system cannot find the file specified.

where MyApp.Hangfire is my hangfire application executing jobs. And I am sure that it is there, and even some successful jobs affirms it.

Please find the attached screenshot for more details.

Observation

The issue is not consistent, the job not always fails, sometimes it fails, re queued and get passed and sometimes when it is out of retries it even fails. As shown in screenshot

答:
I've stumbled upon the same issue a few days ago and decided it's worth adding it here.

Solution: added a reference to 'MyApp.Hangfire' in the dashboard web app.

Context was very similar or identical to yours:

-Hangfire server was running as a Windows service;

-Hangfire dashboard running on top of a ASP.NET MVC 5 app;

-jobs were actually running but dashboard kept displaying a FileNotFoundException;

Same problem was reported and solved in the same way by @reggieboyYEAH.

Details here: https://github.com/HangfireIO/Hangfire/issues/558

Title: Hangfire failes to load assembly


问:
No rule to make target f1.o, needed by f90_simple
I have the following makefile. It works well for .f and .c files but when I have .f90 file and want to compile it with ifort does not work?
Could you please advise me where I should change and how?
Thanks you

```<code>FCOMPFLAGS    =    -O -ffixed-line-length-132
CCOMPFLAGS    =    -O

FFLAGS        =    $(FCOMPFLAGS) -fsecond-underscore
CFLAGS        =    $(CCOMPFLAGS)
LDFLAGS       =    $(FCOMPFLAGS)

LD            =    gfortran
FC            =    gfortran

MAKEFILE      =    Makefile
PROGRAM1      =    f1

OBJS          =    f1.o      \
                   f2.o      \
                   f3.o

all:        $(PROGRAM1)

$(PROGRAM1): $(OBJS) $(MAKEFILE)
    $(LD) $(LDFLAGS) $(OBJS) -o $(PROGRAM1)

clean:         @rm -f $(OBJS) core
</code>```

when I execute "make" I get the following error,

```<code>make: *** No rule to make target `f1.o', needed by `f90_simple'.  Stop.
</code>```

It seems that My makefile does not recognize *.f90 files, and my other question is do we have flag for ifrot compiler to be used in makefile
Thanks

答:
You need to add the implicit rule:</p>

```<code>%.o : %.f90
<tab>$(FC) $(FCOMPLAGS) -c $<
</code>```

Body:
I have the following makefile. It works well for .f and .c files but when I have .f90 file and want to compile it with ifort does not work?
Could you please advise me where I should change and how?
Thanks you

FCOMPFLAGS    =    -O -ffixed-line-length-132
CCOMPFLAGS    =    -O

FFLAGS        =    $(FCOMPFLAGS) -fsecond-underscore
CFLAGS        =    $(CCOMPFLAGS)
LDFLAGS       =    $(FCOMPFLAGS)

LD            =    gfortran
FC            =    gfortran

MAKEFILE      =    Makefile
PROGRAM1      =    f1

OBJS          =    f1.o      \
                   f2.o      \
                   f3.o

all:        $(PROGRAM1)

$(PROGRAM1): $(OBJS) $(MAKEFILE)
    $(LD) $(LDFLAGS) $(OBJS) -o $(PROGRAM1)

clean:         @rm -f $(OBJS) core

when I execute "make" I get the following error,

make: *** No rule to make target `f1.o', needed by `f90_simple'.  Stop.

It seems that My makefile does not recognize *.f90 files, and my other question is do we have flag for ifrot compiler to be used in makefile
Thanks

Body:
You need to add the implicit rule:

%.o : %.f90
<tab>$(FC) $(FCOMPLAGS) -c $<


问:
C++ callback to class function
I'm using the Arduino IDE and the things network arduino library to create a LoRa mote.

I have created a class which should handle all the LoRa related functions. In this class I need to handle a callback if i receive a downlink message.
The ttn library has the onMessage function which I want to setup in my init function and parse another function, which are a class member, called message.
I'm getting the error "invalid use of non-static member function".

```<code>// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>

TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);

LoRa::LoRa(){
}

void LoRa::init(){
  // Set the callback
  ttn.onMessage(this->message);
}

// Other functions

void LoRa::message(const uint8_t *payload, size_t size, port_t port)
{
  // Stuff to do when reciving a downlink
}
</code>```

and the header file

```<code>// File: LoRa.h
#ifndef LoRa_h
#define LoRa_h

#include "Arduino.h"
#include <TheThingsNetwork.h>

// Define serial interface for communication with LoRa module
#define loraSerial Serial1
#define debugSerial Serial

// define the frequency plan - EU or US. (TTN_FP_EU868 or TTN_FP_US915)
#define freqPlan TTN_FP_EU868

class LoRa{
  // const vars

  public:
    LoRa();

    void init();

    // other functions

    void message(const uint8_t *payload, size_t size, port_t port);

  private:
    // Private functions
};

#endif
</code>```

I have tried:

```<code>ttn.onMessage(this->message);
ttn.onMessage(LoRa::message);
ttn.onMessage(message);
</code>```

However none of them worked as I had expected.

答:
You're trying to call a member function (that means, a function belonging to a member of a class type) without using a class member. That means, what you'd usually do is instantiate a member of your class LoRa first, then call it like:

```<code>LoRa loraMember;
loraMember.message();
</code>```

Since you're trying to call that function from inside the class itself, without a member of the class calling the init(), you have to make the function static like:

```<code>static void message(const uint8_t *payload, size_t size, port_t port);
</code>```

Then you can use LoRa::message() from anywhere as long as it's public, but calling it just like that will give you another compiler error, since the interface of message asks for "const uint8_t *payload, size_t size, port_t port". So what you'd have to do is call message like:

```<code>LoRa::message(payloadPointer, sizeVar, portVar);`
</code>```

When you call ttn.onMessage(functionCall) what happens is that the function call gets evaluated, then what is returned by that function gets put into the parentheses and ttn.onMessage is called with that. Since your LoRa::message function returns nothing (void) you'll get another error here.

I suggest a good book on C++ basics to get you started - book list

Good luck!

Title: C++ callback to class function

Body:
I'm using the Arduino IDE and the things network arduino library to create a LoRa mote.

I have created a class which should handle all the LoRa related functions. In this class I need to handle a callback if i receive a downlink message.
The ttn library has the onMessage function which I want to setup in my init function and parse another function, which are a class member, called message.
I'm getting the error "invalid use of non-static member function".

// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>

TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);

LoRa::LoRa(){
}

void LoRa::init(){
  // Set the callback
  ttn.onMessage(this->message);
}

// Other functions

void LoRa::message(const uint8_t *payload, size_t size, port_t port)
{
  // Stuff to do when reciving a downlink
}

and the header file

// File: LoRa.h
#ifndef LoRa_h
#define LoRa_h

#include "Arduino.h"
#include <TheThingsNetwork.h>

// Define serial interface for communication with LoRa module
#define loraSerial Serial1
#define debugSerial Serial

// define the frequency plan - EU or US. (TTN_FP_EU868 or TTN_FP_US915)
#define freqPlan TTN_FP_EU868

class LoRa{
  // const vars

  public:
    LoRa();

    void init();

    // other functions

    void message(const uint8_t *payload, size_t size, port_t port);

  private:
    // Private functions
};

#endif

I have tried:

ttn.onMessage(this->message);
ttn.onMessage(LoRa::message);
ttn.onMessage(message);

However none of them worked as I had expected.

Body:
You're trying to call a member function (that means, a function belonging to a member of a class type) without using a class member. That means, what you'd usually do is instantiate a member of your class LoRa first, then call it like:

LoRa loraMember;
loraMember.message();

Since you're trying to call that function from inside the class itself, without a member of the class calling the init(), you have to make the function static like:

static void message(const uint8_t *payload, size_t size, port_t port);

Then you can use LoRa::message() from anywhere as long as it's public, but calling it just like that will give you another compiler error, since the interface of message asks for "const uint8_t *payload, size_t size, port_t port". So what you'd have to do is call message like:

LoRa::message(payloadPointer, sizeVar, portVar);`

When you call ttn.onMessage(functionCall) what happens is that the function call gets evaluated, then what is returned by that function gets put into the parentheses and ttn.onMessage is called with that. Since your LoRa::message function returns nothing (void) you'll get another error here.

I suggest a good book on C++ basics to get you started - book list

Good luck!


问:
IIS error in deploying asp.net mvc2
I am trying to deploy a wcf webhttp service onto IIS. I am Running Windows 7, IIS 7.5, VS2010.

The Steps
- Created a project WCF Rest Service Application.
- Published the project to localhost
- Ensured that the applicationpool was .net 4.0

However, when trying to access the service published at (Default Web Site/HelloRest ) via http://localhost/HelloRest

It gives an error –

Error Summary
HTTP Error 500.19 - Internal Server Error
This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

In the config source
modules runAllManagedModulesForAllRequests="true" is highlighted

Is there anything I am missing? When I execute from vs the service works just fine.
In globals.asax I have -

```<code>RouteTable.Routes.Add(new ServiceRoute("PrintHelloWorld", new WebServiceHostFactory(), typeof(HelloRestService)));
</code>```

When executed from vs2010
http://localhost:59404/PrintHelloWorld/  returns hello world. However, once published

http://localhost/HelloRest/PrintHelloWorld returns the same error as well.

EDIT
Figured out the solution.
- I had installed IIS after installing the .net framework.
In commandline execute the asp.net registration tool
- Go to the directory in Windows\Microsoft.NET\Framework\v4.0.30319
type aspnet_regiis.exe -ir

Now it starts to work.

答:
I am not a expert in .Net... But did you try these suggestions?
http://forums.asp.net/t/1220987.aspx</p>

Title: IIS error in deploying asp.net mvc2

Body:
I am trying to deploy a wcf webhttp service onto IIS. I am Running Windows 7, IIS 7.5, VS2010.

The Steps
- Created a project WCF Rest Service Application.
- Published the project to localhost
- Ensured that the applicationpool was .net 4.0

However, when trying to access the service published at (Default Web Site/HelloRest ) via http://localhost/HelloRest

It gives an error –

Error Summary
HTTP Error 500.19 - Internal Server Error
This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

In the config source
modules runAllManagedModulesForAllRequests="true" is highlighted

Is there anything I am missing? When I execute from vs the service works just fine.
In globals.asax I have -

RouteTable.Routes.Add(new ServiceRoute("PrintHelloWorld", new WebServiceHostFactory(), typeof(HelloRestService)));

When executed from vs2010
http://localhost:59404/PrintHelloWorld/  returns hello world. However, once published

http://localhost/HelloRest/PrintHelloWorld returns the same error as well.

EDIT
Figured out the solution.
- I had installed IIS after installing the .net framework.
In commandline execute the asp.net registration tool
- Go to the directory in Windows\Microsoft.NET\Framework\v4.0.30319
type aspnet_regiis.exe -ir

Now it starts to work.


问:
Seaborn regplot using datetime64 as the x axis
I have a dataframe looks like this:

```<code>date         score
2017-06-04    90
2017-06-03    80
2017-06-02    70
</code>```

When I tried this:

```<code>sns.regplot(x=date, y=score, data=df)
</code>```

I got an error:

```<code>TypeError: reduction operation 'mean' not allowed for this dtype
</code>```

The dtype for date is datetime64[ns], and int64 for the score column.

How can I covert the date column so that regplot will work?

答:
Seaborn doesn't support datetimes in regplot but here's an ugly hack:

```<code>df = df.sort_values('date')
df['date_f'] = pd.factorize(df['date'])[0] + 1
mapping = dict(zip(df['date_f'], df['date'].dt.date))

ax = sns.regplot('date_f', 'score', data=df)
labels = pd.Series(ax.get_xticks()).map(mapping).fillna('')
ax.set_xticklabels(labels)
</code>```

produces

This is the main approach used in time-series regression. If you have daily data, you code day 1 as 1 and increase the number as the days go by. This assumes you have a regularly-spaced time series.

Body:
I have a dataframe looks like this:

date         score
2017-06-04    90
2017-06-03    80
2017-06-02    70

When I tried this:

sns.regplot(x=date, y=score, data=df)

I got an error:

TypeError: reduction operation 'mean' not allowed for this dtype

The dtype for date is datetime64[ns], and int64 for the score column.

How can I covert the date column so that regplot will work?

Body:
Seaborn doesn't support datetimes in regplot but here's an ugly hack:

df = df.sort_values('date')
df['date_f'] = pd.factorize(df['date'])[0] + 1
mapping = dict(zip(df['date_f'], df['date'].dt.date))

ax = sns.regplot('date_f', 'score', data=df)
labels = pd.Series(ax.get_xticks()).map(mapping).fillna('')
ax.set_xticklabels(labels)

produces

This is the main approach used in time-series regression. If you have daily data, you code day 1 as 1 and increase the number as the days go by. This assumes you have a regularly-spaced time series.


问:
How to properly parse string into integer inside JSONParser?
i have this code to retrieve my values in the database:

```<code>            if(json != null){
            try{
                result = json.getJSONArray("monthly");
                if(!result.toString().equals("[]")) {
                    for (int i = 0; i < result.length(); i++) {
                        JSONObject source = result.getJSONObject(i);
                        String month = source.getString("month");
                        String counted = source.getString("counted");

                        Toast.makeText(getActivity(), month, Toast.LENGTH_SHORT).show();

                    }
</code>```

notice the

String month = source.getString("month");

it is quick to return that value which just loads after 2 seconds or so. but when i try to parse that value into integer using this code:

int month = Integer.parseInt(source.getString("month"));

it takes very long time to finish. so what im asking is how do you properly parse that data into an integer?

Edit:
JSON

{"monthly":[{"month":"2","counted":"1"},{"month":"3","counted":"1"},{"month":"4","counted":"1"},{"month":"5","counted":"5"},{"month":"6","counted":"2"},{"month":"7","counted":"3"},{"month":"8","counted":"1"},{"month":"9","counted":"2"},{"month":"10","counted":"1"},{"month":"11","counted":"3"},{"month":"12","counted":"2"}]}

答:
You can use getInt on the JSONObject:

```<code>source.getInt("month")
</code>```

Performance is always an issue though when parsing data and depending on size could make quite an impact.  If you are trying to do this on the UI thread, you shouldn't.  Instead use some background thread.  AsyncTask is the Android specific way to run code on a background thread and then pass the results back to the UI thread.

Edit:

This is the code I have and there is no significant performance impact using getString vs. getInt so there must be an issue some place else in your code.

```<code>    try {
        JSONObject json =
            new JSONObject("{'monthly':[{'month':'2','counted':'1'},{'month':'3','counted':'1'},{'month':'4','counted':'1'},{'month':'5','counted':'5'},{'month':'6','counted':'2'},{'month':'7','counted':'3'},{'month':'8','counted':'1'},{'month':'9','counted':'2'},{'month':'10','counted':'1'},{'month':'11','counted':'3'},{'month':'12','counted':'2'}]}");
        JSONArray result = json.getJSONArray("monthly");
        for (int i = 0; i < result.length(); i++) {
            JSONObject source = result.getJSONObject(i);
            int month = source.getInt("month");
            String counted = source.getString("counted");

            Toast.makeText(this,
                           "" + month,
                           Toast.LENGTH_SHORT)
                 .show();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

Body:
i have this code to retrieve my values in the database:

            if(json != null){
            try{
                result = json.getJSONArray("monthly");
                if(!result.toString().equals("[]")) {
                    for (int i = 0; i < result.length(); i++) {
                        JSONObject source = result.getJSONObject(i);
                        String month = source.getString("month");
                        String counted = source.getString("counted");

                        Toast.makeText(getActivity(), month, Toast.LENGTH_SHORT).show();

                    }

notice the

String month = source.getString("month");

it is quick to return that value which just loads after 2 seconds or so. but when i try to parse that value into integer using this code:

int month = Integer.parseInt(source.getString("month"));

it takes very long time to finish. so what im asking is how do you properly parse that data into an integer?

Edit:
JSON

{"monthly":[{"month":"2","counted":"1"},{"month":"3","counted":"1"},{"month":"4","counted":"1"},{"month":"5","counted":"5"},{"month":"6","counted":"2"},{"month":"7","counted":"3"},{"month":"8","counted":"1"},{"month":"9","counted":"2"},{"month":"10","counted":"1"},{"month":"11","counted":"3"},{"month":"12","counted":"2"}]}

Body:
You can use getInt on the JSONObject:

source.getInt("month")

Performance is always an issue though when parsing data and depending on size could make quite an impact.  If you are trying to do this on the UI thread, you shouldn't.  Instead use some background thread.  AsyncTask is the Android specific way to run code on a background thread and then pass the results back to the UI thread.

Edit:

This is the code I have and there is no significant performance impact using getString vs. getInt so there must be an issue some place else in your code.

    try {
        JSONObject json =
            new JSONObject("{'monthly':[{'month':'2','counted':'1'},{'month':'3','counted':'1'},{'month':'4','counted':'1'},{'month':'5','counted':'5'},{'month':'6','counted':'2'},{'month':'7','counted':'3'},{'month':'8','counted':'1'},{'month':'9','counted':'2'},{'month':'10','counted':'1'},{'month':'11','counted':'3'},{'month':'12','counted':'2'}]}");
        JSONArray result = json.getJSONArray("monthly");
        for (int i = 0; i < result.length(); i++) {
            JSONObject source = result.getJSONObject(i);
            int month = source.getInt("month");
            String counted = source.getString("counted");

            Toast.makeText(this,
                           "" + month,
                           Toast.LENGTH_SHORT)
                 .show();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }


Title: matplotlib tricontourf ploblem when I give more data point

Body:
I have got a problem when i try to plot the stress.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
import matplotlib.cm as cm

def plot(x_plot, y_plot, a_plot):
    x = np.array(x_plot)
    y = np.array(y_plot)
    a = np.array(a_plot)

    triang = mtri.Triangulation(x, y)
    refiner = mtri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(a, subdiv=4)

    plt.figure(figsize=(18, 9))
    plt.gca().set_aspect('equal')
    #     levels = np.arange(23.4, 23.7, 0.025)
    levels = np.linspace(a.min(), a.max(), num=1000)
    cmap = cm.get_cmap(name='jet')
    plt.tricontourf(tri_refi, z_test_refi, levels=levels, cmap=cmap)
    plt.scatter(x, y, c=a, cmap=cmap)
    plt.colorbar()

    plt.title('stress plot')
    plt.show()

First I have plot by using only 8 points:

x = [2.3384750000000003, 3.671702, 0.3356813, 3.325298666666667, 2.660479, 1.3271675666666667, 1.6680919666666665, 0.6659845666666667]
y = [0.614176, 0.5590579999999999, 0.663329, 0.24002166666666666, 0.26821433333333333, 0.31229233333333334, 0.6367503333333334, 0.3250663333333333]
a = [2.572, 0.8214, 5.689, -0.8214, -2.572, -4.292, 4.292, -5.689]
plot(x, y, a)

then i try to give an information of the bound of rectangle:

x = [2.3384750000000003, 1.983549, 3.018193, 2.013683, 3.671702, 3.978008, 4.018905, 0.3356813, 0.0, 0.0, 1.0070439, 3.325298666666667, 2.979695, 2.660479, 1.3271675666666667, 0.9909098, 1.6680919666666665, 0.6659845666666667]
y = [0.614176, -0.038322, 0.922264, 0.958586, 0.5590579999999999, -0.1229, 0.87781, 0.663329, 1.0, 0.0, 0.989987, 0.24002166666666666, -0.079299, 0.26821433333333333, 0.31229233333333334, -0.014787999999999999, 0.6367503333333334, 0.3250663333333333]
a = [2.572, 2.572, 2.572, 2.572, 0.8214, 0.8214, 0.8214, 5.689, 5.689, 5.689, 5.689, -0.8214, -0.8214, -2.572, -4.292, -4.292, 4.292, -5.689]
plot(x, y, a)

I don't know how to fix it and why this happen.
The figure that i want is:

I have do the scatter plot of each point in second figure and there are correct but why the color is not contour.

Thank you very much.

Body:
The field returned by the UniformTriRefiner does not interpolate well in the case of the additional points. Instead it introduces new minima and maxima with values up to 20 times larger than the original points.

The plot below shows what is happening.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
import matplotlib.cm as cm

def plot(x_plot, y_plot, a_plot, ax=None):
    if ax == None: ax = plt.gca()
    x = np.array(x_plot)
    y = np.array(y_plot)
    a = np.array(a_plot)

    triang = mtri.Triangulation(x, y)
    refiner = mtri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(a, subdiv=2)

    levels = np.linspace(z_test_refi.min(), z_test_refi.max(), num=100)
    cmap = cm.get_cmap(name='jet')

    tric = ax.tricontourf(tri_refi, z_test_refi, levels=levels, cmap=cmap)
    ax.scatter(x, y, c=a, cmap=cmap, vmin= z_test_refi.min(),vmax= z_test_refi.max())
    fig.colorbar(tric, ax=ax)

    ax.set_title('stress plot')

fig, (ax, ax2) = plt.subplots(nrows=2, sharey=True,sharex=True, subplot_kw={"aspect":"equal"} )

x = [2.3384750000000003, 3.671702, 0.3356813, 3.325298666666667, 2.660479, 1.3271675666666667, 1.6680919666666665, 0.6659845666666667]
y = [0.614176, 0.5590579999999999, 0.663329, 0.24002166666666666, 0.26821433333333333, 0.31229233333333334, 0.6367503333333334, 0.3250663333333333]
a = [2.572, 0.8214, 5.689, -0.8214, -2.572, -4.292, 4.292, -5.689]
plot(x, y, a, ax)

x = [2.3384750000000003, 1.983549, 3.018193, 2.013683, 3.671702, 3.978008, 4.018905, 0.3356813, 0.0, 0.0, 1.0070439, 3.325298666666667, 2.979695, 2.660479, 1.3271675666666667, 0.9909098, 1.6680919666666665, 0.6659845666666667]
y = [0.614176, -0.038322, 0.922264, 0.958586, 0.5590579999999999, -0.1229, 0.87781, 0.663329, 1.0, 0.0, 0.989987, 0.24002166666666666, -0.079299, 0.26821433333333333, 0.31229233333333334, -0.014787999999999999, 0.6367503333333334, 0.3250663333333333]
a = [2.572, 2.572, 2.572, 2.572, 0.8214, 0.8214, 0.8214, 5.689, 5.689, 5.689, 5.689, -0.8214, -0.8214, -2.572, -4.292, -4.292, 4.292, -5.689]
plot(x, y, a, ax2)

plt.show()

As can be seen, the values of the "interpolated" field overshoot the original values by a large amount.

The reason is that by default, UniformTriRefiner.refine_field uses a cubic interpolation (a CubicTriInterpolator). The documentation states

The interpolation is based on a Clough-Tocher subdivision scheme of the triangulation mesh (to make it clearer, each triangle of the grid will be divided in 3 child-triangles, and on each child triangle the interpolated function is a cubic polynomial of the 2 coordinates). This technique originates from FEM (Finite Element Method) analysis; the element used is a reduced Hsieh-Clough-Tocher (HCT) element. Its shape functions are described in 1. The assembled function is guaranteed to be C1-smooth, i.e. it is continuous and its first derivatives are also continuous (this is easy to show inside the triangles but is also true when crossing the edges).

In the default case (kind ='min_E'), the interpolant minimizes a curvature energy on the functional space generated by the HCT element shape functions - with imposed values but arbitrary derivatives at each node.

While this is truely very technical, I emphazised some important bits, namely that the interpolation is smooth and continuous with a defined derivative. To guarantee this behaviour, overshoots are inevitable when the data is very sparse but with large amplitude fluctuations.

Here, the data is simply not suitable for cubic interpolation. One would either try to aquire denser data, or use a linear interpolation instead.


答:
You can use flexbox

.c {
border: 1px solid black;
    margin-left: auto;
    margin-right: auto;
    width: 60vw;
    height: 80vh;
    margin-top: 13vh;
}
#wrapper {
  display : flex;
  justify-content : center;
  align-items : center;
    height: 13vh;
    margin-top: 2vh;
    border: 1px solid blue;
}
#center {
    display: inline-block;
    width:12vw;
    height:10vh;
    border: 1px solid red;
}
#left {
    display: inline-block;
    width:13vh;
    height:13vh;
    border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "c">
<div>content content content</div>
<div>content content content</div>

<div id="wrapper">
    <div id="left">left</div>
    <div id="center">center</div>
</div>
<div>content content content</div>
<div>content content content</div> </code>```

Title: Centering two divs in a wrapper

Body:
I am trying to center #left and #center inside #wrapper like this:

I am trying to get #center to be in the actual center of #wrapper both horizontally and vertically, and that #left will be in a slight margin to his left. How do I achieve that?

.c {
  border: 1px solid black;
  margin-left: auto;
  margin-right: auto;
  width: 60vw;
  height: 80vh;
  margin-top: 13vh;
}

#wrapper {
  height: 13vh;
  margin-top: 2vh;
  border: 1px solid blue;
}

#center {
  display: inline-block;
  width: 12vw;
  height: 10vh;
  border: 1px solid red;
}

#left {
  display: inline-block;
  width: 13vh;
  height: 13vh;
  border: 1px solid green;
}

content content content

content content content

left

center

content content content

content content content

Jsfiddle: https://jsfiddle.net/y6r585jk/2/

Body:
You can use flexbox

.c {
border: 1px solid black;
    margin-left: auto;
    margin-right: auto;
    width: 60vw;
    height: 80vh;
    margin-top: 13vh;
}
#wrapper {
  display : flex;
  justify-content : center;
  align-items : center;
    height: 13vh;
    margin-top: 2vh;
    border: 1px solid blue;
}
#center {
    display: inline-block;
    width:12vw;
    height:10vh;
    border: 1px solid red;
}
#left {
    display: inline-block;
    width:13vh;
    height:13vh;
    border: 1px solid green;
}

<div class = "c">
<div>content content content</div>
<div>content content content</div>

<div id="wrapper">
    <div id="left">left</div>
    <div id="center">center</div>
</div>
<div>content content content</div>
<div>content content content</div>


问:
Why do we have implicit receiver in Ruby?
I have two questions regarding Ruby core OOP concepts.

I understand the differences between explicit call  (i.e. with self) and implicit call (i.e. without initialized class object or self in an instance method) of a method. When we have explicit receivers that do very neat and clear job of receiving a method with self (since it refers to the current object) rather than implicit ones (which I believe is very uncertain in situations like when to use method or variable of same name initialized), then why do we still have to call methods implicitly? Is it just a preference or is it necessary because of proper usage of private and public methods?.

In general, OOP private methods are bound within the class itself and cannot be accessed in subclasses or outside. However, those methods that need to be private but also need to be accessed in subclasses then protected methods are used over there. But in Ruby, both private and
protected methods are accessed in inherited classes, and the only difference is that private methods can only be called implicitly and protected methods can either be called implicitly or explicitly. I don't understand the philosophy over here that only because of implicit calling functionality in ruby, general definitions of private methods differ?

答:
I think you have a slight misunderstanding of the purpose of protected methods.  Protected methods can be called from methods of another instance of the same class.

```<code>class Person

  def initialize(name, age)
    @name = name
    @age = age
  end

  def older_than?(other_person)
    age > other_person.age
  end

  protected

  def age
    @age
  end

end

mother = Person.new('Carole', 34)
father = Person.new('George', 37)
</code>```

If you try...

```<code>mother.age
=>NoMethodError: protected method `age' called for #<Person:0x0000000327daa0 @name="Carole", @age=34>
</code>```

So you cannot, externally, call the #age method.

But you can do...

```<code>father.older_than?(mother)
=> true
</code>```

So the father object was able to call the mother object #age method, because he is an object of the same class Person.

Body:
I think you have a slight misunderstanding of the purpose of protected methods.  Protected methods can be called from methods of another instance of the same class.

class Person

  def initialize(name, age)
    @name = name
    @age = age
  end

  def older_than?(other_person)
    age > other_person.age
  end

  protected

  def age
    @age
  end

end

mother = Person.new('Carole', 34)
father = Person.new('George', 37)

If you try...

mother.age
=>NoMethodError: protected method `age' called for #<Person:0x0000000327daa0 @name="Carole", @age=34>

So you cannot, externally, call the #age method.

But you can do...

father.older_than?(mother)
=> true

So the father object was able to call the mother object #age method, because he is an object of the same class Person.


问:
Bash replace character into = separated values
I have the following script:

```<code>#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done

SCRIPT_PATH="$( cd -P "$( dirname "$SOURCE" )" && pwd )"/..

grep -o -P "(\w*_?)*=(\"|\').*(\"|\')" ${SCRIPT_PATH}/start.sh  > ${SCRIPT_PATH}/run.env
</code>```

That generates a file with the contents:

```<code>SOME_VAR="13434"
ANOTHER_VAR="BlAH BLAH BLAH"
</code>```

From a file that has contents:

```<code>asdf SOME_VAR="13434"\
     ANOTHER_VAR= "BlAH BLAH BLAH" some other strings
</code>```

But now I want to remove (trim) ONLY the STARTING and TAILING " characters from the generated result. In my case the result I want it to be:

```<code>SOME_VAR=13434
ANOTHER_VAR=BlAH BLAH BLAH
</code>```

Do you have any ideas how I can do that?

答:
try:

```<code>awk '{sub(/"$/,"");sub(/="/,"=")} 1'   Input_file
</code>```

Simply substituting the last occurrence of " with NULL and substituting =" with =. Then mentioning 1 there to print the edited/non-edited line

Body:
I have the following script:

#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done

SCRIPT_PATH="$( cd -P "$( dirname "$SOURCE" )" && pwd )"/..

grep -o -P "(\w*_?)*=(\"|\').*(\"|\')" ${SCRIPT_PATH}/start.sh  > ${SCRIPT_PATH}/run.env

That generates a file with the contents:

SOME_VAR="13434"
ANOTHER_VAR="BlAH BLAH BLAH"

From a file that has contents:

asdf SOME_VAR="13434"\
     ANOTHER_VAR= "BlAH BLAH BLAH" some other strings

But now I want to remove (trim) ONLY the STARTING and TAILING " characters from the generated result. In my case the result I want it to be:

SOME_VAR=13434
ANOTHER_VAR=BlAH BLAH BLAH

Do you have any ideas how I can do that?

Body:
try:

awk '{sub(/"$/,"");sub(/="/,"=")} 1'   Input_file

Simply substituting the last occurrence of " with NULL and substituting =" with =. Then mentioning 1 there to print the edited/non-edited line


问:
How to generate TypeScript UML class diagrams in VS Code?
Are there any tools that can generate a UML class diagram from a project in TypeScript or a similar language?</p>

答:
Using UML Diagram feature introduced by IntelliJ Editor by Jetbrains and it works very well with typescript.

Open the Diagram Popup

Go to Settings >>> Search for uml and find the keyboard shortcut for it.

OR

Right Click on a class name >>> Diagrams >>> Show Diagram Popup

Show class properties and methods:

Righ Click on the diagram popup >>> Show Categories >>> Methods or Properties

Tips

You will find many options to show through the right click on the diagram popup.

You can zoom on the diagram objects (If there are too much details) by holding the Alt key when hovering on them


问:
Zoom Image into a new Activity
I want to zoom an Image into a new Activity when I click on it.
To undestand what Im trying to achive I uploaded some pictures in a row.
If it is hard to understand it through a picture I could try to upload a video.
The only thing I found was this . But its only for a View. I want to start a complete new Activity or Dialog whatever.

Any suggestions how I could do it on the best way?

答:
What that you want is called 'Shared Element Activity Transition'.

A shared elements transition determines how views that are shared
  between two activities transition between these activities. For
  example, if two activities have the same image in different positions
  and sizes, the changeImageTransform shared element transition
  translates and scales the image smoothly between these activities.

It's require Android 5.0 (API level 21) and above and will be ignored for any lower API versions. Great example to understand how to implement it on your sample see here.

Solution before API 21 you need to use third-party libraries.
An example is this lib that @Markaos mentioned.

Title: Zoom Image into a new Activity


问:
Is it bad practice for me to include an "internal" package in my library?
I am designing a library, and while I know that I should only make public the classes that I want the client to access, I am having trouble sticking to this best practice.  From what I understand, this is best practice.  I decided to put a package named internal inside one of the packages in my library to hold the classes that I intend to be package-private, but may end up as public.

The way packages work in Java seems flawed since you cant make a class "parent-package-private", so is there really a "bad practice" when it comes to issues like this?

答:
Wait for Java 9, things will clear up. The new
module structure will allow restriction of public
classes anywhere outside the module.

But even till then, note that access isn't really enforceable. With the right usage of reflection you can access just anything, even private (not sure but I think Java 9's module will not give access through reflection).

Access modifiers are merely a note to the user "don't rely on me, I may change". If access modifiers are not possible, I'd consider it completely ok to give that note in some other way. Even the JDK has the sun and com.sun packages that are fully accessible but everybody knows that you shouldn't build code on them.

Looking in some popular APIs I find the package name internal quite often, so you're ok IMHO.


问:
How to reset allocated memory and resources in c?
My program consists of a Menu, where you can select 1 of 2 options.
The second is just to exit the program. The first, however, is where you can find a specific sequence of bits that you choose, in a separate ".txt" file with 100.000 lines.

It does what I want the first time, and then returns to the Menu.

The problem is when the user goes for a second (or more) search. The program prints on screen random information.
It seems like I didn't do a "reset" of the resources, memory or values on     the first search.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{

    char ID[8];
    char content[2048];
    int distance;

} DATA;

void search(){

    FILE *f;
    DADO *z=NULL;
    long int tot=0;
    int a;
    int c;
    int i;
    int j=1;
    int k=0;
    char e;
    char b[2048];

    printf("\n");

    f=fopen("DANGER_DB_LARGE.txt", "r");

    printf("\n");
    printf("How many results do you wish?\n");
    scanf("%d",&a);

    printf("Introduce the sequence:\n");
    scanf("%s",b);
    c=strlen(b);

    printf("\n");

    z=(DATA*)realloc(z,(++tot)*sizeof(DATA));

    while(e!=EOF){
        e=fgetc(f);

        if(k<8){
            z[tot-1].ID[k]=e;
        }
        else if(k==8 && e=='\t'){
            continue;
        }
        else if(k>=9 && e!='\n'){
            z[tot-1].content[k-9]=e;
        }
        else if(e=='\n'){
            k=(-1);
            z=(DATA*)realloc(z,(++tot)*sizeof(DATA));
        }
        k++;
    }

    for(i=1; i<=tot; i++){
        distance(z,i,c,b);
    }

    free(z);
    fclose(f);
}
</code>```

I proceed to store the ID and content of every single one of those 100.000 lines of text. I end the function by doing free(z), but when I search again the program just prints random stuff.

答:
Realloc returns void by the way

```<code>void *realloc(void *ptr, size_t size)
</code>```

plus it takes a pointer as input so its pass by reference.

update: This function returns a pointer to the newly allocated memory, or NULL if the request fails.

my bad.

Body:
My program consists of a Menu, where you can select 1 of 2 options.
The second is just to exit the program. The first, however, is where you can find a specific sequence of bits that you choose, in a separate ".txt" file with 100.000 lines.

It does what I want the first time, and then returns to the Menu.

The problem is when the user goes for a second (or more) search. The program prints on screen random information.
It seems like I didn't do a "reset" of the resources, memory or values on     the first search.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{

    char ID[8];
    char content[2048];
    int distance;

} DATA;

void search(){

    FILE *f;
    DADO *z=NULL;
    long int tot=0;
    int a;
    int c;
    int i;
    int j=1;
    int k=0;
    char e;
    char b[2048];

    printf("\n");

    f=fopen("DANGER_DB_LARGE.txt", "r");

    printf("\n");
    printf("How many results do you wish?\n");
    scanf("%d",&a);

    printf("Introduce the sequence:\n");
    scanf("%s",b);
    c=strlen(b);

    printf("\n");

    z=(DATA*)realloc(z,(++tot)*sizeof(DATA));

    while(e!=EOF){
        e=fgetc(f);

        if(k<8){
            z[tot-1].ID[k]=e;
        }
        else if(k==8 && e=='\t'){
            continue;
        }
        else if(k>=9 && e!='\n'){
            z[tot-1].content[k-9]=e;
        }
        else if(e=='\n'){
            k=(-1);
            z=(DATA*)realloc(z,(++tot)*sizeof(DATA));
        }
        k++;
    }

    for(i=1; i<=tot; i++){
        distance(z,i,c,b);
    }

    free(z);
    fclose(f);
}

I proceed to store the ID and content of every single one of those 100.000 lines of text. I end the function by doing free(z), but when I search again the program just prints random stuff.

Body:
Realloc returns void by the way

void *realloc(void *ptr, size_t size)

plus it takes a pointer as input so its pass by reference.

update: This function returns a pointer to the newly allocated memory, or NULL if the request fails.

my bad.


问:
How does this pointer aliasing work?
https://kukuruku.co/post/i-do-not-know-c/

Problem #7:

```<code>#include <stdio.h>
void f(int *i, long *l)
{
  printf("1. v=%ld\n", *l); /* (1) */
  *i = 11;                  /* (2) */
  printf("2. v=%ld\n", *l); /* (3) */
}
int main()
{
  long a = 10;
  f((int *) &a, &a);
  printf("3. v=%ld\n", a);
  return 0;
}
</code>```

Output on two different compilers on a little endian system is:

```<code>1. v=10    2. v=11    3. v=11
1. v=10    2. v=10    3. v=11
</code>```

How is the second result possible ? I didn't quite get how the explanation that explains the result by referring to strict aliasing. Does the compiler ignore the line (2) totally ?

答:
The second result is made possible by the fact that the value of *l cannot change between (1) and (3).  (The strict aliasing rule ensures that.)

Thus, the program only needs to compute its value once, and the compiler has generated code equivalent to

```<code>void f(int *i, long *l)
{
  long l2 = *l;
  printf("1. v=%ld\n", l2); /* (1) */
  *i = 11;                  /* (2) */
  printf("2. v=%ld\n", l2); /* (3) */
}
</code>```

Title: How does this pointer aliasing work?

Body:
https://kukuruku.co/post/i-do-not-know-c/

Problem #7:

#include <stdio.h>
void f(int *i, long *l)
{
  printf("1. v=%ld\n", *l); /* (1) */
  *i = 11;                  /* (2) */
  printf("2. v=%ld\n", *l); /* (3) */
}
int main()
{
  long a = 10;
  f((int *) &a, &a);
  printf("3. v=%ld\n", a);
  return 0;
}

Output on two different compilers on a little endian system is:

1. v=10    2. v=11    3. v=11
1. v=10    2. v=10    3. v=11

How is the second result possible ? I didn't quite get how the explanation that explains the result by referring to strict aliasing. Does the compiler ignore the line (2) totally ?

Body:
The second result is made possible by the fact that the value of *l cannot change between (1) and (3).  (The strict aliasing rule ensures that.)

Thus, the program only needs to compute its value once, and the compiler has generated code equivalent to

void f(int *i, long *l)
{
  long l2 = *l;
  printf("1. v=%ld\n", l2); /* (1) */
  *i = 11;                  /* (2) */
  printf("2. v=%ld\n", l2); /* (3) */
}


问:
How do I get PHP to work with ADOdb and MySQL?
I'm trying to get a PHP site working in IIS on Windows Server with MySQL.

I'm getting this error…

Fatal error: Call to undefined function mysql_connect() in C:\inetpub...\adodb\drivers\adodb-mysql.inc.php on line 363

Update…

This link outlines the steps I followed to install PHP on my server:

How do I get PHP and MySQL working on IIS 7.0 ?

(note especially steps 6 and 8 regarting php.ini and php_mysql.dll).

Only two lines in the phpinfo report reference SQL:

```<code><?php
    phpinfo();
?>
</code>```

Configure Command:

cscript /nologo configure.js "--enable-snapshot-build" "--enable-mysqlnd"

sql.safe_mode:

Local Value Off, Master Value Off

PHP Configure Command http://img79.imageshack.us/img79/2373/configurecommandmw8.gif

PHP sql.safe_mode http://img49.imageshack.us/img49/3066/sqlsafemoderu6.gif

Update…

I found the solution: How do I install MySQL modules within PHP?

答: I found the solution: How do I install MySQL modules within PHP?</p>

OwnerDisplayName: Zack

Body:
I'm trying to get a PHP site working in IIS on Windows Server with MySQL.

I'm getting this error…

Fatal error: Call to undefined function mysql_connect() in C:\inetpub...\adodb\drivers\adodb-mysql.inc.php on line 363

Update…

This link outlines the steps I followed to install PHP on my server:

How do I get PHP and MySQL working on IIS 7.0 ?

(note especially steps 6 and 8 regarting php.ini and php_mysql.dll).

Only two lines in the phpinfo report reference SQL:

<?php
    phpinfo();
?>

Configure Command:

cscript /nologo configure.js "--enable-snapshot-build" "--enable-mysqlnd"

sql.safe_mode:

Local Value Off, Master Value Off

PHP Configure Command http://img79.imageshack.us/img79/2373/configurecommandmw8.gif

PHP sql.safe_mode http://img49.imageshack.us/img49/3066/sqlsafemoderu6.gif

Update…

I found the solution: How do I install MySQL modules within PHP?

LastEditorDisplayName: Zack


问:
Splitting strings into text and number?
Let’s say I have this string 'foo1bar2xyz'

I know the indexes for the digits in it {'1': 3, '2': 7}

I want to form substrings of the parent string which don’t have the numbers. How would I get substrings of a string removing particular indexes?

Which in the above case which would be ['foo', 'bar', 'xyz']

Have tried this so far

```<code>def iterate_string(og_string, start, stop):
    if start == 0:
        return og_string[:stop]
    else:
        return og_string[start+1:stop]

def ret_string(S):
    digit_dict = {c:i for i,c in enumerate(S) if c.isdigit()}
    digit_positions = list(digit_dict.values())
    # return digit_positions
    substrings = []
    start_index = 0
    for position in digit_positions:
        p = iterate_string(S, start_index, position)
        substrings.append(p)
        start_index = position

    return substrings

print ret_string('foo1bar2xyz')
</code>```

But this returns ['foo', 'bar']

Relevant SO questions

答:
If you have the indices and want to use as the input, then that's a good idea too:

```<code>def split_by_indices(s, indices):
    ends = sorted(indices.values())  # we only need the positions
    ends.append(len(s))
    substrings = []
    start = 0
    for end in ends:
        substrings.append(s[start:end])
        start = end + 1
    return substrings
</code>```

Demo:

```<code>>>> split_by_indices('foo1bar2xyz', {'1': 3, '2': 7})
['foo', 'bar', 'xyz']
</code>```

This ignores any actual numeric values in the input string and uses the [3, 7] positions from your dictionary only.

However, if you are currently building the {'1': 3, '2': 7} map just to split your string, it is probably easier to just use a regular expression:

```<code>import re

split_by_digits = re.compile(r'\d').split
result = split_by_digits(inputstring)
</code>```

Title: Splitting strings into text and number?

Body:
Let’s say I have this string 'foo1bar2xyz'

I know the indexes for the digits in it {'1': 3, '2': 7}

I want to form substrings of the parent string which don’t have the numbers. How would I get substrings of a string removing particular indexes?

Which in the above case which would be ['foo', 'bar', 'xyz']

Have tried this so far

def iterate_string(og_string, start, stop):
    if start == 0:
        return og_string[:stop]
    else:
        return og_string[start+1:stop]

def ret_string(S):
    digit_dict = {c:i for i,c in enumerate(S) if c.isdigit()}
    digit_positions = list(digit_dict.values())
    # return digit_positions
    substrings = []
    start_index = 0
    for position in digit_positions:
        p = iterate_string(S, start_index, position)
        substrings.append(p)
        start_index = position

    return substrings

print ret_string('foo1bar2xyz')

But this returns ['foo', 'bar']

Relevant SO questions

Body:
If you have the indices and want to use as the input, then that's a good idea too:

def split_by_indices(s, indices):
    ends = sorted(indices.values())  # we only need the positions
    ends.append(len(s))
    substrings = []
    start = 0
    for end in ends:
        substrings.append(s[start:end])
        start = end + 1
    return substrings

Demo:

>>> split_by_indices('foo1bar2xyz', {'1': 3, '2': 7})
['foo', 'bar', 'xyz']

This ignores any actual numeric values in the input string and uses the [3, 7] positions from your dictionary only.

However, if you are currently building the {'1': 3, '2': 7} map just to split your string, it is probably easier to just use a regular expression:

import re

split_by_digits = re.compile(r'\d').split
result = split_by_digits(inputstring)


问:
How to manually set the class width of histograms in Weka?
I have an instance with values between 0 and 20 (these are school grades). I want to make a histogram with 21 classes, each representing a single grade. The default histograms in the Weka Explorer use Scott's rule to set the class width and amount of classes, but I cannot find a way to change this.</p>

答: If I understand correctly, you have numeric data for the school grade.  You can use the unsupervised attribute filter NumericToNominal to convert the attribute and get your 21 distinct values.


问:
Why is the extended method not over-riding the parent method
I need to be able to run a child method from the parent class.
I am calling the child function $this->getPlan, but it is not calling the child plan, but only the parent one. I thought an extended class over-rides the function.
Here is my code

```<code>class logon{
    public function getPlan(){}
    public function __construct(){
    }
    public function checkWorks(){
        $this->getPlan();
    }
}

class plan extends logon{
    function __construct(){
        parent::__construct();
    }
    public function getPlan(){
        echo "test";
    }
}
$logon = new logon();
$plan = new plan();

$logon->checkWorks();
</code>```

However if I call the code from the parent constructor like this, it calls my child method.

```<code>public function __construct(){
      $this->getPlan();
    }
</code>```

I don't want to use an abstract class to do this, as there is a good reason for this.
Can anyone tell me why my parent method is not being over-ridden by the child class?

答:
I have solved the problem a different way.
The initial problem was this. I needed to include logon class in plan so that I could access the database. The problem was that logon needed to run a method in plan, and I couldn't include the plan class as that would have created a cyclic problem.

My solution was halfway there, but I have a proper solution. By making the plan class a child solved the problem of not including logon to access the database, but I still could call a method in plan. Now I am not including logon in plan I can include plan in logon which has solved the problem, and it works. Here is my solution. Now I can access my method from both classes. I knew I would find a way if I just tried hard enough.

```<code>class logon{
    public function __construct(){
    }
    public function checkWorks(){
        $p= new plan();
        $p->getPlan();
    }
}

class plan extends logon{

    public function __construct(){
        parent::__construct();
    }
    public function getPlan(){
        echo "test";
    }
}

$logon = new logon();
$logon->checkWorks();
</code>```

Body:
I need to be able to run a child method from the parent class.
I am calling the child function $this->getPlan, but it is not calling the child plan, but only the parent one. I thought an extended class over-rides the function.
Here is my code

class logon{
    public function getPlan(){}
    public function __construct(){
    }
    public function checkWorks(){
        $this->getPlan();
    }
}

class plan extends logon{
    function __construct(){
        parent::__construct();
    }
    public function getPlan(){
        echo "test";
    }
}
$logon = new logon();
$plan = new plan();

$logon->checkWorks();

However if I call the code from the parent constructor like this, it calls my child method.

public function __construct(){
      $this->getPlan();
    }

I don't want to use an abstract class to do this, as there is a good reason for this.
Can anyone tell me why my parent method is not being over-ridden by the child class?

Body:
I have solved the problem a different way.
The initial problem was this. I needed to include logon class in plan so that I could access the database. The problem was that logon needed to run a method in plan, and I couldn't include the plan class as that would have created a cyclic problem.

My solution was halfway there, but I have a proper solution. By making the plan class a child solved the problem of not including logon to access the database, but I still could call a method in plan. Now I am not including logon in plan I can include plan in logon which has solved the problem, and it works. Here is my solution. Now I can access my method from both classes. I knew I would find a way if I just tried hard enough.

class logon{
    public function __construct(){
    }
    public function checkWorks(){
        $p= new plan();
        $p->getPlan();
    }
}

class plan extends logon{

    public function __construct(){
        parent::__construct();
    }
    public function getPlan(){
        echo "test";
    }
}

$logon = new logon();
$logon->checkWorks();


问:
Is it okay to have a very long .htaccess file?
I am giving out URLs to people on a website, that actually point to something ugly (on the same website).

http://www.mydomain.com/cool-URL

actually points to

http://www.mydomain.com/boring.php?id=478547&sessid=34734asdf7&otherboringdetails

I'm planning to achieve this by modifying the .htaccess file whenever needed. I'm going to make the PHP script write to the .htaccess file, adding a new rewrite rule whenever there is a new hand-out of a url (from an admin area a non-programmer can control [specify the URL title for this new entry, admin : it will be assigned automagically]).

Is this going to be a problem, especially after 1000 or so such URLs? What is the actual number that is acceptable? Because, I can picture this: the server receives a request for a URL, then it searches the .htaccess file for the right page for this url, and finally sends the user to the right page. If this is anything like Database searching, it might take a long time for the user to actually get to the right page...

Any pointers on this, please?

答:
No, it's not OK and will hamper your page-load speed.

.htaccess files are evaluated on EVERY server request. Even for static images, CSS and JS files. So, you're asking the webserver to parse 1000+ long possibly REGEX lines while executing a request.

Also, parent directory's .htaccess file is processed for files residing in subdirectory too. So, if your large .htaccess is in root directory of website, then it will be processed for all requests made for files in the subdirectories too (along with the .htaccess file in subdirectory).

That my friend is a lot of processing. If you have a page with 10 images (for example) it gets processes 11 times. And the more processing in the file, then the more cycles it takes. So yes, anything in a htaccess file has an impact. Now is that impact noticeable? It is hard to say when it becomes an issue. But it would have to be pretty big as the processing in relatively simple, which in your case is.

The key with an htaccess file is to make it smart. You would not want to list 200 entries. You can so it smart with just a few lines (if you want to use htaccess).


问:
Can't install Microsoft SQL Server Data Tools
I get the following errors when I want to install the Microsoft Server Data Tools:

```<code>[1F7C:1F80][2016-10-19T10:22:28]: Error 0x80044000: Process returned error: 0x80044000
[1F7C:1F80][2016-10-19T10:22:28]: Error 0x80044000: Failed to execute EXE package.
[1D9C:1DA0][2016-10-19T10:22:28]: Error 0x80044000: Failed to configure per-machine EXE package.
[1D9C:1DA0][2016-10-19T10:22:28]: Applied execute package: DEV14ISOSHELLLP, result: 0x80044000, restart: None
[1D9C:1DA0][2016-10-19T10:22:28]: Error 0x80044000: Failed to execute EXE package.
[1F7C:1F80][2016-10-19T10:22:28]: Removing cached package: DEV14ISOSHELLLP, from path: C:\ProgramData\Package Cache\F1CC37BA16D64D101B05001079E51654F38CCE76\
[1F7C:1F80][2016-10-19T10:22:32]: Removed bundle dependency provider: {c2e27636-4c63-47f9-b361-8c61ea7cd504}
[1F7C:1F80][2016-10-19T10:22:32]: Removing cached bundle: {c2e27636-4c63-47f9-b361-8c61ea7cd504}, from path: C:\ProgramData\Package Cache\{c2e27636-4c63-47f9-b361-8c61ea7cd504}\
[1D9C:1DA0][2016-10-19T10:22:32]: Apply complete, result: 0x80044000, restart: None, ba requested restart:  No
</code>```

to get the Tab Item "Server Object Explorer" and the whole funcionality.

Microsoft Visual Studio 2015 Community Edition

And the installer official from Microsoft page

答:
Maybe people still looking for solution of this, I was able to solve this by updating my windows specifically with updates of
KB2919355.

once I installed those updates reboot, restarted the SSDT installation all worked out.

hope it helps others that looking for the solution.

regards

Body:
I get the following errors when I want to install the Microsoft Server Data Tools:

[1F7C:1F80][2016-10-19T10:22:28]: Error 0x80044000: Process returned error: 0x80044000
[1F7C:1F80][2016-10-19T10:22:28]: Error 0x80044000: Failed to execute EXE package.
[1D9C:1DA0][2016-10-19T10:22:28]: Error 0x80044000: Failed to configure per-machine EXE package.
[1D9C:1DA0][2016-10-19T10:22:28]: Applied execute package: DEV14ISOSHELLLP, result: 0x80044000, restart: None
[1D9C:1DA0][2016-10-19T10:22:28]: Error 0x80044000: Failed to execute EXE package.
[1F7C:1F80][2016-10-19T10:22:28]: Removing cached package: DEV14ISOSHELLLP, from path: C:\ProgramData\Package Cache\F1CC37BA16D64D101B05001079E51654F38CCE76\
[1F7C:1F80][2016-10-19T10:22:32]: Removed bundle dependency provider: {c2e27636-4c63-47f9-b361-8c61ea7cd504}
[1F7C:1F80][2016-10-19T10:22:32]: Removing cached bundle: {c2e27636-4c63-47f9-b361-8c61ea7cd504}, from path: C:\ProgramData\Package Cache\{c2e27636-4c63-47f9-b361-8c61ea7cd504}\
[1D9C:1DA0][2016-10-19T10:22:32]: Apply complete, result: 0x80044000, restart: None, ba requested restart:  No

to get the Tab Item "Server Object Explorer" and the whole funcionality.

Microsoft Visual Studio 2015 Community Edition

And the installer official from Microsoft page


问:
How can i solve this error with camera permission on android?
I am a student and I was asked to make an app about image recognition, but when I try to use the camera I always get:

E/CameraService: Permission Denial: can't use the camera

The thing is that I add the permission on the manifest and I also used the on runtime permission request:

```<code>public void onScanButtonClicked(View view) {

    String[] permissos = {"android.permission.CAMERA"};

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this,
                permissos,
                MY_PERMISSIONS_REQUEST_CAMERA
        );
    }
      startActivity(new Intent(this, ScanActivity.class));
 }
</code>```

Here is my manifest:

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.camera2" />
    <uses-feature android:name="android.hardware.camera.any" />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".ScanActivity"
        android:label="@string/app_name"

        android:configChanges="orientation|screenSize"
        android:exported="true">
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-feature
            android:name="android.hardware.camera2"
            android:required="false" />
        <uses-feature
            android:name="android.hardware.camera.any"
            android:required="false" />

    </activity>
</application>
</code>```

答:
I had similar problem.
My manifest file was like

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"

        package="com.example.ildar.textureview">

        <uses-permission android:name="android.permission.CAMERA" />
        <uses-feature android:name="android.hardware.camera" android:required="true"/>
        <uses-feature android:name="android.hardware.camera.autofocus" />

    ....

</manifest>
</code>```

And the code that solved my problem:

```<code>if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){

            mCamera = Camera.open();
        }else{
            ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.CAMERA}, 0);
        }
</code>```

In other words, if permission wasn't granted for me, I request it programmatically

Body:
I am a student and I was asked to make an app about image recognition, but when I try to use the camera I always get:

E/CameraService: Permission Denial: can't use the camera

The thing is that I add the permission on the manifest and I also used the on runtime permission request:

public void onScanButtonClicked(View view) {

    String[] permissos = {"android.permission.CAMERA"};

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this,
                permissos,
                MY_PERMISSIONS_REQUEST_CAMERA
        );
    }
      startActivity(new Intent(this, ScanActivity.class));
 }

Here is my manifest:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.camera2" />
    <uses-feature android:name="android.hardware.camera.any" />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".ScanActivity"
        android:label="@string/app_name"

        android:configChanges="orientation|screenSize"
        android:exported="true">
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-feature
            android:name="android.hardware.camera2"
            android:required="false" />
        <uses-feature
            android:name="android.hardware.camera.any"
            android:required="false" />

    </activity>
</application>

Body:
I had similar problem.
My manifest file was like

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

        package="com.example.ildar.textureview">

        <uses-permission android:name="android.permission.CAMERA" />
        <uses-feature android:name="android.hardware.camera" android:required="true"/>
        <uses-feature android:name="android.hardware.camera.autofocus" />

    ....

</manifest>

And the code that solved my problem:

if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){

            mCamera = Camera.open();
        }else{
            ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.CAMERA}, 0);
        }

In other words, if permission wasn't granted for me, I request it programmatically


问:
C# return method running twice, though only called once
I have this code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            ReturnRandomNumber();
            Console.WriteLine("The number returned by ReturnRandomNumber was: " + ReturnRandomNumber());
            Console.ReadKey();
        }

        static int ReturnRandomNumber()
        {
            Console.WriteLine("This string should only be displayed once, since the method is only called once...");
            Random random = new Random();
            int numberToReturn = random.Next(1, 100);
            Console.WriteLine("So should this string...");

            return numberToReturn;
        }
    }
}
</code>```

The console output when I run the program is:

```
This string should only be displayed once, since the method is only called once...
So should this string...
This string should only be displayed once, since the method is only called once...
So should this string...
The number returned by ReturnRandomNumber was: [some random number between 1-100]
```

I only call ReturnRandomNumber() once from my main method, so why is it apparently run twice?

If I make ReturnRandomNumber a void, and comment out the return line, as well as the WriteLine in Main, the method is only run once, so the double run must have something to do with the return - I just can't figure out what?!

Thanks for your help!

答:
You are calling the method twice.  Once in the first line of main:

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

The second time in your writeline statement:

```<code>Console.WriteLine("The number returned by ReturnRandomNumber was: " + ReturnRandomNumber());
</code>```

If you only want to call the method once, and keep the value for displaying later, you should do something like this:

```<code>static void Main(string[] args)
{
     int number = ReturnRandomNumber();
     Console.WriteLine("The number returned by ReturnRandomNumber was: " + number);
     Console.ReadKey();
}
</code>```

return in a method just means it returns the value.  If you want use the value returned, you need to keep it for later - so store the result in a variable.

You already do this with out realizing it when using Random.Next(1,100).  Random is a class, and Next is a method on that class that returns a value.

Body:
I have this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            ReturnRandomNumber();
            Console.WriteLine("The number returned by ReturnRandomNumber was: " + ReturnRandomNumber());
            Console.ReadKey();
        }

        static int ReturnRandomNumber()
        {
            Console.WriteLine("This string should only be displayed once, since the method is only called once...");
            Random random = new Random();
            int numberToReturn = random.Next(1, 100);
            Console.WriteLine("So should this string...");

            return numberToReturn;
        }
    }
}

The console output when I run the program is:

This string should only be displayed once, since the method is only called once...
So should this string...
This string should only be displayed once, since the method is only called once...
So should this string...
The number returned by ReturnRandomNumber was: [some random number between 1-100]

I only call ReturnRandomNumber() once from my main method, so why is it apparently run twice?

If I make ReturnRandomNumber a void, and comment out the return line, as well as the WriteLine in Main, the method is only run once, so the double run must have something to do with the return - I just can't figure out what?!

Thanks for your help!

Body:
You are calling the method twice.  Once in the first line of main:

ReturnRandomNumber();

The second time in your writeline statement:

Console.WriteLine("The number returned by ReturnRandomNumber was: " + ReturnRandomNumber());

If you only want to call the method once, and keep the value for displaying later, you should do something like this:

static void Main(string[] args)
{
     int number = ReturnRandomNumber();
     Console.WriteLine("The number returned by ReturnRandomNumber was: " + number);
     Console.ReadKey();
}

return in a method just means it returns the value.  If you want use the value returned, you need to keep it for later - so store the result in a variable.

You already do this with out realizing it when using Random.Next(1,100).  Random is a class, and Next is a method on that class that returns a value.


问:
Maven deploy check md5 before deploy
I m using maven 3 and i work on an OSGi project with many module.
Each module have different version, so when someone do a modification, he need to update the version to -SNAPSHOT. But  Sometime people forgot to change the version so when deploy is made, nothing is deploy, and new code is not embeded in the release.
That why i want to overide deploy maven plugin to add a md5 verification only on release jar ( not snapshot because i m sure that they are deployed) and write an log.warn to say "check version for module X because it s seems module have change but version is the same as before"

Currenlty when i doing deploy, i got release jar for a module and i compare md5 with jar in my target directory, but because of MANIFEST, md5 is never the same so i got always my warning.
I change a little the code to check the md5 file by file, and now i can so a report of the different file without checking a list of file (MANIFEST....)
But if 90% of file have same md5, other not, but if. I open 2 different file, in reality they are identic...just because nexus jar is build on linux and target jar is build on windows...some file differ and many other not...

How can i create a jar build on linux or windows with same md5? Does it possible or it depends on many things like processeur, linux/windows?

Thanks by advance and if you have any other idea to do what i want in other manear...

答:
You could improve your release process by not allowing that stable versions are allowed in your commits. In fact, commits should be made in SNAPSHOT versions. So how can you guarantee this? You can write a pre-hook commit that verifies if the pom.xml of this project that is being commited has a SNAPSHOT on his version property.

So before deploying your module, you run your release process, commiting the POM to a stable version. That's what Maven Release Plugin does, for example.

Title: Maven deploy check md5 before deploy


问:
Create a program that calculates the square root of a number without using Math.sqrt
This is the formula that can be used to calculate the square root of a number.

```<code>result=(guess+(number/guess))/2;
</code>```

For example, I need to get the square root of 9. First, I need to make a guess. For this one, it's 6. Although, I know that the square root of 9 is 3, I chose 6 to show how the program should work.

that makes...

```<code>result=(6+(9/6))/2 which is equal to 3.75.
</code>```

To get the actual square root of 9, I need to make the result the new guess.The program should continue as...

```<code>result=(3.75+(9/3.75))/2 which is equal to 3.075.
</code>```

This process should continue till difference between result and the result after it is equal to 0. For example

```<code>result=(3+(9/3))/2 is always equal to 3.
</code>```

When the value of result is passed to guess, the next result will also be 3. That means 3 is the square root of nine.

Here's my code:

```<code>package javaPackage;

public class SquareRoot {

    public static void main(String[] args) {
        calcRoot();
    }

    public static void calcRoot(){
        double num=9;
        double guess=6;
        double result=0;

        while(Math.abs(guess-ans)!=0){
            result=(guess+(num/guess))/2;
            guess=result;
        }
    System.out.print(result);
    }
}
</code>```

Output

```<code>3.75
</code>```

My problem is I can't compare the value of result and the previous result. Since guess is equal to result, the program immediately since guess and result are already equal. How can I fix it?

答:
For performance,following this code:

```<code>    public static double sqrt(double num) {
    double half = 0.5 * num;
    long bit = Double.doubleToLongBits(num);
    bit = 0x5fe6ec85e7de30daL - (bit >> 1);
    num = Double.longBitsToDouble(bit);

    for (int index = 0; index < 4; index++) {
        num = num * (1.5f - half * num * num);
    }

    return 1 / num;
}
</code>```

About the magic number 0x5fe6ec85e7de30daL,you can see the FAST INVERSE SQUARE ROOT
Let's see the performance,the test code:

```<code>    double test = 123456;

    //trigger the jit compiler
    for (int index = 0; index < 100000000; index++) {
        sqrt(test);
    }
    for (int index = 0; index < 100000000; index++) {
        Math.sqrt(test);
    }

    //performance
    long start = System.currentTimeMillis();
    for (long index = 0; index < 10000000000L; index++) {
        sqrt(test);
    }
    System.out.println("this:"+(System.currentTimeMillis() - start));
    start = System.currentTimeMillis();
    for (long index = 0; index < 10000000000L; index++) {
        Math.sqrt(test);
    }
    System.out.println("system:"+(System.currentTimeMillis() - start));

    System.out.println(sqrt(test));
    System.out.println(Math.sqrt(test));
</code>```

and the result is:

```<code>this:3327
system:3236
this result:351.363060095964
system result:351.363060095964
</code>```

Body:
This is the formula that can be used to calculate the square root of a number.

result=(guess+(number/guess))/2;

For example, I need to get the square root of 9. First, I need to make a guess. For this one, it's 6. Although, I know that the square root of 9 is 3, I chose 6 to show how the program should work.

that makes...

result=(6+(9/6))/2 which is equal to 3.75.

To get the actual square root of 9, I need to make the result the new guess.The program should continue as...

result=(3.75+(9/3.75))/2 which is equal to 3.075.

This process should continue till difference between result and the result after it is equal to 0. For example

result=(3+(9/3))/2 is always equal to 3.

When the value of result is passed to guess, the next result will also be 3. That means 3 is the square root of nine.

Here's my code:

package javaPackage;

public class SquareRoot {

    public static void main(String[] args) {
        calcRoot();
    }

    public static void calcRoot(){
        double num=9;
        double guess=6;
        double result=0;

        while(Math.abs(guess-ans)!=0){
            result=(guess+(num/guess))/2;
            guess=result;
        }
    System.out.print(result);
    }
}

Output

3.75

My problem is I can't compare the value of result and the previous result. Since guess is equal to result, the program immediately since guess and result are already equal. How can I fix it?

Body:
For performance,following this code:

    public static double sqrt(double num) {
    double half = 0.5 * num;
    long bit = Double.doubleToLongBits(num);
    bit = 0x5fe6ec85e7de30daL - (bit >> 1);
    num = Double.longBitsToDouble(bit);

    for (int index = 0; index < 4; index++) {
        num = num * (1.5f - half * num * num);
    }

    return 1 / num;
}

About the magic number 0x5fe6ec85e7de30daL,you can see the FAST INVERSE SQUARE ROOT
Let's see the performance,the test code:

    double test = 123456;

    //trigger the jit compiler
    for (int index = 0; index < 100000000; index++) {
        sqrt(test);
    }
    for (int index = 0; index < 100000000; index++) {
        Math.sqrt(test);
    }

    //performance
    long start = System.currentTimeMillis();
    for (long index = 0; index < 10000000000L; index++) {
        sqrt(test);
    }
    System.out.println("this:"+(System.currentTimeMillis() - start));
    start = System.currentTimeMillis();
    for (long index = 0; index < 10000000000L; index++) {
        Math.sqrt(test);
    }
    System.out.println("system:"+(System.currentTimeMillis() - start));

    System.out.println(sqrt(test));
    System.out.println(Math.sqrt(test));

and the result is:

this:3327
system:3236
this result:351.363060095964
system result:351.363060095964