Title: add first entry into next line and shift data after comma & underscore from previous line to the next line

Body:
Data after underscore and comma will go to next line and data from beginning to pipe add before them.

sample data:

1.2.4.0/24|24151_24409_24406
37.99.128.0/19|47794_47795,48695
37.142.128.0/17|21450,65555

expected result should be:

1.2.4.0/24|24151
1.2.4.0/24|24409
1.2.4.0/24|24406
37.99.128.0/19|47794
37.99.128.0/19|47795
37.99.128.0/19|48695
37.142.128.0/17|21450
37.142.128.0/17|65555

Is there a way to do it?

Body:
gawk solution:

awk -F'|' '{ n=split($2,a,/[_,]/); for(i=1;i<=n;i++) print $1,a[i] }' OFS='|' file

The output:

1.2.4.0/24|24151
1.2.4.0/24|24409
1.2.4.0/24|24406
37.99.128.0/19|47794
37.99.128.0/19|47795
37.99.128.0/19|48695
37.142.128.0/17|21450
37.142.128.0/17|65555

split($2,a,/[_,]/) - divide the 2nd field value into pieces defined by pattern /[_,]/ and returns the number of elements created n


来源: stackexchange

问:
Google play store can't upload apk
I can't find any reason why the store doesn't accept any apks on new apps and others, it every time return please upload another apk

1.0, app code 1 brand new app returns same error with 2 different dev accounts on 4 different vpn(Netherlands/germanmy/singapur..) and 2 different browsers?(opera/safari) also I have deleted cookies etc

my signin in that project is react native

```<code>  signingConfigs {
        release {
            storeFile file("key.jks")
            storePassword "dosa"
            keyAlias "dsa"
            keyPassword "dsa"
            v2SigningEnabled true
        }
    }
</code>```

答:
1.0, app code 1 brand new app returns same error with 2 different dev accounts on 4 different vpn(Netherlands/germanmy/singapur..) and 2
  different browsers?(opera/safari) also I have deleted cookies etc

I tried with Firefox and it worked thanks...

ContentLicense: CC BY-SA 3.0

Title: Google play store can't upload apk

Body:
I can't find any reason why the store doesn't accept any apks on new apps and others, it every time return please upload another apk

1.0, app code 1 brand new app returns same error with 2 different dev accounts on 4 different vpn(Netherlands/germanmy/singapur..) and 2 different browsers?(opera/safari) also I have deleted cookies etc

my signin in that project is react native

  signingConfigs {
        release {
            storeFile file("key.jks")
            storePassword "dosa"
            keyAlias "dsa"
            keyPassword "dsa"
            v2SigningEnabled true
        }
    }


问:
When creating game object position is wrong when set
This is my code

```<code>GameObject tocreate = new GameObject ("newsstory1");
    tocreate.AddComponent<SpriteRenderer> ();
    tocreate.GetComponent<SpriteRenderer> ().sprite = newsbuilten;

    tocreate.transform.parent = notifcationparents.transform;
    tocreate.transform.localScale = new Vector3 (6, 6, 0);
    tocreate.transform.position = new Vector3 (80, 18 ,5);
</code>```

My problem is when I run this the game object is in the wrong position; here is the image

答:
Don't use transform.parent, instead use transform.SetParent().
Also, first set the position of the game object and then set it's parent using transform.SetParent(parent, true).</p>

Body:
This is my code

GameObject tocreate = new GameObject ("newsstory1");
    tocreate.AddComponent<SpriteRenderer> ();
    tocreate.GetComponent<SpriteRenderer> ().sprite = newsbuilten;

    tocreate.transform.parent = notifcationparents.transform;
    tocreate.transform.localScale = new Vector3 (6, 6, 0);
    tocreate.transform.position = new Vector3 (80, 18 ,5);

My problem is when I run this the game object is in the wrong position; here is the image


问:
Unexpected behavior when printing out char array
i'm currently trying to debug my program over UART by printing the values of some variables at specific points. My issue is with printing two char arrays. The order in which i print them seems to have an effect on if it prints. The declarations of the arrays are in a struct in a header file as follows-

```<code>//header file
typedef struct
{
  char latitude[10];
  char longitude[11];
}NMEA_RMC_t;

NMEA_RMC_t rmc;
</code>```

The char arrays are manipulated in another function after parsing data from an input. They are not updated with an interrupt, although there are interrupts elsewhere in the program. In the main code if i print them as follows-

```<code>//main program loop
printf("lat: %s \t long: %s \n", rmc.latitude, rmc.longitude);
</code>```

the output to the terminal is this-

lat: +50.71735        long:

whereas if i print them in a different order like this-

```<code>printf("long: %s \t lat: %s \n", rmc.longitude, rmc.latitude);
</code>```

i get this output.

long: -001.39118         lat:

also if i split the printing up into two separate printf statements, only the first print statement correctly prints the char array. I haven't had to ask for help on here before but this has had me stuck for a good week now. Any help would be massively appreciated! cheers.

edit

The part of the program that writes into the array is this. its essentially the same for the latitude and longitude array.

```<code>/* now we are in first char of latitude */

/* copy latitude chars */
strlcpy ((char*)lat, (const char*)ptr_to_comma, 10 );/*copies most size-1, null terminated*/   //changed 11 to 10

/* default latitude presentation is ddmm.mmmmm
    we need to change it to dd.mmmmmmm
*/
unsigned char ind;
for (ind=0; ind<9; ind++)
{
    if (*ptr_to_comma == '.')
    {
        ptr_to_comma++;//step over '.'
    }
    if ( ind==2 )
    {
        lat[ind++]='.';
    }
    lat[ind] = *ptr_to_comma;
    ptr_to_comma++;
}
lat[10] = '\0'; //terminate
/* now lat == dd.mmmmmmm */

ptr_to_comma++; /*step over comma to the NS-indicator*/

/*catch NorthSouth-indicator and step*/
if ( *ptr_to_comma == 'N'){ /*if we are in the North*/
    sign = '+';
    rmc.ns_indicator = 'N';
} else if ( *ptr_to_comma == 'S'){ /*else we are in the South*/
    sign = '-';
    rmc.ns_indicator = 'S';
}
ptr_to_comma++;//step over NS-indicator
ptr_to_comma++;//step over comma to the longitude field

/* dd.mmmmmmm to dd.ddddddd */

_convert_minutes( (unsigned char*) lat+3 );

/* copy latitude with sign to the rmc-struct */
rmc.latitude[0] = sign;
strcpy ( (char*)rmc.latitude+1, (const char*)lat);
rmc.latitude[10]='\0';
</code>```

essentially it is parsing the information from a stream of data coming in.

答:
For %s to work correctly, the char array must have a NUL-terminator \0 which signifies the end of the string.

If you don't leave room for that, the behaviour of your program is undefined.

You need to initialise the arrays yourself - don't rely on the compiler to do it.

Get your debugger out and check the memory associated with rmc at the point of the printf.

Body:
i'm currently trying to debug my program over UART by printing the values of some variables at specific points. My issue is with printing two char arrays. The order in which i print them seems to have an effect on if it prints. The declarations of the arrays are in a struct in a header file as follows-

//header file
typedef struct
{
  char latitude[10];
  char longitude[11];
}NMEA_RMC_t;

NMEA_RMC_t rmc;

The char arrays are manipulated in another function after parsing data from an input. They are not updated with an interrupt, although there are interrupts elsewhere in the program. In the main code if i print them as follows-

//main program loop
printf("lat: %s \t long: %s \n", rmc.latitude, rmc.longitude);

the output to the terminal is this-

lat: +50.71735        long:

whereas if i print them in a different order like this-

printf("long: %s \t lat: %s \n", rmc.longitude, rmc.latitude);

i get this output.

long: -001.39118         lat:

also if i split the printing up into two separate printf statements, only the first print statement correctly prints the char array. I haven't had to ask for help on here before but this has had me stuck for a good week now. Any help would be massively appreciated! cheers.

edit

The part of the program that writes into the array is this. its essentially the same for the latitude and longitude array.

/* now we are in first char of latitude */

/* copy latitude chars */
strlcpy ((char*)lat, (const char*)ptr_to_comma, 10 );/*copies most size-1, null terminated*/   //changed 11 to 10

/* default latitude presentation is ddmm.mmmmm
    we need to change it to dd.mmmmmmm
*/
unsigned char ind;
for (ind=0; ind<9; ind++)
{
    if (*ptr_to_comma == '.')
    {
        ptr_to_comma++;//step over '.'
    }
    if ( ind==2 )
    {
        lat[ind++]='.';
    }
    lat[ind] = *ptr_to_comma;
    ptr_to_comma++;
}
lat[10] = '\0'; //terminate
/* now lat == dd.mmmmmmm */

ptr_to_comma++; /*step over comma to the NS-indicator*/

/*catch NorthSouth-indicator and step*/
if ( *ptr_to_comma == 'N'){ /*if we are in the North*/
    sign = '+';
    rmc.ns_indicator = 'N';
} else if ( *ptr_to_comma == 'S'){ /*else we are in the South*/
    sign = '-';
    rmc.ns_indicator = 'S';
}
ptr_to_comma++;//step over NS-indicator
ptr_to_comma++;//step over comma to the longitude field

/* dd.mmmmmmm to dd.ddddddd */

_convert_minutes( (unsigned char*) lat+3 );

/* copy latitude with sign to the rmc-struct */
rmc.latitude[0] = sign;
strcpy ( (char*)rmc.latitude+1, (const char*)lat);
rmc.latitude[10]='\0';

essentially it is parsing the information from a stream of data coming in.


问:
Text shows in header instead of new section BS4
I have a problem with my one-page website. My new text section shows in my header video. instead in my new section. I want it after video header. What am I doing wrong?

My HTML

```<code><header>
<div class="container">
  <div class="bg-wrap">

      <video poster="poster.png" autoplay="true" loop muted>
      <source src="img/video.mp4" type="video/mp4">
      <source src="img/video.webm" type="video/webm">
    </video>

    <div class="header-text">
      <h1>Elektro Sikora</h1>
      <p>Informační portál Elektro Sikora Český Těšín</p>
    </div>

    <div id="scroll">
      <div class="round">
        <div class="wheel"></div>
      </div>
      <div class="scrolling">
        <span class="arrow"></span>
      </div>
    </div>
  </div>
  </div>
</header>

  <section id="content-space">
    <div class="container">
      <div class="row">
        <div class="col-lg-12 text-center">
          <p>
            Kompletní nabídka produktů, které nabízíme. Najdete zde od elektroniky až po zdravou výživu.
          </p>
        </div>
      </div>
    </div>
  </section>
</code>```

My CSS

```<code>/* Nav */
.navbar {
  padding: 1,2rem;
}
/* Video */
.bg-wrap {
  position: fixed;
  z-index: -1000;
  width: 100%;
  height: 100%;
  overflow: hidden;
  top: 0;
  left: 0;
}
video {
  top: 70px;
  left: 0;
  min-height: 100%;
  min-width: 100%;
}
.header-text {
  position: absolute;
  width: 100%;
  min-height: 100%;
  z-index: 1000;
  background-color: rgba(0, 0, 0, 0.4);
}
.header-text h1 {
  text-align: center;
  font-size: 65px;
  text-transform: uppercase;
  font-weight: 300;
  color: #fff;
  padding-top: 15%;
  margin-bottom: 10px;
}
.header-text p {
  text-align: center;
  font-size: 20px;
  letter-spacing: 3px;
  color: #fff;
}
#scroll {
  cursor: pointer;
  display: block;
  position: absolute;
  bottom: 50px;
  left: 50%;
  z-index: 1000;
}
.round {
  height: 21px;
  width: 14px;
  border-radius: 10px;
  transform: none;
  border: 2px solid #fff;
  top: 170px;
}
.wheel {
  animation-delay: 0s;
  animation-duration: 1s;
  animation-iteration-count: infinite;
  animation-name: scrolling;
  animation-play-state: running;
  animation-timing-function: linear;
  background: #fff none repeat scroll 0 0;
  border-radius: 10px;
  height: 3px;
  margin-left: auto;
  margin-right: auto;
  position: relative;
  top: 4px;
  width: 2px;
}
.scrolling span {
    display: block;
    width: 5px;
    height: 5px;
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    transform: rotate(45deg);
    border-right: 2px solid #fff;
    border-bottom: 2px solid #fff;
    margin: 3px 0 3px 5px;
}
.arrow {
    margin-top: 6px;
}
header {
  height: 100vh;
  overflow: hidden;
}
</code>```

Nav dissapear and scrollable video

答:
Since the video is position: absolute; it is out of the flow of the page. You need to add a height to the header element in order for this to work.

```<code>header {
    height: 100vh;
    overflow: hidden;
}
</code>```

I hope this modified CSS works for you.

/* Nav */
.navbar {
  padding: 1.2rem;
}
/* Video */
.bg-wrap {
  position: absolute;
  z-index: -1000;
  width: 100%;
  height: 100%;
  overflow: hidden;
  top: 0;
  left: 0;
}
video {
  position: relative;
  top: 70px;
  left: 0;
  min-width: 100%;
  background: black;
}
.header-text {
  position: absolute;
  top: 0;
  width: 100%;
  min-height: 100%;
  z-index: 1000;
  background-color: rgba(0, 0, 0, 0.4);
}
.header-text h1 {
  text-align: center;
  font-size: 65px;
  text-transform: uppercase;
  font-weight: 300;
  color: #fff;
  padding-top: 15%;
  margin-bottom: 10px;
}
.header-text p {
  text-align: center;
  font-size: 20px;
  letter-spacing: 3px;
  color: #fff;
}
#scroll {
  cursor: pointer;
  display: block;
  position: absolute;
  bottom: 50px;
  left: 50%;
  z-index: 1000;
}
.round {
  height: 21px;
  width: 14px;
  border-radius: 10px;
  transform: none;
  border: 2px solid #fff;
  top: 170px;
}
.wheel {
  animation-delay: 0s;
  animation-duration: 1s;
  animation-iteration-count: infinite;
  animation-name: scrolling;
  animation-play-state: running;
  animation-timing-function: linear;
  background: #fff none repeat scroll 0 0;
  border-radius: 10px;
  height: 3px;
  margin-left: auto;
  margin-right: auto;
  position: relative;
  top: 4px;
  width: 2px;
}
.scrolling span {
    display: block;
    width: 5px;
    height: 5px;
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    transform: rotate(45deg);
    border-right: 2px solid #fff;
    border-bottom: 2px solid #fff;
    margin: 3px 0 3px 5px;
}
.arrow {
    margin-top: 6px;
}
header {
  height: 100vh;
  overflow: hidden;
}

.container {
  height: 100%;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
<div class="container">
  <div class="bg-wrap">

      <video poster="poster.png" autoplay="true" loop muted>
      <source src="img/video.mp4" type="video/mp4">
      <source src="img/video.webm" type="video/webm">
    </video>

    <div class="header-text">
      <h1>Elektro Sikora</h1>
      <p>Informační portál Elektro Sikora Český Těšín</p>
    </div>

    <div id="scroll">
      <div class="round">
        <div class="wheel"></div>
      </div>
      <div class="scrolling">
        <span class="arrow"></span>
      </div>
    </div>
  </div>
  </div>
</header>

  <section id="content-space">
    <div class="container">
      <div class="row">
        <div class="col-lg-12 text-center">
          <p>
            Kompletní nabídka produktů, které nabízíme. Najdete zde od elektroniky až po zdravou výživu.
          </p>
        </div>
      </div>
    </div>
  </section></code>```

Body:
I have a problem with my one-page website. My new text section shows in my header video. instead in my new section. I want it after video header. What am I doing wrong?

My HTML

      <video poster="poster.png" autoplay="true" loop muted>
      <source src="img/video.mp4" type="video/mp4">
      <source src="img/video.webm" type="video/webm">
    </video>

Elektro Sikora

Informační portál Elektro Sikora Český Těšín

            Kompletní nabídka produktů, které nabízíme. Najdete zde od elektroniky až po zdravou výživu.

My CSS

/* Nav */
.navbar {
  padding: 1,2rem;
}
/* Video */
.bg-wrap {
  position: fixed;
  z-index: -1000;
  width: 100%;
  height: 100%;
  overflow: hidden;
  top: 0;
  left: 0;
}
video {
  top: 70px;
  left: 0;
  min-height: 100%;
  min-width: 100%;
}
.header-text {
  position: absolute;
  width: 100%;
  min-height: 100%;
  z-index: 1000;
  background-color: rgba(0, 0, 0, 0.4);
}
.header-text h1 {
  text-align: center;
  font-size: 65px;
  text-transform: uppercase;
  font-weight: 300;
  color: #fff;
  padding-top: 15%;
  margin-bottom: 10px;
}
.header-text p {
  text-align: center;
  font-size: 20px;
  letter-spacing: 3px;
  color: #fff;
}
#scroll {
  cursor: pointer;
  display: block;
  position: absolute;
  bottom: 50px;
  left: 50%;
  z-index: 1000;
}
.round {
  height: 21px;
  width: 14px;
  border-radius: 10px;
  transform: none;
  border: 2px solid #fff;
  top: 170px;
}
.wheel {
  animation-delay: 0s;
  animation-duration: 1s;
  animation-iteration-count: infinite;
  animation-name: scrolling;
  animation-play-state: running;
  animation-timing-function: linear;
  background: #fff none repeat scroll 0 0;
  border-radius: 10px;
  height: 3px;
  margin-left: auto;
  margin-right: auto;
  position: relative;
  top: 4px;
  width: 2px;
}
.scrolling span {
    display: block;
    width: 5px;
    height: 5px;
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    transform: rotate(45deg);
    border-right: 2px solid #fff;
    border-bottom: 2px solid #fff;
    margin: 3px 0 3px 5px;
}
.arrow {
    margin-top: 6px;
}
header {
  height: 100vh;
  overflow: hidden;
}

Nav dissapear and scrollable video

Body:
Since the video is position: absolute; it is out of the flow of the page. You need to add a height to the header element in order for this to work.

header {
    height: 100vh;
    overflow: hidden;
}

I hope this modified CSS works for you.

/* Nav */
.navbar {
  padding: 1.2rem;
}
/* Video */
.bg-wrap {
  position: absolute;
  z-index: -1000;
  width: 100%;
  height: 100%;
  overflow: hidden;
  top: 0;
  left: 0;
}
video {
  position: relative;
  top: 70px;
  left: 0;
  min-width: 100%;
  background: black;
}
.header-text {
  position: absolute;
  top: 0;
  width: 100%;
  min-height: 100%;
  z-index: 1000;
  background-color: rgba(0, 0, 0, 0.4);
}
.header-text h1 {
  text-align: center;
  font-size: 65px;
  text-transform: uppercase;
  font-weight: 300;
  color: #fff;
  padding-top: 15%;
  margin-bottom: 10px;
}
.header-text p {
  text-align: center;
  font-size: 20px;
  letter-spacing: 3px;
  color: #fff;
}
#scroll {
  cursor: pointer;
  display: block;
  position: absolute;
  bottom: 50px;
  left: 50%;
  z-index: 1000;
}
.round {
  height: 21px;
  width: 14px;
  border-radius: 10px;
  transform: none;
  border: 2px solid #fff;
  top: 170px;
}
.wheel {
  animation-delay: 0s;
  animation-duration: 1s;
  animation-iteration-count: infinite;
  animation-name: scrolling;
  animation-play-state: running;
  animation-timing-function: linear;
  background: #fff none repeat scroll 0 0;
  border-radius: 10px;
  height: 3px;
  margin-left: auto;
  margin-right: auto;
  position: relative;
  top: 4px;
  width: 2px;
}
.scrolling span {
    display: block;
    width: 5px;
    height: 5px;
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    transform: rotate(45deg);
    border-right: 2px solid #fff;
    border-bottom: 2px solid #fff;
    margin: 3px 0 3px 5px;
}
.arrow {
    margin-top: 6px;
}
header {
  height: 100vh;
  overflow: hidden;
}

.container {
  height: 100%;
  width: 100%;
}

<header>
<div class="container">
  <div class="bg-wrap">

      <video poster="poster.png" autoplay="true" loop muted>
      <source src="img/video.mp4" type="video/mp4">
      <source src="img/video.webm" type="video/webm">
    </video>

    <div class="header-text">
      <h1>Elektro Sikora</h1>
      <p>Informační portál Elektro Sikora Český Těšín</p>
    </div>

    <div id="scroll">
      <div class="round">
        <div class="wheel"></div>
      </div>
      <div class="scrolling">
        <span class="arrow"></span>
      </div>
    </div>
  </div>
  </div>
</header>

  <section id="content-space">
    <div class="container">
      <div class="row">
        <div class="col-lg-12 text-center">
          <p>
            Kompletní nabídka produktů, které nabízíme. Najdete zde od elektroniky až po zdravou výživu.
          </p>
        </div>
      </div>
    </div>
  </section>


问:
external resolve dns linux bind9
I'm 3 days trying to fix my nameservers to a .tk domain, just for testing because I'm going to not go to .com. I wanted to understand how I could solve my DNS even outside and not just on a private network. Repeat the server configuration:

named.conf.options

```<code>    options {
        directory "/var/cache/bind";

        // If there is a firewall between you and nameservers you want
        // to talk to, you may need to fix the firewall to allow multiple
        // ports to talk.  See http://www.kb.cert.org/vuls/id/800113

        // If your ISP provided one or more IP addresses for stable
        // nameservers, you probably want to use them as forwarders.
        // Uncomment the following block, and insert the addresses replacing
        // the all-0's placeholder.

        // forwarders {
        //      0.0.0.0;
        // };

        //========================================================================
        // If BIND logs error messages about the root key being expired,
        // you will need to update your keys.  See https://www.isc.org/bind-keys
        //========================================================================
        dnssec-validation auto;

        auth-nxdomain no;    # conform to RFC1035
        listen-on-v6 { any; };
};
</code>```

named.conf.local

```<code>    //
// Do any local configuration here
//

// Consider adding the 1918 zones here, if they are not used in your
// organization
//include "/etc/bind/zones.rfc1918";

zone "fresky.tk" IN {
        type master;
        file "/etc/bind/zones/db.fresky.tk";
};

zone "33.163.31.176.in-addr.arpa" IN {
        type master;
        file "/etc/bind/zones/db.33.163.31.176.in-addr.arpa";
};
</code>```

ZONE fresky.tk

```<code>;
; BIND data file for local loopback interface
;
$TTL    604800
@       IN      SOA     ns1.fresky.tk. admin.fresky.tk. (
                     2006020201 ; Serial
                         604800 ; Refresh
                          86400 ; Retry
                        2419200 ; Expire
                         604800); Negative Cache TTL
;

;
; NS Records
;

fresky.tk.      IN      NS      ns1.fresky.tk.
fresky.tk.      IN      NS      ns2.fresky.tk.

;
; A Records (Only Nameservers)
;

ns1     IN      A       176.31.163.33
ns2     IN      A       176.31.163.33

;
; A Records (General)
;
fresky.tk.      IN      A       176.31.163.33
www.fresky.tk.  IN      A       176.31.163.33
ftp.fresky.tk.  IN      A       176.31.163.33
</code>```

ZONE Reverse 33.163.31.173.in-addr.arpa

```<code>;
; BIND reverse data file for local loopback interface
;
$TTL    604800
@       IN      SOA     fresky.tk. admin.fresky.tk. (
                     2006020201 ; Serial
                         604800 ; Refresh
                          86400 ; Retry
                        2419200 ; Expire
                         604800); Negative Cache TTL
;

;
; NS Records
;
        IN      NS      ns1.fresky.tk.
        IN      NS      ns2.fresky.tk.
;
; PTR Records (Only NameSever)
;
33.163.31.176.in-addr.arpa.     IN      PTR     ns1.fresky.tk.
33.163.31.176.in-addr.arpa.     IN      PTR     ns2.fresky.tk.

;
; PTR Records (General)
;
33.163.31.176.in-addr.arpa.     IN      PTR     ftp.fresky.tk.
33.163.31.176.in-addr.arpa.     IN      PTR     www.fresky.tk.
</code>```

/etc/hosts && /etc/resolv.con

```<code># Your system has configured 'manage_etc_hosts' as True.
# As a result, if you wish for changes to this file to persist
# then you will need to either
# a.) make changes to the master file in /etc/cloud/templates/hosts.tmpl
# b.) change or remove the value of 'manage_etc_hosts' in
#     /etc/cloud/cloud.cfg or cloud-config from user-data
176.31.163.33 fresky.tk fresky
127.0.0.1 localhost

# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

search fresky.tk
nameserver 127.0.0.1
</code>```

答:
You need to register glue records at https://my.freenom.com

(My Domains / Manage Domain / Management tools / Register glue records)

Add 176.31.163.33 as IP address for ns1.fresky.tk and ns2.fresky.tk

Title: external resolve dns linux bind9

Body:
I'm 3 days trying to fix my nameservers to a .tk domain, just for testing because I'm going to not go to .com. I wanted to understand how I could solve my DNS even outside and not just on a private network. Repeat the server configuration:

named.conf.options

    options {
        directory "/var/cache/bind";

        // If there is a firewall between you and nameservers you want
        // to talk to, you may need to fix the firewall to allow multiple
        // ports to talk.  See http://www.kb.cert.org/vuls/id/800113

        // If your ISP provided one or more IP addresses for stable
        // nameservers, you probably want to use them as forwarders.
        // Uncomment the following block, and insert the addresses replacing
        // the all-0's placeholder.

        // forwarders {
        //      0.0.0.0;
        // };

        //========================================================================
        // If BIND logs error messages about the root key being expired,
        // you will need to update your keys.  See https://www.isc.org/bind-keys
        //========================================================================
        dnssec-validation auto;

        auth-nxdomain no;    # conform to RFC1035
        listen-on-v6 { any; };
};

named.conf.local

    //
// Do any local configuration here
//

// Consider adding the 1918 zones here, if they are not used in your
// organization
//include "/etc/bind/zones.rfc1918";

zone "fresky.tk" IN {
        type master;
        file "/etc/bind/zones/db.fresky.tk";
};

zone "33.163.31.176.in-addr.arpa" IN {
        type master;
        file "/etc/bind/zones/db.33.163.31.176.in-addr.arpa";
};

ZONE fresky.tk

;
; BIND data file for local loopback interface
;
$TTL    604800
@       IN      SOA     ns1.fresky.tk. admin.fresky.tk. (
                     2006020201 ; Serial
                         604800 ; Refresh
                          86400 ; Retry
                        2419200 ; Expire
                         604800); Negative Cache TTL
;

;
; NS Records
;

fresky.tk.      IN      NS      ns1.fresky.tk.
fresky.tk.      IN      NS      ns2.fresky.tk.

;
; A Records (Only Nameservers)
;

ns1     IN      A       176.31.163.33
ns2     IN      A       176.31.163.33

;
; A Records (General)
;
fresky.tk.      IN      A       176.31.163.33
www.fresky.tk.  IN      A       176.31.163.33
ftp.fresky.tk.  IN      A       176.31.163.33

ZONE Reverse 33.163.31.173.in-addr.arpa

;
; BIND reverse data file for local loopback interface
;
$TTL    604800
@       IN      SOA     fresky.tk. admin.fresky.tk. (
                     2006020201 ; Serial
                         604800 ; Refresh
                          86400 ; Retry
                        2419200 ; Expire
                         604800); Negative Cache TTL
;

;
; NS Records
;
        IN      NS      ns1.fresky.tk.
        IN      NS      ns2.fresky.tk.
;
; PTR Records (Only NameSever)
;
33.163.31.176.in-addr.arpa.     IN      PTR     ns1.fresky.tk.
33.163.31.176.in-addr.arpa.     IN      PTR     ns2.fresky.tk.

;
; PTR Records (General)
;
33.163.31.176.in-addr.arpa.     IN      PTR     ftp.fresky.tk.
33.163.31.176.in-addr.arpa.     IN      PTR     www.fresky.tk.

/etc/hosts && /etc/resolv.con

# Your system has configured 'manage_etc_hosts' as True.
# As a result, if you wish for changes to this file to persist
# then you will need to either
# a.) make changes to the master file in /etc/cloud/templates/hosts.tmpl
# b.) change or remove the value of 'manage_etc_hosts' in
#     /etc/cloud/cloud.cfg or cloud-config from user-data
176.31.163.33 fresky.tk fresky
127.0.0.1 localhost

# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

search fresky.tk
nameserver 127.0.0.1


问:
PayU Money Integration in Android application
When I am using Pay U Money SDKUI in Test environment everything is working fine. However, when I am using the same SDKUI in the Production environment it's giving me an error (5014): Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

I am successfully able to create hash key from my own server, I'm not able to understand what I am missing. Please help.

```<code>public void onPaymentRelatedDetailsResponse(PayuResponse payuResponse) {
        mPayuResponse = payuResponse;
        findViewById(R.id.progress_bar).setVisibility(View.GONE);
        if(payuResponse.isResponseAvailable() && payuResponse.getResponseStatus().getCode() == PayuErrors.NO_ERROR){ // ok we are good to go
            Toast.makeText(this, payuResponse.getResponseStatus().getResult(), Toast.LENGTH_LONG).show();
            if(payuResponse.isStoredCardsAvailable()){
                findViewById(R.id.linear_layout_stored_card).setVisibility(View.VISIBLE);
            }
            if(payuResponse.isNetBanksAvailable()){ // okay we have net banks now.
                findViewById(R.id.linear_layout_netbanking).setVisibility(View.VISIBLE);
            }
            if(payuResponse.isCashCardAvailable()){ // we have cash card too
                findViewById(R.id.linear_layout_cash_card).setVisibility(View.VISIBLE);
            }
            if(payuResponse.isCreditCardAvailable() || payuResponse.isDebitCardAvailable()){
                findViewById(R.id.linear_layout_credit_debit_card).setVisibility(View.VISIBLE);
            }
            if(payuResponse.isEmiAvailable()){
                findViewById(R.id.linear_layout_emi).setVisibility(View.VISIBLE);
            }
            if(payuResponse.isPaisaWalletAvailable() && payuResponse.getPaisaWallet().get(0).getBankCode().contains(PayuConstants.PAYUW)) {
                findViewById(R.id.linear_layout_payumoney).setVisibility(View.VISIBLE);
            }
        }else{
            Toast.makeText(this, "Something went wrong : " + payuResponse.getResponseStatus().getResult(), Toast.LENGTH_LONG).show();
        }

        // no mater what response i get just show this button, so that we can go further.
        findViewById(R.id.linear_layout_verify_api).setVisibility(View.VISIBLE);
    }
</code>```

I am getting the response

```<code>status = "ERROR"
result = "Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject"
code = 5014
</code>```

答:
Debug the payumoney sdk line by line and you will be able to get exact failure reason.
In most of cases there is mismatch in hash. Its a bug in their sdk that errors are not handled properly, as a result above html page is returned.</p>

ContentLicense: CC BY-SA 4.0

Body:
When I am using Pay U Money SDKUI in Test environment everything is working fine. However, when I am using the same SDKUI in the Production environment it's giving me an error (5014): Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

I am successfully able to create hash key from my own server, I'm not able to understand what I am missing. Please help.

public void onPaymentRelatedDetailsResponse(PayuResponse payuResponse) {
        mPayuResponse = payuResponse;
        findViewById(R.id.progress_bar).setVisibility(View.GONE);
        if(payuResponse.isResponseAvailable() && payuResponse.getResponseStatus().getCode() == PayuErrors.NO_ERROR){ // ok we are good to go
            Toast.makeText(this, payuResponse.getResponseStatus().getResult(), Toast.LENGTH_LONG).show();
            if(payuResponse.isStoredCardsAvailable()){
                findViewById(R.id.linear_layout_stored_card).setVisibility(View.VISIBLE);
            }
            if(payuResponse.isNetBanksAvailable()){ // okay we have net banks now.
                findViewById(R.id.linear_layout_netbanking).setVisibility(View.VISIBLE);
            }
            if(payuResponse.isCashCardAvailable()){ // we have cash card too
                findViewById(R.id.linear_layout_cash_card).setVisibility(View.VISIBLE);
            }
            if(payuResponse.isCreditCardAvailable() || payuResponse.isDebitCardAvailable()){
                findViewById(R.id.linear_layout_credit_debit_card).setVisibility(View.VISIBLE);
            }
            if(payuResponse.isEmiAvailable()){
                findViewById(R.id.linear_layout_emi).setVisibility(View.VISIBLE);
            }
            if(payuResponse.isPaisaWalletAvailable() && payuResponse.getPaisaWallet().get(0).getBankCode().contains(PayuConstants.PAYUW)) {
                findViewById(R.id.linear_layout_payumoney).setVisibility(View.VISIBLE);
            }
        }else{
            Toast.makeText(this, "Something went wrong : " + payuResponse.getResponseStatus().getResult(), Toast.LENGTH_LONG).show();
        }

        // no mater what response i get just show this button, so that we can go further.
        findViewById(R.id.linear_layout_verify_api).setVisibility(View.VISIBLE);
    }

I am getting the response

status = "ERROR"
result = "Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject"
code = 5014


问:
JavaScript - How to count an arbitrary number of clicks on a button
I've made a simple javascript application, for calculating the reaction time based on the speed in which a div is clicked. It's working pretty well. But i whish to count an arbitrary series of click (for examples, the first 10 clicks), and, afterwards, calculating the average of reaction time in these range of clicks.
Thanks for the help:</p>

答:
for each and every click update the count value in the button tag.

Ex:

function updateCount(){
 var oldClicks=parseInt($("#counter").attr("data-clicks"))
$("#counter").attr("data-clicks",oldClicks+1)
alert($("#counter").attr("data-clicks"))
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='button' class='btn btn-primary' id='counter' data-clicks='0' onclick='updateCount()'>counts</button></code>```

Body:
for each and every click update the count value in the button tag.

Ex:

function updateCount(){
 var oldClicks=parseInt($("#counter").attr("data-clicks"))
$("#counter").attr("data-clicks",oldClicks+1)
alert($("#counter").attr("data-clicks"))
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='button' class='btn btn-primary' id='counter' data-clicks='0' onclick='updateCount()'>counts</button>


问:
Gulp browserSync Firefox Ubuntu 16.04
How do we define the browser for gulp browserSync. I am on ubuntu 16.04, I have chrome, firefox and firefox developer edition installed on my machine and I want gulp browserSync to open firefox developer edition. How can I do that? Here is my configuration :</p>

```<code>function startBrowserSync() {
    options = {
        browser: 'FirefoxDeveloperEdition',
        proxy: 'localhost:' + port,
        port: 3000,
        files: [],
        ghostMode: {
            clicks: true,
            location: false,
            forms: true,
            scroll: true
        },
        injectChanges: true,
        logFileChanges: true,
        logLevel: 'debug',
        logPrefix: 'gulp-patterns',
        notify: true,
        reloadDelay: 0
    };
    browserSync(options);
</code>```

答:
I got this working by typing firefox, then hitting tab on the command line. It auto completed to firefox-developer. So add this line and it should work fine.

browser: 'firefox-developer',

Title: Gulp browserSync Firefox Ubuntu 16.04

Body:
How do we define the browser for gulp browserSync. I am on ubuntu 16.04, I have chrome, firefox and firefox developer edition installed on my machine and I want gulp browserSync to open firefox developer edition. How can I do that? Here is my configuration :

function startBrowserSync() {
    options = {
        browser: 'FirefoxDeveloperEdition',
        proxy: 'localhost:' + port,
        port: 3000,
        files: [],
        ghostMode: {
            clicks: true,
            location: false,
            forms: true,
            scroll: true
        },
        injectChanges: true,
        logFileChanges: true,
        logLevel: 'debug',
        logPrefix: 'gulp-patterns',
        notify: true,
        reloadDelay: 0
    };
    browserSync(options);


问:
Recursion function (with bit shift)
```<code>def recursion(x):
    if x == 0:
        return 0
    else:
        return x << 1 + recursion(x - 1)

print(recursion(3)) # 393216

print(3 << 1) # 6
print(2 << 1) # 4
print(1 << 1) # 2
</code>```

In my head the output of the recursion function should be: 12 (6+4+2)
Why is this not the case? I must say "393216" is slightly bigger than my expected number "12".

My expectation:

```<code>--> return 1<<1==2 for 1
--> return 2<<1==4 for 2
--> return 3<<1==6 for 3
0 --> return 0 for 0
</code>```

All together = 12

答:
The reason is due to operator precedence. Bitshift operators have lower precedence than arithmetic.

By default, x << 1 + recursion(x - 1) is assumed to be x << (1 + recursion(x - 1)).

You can fix the issue by overriding the default precedence using parentheses.

```<code>def recursion(x):
    if x == 0:
        return 0
    else:
        return (x << 1) + recursion(x - 1)

print(recursion(3)) # 12
</code>```

Title: Recursion function (with bit shift)

Body:
def recursion(x):
    if x == 0:
        return 0
    else:
        return x << 1 + recursion(x - 1)

print(recursion(3)) # 393216

print(3 << 1) # 6
print(2 << 1) # 4
print(1 << 1) # 2

In my head the output of the recursion function should be: 12 (6+4+2)
Why is this not the case? I must say "393216" is slightly bigger than my expected number "12".

My expectation:

--> return 1<<1==2 for 1
--> return 2<<1==4 for 2
--> return 3<<1==6 for 3
0 --> return 0 for 0

All together = 12

Body:
The reason is due to operator precedence. Bitshift operators have lower precedence than arithmetic.

By default, x << 1 + recursion(x - 1) is assumed to be x << (1 + recursion(x - 1)).

You can fix the issue by overriding the default precedence using parentheses.

def recursion(x):
    if x == 0:
        return 0
    else:
        return (x << 1) + recursion(x - 1)

print(recursion(3)) # 12


答:
Operator precedence. Bit shifts have lower precedence than addition/subtraction (see in docs). Hence you need </p>

```<code>def recursion(x):
    if x == 0:
        return 0
    else:
        return (x << 1) + recursion(x - 1)
</code>```

<p>as currently your function is being interpreted equivalent to </p>

```<code>def recursion(x):
    if x == 0:
        return 0
    else:
        return x << (1 + recursion(x - 1))
</code>```

Title: Recursion function (with bit shift)

Body:
Operator precedence. Bit shifts have lower precedence than addition/subtraction (see in docs). Hence you need

def recursion(x):
    if x == 0:
        return 0
    else:
        return (x << 1) + recursion(x - 1)

as currently your function is being interpreted equivalent to

def recursion(x):
    if x == 0:
        return 0
    else:
        return x << (1 + recursion(x - 1))


问:
GlassFish 4.1 OutOfMemoryError during FilterChain execution
I am using a web application for websockets in GlassFish 4.1 for quite sometime and it has been running well until recently I came across this problem twice. It caused my application to crash as expected and I have not been able to pinpoint the exact reason. Here is the error trace I get:

```<code>GRIZZLY0013: Exception during FilterChain execution
java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3181)
    at java.util.ArrayList.grow(ArrayList.java:261)
    at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
    at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
    at java.util.ArrayList.add(ArrayList.java:458)
    at org.glassfish.grizzly.filterchain.FilterChainContext.addCompletionListener(FilterChainContext.java:930)
    at org.glassfish.grizzly.utils.IdleTimeoutFilter.queueAction(IdleTimeoutFilter.java:249)
    at org.glassfish.grizzly.utils.IdleTimeoutFilter.handleRead(IdleTimeoutFilter.java:167)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)
</code>```

From the trace it would seem that FilterChainContext.addCompletionListener is getting called too often causing the ArrayList to increase greatly in size - eating up memory. What could be causing the server to add this type of listener so many times? Is the server receiving too many requests? Is this a GlassFish bug or does this simply have to do with increasing heap size?

For the moment I have increased heap size denoted by the flag -Xmx from 512MB to 2GB. Also enforced parallel collector for GC via -XX:+UseParallelGC.

It would be great if you could provide further insight to help solve this problem.

答:
It's been a long time since I have fixed the issue, but I would like to share the change I had to make just in case it helps out people facing the same issue - who are making the same mistake like I did.

The problem was in my application. Deep down in my code the application created a new object for every new client request. Like so:

```<code>Worker workerObj = new Worker();
</code>```

Initially, when it was deployed this did not cause any problems because the server load was far less but as clients rapidly increased the memory was consumed more and more and finally it caused the server to crash.

The solution was to make a single Worker object and re-use for all the requests in a thread-safe manner.

Body:
I am using a web application for websockets in GlassFish 4.1 for quite sometime and it has been running well until recently I came across this problem twice. It caused my application to crash as expected and I have not been able to pinpoint the exact reason. Here is the error trace I get:

GRIZZLY0013: Exception during FilterChain execution
java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3181)
    at java.util.ArrayList.grow(ArrayList.java:261)
    at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
    at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
    at java.util.ArrayList.add(ArrayList.java:458)
    at org.glassfish.grizzly.filterchain.FilterChainContext.addCompletionListener(FilterChainContext.java:930)
    at org.glassfish.grizzly.utils.IdleTimeoutFilter.queueAction(IdleTimeoutFilter.java:249)
    at org.glassfish.grizzly.utils.IdleTimeoutFilter.handleRead(IdleTimeoutFilter.java:167)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)

From the trace it would seem that FilterChainContext.addCompletionListener is getting called too often causing the ArrayList to increase greatly in size - eating up memory. What could be causing the server to add this type of listener so many times? Is the server receiving too many requests? Is this a GlassFish bug or does this simply have to do with increasing heap size?

For the moment I have increased heap size denoted by the flag -Xmx from 512MB to 2GB. Also enforced parallel collector for GC via -XX:+UseParallelGC.

It would be great if you could provide further insight to help solve this problem.

Body:
It's been a long time since I have fixed the issue, but I would like to share the change I had to make just in case it helps out people facing the same issue - who are making the same mistake like I did.

The problem was in my application. Deep down in my code the application created a new object for every new client request. Like so:

Worker workerObj = new Worker();

Initially, when it was deployed this did not cause any problems because the server load was far less but as clients rapidly increased the memory was consumed more and more and finally it caused the server to crash.

The solution was to make a single Worker object and re-use for all the requests in a thread-safe manner.


问:
Questions about COM/ActiveX objects
I have good knowledge on the working of a "traditional" .dll. Also the differences between dynamic loading and static loading, etc.

But I have the following doubts about the working of COM objects,

Is it mandatory to register COM objects with regsvr32?

can I have two versions of a registered COM object lying in the same/different directory?

besides being packaged inside a .dll file is there anything in common between a "traditional" .dll and a COM object?

答:
1) No - it is NOT necessary to register COM objects. Registration is needed to create new COM objects. There are many interfaces (COM or native functions) that want a COM object. Their API tells you which interface your COM object should support. Since you pass in an existing COM object, they don't need registration information to create your COM object. A variation of this scenario is the RUnning Object Table, in which you can register created COM objects. Those objects are also created by you, and you don't need the registration info.

Example interface: IQueryCancelAutoplay.

2) A COM object exists in memory. You're probably thinking about a COM class, implemented in a DLL together with its COM factory. COM classes are registered by their GUID. You can have multipe classes=GUIDs per DLL, but only one DLL per class. Remember, the caller asks COM for an instance of your class. Which DLL would COM load if there would be two DLLs implementing the same class?!
Of course, there can be two DLLs each implementing one class, where the two classes share some interfaces. They will always share IUnknown, for instance, often IDispatch, but rarely IAcmeCorpFooBarv2

3) A COM DLL is a normal DLL which (a) exposes some COM-specific functions and (b) is registered so the COM framewrok can call LoadLibrary on it. The DLL may also expose other non-COM functions. As a result, you can call LoadLibrary on a COM DLL yourself. This can occasionally be useful to reduce the latency involved in creating your first COM object.

OwnerDisplayName: Fábio

Title: Questions about COM/ActiveX objects

LastEditorDisplayName: Fábio

OwnerDisplayName: MSalters

ContentLicense: CC BY-SA 2.5


问:
whats wrong with this code?
I am reading contents from files of a directory. I have to segregate the files according to their names and then read their contents. When I run the code simply without reading the contents, all the files are being listed of a particular file name, but when I try to read the contents, it reads contents from only few files, in fact just 10 of them. But the directory has about 1000 files of a particular name. I am posting the code here.

```<code>for (i = 0; i <= filenames.length; i++) {
    read = new FileReader("trainfiles/"+filenames[i]);
    br = new BufferedReader(read);

    if (filenames[i].matches(".*ham.*")) {
        System.out.println("ham:" + filenames[i]);
        while ((lines = br.readLine()) != null) {
            st = new StringTokenizer(lines);
            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }
        }
        br.close();
    }
}
</code>```

Could anyone tell me where am i doing wrong!?

thanks

EDIT #1 I did some modifications which I have been told here, but the problem still persists, here is the code.

```<code>for(i=0;i<=filenames.length;i++){
            read = new FileReader("trainfiles/"+filenames[i]);

            br = new BufferedReader(read);

            if(filenames[i].matches(".*ham.*")){
                System.out.println("ham:"+filenames[i]);

                        while((lines = br.readLine())!= null){
                            st = new StringTokenizer(lines);
                            while(st.hasMoreTokens()){
                                System.out.println(st.nextToken());
                            }

                        }

            }
            br.close();
            read.close();

                        }
</code>```

EDIT #2 Now the code looks like this, but again...its not giving me the result I want.

```<code>for (i = 0; i < filenames.length; i++) {
               try {

                if (filenames[i].matches(".*ham.*")) {
                     read = new FileReader("trainfiles/"+filenames[i]);
                        br = new BufferedReader(read);
                    System.out.println("ham:" + filenames[i]);
                    while ((lines = br.readLine()) != null) {
                        st = new StringTokenizer(lines);
                        while (st.hasMoreTokens()) {
                            System.out.println(st.nextToken());
                        }
                    }
                }
               } finally {

                read.close();
                br.close();
               }
            }
</code>```

答:
1000+ files are a lot of files to read. If it can't read a file it should throw an exception (IOException to be specific). Maybe print the exception message in the catch block and paste it here.

I don't know the StringTokenizer class but does the code give errors when you just print the line without the StringTokenizer?

An other option is to use threads. You have the array of files and then you start some threads who reads a file (producer/consumer problem).

By the way, you can filter files with the class FileFilter.

http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#listFiles%28java.io.FileFilter%29

Title: whats wrong with this code?

Body:
I am reading contents from files of a directory. I have to segregate the files according to their names and then read their contents. When I run the code simply without reading the contents, all the files are being listed of a particular file name, but when I try to read the contents, it reads contents from only few files, in fact just 10 of them. But the directory has about 1000 files of a particular name. I am posting the code here.

for (i = 0; i <= filenames.length; i++) {
    read = new FileReader("trainfiles/"+filenames[i]);
    br = new BufferedReader(read);

    if (filenames[i].matches(".*ham.*")) {
        System.out.println("ham:" + filenames[i]);
        while ((lines = br.readLine()) != null) {
            st = new StringTokenizer(lines);
            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }
        }
        br.close();
    }
}

Could anyone tell me where am i doing wrong!?

thanks

EDIT #1 I did some modifications which I have been told here, but the problem still persists, here is the code.

for(i=0;i<=filenames.length;i++){
            read = new FileReader("trainfiles/"+filenames[i]);

            br = new BufferedReader(read);

            if(filenames[i].matches(".*ham.*")){
                System.out.println("ham:"+filenames[i]);

                        while((lines = br.readLine())!= null){
                            st = new StringTokenizer(lines);
                            while(st.hasMoreTokens()){
                                System.out.println(st.nextToken());
                            }

                        }

            }
            br.close();
            read.close();

                        }

EDIT #2 Now the code looks like this, but again...its not giving me the result I want.

for (i = 0; i < filenames.length; i++) {
               try {

                if (filenames[i].matches(".*ham.*")) {
                     read = new FileReader("trainfiles/"+filenames[i]);
                        br = new BufferedReader(read);
                    System.out.println("ham:" + filenames[i]);
                    while ((lines = br.readLine()) != null) {
                        st = new StringTokenizer(lines);
                        while (st.hasMoreTokens()) {
                            System.out.println(st.nextToken());
                        }
                    }
                }
               } finally {

                read.close();
                br.close();
               }
            }


问:
Need Self-Signed Certificate Win2012 r2 SHA256 4-year expiration
I've been trying to figure out how to do this much of this afternoon, so it's very possible I'm missing something simple.

I need to create a self-signed certificate on Windows Server 2012 R2 that is SHA256, 2048 bit, and doesn't expire for four years.

From my searching I see that PowerShell (PS) is the way to go, and see a reasonable number of examples - none of which have everything I need.

For example I tried searching for the PS command New-SelfSignedCertificate and adding the "-NotAfter" option, but I get the error message "A parameter cannot be found that matches parameter name 'NotAfter'."

Even though I see "[-NotAfter]" here: https://technet.microsoft.com/en-us/itpro/powershell/windows/pkiclient/new-selfsignedcertificate (and that article has a March 2017 update)

I've tried a couple PS scripts people wrote, those seem to work with a 1+ year date, but they all don't work with one of the above criteria and, in any event, don't show up in IIS 8.5 for me to bind them to a site (I'm creating on the server).

$psversiontable on the server gives "PSVersion" = 5.0.10586.117

Thanks in advance for the help!

答:
New-SelfSignedCertificate (PKIClient module) cmdlet with advanced parameters is available starting from Windows Server 2016. The article you've mentioned applies to Server 2016 only.

In Windows 2012/2012 R2 you only have this thing: New-SelfSignedCertificate (PKI module). It is useless.

You can try to use CertReq utility instead, but it is not automation-friendly.


问:
Unable to use automatic PR service
I've been trying to use bitbake PR service. I've followed the instructions in https://wiki.yoctoproject.org/wiki/PR_Service and added these lines to my local.conf file:

```<code>PRSERV_HOST = "localhost:0"
INHERIT += "buildhistory"
BUILDHISTORY_COMMIT = "1"
</code>```

I expected that PR values of my recipies will be incrementing automatically after each change, but they are still the same

答:
In addition to the versioning server being enabled you also need to make sure your .bb's are using the auto rev:

```<code>PV = "1.0.0.0+git${SRCPV}"
</code>```

and they pulling from some source

```<code>SRC_URI = "git:/my_repo/program.git"
</code>```

Title: Unable to use automatic PR service

Body:
I've been trying to use bitbake PR service. I've followed the instructions in https://wiki.yoctoproject.org/wiki/PR_Service and added these lines to my local.conf file:

PRSERV_HOST = "localhost:0"
INHERIT += "buildhistory"
BUILDHISTORY_COMMIT = "1"

I expected that PR values of my recipies will be incrementing automatically after each change, but they are still the same

Body:
In addition to the versioning server being enabled you also need to make sure your .bb's are using the auto rev:

PV = "1.0.0.0+git${SRCPV}"

and they pulling from some source

SRC_URI = "git:/my_repo/program.git"


问:
Microservices and Messaging: Message Content
I'm building an application that consists out of several microservices. One of the microservices, which is called Hera, manages users. Another microservice manages authorization and authentication. This microservice is called Zeus and is an implementation of Spring OAuth 2.0.

When a user is created, updated or deleted in Hera, I'd like to replicate certain information to Zeus via RabbitMQ. This information includes the username, the user type (an enum) and a flag to indicate whether the user is enabled.

I've already set up RabbitMQ and everything is working properly. The only thing I'm not certain about is the message body content. How should this information be packaged in the message? For instance, should I create a maven project containing the POJO with the required properties which will be marshalled and send via RabbitMQ and add dependency to this project in both Hera and Zeus? Or should I just add this information as a list of plain properties?

I could not find any best practices or guidelines on this subject, so I'm asking you.

Thank you in advance!

答:
I suggest that you use POJO + JSON + GSON like this:

POJO(DTO) -> Serialize to JSON (Using GSON) -> Transfer it over Message Broker (RabbitMQ) -> Deserialize it (Using GSON) -> Getting POJO(DTO) again and Consuming it.

This Approach is common when you are using Event sourcing + CQRS and when you want adhere to CAP theorem and Using BASE instead of ACID (ACID is not possible to be implemented in distributing systems)


问:
Linux kernel module compiling
I try to compile simple linux kernel module:

```<code>#include <linux/module.h>
#include <linux/kernel.h>

int init_module(void)
{
        printk("Hello world 1.\n");
        return 0;
}

void cleanup_module(void)
{
        printk(KERN_ALERT "Goodbye world 1.\n");
}
</code>```

My makefile:

```<code>obj-m = testmodule.o
KVERSION = $(shell uname -r)
all:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean
</code>```

Now i haven't errors in my .c file.

But when i try make in terminal: make: Nothing to be done for `all'.

What's wrong?

Thank you.

答:
This is because your Makefile contains no tab before giving make command

```<code>make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
</code>```

So normally your file should be like below:

```<code>obj-m = test.o

KVERSION = $(shell uname -r)

all:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean
</code>```

Title: Linux kernel module compiling

Body:
I try to compile simple linux kernel module:

#include <linux/module.h>
#include <linux/kernel.h>

int init_module(void)
{
        printk("Hello world 1.\n");
        return 0;
}

void cleanup_module(void)
{
        printk(KERN_ALERT "Goodbye world 1.\n");
}

My makefile:

obj-m = testmodule.o
KVERSION = $(shell uname -r)
all:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean

Now i haven't errors in my .c file.

But when i try make in terminal: make: Nothing to be done for `all'.

What's wrong?

Thank you.

Body:
This is because your Makefile contains no tab before giving make command

make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules

So normally your file should be like below:

obj-m = test.o

KVERSION = $(shell uname -r)

all:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean


问:
Size of compiled vue apps
I have 3.6kb worth of .vue component files. Minified vue is 77kb, but when I build them with webpack I end up with a file that's 84kb.

Is this just overhead from translating templates into js? Is it overhead from webpack? Is it just expected to have this kind of overhead for bundling separate JS files?

When I use browserify it gets the file size down to 61kb (Wow) but then it doesn't work. Vue starts up and replaces the template but it's blank, created never gets called.

答: Browserify is a bit smaller, but not much. The 20kb less file size was a bug in the vue template</p>

Title: Size of compiled vue apps


问:
'sorry some error occurred' while integrating PayUMoney payment gateway in asp.net mvc
I'm trying to integrate PayUMoney payment gateway in my client site.

1) My account is already activated.

2) Merchant key & Salt key is right.

3) I have already added payu_paisa in service provider field.

when adding more than 700 amounts it gives the message: sorry some error occurred.

Here is the code:

```<code>public ActionResult PaymentWithPayuMoney()
    {

        var objOrderBal = new OrderBal();
        var objOrderDetail = objOrderBal.GetOrderDetail(User.Identity.GetUserId());
        //var userDetails = UserManager.FindById(User.Identity.GetUserId());
        var userDetails = objOrderBal.GetOrder(User.Identity.GetUserId());
        var ordersubTotal = 0.00m;
        var shipping = 0;
        foreach (var objOrder in objOrderDetail)
        {
            ordersubTotal = objOrder.TotalPrice * objOrder.Quantity + ordersubTotal;
            shipping = Convert.ToInt32(shipping) + Convert.ToInt32(objOrder.ShippingCharge);
        }

        var orderTotal = Convert.ToString(Convert.ToDouble(shipping) + Convert.ToDouble(ordersubTotal), CultureInfo.InvariantCulture);
        var key = ConfigurationManager.AppSettings["MERCHANT_KEY"];
        var myremotepost = new RemotePost { Url = ConfigurationManager.AppSettings["PAYU_BASE_URL"] + "/_payment" };
        myremotepost.Add("key", key);
        myremotepost.Add("txnid", Generatetxnid());
        myremotepost.Add("amount", orderTotal);
        myremotepost.Add("productinfo", "productname");
        myremotepost.Add("firstname", userDetails.Name);
        myremotepost.Add("phone", userDetails.MobileNo);
        myremotepost.Add("email", userDetails.Email);
        if (Request.Url != null)
        {
            myremotepost.Add("surl", "" + Request.Url.Scheme + "://" + Request.Url.Authority + "/Order/Return");
            myremotepost.Add("furl", "" + Request.Url.Scheme + "://" + Request.Url.Authority + "/Order/Return");
        }
        myremotepost.Add("service_provider", "payu_paisa");

        string hashString = key + "|" + Generatetxnid() + "|" + orderTotal + "|productname|" + userDetails.Name + "|" + userDetails.Email + "|||||||||||" + ConfigurationManager.AppSettings["SALT"];
        string hash = Generatehash512(hashString);
        myremotepost.Add("hash", hash);
        myremotepost.Post();
        return View("SuccessView");
    }

    public class RemotePost
    {
        public readonly System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();

        public string Url = "";
        public string Method = "post";
        public string FormName = "form1";

        public void Add(string name, string value)
        {
            Inputs.Add(name, value);
        }

        public void Post()
            {
            System.Web.HttpContext.Current.Response.Clear();

            System.Web.HttpContext.Current.Response.Write("<html><head>");

            System.Web.HttpContext.Current.Response.Write($"</head><body onload=\"document.{FormName}.submit()\">");
            System.Web.HttpContext.Current.Response.Write($"<form name=\"{FormName}\" method=\"{Method}\" action=\"{Url}\" >");
            for (var i = 0; i < Inputs.Keys.Count; i++)
            {
                System.Web.HttpContext.Current.Response.Write($"<input name=\"{Inputs.Keys[i]}\" type=\"hidden\" value=\"{Inputs[Inputs.Keys[i]]}\">");
            }
            System.Web.HttpContext.Current.Response.Write("</form>");
            System.Web.HttpContext.Current.Response.Write("</body></html>");

            System.Web.HttpContext.Current.Response.End();
        }
    }

    public string Generatehash512(string text)
    {
        var message = Encoding.UTF8.GetBytes(text);
        var hashString = new SHA512Managed();
        var hashValue = hashString.ComputeHash(message);
        return hashValue.Aggregate("", (current, x) => current + $"{x:x2}");
    }

    public string Generatetxnid()
    {
        var rnd = new Random();
        var strHash = Generatehash512(rnd.ToString() + DateTime.Now);
        var txnid1 = strHash.Substring(0, 20);
        return txnid1;
    }
</code>```

答: Please check the hash calculated by you is matching with the one generated at payu server.</p>

Body:
I'm trying to integrate PayUMoney payment gateway in my client site.

1) My account is already activated.

2) Merchant key & Salt key is right.

3) I have already added payu_paisa in service provider field.

when adding more than 700 amounts it gives the message: sorry some error occurred.

Here is the code:

public ActionResult PaymentWithPayuMoney()
    {

        var objOrderBal = new OrderBal();
        var objOrderDetail = objOrderBal.GetOrderDetail(User.Identity.GetUserId());
        //var userDetails = UserManager.FindById(User.Identity.GetUserId());
        var userDetails = objOrderBal.GetOrder(User.Identity.GetUserId());
        var ordersubTotal = 0.00m;
        var shipping = 0;
        foreach (var objOrder in objOrderDetail)
        {
            ordersubTotal = objOrder.TotalPrice * objOrder.Quantity + ordersubTotal;
            shipping = Convert.ToInt32(shipping) + Convert.ToInt32(objOrder.ShippingCharge);
        }

        var orderTotal = Convert.ToString(Convert.ToDouble(shipping) + Convert.ToDouble(ordersubTotal), CultureInfo.InvariantCulture);
        var key = ConfigurationManager.AppSettings["MERCHANT_KEY"];
        var myremotepost = new RemotePost { Url = ConfigurationManager.AppSettings["PAYU_BASE_URL"] + "/_payment" };
        myremotepost.Add("key", key);
        myremotepost.Add("txnid", Generatetxnid());
        myremotepost.Add("amount", orderTotal);
        myremotepost.Add("productinfo", "productname");
        myremotepost.Add("firstname", userDetails.Name);
        myremotepost.Add("phone", userDetails.MobileNo);
        myremotepost.Add("email", userDetails.Email);
        if (Request.Url != null)
        {
            myremotepost.Add("surl", "" + Request.Url.Scheme + "://" + Request.Url.Authority + "/Order/Return");
            myremotepost.Add("furl", "" + Request.Url.Scheme + "://" + Request.Url.Authority + "/Order/Return");
        }
        myremotepost.Add("service_provider", "payu_paisa");

        string hashString = key + "|" + Generatetxnid() + "|" + orderTotal + "|productname|" + userDetails.Name + "|" + userDetails.Email + "|||||||||||" + ConfigurationManager.AppSettings["SALT"];
        string hash = Generatehash512(hashString);
        myremotepost.Add("hash", hash);
        myremotepost.Post();
        return View("SuccessView");
    }

    public class RemotePost
    {
        public readonly System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();

        public string Url = "";
        public string Method = "post";
        public string FormName = "form1";

        public void Add(string name, string value)
        {
            Inputs.Add(name, value);
        }

        public void Post()
            {
            System.Web.HttpContext.Current.Response.Clear();

            System.Web.HttpContext.Current.Response.Write("");

            System.Web.HttpContext.Current.Response.Write($"");
            System.Web.HttpContext.Current.Response.Write($"<form name=\"{FormName}\" method=\"{Method}\" action=\"{Url}\" >");
            for (var i = 0; i < Inputs.Keys.Count; i++)
            {
                System.Web.HttpContext.Current.Response.Write($"<input name=\"{Inputs.Keys[i]}\" type=\"hidden\" value=\"{Inputs[Inputs.Keys[i]]}\">");
            }
            System.Web.HttpContext.Current.Response.Write("</form>");
            System.Web.HttpContext.Current.Response.Write("");

            System.Web.HttpContext.Current.Response.End();
        }
    }

    public string Generatehash512(string text)
    {
        var message = Encoding.UTF8.GetBytes(text);
        var hashString = new SHA512Managed();
        var hashValue = hashString.ComputeHash(message);
        return hashValue.Aggregate("", (current, x) => current + $"{x:x2}");
    }

    public string Generatetxnid()
    {
        var rnd = new Random();
        var strHash = Generatehash512(rnd.ToString() + DateTime.Now);
        var txnid1 = strHash.Substring(0, 20);
        return txnid1;
    }


问:
How to scale border on a div?
I used borders to make 4 right triangles in the corners of the screen on divs. This is the link that I used to make this. http://www.howtocreate.co.uk/tutorials/css/slopes

How can I scale this border based on window size? For example I want each triangle to take up 33% of the width and 25% of the height of the browser.

Would prefer if there is a solution in CSS or jQuery.

This is the link to a simplified version of my HTML and CSS. I shrunk the triangle to make them fit (on my site the triangles are 350px by 250px, so they need to be scaled down when window is resized). https://jsfiddle.net/9L5fkohr/enter code here

答:
You could use:

```<code>#topLeftTriangle {
  font-size: 0px;
  line-height: 0%;
  width: 0px;
  border-top: 25vh solid #ceecec;
  border-right: 33vw solid transparent;
  float: left;
}
</code>```

25vh = screen height

33vw = screen width

REF: https://developer.mozilla.org/en/docs/Mozilla/Mobile/Viewport_meta_tag

Alos I added body { margin: 0; } to remove default margion from body.

body {
  margin: 0;
}

#wrapper {
  background-color: #ffffff;
  width: 100%;
  height: 100%;
}

#topRow {
  width: 100%;
}

.topRowElement {
  display: inline;
  float: left;
  width: 33.33%;
}

#topLeftTriangle {
  font-size: 0px;
  line-height: 0%;
  width: 0px;
  border-top: 25vh solid #ceecec;
  border-right: 33vw solid transparent;
  float: left;
}

#title {
  text-align: center;
}

#topRightTriangle {
  font-size: 0px;
  line-height: 0%;
  width: 0px;
  border-top: 25vh solid #ceecec;
  border-left: 33vw solid transparent;
  float: right;
}

.portalC {
  display: inline;
  float: left;
  width: 50%;
}

.portal {
  text-align: center;
}

.botRowElement {
  display: inline;
  width: 33.33%;
}

#botRow {
  position: fixed;
  bottom: 0px;
  width: 100%;
}

#botLeftTriangleC {
  font-size: 0px;
  line-height: 0%;
  width: 0px;
  border-bottom: 25vh solid #ceecec;
  border-right: 33vw solid transparent;
  float: left;
}

#botRightTriangleC {
  font-size: 0px;
  line-height: 0%;
  width: 0px;
  border-bottom: 25vh solid #ceecec;
  border-left: 33vw solid transparent;
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="wrapper">
    <div id="topRow">
      <div class="triangleC topRowElement" id="topLeftTriangleC">
        <div class="triangle" id="topLeftTriangle">
          triangle
        </div>
      </div>
      <div class="topRowElement" id="titleC">
        <div id="title">
          Title
        </div>
      </div>
      <div class="triangleC topRowElement" id="topRightTriangleC">
        <div class="triangle" id="topRightTriangle">
          triangle
        </div>
      </div>
    </div>
    <div id="main">
      <div id="portalMenu">
        <div class="portalC" id="docPortalC">
          <div class="portal" id="docPortal">
            Head1
          </div>
        </div>
        <div class="portalC" id="pharmaPortalC">
          <div class="portal" id="pharmaPortal">
            Head2
          </div>
        </div>
      </div>
    </div>
    <div id="botRow">
      <div class="triangleC botRowElement" id="botLeftTriangleC">
        <div class="triangle" id="botLeftTriangle">
          triangle
        </div>
      </div>
      <div class="triangleC botRowElement" id="botRightTriangleC">
        <div class="triangle" id="botRightTriangle">
          triangle
        </div>
      </div>
    </div>
  </div>
</body></code>```

Title: How to scale border on a div?

Body:
You could use:

#topLeftTriangle {
  font-size: 0px;
  line-height: 0%;
  width: 0px;
  border-top: 25vh solid #ceecec;
  border-right: 33vw solid transparent;
  float: left;
}

25vh = screen height

33vw = screen width

REF: https://developer.mozilla.org/en/docs/Mozilla/Mobile/Viewport_meta_tag

Alos I added body { margin: 0; } to remove default margion from body.

body {
  margin: 0;
}

#wrapper {
  background-color: #ffffff;
  width: 100%;
  height: 100%;
}

#topRow {
  width: 100%;
}

.topRowElement {
  display: inline;
  float: left;
  width: 33.33%;
}

#topLeftTriangle {
  font-size: 0px;
  line-height: 0%;
  width: 0px;
  border-top: 25vh solid #ceecec;
  border-right: 33vw solid transparent;
  float: left;
}

#title {
  text-align: center;
}

#topRightTriangle {
  font-size: 0px;
  line-height: 0%;
  width: 0px;
  border-top: 25vh solid #ceecec;
  border-left: 33vw solid transparent;
  float: right;
}

.portalC {
  display: inline;
  float: left;
  width: 50%;
}

.portal {
  text-align: center;
}

.botRowElement {
  display: inline;
  width: 33.33%;
}

#botRow {
  position: fixed;
  bottom: 0px;
  width: 100%;
}

#botLeftTriangleC {
  font-size: 0px;
  line-height: 0%;
  width: 0px;
  border-bottom: 25vh solid #ceecec;
  border-right: 33vw solid transparent;
  float: left;
}

#botRightTriangleC {
  font-size: 0px;
  line-height: 0%;
  width: 0px;
  border-bottom: 25vh solid #ceecec;
  border-left: 33vw solid transparent;
  float: right;
}

<body>
  <div id="wrapper">
    <div id="topRow">
      <div class="triangleC topRowElement" id="topLeftTriangleC">
        <div class="triangle" id="topLeftTriangle">
          triangle
        </div>
      </div>
      <div class="topRowElement" id="titleC">
        <div id="title">
          Title
        </div>
      </div>
      <div class="triangleC topRowElement" id="topRightTriangleC">
        <div class="triangle" id="topRightTriangle">
          triangle
        </div>
      </div>
    </div>
    <div id="main">
      <div id="portalMenu">
        <div class="portalC" id="docPortalC">
          <div class="portal" id="docPortal">
            Head1
          </div>
        </div>
        <div class="portalC" id="pharmaPortalC">
          <div class="portal" id="pharmaPortal">
            Head2
          </div>
        </div>
      </div>
    </div>
    <div id="botRow">
      <div class="triangleC botRowElement" id="botLeftTriangleC">
        <div class="triangle" id="botLeftTriangle">
          triangle
        </div>
      </div>
      <div class="triangleC botRowElement" id="botRightTriangleC">
        <div class="triangle" id="botRightTriangle">
          triangle
        </div>
      </div>
    </div>
  </div>
</body>


问:
Python catch int or str
I've written a program that generates a random number for the user to guess. I'm working on trying to catch all the possible errors. The only one I can't seem to figure out is this. At the beginning I ask the user to hit enter to continue to the game. The program catches if they type a string or even special characters and punctuation. The only thing I can't seem to prevent is if they they type a number, the program terminates. This is what I have. The issue is in the first while loop in the try block. Any suggestions or help would be appreciated.
Thanks in advance.</p>

```<code>from random import randint #imports randint from random class

cont = input('Press enter to continue')

while True:
    if cont != '':
        try:
            int(cont)
            str(cont)
            break
        except ValueError:
            print('Just hit enter')
            cont = input()
            continue
    elif cont == '':
        while True:

            randNum = randint(1, 100)
            print('Try guesssing a number between 1 and 100')
            num = input()

            while True:
                try:
                    int(num)
                    break
                except ValueError:
                    print('Please enter a number')
                    num = input()

                int(num)
            if num == randNum:
                print('Good job, ' + str(num) + ' is correct.')
            else:
            print('Sorry, the number was ' + str(randNum) + '.')

        print('Would you like to try again?')
        answer = input().lower()
        if answer == 'yes':
            continue
        elif answer == 'no':
            print('Thanks for playing')
            exit()
        else:
            while True:
                print('Please type yes or no')
                answer = input()
                if answer == 'yes':
                    break
                elif answer == 'no':
                    print('Thanks for playing.')
                    exit()
</code>```

答:
What happens when you enter a number is that the program tries to convert the number to an int (which works), and then to a str (which also works), after which it breaks. Instead, try the following:

```<code>from random import randint #imports randint from random class

cont = input('Press enter to continue')

while cont != '':
    cont = input('Press enter to continue')

while True:

    randNum = randint(1, 100)
    print('Try guesssing a number between 1 and 100')
    num = input()

    while True:
        try:
            int(num)
            break
        except ValueError:
            print('Please enter a number')
            num = input()

        num = int(num)
    if num == randNum:
        print('Good job, ' + str(num) + ' is correct.')
    else:
    print('Sorry, the number was ' + str(randNum) + '.')

print('Would you like to try again?')
answer = input().lower()
if answer == 'yes':
    continue
elif answer == 'no':
    print('Thanks for playing')
    exit()
else:
    while True:
        print('Please type yes or no')
        answer = input()
        if answer == 'yes':
            break
        elif answer == 'no':
            print('Thanks for playing.')
            exit()
</code>```

Title: Python catch int or str

Body:
I've written a program that generates a random number for the user to guess. I'm working on trying to catch all the possible errors. The only one I can't seem to figure out is this. At the beginning I ask the user to hit enter to continue to the game. The program catches if they type a string or even special characters and punctuation. The only thing I can't seem to prevent is if they they type a number, the program terminates. This is what I have. The issue is in the first while loop in the try block. Any suggestions or help would be appreciated.
Thanks in advance.

from random import randint #imports randint from random class

cont = input('Press enter to continue')

while True:
    if cont != '':
        try:
            int(cont)
            str(cont)
            break
        except ValueError:
            print('Just hit enter')
            cont = input()
            continue
    elif cont == '':
        while True:

            randNum = randint(1, 100)
            print('Try guesssing a number between 1 and 100')
            num = input()

            while True:
                try:
                    int(num)
                    break
                except ValueError:
                    print('Please enter a number')
                    num = input()

                int(num)
            if num == randNum:
                print('Good job, ' + str(num) + ' is correct.')
            else:
            print('Sorry, the number was ' + str(randNum) + '.')

        print('Would you like to try again?')
        answer = input().lower()
        if answer == 'yes':
            continue
        elif answer == 'no':
            print('Thanks for playing')
            exit()
        else:
            while True:
                print('Please type yes or no')
                answer = input()
                if answer == 'yes':
                    break
                elif answer == 'no':
                    print('Thanks for playing.')
                    exit()

Body:
What happens when you enter a number is that the program tries to convert the number to an int (which works), and then to a str (which also works), after which it breaks. Instead, try the following:

from random import randint #imports randint from random class

cont = input('Press enter to continue')

while cont != '':
    cont = input('Press enter to continue')

while True:

    randNum = randint(1, 100)
    print('Try guesssing a number between 1 and 100')
    num = input()

    while True:
        try:
            int(num)
            break
        except ValueError:
            print('Please enter a number')
            num = input()

        num = int(num)
    if num == randNum:
        print('Good job, ' + str(num) + ' is correct.')
    else:
    print('Sorry, the number was ' + str(randNum) + '.')

print('Would you like to try again?')
answer = input().lower()
if answer == 'yes':
    continue
elif answer == 'no':
    print('Thanks for playing')
    exit()
else:
    while True:
        print('Please type yes or no')
        answer = input()
        if answer == 'yes':
            break
        elif answer == 'no':
            print('Thanks for playing.')
            exit()


问:
How to create a cron job using Bash automatically without the interactive editor?
Does crontab have an argument for creating cron jobs without using the editor (crontab -e)? If so, what would be the code to create a cron job from a Bash script?

答:
Here is a bash function for adding a command to crontab without duplication

```<code>function addtocrontab () {
  local frequency=$1
  local command=$2
  local job="$frequency $command"
  cat <(fgrep -i -v "$command" <(crontab -l)) <(echo "$job") | crontab -
}
addtocrontab "0 0 1 * *" "echo hello"
</code>```

Body:
Here is a bash function for adding a command to crontab without duplication

function addtocrontab () {
  local frequency=$1
  local command=$2
  local job="$frequency $command"
  cat <(fgrep -i -v "$command" <(crontab -l)) <(echo "$job") | crontab -
}
addtocrontab "0 0 1 * *" "echo hello"


问:
In Django forms, how do I "add" an error into the queue?
```<code>def clean(self):
        cleaned_data = self.cleaned_data
        current_pass = cleaned_data['current_pass']
        new_pass = cleaned_data['new_pass']
        new_pass2 = cleaned_data['new_pass2']
        if current_pass or new_pass or new_pass2:
            if not current_pass:
                raise forms.ValidationError("- You must enter your current password.")
            if not new_pass:
                raise forms.ValidationError("- You must enter a new password.")
            if not new_pass2:
                raise forms.ValidationError("- You must re-confirm your new password.")
        return cleaned_data
</code>```

Right now, I raise my errors. But this means that the other errors won't pop up. it ends the function when I raise the first one. What if I want to have all 3 errors?

答:
A solution could be to bind those errors to the relevant fields, as explained in the docs.

Your code would look like this:

```<code>def clean(self):
    cleaned_data = self.cleaned_data
    current_pass = cleaned_data['current_pass']
    new_pass = cleaned_data['new_pass']
    new_pass2 = cleaned_data['new_pass2']
    if current_pass or new_pass or new_pass2:
        if not current_pass:
            self._errors["current_pass"] = self.error_class(["- You must enter your current password."])
        if not new_pass:
            self._errors["new_pass"] = self.error_class(["- You must enter a new password."])
        if not new_pass2:
            self._errors["new_pass2"] = self.error_class(["- You must re-confirm your new password."])
        del cleaned_data["current_pass"]
        del cleaned_data["new_pass"]
        del cleaned_data["new_pass2"]
    return cleaned_data
</code>```

Please beware that I could not test it personally though.

Body:
def clean(self):
        cleaned_data = self.cleaned_data
        current_pass = cleaned_data['current_pass']
        new_pass = cleaned_data['new_pass']
        new_pass2 = cleaned_data['new_pass2']
        if current_pass or new_pass or new_pass2:
            if not current_pass:
                raise forms.ValidationError("- You must enter your current password.")
            if not new_pass:
                raise forms.ValidationError("- You must enter a new password.")
            if not new_pass2:
                raise forms.ValidationError("- You must re-confirm your new password.")
        return cleaned_data

Right now, I raise my errors. But this means that the other errors won't pop up. it ends the function when I raise the first one. What if I want to have all 3 errors?

Body:
A solution could be to bind those errors to the relevant fields, as explained in the docs.

Your code would look like this:

def clean(self):
    cleaned_data = self.cleaned_data
    current_pass = cleaned_data['current_pass']
    new_pass = cleaned_data['new_pass']
    new_pass2 = cleaned_data['new_pass2']
    if current_pass or new_pass or new_pass2:
        if not current_pass:
            self._errors["current_pass"] = self.error_class(["- You must enter your current password."])
        if not new_pass:
            self._errors["new_pass"] = self.error_class(["- You must enter a new password."])
        if not new_pass2:
            self._errors["new_pass2"] = self.error_class(["- You must re-confirm your new password."])
        del cleaned_data["current_pass"]
        del cleaned_data["new_pass"]
        del cleaned_data["new_pass2"]
    return cleaned_data

Please beware that I could not test it personally though.


问:
CoreData not saving attribute as string
Below is my saving method

```<code>-(void)createData
{
    //    // get date and time and store in two separate variables
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd/MM/yyyy"];
    NSString *dateString = [dateFormat stringFromDate:today];
    NSLog(@"Date is: %@",dateString);
    NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
    timeFormatter.dateFormat = @"HH:mm";
    NSString *timeString = [timeFormatter stringFromDate:today];
    NSLog(@"Time is: %@",timeString);
    //
    //

    ReminderInfo *reminderInfo = [NSEntityDescription insertNewObjectForEntityForName:@"ReminderInfo" inManagedObjectContext:[DataManager sharedDataManager].managedObjectContext];

    reminderInfo.date = today;
    reminderInfo.reminderTime = @"06:30";
    reminderInfo.medicationType = @"Cream";
    [[DataManager sharedDataManager] saveReminderInfo:reminderInfo];
    NSLog(@"reminder created");

}
</code>```

Below is the output from console:

```<code><ReminderInfo: 0x6080002887a0> (entity: ReminderInfo; id: 0xd000000000480002 <x-coredata://8055FB8D-6E6A-44B2-9456-3E6932ACBE32/ReminderInfo/p18> ; data: {
    date = "2017-06-03 08:03:40 +0000";
    medicationType = Cream;
    reminderTime = "06:30";
})
</code>```

medicationType is an attribute with String type. As you can see from the console, there isn't any "" in Cream. Could this be the reason im not saving anything to coredata?

答: The lack of quote marks there has nothing to do with the data type. When printing a Core Data object to the Xcode console, quote marks are not used if there are no spaces in the string. What you are seeing is exactly what would be expected for the string you're using. If you changed the string to @"Cream cheese", you would see quote marks, but the data type would be the same. If it wasn't a string, Core Core Data would have no way to convert the value-- a numeric type maybe?-- to Cream.

Title: CoreData not saving attribute as string

Body:
Below is my saving method

-(void)createData
{
    //    // get date and time and store in two separate variables
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd/MM/yyyy"];
    NSString *dateString = [dateFormat stringFromDate:today];
    NSLog(@"Date is: %@",dateString);
    NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
    timeFormatter.dateFormat = @"HH:mm";
    NSString *timeString = [timeFormatter stringFromDate:today];
    NSLog(@"Time is: %@",timeString);
    //
    //

    ReminderInfo *reminderInfo = [NSEntityDescription insertNewObjectForEntityForName:@"ReminderInfo" inManagedObjectContext:[DataManager sharedDataManager].managedObjectContext];

    reminderInfo.date = today;
    reminderInfo.reminderTime = @"06:30";
    reminderInfo.medicationType = @"Cream";
    [[DataManager sharedDataManager] saveReminderInfo:reminderInfo];
    NSLog(@"reminder created");

}

Below is the output from console:

<ReminderInfo: 0x6080002887a0> (entity: ReminderInfo; id: 0xd000000000480002 <x-coredata://8055FB8D-6E6A-44B2-9456-3E6932ACBE32/ReminderInfo/p18> ; data: {
    date = "2017-06-03 08:03:40 +0000";
    medicationType = Cream;
    reminderTime = "06:30";
})

medicationType is an attribute with String type. As you can see from the console, there isn't any "" in Cream. Could this be the reason im not saving anything to coredata?


问:
Split CSV file after specified row Python
I'm trying to split a CSV file that has 201 rows. The first 136 rows contains information that is different from the remaining 65 rows. Is there anyway I can split the CSV file after 136 rows?

The solutions I have found so far split the file evenly. I have looked into this as a possible solution as well: https://gist.github.com/jrivero/1085501

答: If you know the number of lines you need to skip you can use csvreader.line_num to know the line you're reading, you can find more info about it here: https://docs.python.org/2/library/csv.html#reader-objects


答:
```<code>while True:
    if cont != '':
        try:
            int(cont)
            str(cont)
            break
</code>```

What it does here is try and convert cont to an int, if it succeeds it tries to convert it to a string (which is virtually always possible). If that succeeds it breaks the while loop and ends the program.
In any other scenario other than an int when it tries to parse it int(cont) it raises an error and you continue to your program.

Once he pressed enter cont starts. there is no reason for you to verify he didn't write something before entering the text.

Title: Python catch int or str

Body:
while True:
    if cont != '':
        try:
            int(cont)
            str(cont)
            break

What it does here is try and convert cont to an int, if it succeeds it tries to convert it to a string (which is virtually always possible). If that succeeds it breaks the while loop and ends the program.
In any other scenario other than an int when it tries to parse it int(cont) it raises an error and you continue to your program.

Once he pressed enter cont starts. there is no reason for you to verify he didn't write something before entering the text.


问:
Read a config file in BASH without using "source"
I'm attempting to read a config file that is formatted as follows:

```<code>USER = username
TARGET = arrows
</code>```

I realize that if I got rid of the spaces, I could simply source the config file, but for security reasons I'm trying to avoid that.  I know there is a way to read the config file line by line.  I think the process is something like:

Read lines into an array

Filter out all of the lines that start with #

search for the variable names in the array

After that I'm lost.  Any and all help would be greatly appreciated. I've tried something like this with no success:

```<code>backup2.config>cat ~/1

grep '^[^#].*' | while read one two;do
    echo $two
done
</code>```

I pulled that from a forum post I found, just not sure how to modify it to fit my needs since I'm so new to shell scripting.

http://www.linuxquestions.org/questions/programming-9/bash-shell-program-read-a-configuration-file-276852/

Would it be possible to automatically assign a variable by looping through both arrays?

```<code>for (( i = 0 ; i < ${#VALUE[@]} ; i++ ))
do
    "${NAME[i]}"=VALUE[i]
done
echo $USER
</code>```

Such that calling $USER would output "username"?  The above code isn't working but I know the solution is something similar to that.

答:
The following script iterates over each line in your input file (vars in my case) and does a pattern match against =. If the equal sign is found it will use Parameter Expansion to parse out the variable name from the value.  It then stores each part in it's own array, name and value respectively.

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

i=0
while read line; do
  if [[ "$line" =~ ^[^#]*= ]]; then
    name[i]=${line%% =*}
    value[i]=${line#*= }
    ((i++))
  fi
done < vars

echo "total array elements: ${#name[@]}"
echo "name[0]: ${name[0]}"
echo "value[0]: ${value[0]}"
echo "name[1]: ${name[1]}"
echo "value[1]: ${value[1]}"
echo "name array: ${name[@]}"
echo "value array: ${value[@]}"
</code>```

Input

```<code>$ cat vars
sdf
USER = username
TARGET = arrows
asdf
as23
</code>```

Output

```<code>$ ./varscript
total array elements: 2
name[0]: USER
value[0]: username
name[1]: TARGET
value[1]: arrows
name array: USER TARGET
value array: username arrows
</code>```

Body:
I'm attempting to read a config file that is formatted as follows:

USER = username
TARGET = arrows

I realize that if I got rid of the spaces, I could simply source the config file, but for security reasons I'm trying to avoid that.  I know there is a way to read the config file line by line.  I think the process is something like:

Read lines into an array

Filter out all of the lines that start with #

search for the variable names in the array

After that I'm lost.  Any and all help would be greatly appreciated. I've tried something like this with no success:

backup2.config>cat ~/1

grep '^[^#].*' | while read one two;do
    echo $two
done

I pulled that from a forum post I found, just not sure how to modify it to fit my needs since I'm so new to shell scripting.

http://www.linuxquestions.org/questions/programming-9/bash-shell-program-read-a-configuration-file-276852/

Would it be possible to automatically assign a variable by looping through both arrays?

for (( i = 0 ; i < ${#VALUE[@]} ; i++ ))
do
    "${NAME[i]}"=VALUE[i]
done
echo $USER

Such that calling $USER would output "username"?  The above code isn't working but I know the solution is something similar to that.

Body:
The following script iterates over each line in your input file (vars in my case) and does a pattern match against =. If the equal sign is found it will use Parameter Expansion to parse out the variable name from the value.  It then stores each part in it's own array, name and value respectively.

#!/bin/bash

i=0
while read line; do
  if [[ "$line" =~ ^[^#]*= ]]; then
    name[i]=${line%% =*}
    value[i]=${line#*= }
    ((i++))
  fi
done < vars

echo "total array elements: ${#name[@]}"
echo "name[0]: ${name[0]}"
echo "value[0]: ${value[0]}"
echo "name[1]: ${name[1]}"
echo "value[1]: ${value[1]}"
echo "name array: ${name[@]}"
echo "value array: ${value[@]}"

Input

$ cat vars
sdf
USER = username
TARGET = arrows
asdf
as23

Output

$ ./varscript
total array elements: 2
name[0]: USER
value[0]: username
name[1]: TARGET
value[1]: arrows
name array: USER TARGET
value array: username arrows


问:
How to get the desktop resolution in Mac via Python?
Trying to write a python application that downloads images from an RSS feed, and makes a composite background. How do I get the current desktop resolution on Mac OS X (leopard?)</p>

答:
I was having a hard time getting any of this to work so I looked around and put something together that seems to work. I am kinda new at coding so please excuse any errors. If you have any thoughts please comment. </p>

```<code>results = str(subprocess.Popen(['system_profiler SPDisplaysDataType'],stdout=subprocess.PIPE, shell=True).communicate()[0])
res = re.search('Resolution: \d* x \d*', results).group(0).split(' ')
width, height = res[1], res[3]
return width, height
</code>```

Body:
I was having a hard time getting any of this to work so I looked around and put something together that seems to work. I am kinda new at coding so please excuse any errors. If you have any thoughts please comment.

results = str(subprocess.Popen(['system_profiler SPDisplaysDataType'],stdout=subprocess.PIPE, shell=True).communicate()[0])
res = re.search('Resolution: \d* x \d*', results).group(0).split(' ')
width, height = res[1], res[3]
return width, height