问:
Questions about R package publishing and code visibility
When I use a package in R I install it and use it with loading it. Now what if I add a package which uses another package? Is this package automatically downloaded and loaded too? Or is it in general forbidden for a R package to use another package? I don't think that.

Suppose I want to publish a R package. Within my code, can I use functions from other packages and install and load these packages? Or how does this work when I need functions from other packages? Do I have to implement a message that this and that package is needed and that the user has to install and load it prior to it and I need to implement error catching functions in case the package cannot be found on the pc system?

When I want to publish a R package, can I use/call Java code within my package/code?

For a package which was already published - so let's take just as an example the fGarch package - I would like to see the complete code. How can I see this? I know that R is open source and I think it is more or less possible to just enter a function empty and get the code displayed, but sometimes this does not work and especially my question is: Is there a way I can look into the whole code of the package?

For a package which was already published, is it possible to see and look into all files which were submitted? So like a repository as git where all files are submitted - the code itself and further files which are needed like description files or whatever - and I can see these files and look into them?

Furthermore regarding this post here and hiding functions: Is there code in a R package which I cannot see as an end user? This refers also to my previous question, how can I or which way can I see the whole code in a R package?

答:
I guess you have a few different questions here. Let's take them in the order you asked them:

What if I add a package which uses another package? Is this package automatically downloaded and loaded too? Or is it in general forbidden for a R package to use another package?

It is certainly not forbidden for an R package to use another R package. In fact, the majority of R packages rely on other packages.

The source code for each R package must include a text-based DESCRIPTION file in the root directory. In this file you will find (among other things) a "Depends" field, and an "Imports" field. Together, these two fields list all the other packages required to use this package. If a user doesn't already have these other packages installed in their local library, R will install them automatically when it installs the requested package.

If your package lists a dependency in "Depends", then the dependency package is attached whenever your package is attached. Thus if you looked at the source code for a package called "foo" and you see that its DESCRIPTION file contains the line

Depends: bar,
```
<p>you know that when you call <code>library(foo)</code> in your R console, you have effectively done <code>library(bar); library(foo)</code></p>
<p>This isn't always ideal. The package <code>foo</code> might only need a couple of functions from package <code>bar</code>, and <code>bar</code> might contain some other functions whose names could clash with other commonly used functions. Therefore, in general, if you are writing a package and you only want to use a few functions from another package, it would be better to use "Imports" rather than "Depends" to limit the number of unnecessary symbols being added to your user's search path.</p>
<hr />
<blockquote>
<p><strong>Suppose I want to publish a R package. Within my code, can I use functions from other packages and install and load these packages</strong></p>
</blockquote>
<p>Yes, you can use functions from other packages. The simplest way to do this is to include the name of the package in the <code>Depends</code> field of your <code>DESCRIPTION</code> file.</p>
<p>However, when using just a few functions from another package inside your own package, best practice is to use the "Imports" field in the <code>DESCRIPTION</code> file, and use a namespace qualifier for the imported function in your actual R code. For example, if you wanted to use <code>ggplot</code> from the <code>ggplot2</code> package, then inside your function you would call it <code>ggplot2::ggplot</code> rather than just <code>ggplot</code>.</p>
<p>If you publish your package for others to use, the dependencies will be installed automatically along with your package if the user calls <code>install.packages</code> with the default settings. For example, when I did:</p>
```install.packages("fGarch")
```
<p>I got the associated message:</p>
```#> also installing the dependencies ‘timeSeries’, ‘fBasics’, ‘fastICA’
```

Do I have to implement a message that this and that package is needed and that the user has to install and load it prior to it and I need to implement error catching functions in case the package cannot be found on the pc system?

No, not in general. R will take care of this as long as you have listed the correct packages in your DESCRIPTION file.

When I want to publish a R package, can I use/call Java code within my package/code?

R does not have a native Java API, but you can use your own Java code via the rJava package, which you can list as a dependency for your package. However, there are some users who have difficulty getting Java to run, for example business and academic users who may use R but do not have Java installed and do not have admin rights to install it, so this is something to bear in mind when writing a package.

For a package which was already published - so let's take just as an example the fGarch package - I would like to see the complete code. How can I see this?

Every package available for download from CRAN has its source code available. In the case of fGarch, its CRAN page contains a link to the gzipped tarball of the source code. You can download this and use untar in R to review all the source code. Alternatively, many packages will have an easily-found repository on Github or other source-control sites where you can examine the source code via a browser. For example, you can browse the fGarch source on Github here.

For a package which was already published, is it possible to see and look into all files which were submitted? So like a repository as git where all files are submitted - the code itself and further files which are needed like description files or whatever - and I can see these files and look into them?

Yes, you can look at all the sources files for all the packages uploaded to CRAN on Github at the unofficial Github CRAN mirror here

Is there code in a R package which I cannot see as an end user? This refers also to my previous question, how can I or which way can I see the whole code in a R package?

As above, you can get the source code for any package via CRAN or Github. As you said, you can look at the source code for exported functions just by typing the name of that function into R. For unexported functions, you can do the same with a triple colon. For example, ggplot2:::adjust_breaks allows you to see the function body of the unexported function adjust_breaks from ggplot2. There are some complexities when an object-oriented system like S4, ggproto or R6 is used, or when the source code includes compiled C or C++ code, but I haven't come across a situation yet in which I was not able to find the relevant source code after a minute or two with an R console and a good search engine.

Body:
I guess you have a few different questions here. Let's take them in the order you asked them:

What if I add a package which uses another package? Is this package automatically downloaded and loaded too? Or is it in general forbidden for a R package to use another package?

It is certainly not forbidden for an R package to use another R package. In fact, the majority of R packages rely on other packages.

The source code for each R package must include a text-based DESCRIPTION file in the root directory. In this file you will find (among other things) a "Depends" field, and an "Imports" field. Together, these two fields list all the other packages required to use this package. If a user doesn't already have these other packages installed in their local library, R will install them automatically when it installs the requested package.

If your package lists a dependency in "Depends", then the dependency package is attached whenever your package is attached. Thus if you looked at the source code for a package called "foo" and you see that its DESCRIPTION file contains the line

Depends: bar,

you know that when you call library(foo) in your R console, you have effectively done library(bar); library(foo)

This isn't always ideal. The package foo might only need a couple of functions from package bar, and bar might contain some other functions whose names could clash with other commonly used functions. Therefore, in general, if you are writing a package and you only want to use a few functions from another package, it would be better to use "Imports" rather than "Depends" to limit the number of unnecessary symbols being added to your user's search path.

Suppose I want to publish a R package. Within my code, can I use functions from other packages and install and load these packages

Yes, you can use functions from other packages. The simplest way to do this is to include the name of the package in the Depends field of your DESCRIPTION file.

However, when using just a few functions from another package inside your own package, best practice is to use the "Imports" field in the DESCRIPTION file, and use a namespace qualifier for the imported function in your actual R code. For example, if you wanted to use ggplot from the ggplot2 package, then inside your function you would call it ggplot2::ggplot rather than just ggplot.

If you publish your package for others to use, the dependencies will be installed automatically along with your package if the user calls install.packages with the default settings. For example, when I did:

install.packages("fGarch")

I got the associated message:

#> also installing the dependencies ‘timeSeries’, ‘fBasics’, ‘fastICA’

Do I have to implement a message that this and that package is needed and that the user has to install and load it prior to it and I need to implement error catching functions in case the package cannot be found on the pc system?

No, not in general. R will take care of this as long as you have listed the correct packages in your DESCRIPTION file.

When I want to publish a R package, can I use/call Java code within my package/code?

R does not have a native Java API, but you can use your own Java code via the rJava package, which you can list as a dependency for your package. However, there are some users who have difficulty getting Java to run, for example business and academic users who may use R but do not have Java installed and do not have admin rights to install it, so this is something to bear in mind when writing a package.

For a package which was already published - so let's take just as an example the fGarch package - I would like to see the complete code. How can I see this?

Every package available for download from CRAN has its source code available. In the case of fGarch, its CRAN page contains a link to the gzipped tarball of the source code. You can download this and use untar in R to review all the source code. Alternatively, many packages will have an easily-found repository on Github or other source-control sites where you can examine the source code via a browser. For example, you can browse the fGarch source on Github here.

For a package which was already published, is it possible to see and look into all files which were submitted? So like a repository as git where all files are submitted - the code itself and further files which are needed like description files or whatever - and I can see these files and look into them?

Yes, you can look at all the sources files for all the packages uploaded to CRAN on Github at the unofficial Github CRAN mirror here

Is there code in a R package which I cannot see as an end user? This refers also to my previous question, how can I or which way can I see the whole code in a R package?

As above, you can get the source code for any package via CRAN or Github. As you said, you can look at the source code for exported functions just by typing the name of that function into R. For unexported functions, you can do the same with a triple colon. For example, ggplot2:::adjust_breaks allows you to see the function body of the unexported function adjust_breaks from ggplot2. There are some complexities when an object-oriented system like S4, ggproto or R6 is used, or when the source code includes compiled C or C++ code, but I haven't come across a situation yet in which I was not able to find the relevant source code after a minute or two with an R console and a good search engine.


来源: stackexchange

问:
Angular Change Component Declarations Location
this might be a dumb question but there it goes:

In my angular project i want to change my components declarations from angular.module.ts to modules/modules.modules.ts.

In order to make my src/app structure look like:

```<code>src/
   app/
   .  modules/
   .  .  about/...
   .  .  banner/...
   .  .  contact/...
   .  .  portfolio/...
   .  .  services/...
   .  .  testimonial/...
   .  .  modules.module.ts
   .  app-routing.module.ts
   .  app.component.html
   .  app.component.scss
   .  app.component.spec.ts
   .  app.component.ts
   .  app.module.ts
</code>```

In Resume want to move all my component declarations to modules/modules.module.ts

This is my best attemp so far:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

// Modules Components
import { BannerComponent } from './banner/banner.component';
import { ServicesComponent } from './services/services.component';
import { PortfolioComponent } from './portfolio/portfolio.component';
import { TestimonialComponent } from './testimonial/testimonial.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';

@NgModule({
  imports: [CommonModule],
  declarations: [
    AboutComponent,
    BannerComponent,
    ContactComponent,
    PortfolioComponent,
    ServicesComponent,
    TestimonialComponent,
  ],
  exports: [
    AboutComponent,
    BannerComponent,
    ContactComponent,
    PortfolioComponent,
    ServicesComponent,
    TestimonialComponent,
  ],
})
export class ModulesModule {}
</code>```

app.module.ts:

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

// App Component
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

// Pages Components
import { HomePageComponent } from './pages/home-page/home-page.component';
import { AboutPageComponent } from './pages/about-page/about-page.component';
import { ServicesPageComponent } from './pages/services-page/services-page.component';
import { PortfolioPageComponent } from './pages/portfolio-page/portfolio-page.component';
import { PortfolioSinglePageComponent } from './pages/portfolio-single-page/portfolio-single-page.component';
import { ContactPageComponent } from './pages/contact-page/contact-page.component';

// Modules Components
//import { BannerComponent } from './modules/banner/banner.component';
//import { ServicesComponent } from './modules/services/services.component';
//import { PortfolioComponent } from './modules/portfolio/portfolio.component';
//import { TestimonialComponent } from './modules/testimonial/testimonial.component';
//import { AboutComponent } from './modules/about/about.component';
//import { ContactComponent } from './modules/contact/contact.component';
import { ModulesModule } from './modules/modules.module';

// Angular Material
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material/material.module';

// Third Party
import { OwlModule } from 'ngx-owl-carousel';
import { NgxSpinnerModule } from 'ngx-spinner';

// PWA
import { ServiceWorkerModule } from '@angular/service-worker';

// Environment
import { environment } from '../environments/environment';

// Firebase
import { AngularFireModule } from '@angular/fire';
import { AngularFireDatabaseModule } from '@angular/fire/database';

@NgModule({
  declarations: [
    AppComponent,
    HomePageComponent,
    AboutPageComponent,
    ServicesPageComponent,
    ContactPageComponent,
    PortfolioPageComponent,
    PortfolioSinglePageComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ModulesModule, // here
    BrowserAnimationsModule,
    MaterialModule,
    OwlModule,
    NgxSpinnerModule,
    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: true, //environment.production,
    }),
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireDatabaseModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}
</code>```

Please note that i just changes the names to simplify the question. And it was fully working when the declarations wore in the app.module.ts

答:
You need to export each component in ModulesModule. This strategy is similar to what is described in Sharing modules. Also it looks like the errors you are receiving are unknown element errors surrounding owl carousel, angular router, and possibly other modules. Try creating a SharedModule that imports/exports these third party modules as well as any shared components and import it into your other modules where they are used:

Shared:

```<code>@NgModule({
 imports:      [CommonModule],
 declarations: [],
 exports:      [CommonModule, OwlModule, RouterModule]
})
export class SharedModule { }
</code>```

Modules:

```<code>@NgModule({
  imports: [SharedModule],
  declarations: [
    Component1,
    Component2,
  ],
  exports: [
    Component1,
    Component2,
  ],
})
export class ModulesModule { }
</code>```

Hopefully that helps!

ContentLicense: CC BY-SA 4.0

Body:
this might be a dumb question but there it goes:

In my angular project i want to change my components declarations from angular.module.ts to modules/modules.modules.ts.

In order to make my src/app structure look like:

src/
   app/
   .  modules/
   .  .  about/...
   .  .  banner/...
   .  .  contact/...
   .  .  portfolio/...
   .  .  services/...
   .  .  testimonial/...
   .  .  modules.module.ts
   .  app-routing.module.ts
   .  app.component.html
   .  app.component.scss
   .  app.component.spec.ts
   .  app.component.ts
   .  app.module.ts

In Resume want to move all my component declarations to modules/modules.module.ts

This is my best attemp so far:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

// Modules Components
import { BannerComponent } from './banner/banner.component';
import { ServicesComponent } from './services/services.component';
import { PortfolioComponent } from './portfolio/portfolio.component';
import { TestimonialComponent } from './testimonial/testimonial.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';

@NgModule({
  imports: [CommonModule],
  declarations: [
    AboutComponent,
    BannerComponent,
    ContactComponent,
    PortfolioComponent,
    ServicesComponent,
    TestimonialComponent,
  ],
  exports: [
    AboutComponent,
    BannerComponent,
    ContactComponent,
    PortfolioComponent,
    ServicesComponent,
    TestimonialComponent,
  ],
})
export class ModulesModule {}

app.module.ts:

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

// App Component
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

// Pages Components
import { HomePageComponent } from './pages/home-page/home-page.component';
import { AboutPageComponent } from './pages/about-page/about-page.component';
import { ServicesPageComponent } from './pages/services-page/services-page.component';
import { PortfolioPageComponent } from './pages/portfolio-page/portfolio-page.component';
import { PortfolioSinglePageComponent } from './pages/portfolio-single-page/portfolio-single-page.component';
import { ContactPageComponent } from './pages/contact-page/contact-page.component';

// Modules Components
//import { BannerComponent } from './modules/banner/banner.component';
//import { ServicesComponent } from './modules/services/services.component';
//import { PortfolioComponent } from './modules/portfolio/portfolio.component';
//import { TestimonialComponent } from './modules/testimonial/testimonial.component';
//import { AboutComponent } from './modules/about/about.component';
//import { ContactComponent } from './modules/contact/contact.component';
import { ModulesModule } from './modules/modules.module';

// Angular Material
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material/material.module';

// Third Party
import { OwlModule } from 'ngx-owl-carousel';
import { NgxSpinnerModule } from 'ngx-spinner';

// PWA
import { ServiceWorkerModule } from '@angular/service-worker';

// Environment
import { environment } from '../environments/environment';

// Firebase
import { AngularFireModule } from '@angular/fire';
import { AngularFireDatabaseModule } from '@angular/fire/database';

@NgModule({
  declarations: [
    AppComponent,
    HomePageComponent,
    AboutPageComponent,
    ServicesPageComponent,
    ContactPageComponent,
    PortfolioPageComponent,
    PortfolioSinglePageComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ModulesModule, // here
    BrowserAnimationsModule,
    MaterialModule,
    OwlModule,
    NgxSpinnerModule,
    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: true, //environment.production,
    }),
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireDatabaseModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Please note that i just changes the names to simplify the question. And it was fully working when the declarations wore in the app.module.ts

Body:
You need to export each component in ModulesModule. This strategy is similar to what is described in Sharing modules. Also it looks like the errors you are receiving are unknown element errors surrounding owl carousel, angular router, and possibly other modules. Try creating a SharedModule that imports/exports these third party modules as well as any shared components and import it into your other modules where they are used:

Shared:

@NgModule({
 imports:      [CommonModule],
 declarations: [],
 exports:      [CommonModule, OwlModule, RouterModule]
})
export class SharedModule { }

Modules:

@NgModule({
  imports: [SharedModule],
  declarations: [
    Component1,
    Component2,
  ],
  exports: [
    Component1,
    Component2,
  ],
})
export class ModulesModule { }

Hopefully that helps!


问:
Slick slider - Add class name when moving left to right and right to left
From the following slick slider I can move left to right(lft) and right to left(rtl). I want to add two different class name for rtl and lft direction movement.

Anyone help me to achieve this. If you have any doubts just comment for more info.

Script I have tried:

```<code>var dir;
if(dir=='right')
{
    $('.slick-active').addClass('right-effect');
}
if(dir=='left')
{
    $('.slick-active').addClass('left-effect');
}
</code>```

console.clear();

$(".slider").slick({
    // autoplay: true,
    dots: true,
    arrows: false,
 slidesToShow: 2,
 slidesToScroll: 2
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  background: #102131;
  color: white;
}
 .container {
  padding: 30px;
}
 .test-case-wrap {
  margin-bottom: 60px;
}
 .slick-slider {
  background: #3a8999;
  font-size: 30px;
  line-height: 1;
  text-align: center;
  color: white;
}
 .slick-slider .slick-dots button:before, .slick-slider .slick-dots .slick-active button:before {
  color: rgba(255, 255, 255, .85);
}
 .slick-slider .slick-slide {
  background: #3a8999;
  padding: 40px 0;
}
 .slick-slider .slick-slide:nth-child(odd) {
  background: #e84a69;
}
 .slick-track {
  display: flex;
}
 .slick-track .slick-slide {
  display: flex;
  height: auto;
  align-items: center;
  justify-content: center;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://rawgit.com/kenwheeler/slick/master/slick/slick.css" rel="stylesheet"/>

Lorem ipsum dolor sit amet

slide 1

slide 2

slide 3

slide 4

slide 5

```

答:
You can add click() events to the slider navigation like this:

$(".slider").slick({
    dots: false,
 slidesToShow: 2,
 slidesToScroll: 2
});
$(".slick-prev").on("click", function() {
   $('.slick-active').removeClass('right-effect');
   $('.slick-active').addClass('left-effect');
});
$(".slick-next").on("click", function() {
   $('.slick-active').removeClass('left-effect');
   $('.slick-active').addClass('right-effect');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  background: #102131;
  color: white;
}
 .container {
  padding: 30px;
}
 .test-case-wrap {
  margin-bottom: 60px;
}
 .slick-slider {
  background: #3a8999;
  font-size: 30px;
  line-height: 1;
  text-align: center;
  color: white;
}
 .slick-slider .slick-dots button:before, .slick-slider .slick-dots .slick-active button:before {
  color: rgba(255, 255, 255, .85);
}
 .slick-slider .slick-slide {
  background: #3a8999;
  padding: 40px 0;
}
 .slick-slider .slick-slide:nth-child(odd) {
  background: #e84a69;
}
 .slick-track {
  display: flex;
}
 .slick-track .slick-slide {
  display: flex;
  height: auto;
  align-items: center;
  justify-content: center;
}
.right-effect {
  background-color:red !important;
}
.left-effect {
  background-color:blue !important;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://rawgit.com/kenwheeler/slick/master/slick/slick.css" rel="stylesheet"/>

Lorem ipsum dolor sit amet

slide 1

slide 2

slide 3

slide 4

slide 5

```
</div>
</div>
</p>

<p>Update: As mentioned as comment, the slider isn't used with the "previous" and "next" slider navigation, but with the dot navigation. For the dot navigation, the following approach should work:</p>

``` $(".slick-dots li").on("click", function() {
    let current = $(this).index();
    let previous = $(".slick-dots").attr("data-previous") ? $(".slick-dots").attr("data-previous") : 0;
    if (current > previous) {
       $('.slick-active').removeClass('left-effect');
       $('.slick-active').addClass('right-effect');
    } else if (current < previous) {
       $('.slick-active').removeClass('right-effect');
       $('.slick-active').addClass('left-effect');
    }
    $(".slick-dots").attr("data-previous", $(this).index());
 });
```

Body:
From the following slick slider I can move left to right(lft) and right to left(rtl). I want to add two different class name for rtl and lft direction movement.

Anyone help me to achieve this. If you have any doubts just comment for more info.

Script I have tried:

var dir;
if(dir=='right')
{
    $('.slick-active').addClass('right-effect');
}
if(dir=='left')
{
    $('.slick-active').addClass('left-effect');
}

console.clear();

$(".slider").slick({
    // autoplay: true,
    dots: true,
    arrows: false,
 slidesToShow: 2,
 slidesToScroll: 2
});

html, body {
  background: #102131;
  color: white;
}
 .container {
  padding: 30px;
}
 .test-case-wrap {
  margin-bottom: 60px;
}
 .slick-slider {
  background: #3a8999;
  font-size: 30px;
  line-height: 1;
  text-align: center;
  color: white;
}
 .slick-slider .slick-dots button:before, .slick-slider .slick-dots .slick-active button:before {
  color: rgba(255, 255, 255, .85);
}
 .slick-slider .slick-slide {
  background: #3a8999;
  padding: 40px 0;
}
 .slick-slider .slick-slide:nth-child(odd) {
  background: #e84a69;
}
 .slick-track {
  display: flex;
}
 .slick-track .slick-slide {
  display: flex;
  height: auto;
  align-items: center;
  justify-content: center;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://rawgit.com/kenwheeler/slick/master/slick/slick.css" rel="stylesheet"/>

Lorem ipsum dolor sit amet

slide 1

slide 2

slide 3

slide 4

slide 5

Body:
You can add click() events to the slider navigation like this:

$(".slider").slick({
    dots: false,
 slidesToShow: 2,
 slidesToScroll: 2
});
$(".slick-prev").on("click", function() {
   $('.slick-active').removeClass('right-effect');
   $('.slick-active').addClass('left-effect');
});
$(".slick-next").on("click", function() {
   $('.slick-active').removeClass('left-effect');
   $('.slick-active').addClass('right-effect');
});

html, body {
  background: #102131;
  color: white;
}
 .container {
  padding: 30px;
}
 .test-case-wrap {
  margin-bottom: 60px;
}
 .slick-slider {
  background: #3a8999;
  font-size: 30px;
  line-height: 1;
  text-align: center;
  color: white;
}
 .slick-slider .slick-dots button:before, .slick-slider .slick-dots .slick-active button:before {
  color: rgba(255, 255, 255, .85);
}
 .slick-slider .slick-slide {
  background: #3a8999;
  padding: 40px 0;
}
 .slick-slider .slick-slide:nth-child(odd) {
  background: #e84a69;
}
 .slick-track {
  display: flex;
}
 .slick-track .slick-slide {
  display: flex;
  height: auto;
  align-items: center;
  justify-content: center;
}
.right-effect {
  background-color:red !important;
}
.left-effect {
  background-color:blue !important;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://rawgit.com/kenwheeler/slick/master/slick/slick.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/kenwheeler/slick/master/slick/slick.js"></script>
<div class="container">
  <div class="slider">
    <div>Lorem ipsum dolor sit amet</div>
    <div>slide 1</div>
    <div>slide 2</div>
    <div>slide 3</div>
    <div>slide 4</div>
    <div>slide 5</div>
  </div>
</div>

Update: As mentioned as comment, the slider isn't used with the "previous" and "next" slider navigation, but with the dot navigation. For the dot navigation, the following approach should work:

 $(".slick-dots li").on("click", function() {
    let current = $(this).index();
    let previous = $(".slick-dots").attr("data-previous") ? $(".slick-dots").attr("data-previous") : 0;
    if (current > previous) {
       $('.slick-active').removeClass('left-effect');
       $('.slick-active').addClass('right-effect');
    } else if (current < previous) {
       $('.slick-active').removeClass('right-effect');
       $('.slick-active').addClass('left-effect');
    }
    $(".slick-dots").attr("data-previous", $(this).index());
 });


问:
How can I remove row name from my table in R?
Here is my code:

```<code>day = c("2019-01-01", "2019-01-02", "2019-01-03","2019-01-04")
case = c(3,2,8,11)
rbind(day, case)
data = data.frame(rbind(day, case))
row.names(data) = colnames (data) = NULL
row.names(data)=NULL
print(data,row.names = F)
</code>```

The output is this:

```<code>2019-01-01   2019-01-02   2019-01-03   2019-01-04

    3            2            8            11
</code>```

but If I use

```<code>print(data)
</code>```

I have this:

```<code>1 2019-01-01 2019-01-02 2019-01-03 2019-01-04

2      3          2          8         11
</code>```

My question: How can I assign a variable name to this output from "print(data)" to make it usable for my work, without row name and without column name which I need. Thanks

答:
In R, objects of class data.frame must have row names. Unfortunately, there's no way around it.

When you try to remove the rownames, the system simply puts them back. If you try to remove them at a low level, it breaks the object:

```<code>attr(data,"row.names") <- NULL
data
#NULL
#<0 rows> (or 0-length row.names)
</code>```

You could convert your data object to class matrix, but in R, matrices can only have one type of data. So (in a hypothetical example) if you had columns with both numeric type data and character type data, the numeric data would have to be converted to character:

```<code>as.matrix(data)
#     [,1]         [,2]         [,3]         [,4]
#[1,] "2019-01-01" "2019-01-02" "2019-01-03" "2019-01-04"
#[2,] "3"          "2"          "8"          "11"
</code>```

Overall, I don't think you should worry about the row names and just continue with your analysis.

Body:
Here is my code:

day = c("2019-01-01", "2019-01-02", "2019-01-03","2019-01-04")
case = c(3,2,8,11)
rbind(day, case)
data = data.frame(rbind(day, case))
row.names(data) = colnames (data) = NULL
row.names(data)=NULL
print(data,row.names = F)

The output is this:

2019-01-01   2019-01-02   2019-01-03   2019-01-04

    3            2            8            11

but If I use

print(data)

I have this:

1 2019-01-01 2019-01-02 2019-01-03 2019-01-04

2      3          2          8         11

My question: How can I assign a variable name to this output from "print(data)" to make it usable for my work, without row name and without column name which I need. Thanks

Body:
In R, objects of class data.frame must have row names. Unfortunately, there's no way around it.

When you try to remove the rownames, the system simply puts them back. If you try to remove them at a low level, it breaks the object:

attr(data,"row.names") <- NULL
data
#NULL
#<0 rows> (or 0-length row.names)

You could convert your data object to class matrix, but in R, matrices can only have one type of data. So (in a hypothetical example) if you had columns with both numeric type data and character type data, the numeric data would have to be converted to character:

as.matrix(data)
#     [,1]         [,2]         [,3]         [,4]
#[1,] "2019-01-01" "2019-01-02" "2019-01-03" "2019-01-04"
#[2,] "3"          "2"          "8"          "11"

Overall, I don't think you should worry about the row names and just continue with your analysis.


问:
SELECT statement is MySql returning wrong value using python
I am trying to retrieve a value from a table stored in Mysql database using python(pycharm). But instead of outputting the stored value it outputs number of rows instead.

```<code>import pymysql
connection = pymysql.connect(host='localhost',
                             user='root',
                             password='passw',
                             database='database1',
                             charset='utf8',
                             port=3306
                             )
x=connection.cursor()
select = x.execute('''SELECT
    update_id
FROM
    telegram;
''')
print(select)

Output: 1
</code>```

^Wrong output(Output equals number of rows). As I keep adding on rows the output changes to the number of rows but never returns the value stored.

The command works from MySql perfectly.

```<code>SELECT
        update_id
    FROM
        telegram;
Output:233
</code>```

^This is the correct output.
Why is this happening? What changes should I make in my python code?

答:
According to the documentation on pymysql, this is how you are supposed to do the print out:

```<code>    sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
    cursor.execute(sql, ('webmaster@python.org',))
    result = cursor.fetchone()
    print(result)
</code>```

You are missing "cursor.fetchone()"

I hope that helps

Body:
I am trying to retrieve a value from a table stored in Mysql database using python(pycharm). But instead of outputting the stored value it outputs number of rows instead.

import pymysql
connection = pymysql.connect(host='localhost',
                             user='root',
                             password='passw',
                             database='database1',
                             charset='utf8',
                             port=3306
                             )
x=connection.cursor()
select = x.execute('''SELECT
    update_id
FROM
    telegram;
''')
print(select)

Output: 1

^Wrong output(Output equals number of rows). As I keep adding on rows the output changes to the number of rows but never returns the value stored.

The command works from MySql perfectly.

SELECT
        update_id
    FROM
        telegram;
Output:233

^This is the correct output.
Why is this happening? What changes should I make in my python code?

Body:
According to the documentation on pymysql, this is how you are supposed to do the print out:

    sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
    cursor.execute(sql, ('webmaster@python.org',))
    result = cursor.fetchone()
    print(result)

You are missing "cursor.fetchone()"

I hope that helps


问:
In emacs lisp, is there a way to search text that will match a string that overlaps the current point?
I'm not exactly a lisp expert, so please forgive a fairly newbie question.

I'm writing a fairly simple elisp function, trying to find a short string on the same line as the current cursor position.  The relevant part of the code as written now is:

```<code>(let ((matchpos (search-forward myword (line-end-position) t)))
  (if matchpos
      (goto-char (- matchpos (length myword)))
    (setq matchpos (search-backward myword (line-beginning-position) t)))
  ...
</code>```

This mostly works without trouble, but it fails to find a string containing the current cursor position.  Apparently, search-backward only looks for strings that end before point.  In truth, I can solve this particular problem by going to the end of the line before doing the search-backward, but I'm rather curious whether this behavior can be modified.

Is there any variant on search-backward that matches any string that starts before point?

Edit:  Perhaps an example is in order, since those answering don't seem to quite understand the question.  Suppose I am searching for the string "search this", and my line looks like this (point noted by the *):

```<code>I want to search this string, I have code to search t*his string
</code>```

Unfortunately, the code fragment shown above moves point to the first occurrence of "search this" in the line above.  I want point to end up at the beginning of the second "search this" string, the one currently containing point, since it's the nearest one.

答:
I would suggest that you move the cursor to the right the number of characters that corresponds to the length of the string you search for (possibly minus one, depending on if you would like to match something immediately to the right of the point).

Something like:

```<code>(goto-char (min (end-of-line-position)
                (+ (point) (length myword))))
(setq matchpos (search-backward myword (line-beginning-position) t))
</code>```

This will work, as you have moved the point out of the way for search-backword.

Another solution would be to go to the beginning of the line and repeatedly search forward until you have passed the point.

ContentLicense: CC BY-SA 3.0

Body:
I'm not exactly a lisp expert, so please forgive a fairly newbie question.

I'm writing a fairly simple elisp function, trying to find a short string on the same line as the current cursor position.  The relevant part of the code as written now is:

(let ((matchpos (search-forward myword (line-end-position) t)))
  (if matchpos
      (goto-char (- matchpos (length myword)))
    (setq matchpos (search-backward myword (line-beginning-position) t)))
  ...

This mostly works without trouble, but it fails to find a string containing the current cursor position.  Apparently, search-backward only looks for strings that end before point.  In truth, I can solve this particular problem by going to the end of the line before doing the search-backward, but I'm rather curious whether this behavior can be modified.

Is there any variant on search-backward that matches any string that starts before point?

Edit:  Perhaps an example is in order, since those answering don't seem to quite understand the question.  Suppose I am searching for the string "search this", and my line looks like this (point noted by the *):

I want to search this string, I have code to search t*his string

Unfortunately, the code fragment shown above moves point to the first occurrence of "search this" in the line above.  I want point to end up at the beginning of the second "search this" string, the one currently containing point, since it's the nearest one.

Body:
I would suggest that you move the cursor to the right the number of characters that corresponds to the length of the string you search for (possibly minus one, depending on if you would like to match something immediately to the right of the point).

Something like:

(goto-char (min (end-of-line-position)
                (+ (point) (length myword))))
(setq matchpos (search-backward myword (line-beginning-position) t))

This will work, as you have moved the point out of the way for search-backword.

Another solution would be to go to the beginning of the line and repeatedly search forward until you have passed the point.


问:
Issue with "toUpperCase" which outputs "function toUpperCase() { [native code] }" instead of desired output. Make loop stop when a value is reached
So basically I have to following snippet of script :

```<code>for (let i = 0; i < 5; i++){
            result = window.prompt('Rock, Paper or Scissor?', 'What do you choose?') //prompt user to input choice
            let playerSelection = result.toUpperCase
            console.log(playRound(playerSelection, computerPlay())) // to see that loop for "playRound works"
        }
</code>```

It works fine before I add "toUpperCase" after "let playerSelection = result.toUpperCase" (which I do in order to make user able to input any variant of e.g "RoCK", "ROCK", "rock" and "RocK"). After I've added the "toUpperCase" I get the wrong output in the console. Instead of desired output I get: "function toUpperCase() { [native code] }" which I'm looking to fix.

Here is my full script:

```<code>    let computerScore = 0
let playerScore = 0

function computerPlay (){
    const choices = ["Rock", "Paper", "Scissor"];
    const randomChoice = choices[Math.floor(Math.random() * choices.length)];

    return(randomChoice);
    }

function playRound(playerSelection, computerPlay) { //This is the actual round, increments "playerScore" and "computerScore" based on who wins round
if (playerSelection == computerPlay) {
        result = `Computer also choose ${computerPlay}! It's a Draw!`;
    } else if ((playerSelection == "Paper" && computerPlay == "Rock") ||
               (playerSelection == "Rock" && computerPlay == "Scissor") ||
               (playerSelection == "Scissor" && computerPlay == "Paper")) {
                   playerScore = playerScore + 1;
                   result = `Computer choose: ${computerPlay}! ${playerSelection} beats ${computerPlay}. You get one point! Your score is: ${playerScore} Computer score is: ${computerScore}`;
               } else {
                computerScore = computerScore + 1;
                   result = `Computer choose: ${computerPlay}! ${computerPlay} beats ${playerSelection}. Computer gets one point! Your score is: ${playerScore} Computer score is: ${computerScore}`;
               }

            return (result);
        }

       // console.log(playRound(playerSelection, computerPlay())) // to test if function "playRound works"

        for (let i = 0; i < 5; i++){
            result = window.prompt('Rock, Paper or Scissor?', 'What do you choose?') //prompt user to input choice
            let playerSelection = result.toUpperCase
            console.log(playRound(playerSelection, computerPlay())) // to see that loop for "playRound works"
        }

        function winLose () { //to give output based on who wins or loses (or if draw)
            if (playerScore > computerScore){
                console.log(`You won over the computer with ${playerScore} points. Yay! You sure showed that computer who's boss!`)
            } else if (computerScore > playerScore) {
                console.log(`The computer won over you with ${computerScore} points. Oh no! You are inferior to the computer!`)
            } else if (playerScore == computerScore){
                console.log(`You had ${playerScore} points and the computer had ${computerScore} points. No one wins! Boring...`)
            } else {
                console.log("You and the computer where both unlucky and had too many draws to decide who's the superior life form")
            }
        }
        winLose()
</code>```

I'm also wondering how to make the "loop" I have stop, once either the "computerScore" or "playerScore" reaches 3. Since it doesn't make sense to get prompted to keep playing once you've lost or won 3 times.

Thanks for any pointers and help!

答:
The Error is basically that you are using toUpperCase like a property instead of a function call. To call the function on the string, you need to add parentheses:

```<code>let playerSelection = result.toUpperCase()
</code>```

But judging your code, I don't think that you want this function. What it does is turning every character into it's uppercase version, so paper will become PAPER. I think you had more something like a capitalize function in mind, like this paper --> Paper. In order for your code to work, you will also have to change your playround function to this:

```<code> else if ((playerSelection == "PAPER" && computerPlay == "Rock") ||
           (playerSelection == "ROCK" && computerPlay == "Scissor") ||
           (playerSelection == "SCISSOR" && computerPlay == "Paper"))
</code>```

Body:
So basically I have to following snippet of script :

for (let i = 0; i < 5; i++){
            result = window.prompt('Rock, Paper or Scissor?', 'What do you choose?') //prompt user to input choice
            let playerSelection = result.toUpperCase
            console.log(playRound(playerSelection, computerPlay())) // to see that loop for "playRound works"
        }

It works fine before I add "toUpperCase" after "let playerSelection = result.toUpperCase" (which I do in order to make user able to input any variant of e.g "RoCK", "ROCK", "rock" and "RocK"). After I've added the "toUpperCase" I get the wrong output in the console. Instead of desired output I get: "function toUpperCase() { [native code] }" which I'm looking to fix.

Here is my full script:

    let computerScore = 0
let playerScore = 0

function computerPlay (){
    const choices = ["Rock", "Paper", "Scissor"];
    const randomChoice = choices[Math.floor(Math.random() * choices.length)];

    return(randomChoice);
    }

function playRound(playerSelection, computerPlay) { //This is the actual round, increments "playerScore" and "computerScore" based on who wins round
if (playerSelection == computerPlay) {
        result = `Computer also choose ${computerPlay}! It's a Draw!`;
    } else if ((playerSelection == "Paper" && computerPlay == "Rock") ||
               (playerSelection == "Rock" && computerPlay == "Scissor") ||
               (playerSelection == "Scissor" && computerPlay == "Paper")) {
                   playerScore = playerScore + 1;
                   result = `Computer choose: ${computerPlay}! ${playerSelection} beats ${computerPlay}. You get one point! Your score is: ${playerScore} Computer score is: ${computerScore}`;
               } else {
                computerScore = computerScore + 1;
                   result = `Computer choose: ${computerPlay}! ${computerPlay} beats ${playerSelection}. Computer gets one point! Your score is: ${playerScore} Computer score is: ${computerScore}`;
               }

            return (result);
        }

       // console.log(playRound(playerSelection, computerPlay())) // to test if function "playRound works"

        for (let i = 0; i < 5; i++){
            result = window.prompt('Rock, Paper or Scissor?', 'What do you choose?') //prompt user to input choice
            let playerSelection = result.toUpperCase
            console.log(playRound(playerSelection, computerPlay())) // to see that loop for "playRound works"
        }

        function winLose () { //to give output based on who wins or loses (or if draw)
            if (playerScore > computerScore){
                console.log(`You won over the computer with ${playerScore} points. Yay! You sure showed that computer who's boss!`)
            } else if (computerScore > playerScore) {
                console.log(`The computer won over you with ${computerScore} points. Oh no! You are inferior to the computer!`)
            } else if (playerScore == computerScore){
                console.log(`You had ${playerScore} points and the computer had ${computerScore} points. No one wins! Boring...`)
            } else {
                console.log("You and the computer where both unlucky and had too many draws to decide who's the superior life form")
            }
        }
        winLose()

I'm also wondering how to make the "loop" I have stop, once either the "computerScore" or "playerScore" reaches 3. Since it doesn't make sense to get prompted to keep playing once you've lost or won 3 times.

Thanks for any pointers and help!

Body:
The Error is basically that you are using toUpperCase like a property instead of a function call. To call the function on the string, you need to add parentheses:

let playerSelection = result.toUpperCase()

But judging your code, I don't think that you want this function. What it does is turning every character into it's uppercase version, so paper will become PAPER. I think you had more something like a capitalize function in mind, like this paper --> Paper. In order for your code to work, you will also have to change your playround function to this:

 else if ((playerSelection == "PAPER" && computerPlay == "Rock") ||
           (playerSelection == "ROCK" && computerPlay == "Scissor") ||
           (playerSelection == "SCISSOR" && computerPlay == "Paper"))


问:
Docker host port 80 to multiple containers
New to docker..

Is it possible to support multiple containers in different ports but to map to the same docker host port 80 ?

I have two apps, one running in apache, the other on glassfish server.

I want to run these two containers in the same linux instance in aws.

Is it possible to have something like the following:

container 1  apache EXPOSE 9090

container 2  glassf EXPOSE 8080

docker run -p 80:9090 container1

docker run -p 80:8080 container2

Already tried, obviously getting:

```<code>Bind for 0.0.0.0:80 failed: port is already allocated
</code>```

But what I want' to know if is it possible, how to achieve it, and also is it recommended or not and why ?

Thanks

Edit

According to nginx-proxy

Usage To run it:

$ docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro
  jwilder/nginx-proxy Then start any containers you want proxied with an
  env var VIRTUAL_HOST=subdomain.youdomain.com

$ docker run -e VIRTUAL_HOST=foo.bar.com  ... The containers being
  proxied must expose the port to be proxied, either by using the EXPOSE
  directive in their Dockerfile or by using the --expose flag to docker
  run or docker create.

Provided your DNS is setup to forward foo.bar.com to the host running
  nginx-proxy, the request will be routed to a container with the
  VIRTUAL_HOST env var set.

I performed the following:

```<code>docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock jwilder/nginx-proxy
</code>```

Then ran one of my images to test, but no luck, what am I doing wrong:

```<code>docker run -e docker run -e VIRTUAL_HOST=my.host my/image
</code>```

Where my.host is in /etc/hosts:

```<code>127.0.0.1 localhost
127.0.0.1 my.host
</code>```

Also, my/image is exposed at 8080
This doesn't work, test: my.host/app-context-root throws:

502 Bad Gateway nginx/1.13.12

答:
Answer:

As you'll start to see by the current answers, it is not possible or recommended to achieve what you are doing.

The ports you use in an interface are there to delegate traffic to its correct destination. Think of it as if your street had two houses, with the same ZIP code, and the same house number - where would your delivery go?

The big question is, why do you want it this way? the obvious solution is to have them on separate ports - and any requests for apache would go to the apache port, and vice versa for glassf.

If they must be given the same port number on the same box - you could have a second instance of docker running pointed to a second interface (or secondary IP on the same interface). The trade-off here is that your docker containers would no longer be on the same network.

Body:
New to docker..

Is it possible to support multiple containers in different ports but to map to the same docker host port 80 ?

I have two apps, one running in apache, the other on glassfish server.

I want to run these two containers in the same linux instance in aws.

Is it possible to have something like the following:

container 1  apache EXPOSE 9090

container 2  glassf EXPOSE 8080

docker run -p 80:9090 container1

docker run -p 80:8080 container2

Already tried, obviously getting:

Bind for 0.0.0.0:80 failed: port is already allocated

But what I want' to know if is it possible, how to achieve it, and also is it recommended or not and why ?

Thanks

Edit

According to nginx-proxy

Usage To run it:

$ docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro
  jwilder/nginx-proxy Then start any containers you want proxied with an
  env var VIRTUAL_HOST=subdomain.youdomain.com

$ docker run -e VIRTUAL_HOST=foo.bar.com  ... The containers being
  proxied must expose the port to be proxied, either by using the EXPOSE
  directive in their Dockerfile or by using the --expose flag to docker
  run or docker create.

Provided your DNS is setup to forward foo.bar.com to the host running
  nginx-proxy, the request will be routed to a container with the
  VIRTUAL_HOST env var set.

I performed the following:

docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock jwilder/nginx-proxy

Then ran one of my images to test, but no luck, what am I doing wrong:

docker run -e docker run -e VIRTUAL_HOST=my.host my/image

Where my.host is in /etc/hosts:

127.0.0.1 localhost
127.0.0.1 my.host

Also, my/image is exposed at 8080
This doesn't work, test: my.host/app-context-root throws:

502 Bad Gateway nginx/1.13.12


问:
Updating large amount of documents in mongodb
I am working on solution to this problem:

I have got a large collection of entries, that regularly I have to update from the other database. I am using express.js with mongodb. The schedule of updating starts everyday at 1am. I fetch external data, compare to currently existing and update all entries in our databse.

The process looks like:
1) Fetch internal and external data
2) Combine them together (past entries from our database, future entries from the other database)
3) Delete all records in our database
4) InsertMany - records that the program just combined.

So as you can see it's a quite risky task. If any error would occur between deleting and inserting data in the collection, we lose all data.

And there are my questions:

1) Is there any effective way of reverting data that has been just deleted in mongo? Or keep them on hold and insert back on its place, if any error occurs?

2) Is there any other effective way of updating few hundreds/thousands of documents apart from deleteMany -> insertMany // updateOne on each document?

Any advice would be appreciated.

答:
An alternative to your set of operation could be:

fetch external data

add external data in to a new
database/collection

merge the data together with an aggeration
query using $merge
(https://docs.mongodb.com/manual/reference/operator/aggregation/merge/)

That way you wouldn't have to delete all your data and could possibly end up with data loss.


问:
Setting a request body in Android's DownloadManager?
For the next step of my application, I need to add download functionality. The user chooses what they want to download and could select anything from 1 file to thousands of them if they could be bothered to select that many.

I want to use Android's built in DownloadManager to provide this downloading functionality, but unfortunately I cannot see how I could implement it for my scenario.

In order for the target server to authorize the download, I need to send some JSON along in the request body. Like this, if I was doing it manually:

```DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeBytes(rawData);
output.flush();```

Where rawData is the JSON string. The request body is always set to POST.

I can't seem to find any way to add this JSON string to the DownloadManager, and until I can do that, the server will always reject the download.

The only other solution that I can think of, which I desperately want to avoid, is writing a PHP script on my server to take some GET parameters, generate the JSON and then redirect the request.

Does anybody know of a way that I can send my JSON data along with the DownloadManager? Each file that I'm downloading needs its own, unique, JSON string.

答:
you cannot do that in Android's Download manager, see Download Manager Issue,
I had a similar requirement and I ended up Using HttpClient (Xamarin).

Sample Code-

```<code>using(var httpClient = new HttpClient()) {
  using(var request = new HttpRequestMessage(new HttpMethod("POST"), URL)) {
   request.Headers.TryAddWithoutValidation("User-Agent", userAgent);
   request.Headers.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
   request.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.5");
   request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
   request.Headers.TryAddWithoutValidation("Referer",RefererURL);
   request.Content = new StringContent("YOUR_REQUEST_BODY_HERE");
   request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");

   var responser = await httpClient.SendAsync(request);
   return responser;
  }
</code>```

Body:
For the next step of my application, I need to add download functionality. The user chooses what they want to download and could select anything from 1 file to thousands of them if they could be bothered to select that many.

I want to use Android's built in DownloadManager to provide this downloading functionality, but unfortunately I cannot see how I could implement it for my scenario.

In order for the target server to authorize the download, I need to send some JSON along in the request body. Like this, if I was doing it manually:

DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeBytes(rawData);
output.flush();

Where rawData is the JSON string. The request body is always set to POST.

I can't seem to find any way to add this JSON string to the DownloadManager, and until I can do that, the server will always reject the download.

The only other solution that I can think of, which I desperately want to avoid, is writing a PHP script on my server to take some GET parameters, generate the JSON and then redirect the request.

Does anybody know of a way that I can send my JSON data along with the DownloadManager? Each file that I'm downloading needs its own, unique, JSON string.

Body:
you cannot do that in Android's Download manager, see Download Manager Issue,
I had a similar requirement and I ended up Using HttpClient (Xamarin).

Sample Code-

using(var httpClient = new HttpClient()) {
  using(var request = new HttpRequestMessage(new HttpMethod("POST"), URL)) {
   request.Headers.TryAddWithoutValidation("User-Agent", userAgent);
   request.Headers.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
   request.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.5");
   request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
   request.Headers.TryAddWithoutValidation("Referer",RefererURL);
   request.Content = new StringContent("YOUR_REQUEST_BODY_HERE");
   request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");

   var responser = await httpClient.SendAsync(request);
   return responser;
  }


问:
Table Row onClick Overriding Checkbox
I'm having some issues with checkboxes in a table being "overridden" by the onClick attribute of the table row they are placed in.

I have a column with checkboxes as the leftmost column of a table, and I also have an onClick function defined for each table row. As a result, when I click any of the checkboxes, the onClick function of the table row triggers (though the checkbox is still clicked correctly).

Is there any way I can work around this? Having the table row's onClick only register for the other columns, for example? (I have no clue how the implementation of that would work, unfortunately, but that's the first solution I can think of.)

Thanks in advance!

答: some code would be helpful. May be copy/paste error with name on checkbox and button. Provide code for more suggestions.</p>

Title: Table Row onClick Overriding Checkbox


问:
VS Code/Flutter/Android - Keystore file not set for signing config release
I followed those steps to build apk on VS Code: https://flutter.dev/docs/deployment/android

But I always get:

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:validateSigningRelease'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 35s
Running Gradle task 'assembleRelease'...
Running Gradle task 'assembleRelease'... Done                      36,0s
Gradle task assembleRelease failed with exit code 1

I've already tried to create my keys on build.gradle like this:

```<code>buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.release
        }
    }
</code>```

and like this:

```<code>buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
</code>```

but I've got the same error to build apk.
The official documentation seems to be wrong.
How to create apk on VS Code?

答:
I just had the same error. I think the docs for editing app/build.gradle are a bit confusing.

Here is how I solved it. Note the duplicate buildTypes block.

```<code>    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
</code>```

Here is my full app/build.gradle (remember to change the applicationId).

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        applicationId "!!!YOUR APP ID HERE!!!"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
</code>```

Body:
I followed those steps to build apk on VS Code: https://flutter.dev/docs/deployment/android

But I always get:

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:validateSigningRelease'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 35s
Running Gradle task 'assembleRelease'...
Running Gradle task 'assembleRelease'... Done                      36,0s
Gradle task assembleRelease failed with exit code 1

I've already tried to create my keys on build.gradle like this:

buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.release
        }
    }

and like this:

buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }

but I've got the same error to build apk.
The official documentation seems to be wrong.
How to create apk on VS Code?

Body:
I just had the same error. I think the docs for editing app/build.gradle are a bit confusing.

Here is how I solved it. Note the duplicate buildTypes block.

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }

Here is my full app/build.gradle (remember to change the applicationId).

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        applicationId "!!!YOUR APP ID HERE!!!"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}


问:
Undo a git squash rebase
I messed up squashing my commits into one commit.

If the commits went

NOTMINE -> MINE1 -> MINE2 -> MINE3 -> MINE4 -> MINE5

I tried to squash MINE1-4 into MINE5, but ended up squashing them into NOTMINE.

I ran git rebase -i HEAD~5 and set it to pick MINE5 and squash MINE1-4.

In order to fix this I tried git reflog and based on that I ran git reset --hard HEAD@{1}, which looked like the moment before the squash, but that had no effect.

Any ideas?

答:
Check your reflog.

One line should indicate the beginning of your rebase :

```<code><sha> HEAD@{xx} rebase (start): checkout <something>
</code>```

(since you asked for git rebase -i HEAD~5, <something> will probably be an explicit sha1 ;

when you ask for a named ref as in git rebase -i origin/master, the log mentions that name)

The line below that one (<sha> HEAD@{xx+1}) is the commit you are looking for.

Title: Undo a git squash rebase

Body:
Check your reflog.

One line should indicate the beginning of your rebase :

<sha> HEAD@{xx} rebase (start): checkout <something>

(since you asked for git rebase -i HEAD~5, <something> will probably be an explicit sha1 ;

when you ask for a named ref as in git rebase -i origin/master, the log mentions that name)

The line below that one (<sha> HEAD@{xx+1}) is the commit you are looking for.


问:
Node Js - EISDIR: illegal operation on a directory, open 'tmp'
I've facing the issue on npm 6.13.1 version, when i upload a CSV file using the multer it's response an error "EISDIR: illegal operation on a directory, open 'tmp'". I can not downgrade my npm version.</p>

答:
You probably have that directory locked for some other package/program.

Check your global variables to see if there is anything like export BABEL_CACHE_PATH=/tmp

Reference: https://github.com/expo/expo-cli/issues/388#issuecomment-466298734


问:
Knapstack implementation in c++ using memoization
What is the difference between doing int t[102][1002] = {-1}; vs running a for loop and doing

```<code>for(int i = 0; i < 102; i++)
        for(int j = 0; j < 1002; j++)
            t[i][j] = -1;
</code>```

The code below does not work when the former method is used. It works only when we I loop through and initialize. Why is that?

```<code>#include<bits/stdc++.h>
using namespace std;
int t[102][1002] = {-1};
int knapstack(int wt[], int val[], int w, int n)
{
    if(n == 0 || w == 0)
        return 0;

    if (t[n][w] != -1)
        return t[n][w];

    if(wt[n-1] <= w ){
        t[n][w] = max(val[n-1] + knapstack(wt,val, w - wt[n-1],n-1) , knapstack(wt, val, w, n-1));
        return t[n][w];
    }

    if(wt[n-1] > w){
       t[n][w] = knapstack(wt,val,w,n-1);
       return t[n][w];
    }
}

int main()
{
    int wt[] = {10, 20, 30};
    int val[] = { 60, 100, 120};
    int w = 50, n = sizeof(val)/sizeof(val[0]);
    cout<< knapstack(wt, val, w, n);
}

</code>```

答:
As others have stated, you're simply setting the first element to -1. I'll offer a more C++11 alternative to memset. Should be pretty similar performance if you use -O2 compiler optimization option.

```<code>std::fill_n(&t[0][0], sizeof(t)/sizeof(int),-1);
</code>```

edit: for typos

Body:
What is the difference between doing int t[102][1002] = {-1}; vs running a for loop and doing

for(int i = 0; i < 102; i++)
        for(int j = 0; j < 1002; j++)
            t[i][j] = -1;

The code below does not work when the former method is used. It works only when we I loop through and initialize. Why is that?

#include<bits/stdc++.h>
using namespace std;
int t[102][1002] = {-1};
int knapstack(int wt[], int val[], int w, int n)
{
    if(n == 0 || w == 0)
        return 0;

    if (t[n][w] != -1)
        return t[n][w];

    if(wt[n-1] <= w ){
        t[n][w] = max(val[n-1] + knapstack(wt,val, w - wt[n-1],n-1) , knapstack(wt, val, w, n-1));
        return t[n][w];
    }

    if(wt[n-1] > w){
       t[n][w] = knapstack(wt,val,w,n-1);
       return t[n][w];
    }
}

int main()
{
    int wt[] = {10, 20, 30};
    int val[] = { 60, 100, 120};
    int w = 50, n = sizeof(val)/sizeof(val[0]);
    cout<< knapstack(wt, val, w, n);
}

Body:
As others have stated, you're simply setting the first element to -1. I'll offer a more C++11 alternative to memset. Should be pretty similar performance if you use -O2 compiler optimization option.

std::fill_n(&t[0][0], sizeof(t)/sizeof(int),-1);

edit: for typos


问:
How to build node 5.4.0 npm 3.3.12 - earlier it was working fine
Our application is in live that built with node 5.4.0 and npm 3.3.12. Till last week it was working fine. Now when we try to run command npm install I am getting npm error

```<code>38626 error node v5.4.0
38627 error npm  v3.3.12
38628 error code EMISSINGARG
38629 error typeerror Error: Missing required argument #1
</code>```

I see that I need to upgrade my project to latest npm. But that requires lot of time as my project is depending on webpack 1 version and old libraries. My question here is why it is stopped working. How can I fix this? I am attaching npm logs.

```<code>    38619 verbose headers   'content-encoding': 'gzip' }
38620 silly get cb [ 200,
38620 silly get   { date: 'Thu, 28 May 2020 09:46:20 GMT',
38620 silly get     'content-type': 'application/json',
38620 silly get     'transfer-encoding': 'chunked',
38620 silly get     connection: 'keep-alive',
38620 silly get     'set-cookie': [ '__cfduid=de470fd6ae02fefdbbaf3cbeada2f984c1590659179; expires=Sat, 27-Jun-20 09:46:19 GMT; path=/; domain=.npmjs.org; HttpOnly; SameSite=Lax' ],
38620 silly get     'cf-ray': '59a70c3d493fc938-HYD',
38620 silly get     'cache-control': 'public, max-age=300',
38620 silly get     etag: 'W/"414ba14c1fef3e9df9d31821a3c138cf"',
38620 silly get     'last-modified': 'Sun, 26 Jan 2020 08:06:08 GMT',
38620 silly get     vary: 'accept-encoding, accept',
38620 silly get     'cf-cache-status': 'EXPIRED',
38620 silly get     'cf-request-id': '02fc45fa4f0000c9383abe1200000001',
38620 silly get     'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
38620 silly get     server: 'cloudflare',
38620 silly get     'content-encoding': 'gzip' } ]
38621 verbose get saving available-typed-arrays to /Users/thrinethrasiddani/.npm/registry.npmjs.org/available-typed-arrays/.cache.json
38622 verbose stack Error: Missing required argument #1
38622 verbose stack     at andLogAndFinish
</code>```

答:
The problem most probably was older but you only discovered it last week/today. There is a GitHub issue in npm repository with people running on npm 3.5.2 complaining about the same thing. In short, it appears to be a npm bug or they have intentionally dropped support for older npm versions. The last comment in the thread suggests upgrading to latest npm 3.x, which is 3.10.10, which appears to still work.

As far as I'm aware, you only need to upgrade npm, not all the dependencies. However, I do suggest trying to keep your dependencies up to date to be compliant, have the latest security fixes and features.

If you wanna dig into it, this is where the error is thrown.

Update:
Somebody has found a fix which doesn't require npm/node upgrade: https://askubuntu.com/a/1098249/162155

Body:
Our application is in live that built with node 5.4.0 and npm 3.3.12. Till last week it was working fine. Now when we try to run command npm install I am getting npm error

38626 error node v5.4.0
38627 error npm  v3.3.12
38628 error code EMISSINGARG
38629 error typeerror Error: Missing required argument #1

I see that I need to upgrade my project to latest npm. But that requires lot of time as my project is depending on webpack 1 version and old libraries. My question here is why it is stopped working. How can I fix this? I am attaching npm logs.

    38619 verbose headers   'content-encoding': 'gzip' }
38620 silly get cb [ 200,
38620 silly get   { date: 'Thu, 28 May 2020 09:46:20 GMT',
38620 silly get     'content-type': 'application/json',
38620 silly get     'transfer-encoding': 'chunked',
38620 silly get     connection: 'keep-alive',
38620 silly get     'set-cookie': [ '__cfduid=de470fd6ae02fefdbbaf3cbeada2f984c1590659179; expires=Sat, 27-Jun-20 09:46:19 GMT; path=/; domain=.npmjs.org; HttpOnly; SameSite=Lax' ],
38620 silly get     'cf-ray': '59a70c3d493fc938-HYD',
38620 silly get     'cache-control': 'public, max-age=300',
38620 silly get     etag: 'W/"414ba14c1fef3e9df9d31821a3c138cf"',
38620 silly get     'last-modified': 'Sun, 26 Jan 2020 08:06:08 GMT',
38620 silly get     vary: 'accept-encoding, accept',
38620 silly get     'cf-cache-status': 'EXPIRED',
38620 silly get     'cf-request-id': '02fc45fa4f0000c9383abe1200000001',
38620 silly get     'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
38620 silly get     server: 'cloudflare',
38620 silly get     'content-encoding': 'gzip' } ]
38621 verbose get saving available-typed-arrays to /Users/thrinethrasiddani/.npm/registry.npmjs.org/available-typed-arrays/.cache.json
38622 verbose stack Error: Missing required argument #1
38622 verbose stack     at andLogAndFinish


问:
How to exclude a package.json from a git merge?
I have three branches in the repository.

```<code>master
slave 1
slave 2
</code>```

there is one package.json file. It should be different in each of the branches. But if I run the git merge master command. These two branches merge into one. How to exclude package.json from merging branches so that each branch has its own version?

add:

I have a sequence

git checkout slave 1 && git merge -Xtheirs --no-edit master  && git push && git checkout master

答:
There is no automatic way to tell git to avoid merging changes on a file. You can ask to check out the file from HEAD before finishing the merge:</p>

```<code>git merge other-branch --no-commit
git checkout HEAD -- package.json # get the file back
git commit -m "Now we finish the merge"
</code>```

Body:
I have three branches in the repository.

master
slave 1
slave 2

there is one package.json file. It should be different in each of the branches. But if I run the git merge master command. These two branches merge into one. How to exclude package.json from merging branches so that each branch has its own version?

add:

I have a sequence

git checkout slave 1 && git merge -Xtheirs --no-edit master  && git push && git checkout master

Body:
There is no automatic way to tell git to avoid merging changes on a file. You can ask to check out the file from HEAD before finishing the merge:

git merge other-branch --no-commit
git checkout HEAD -- package.json # get the file back
git commit -m "Now we finish the merge"


问:
How does WCF + SSL working with load balancing?
If SSL is handled by a load balancer, do I still need to configure it in the WCF serviceCertificate node?  My scenario is to use message level security.  If someone can explain how load balancing with wcf and ssl works, that would be very nice.</p>

答: It doesn't. Don't bother with this. You will be in a world of hurt. Just install the certs on each machine. We've recently been through this fiasco. WCF is not worth the effort it thinks it needs SSL but sees that it doesn't have it. Take a look at openrasta or something else if you want to do all your SSL on the loadbalancer. #microsoftfail</p>


答: According to the documentation, cursor.execute() returns the number of affected rows.  You then need to fetch the content with fetch() or fetchall().  See the example at PyMySQL.</p>

Title: SELECT statement is MySql returning wrong value using python

Body:
I am trying to retrieve a value from a table stored in Mysql database using python(pycharm). But instead of outputting the stored value it outputs number of rows instead.

import pymysql
connection = pymysql.connect(host='localhost',
                             user='root',
                             password='passw',
                             database='database1',
                             charset='utf8',
                             port=3306
                             )
x=connection.cursor()
select = x.execute('''SELECT
    update_id
FROM
    telegram;
''')
print(select)

Output: 1

^Wrong output(Output equals number of rows). As I keep adding on rows the output changes to the number of rows but never returns the value stored.

The command works from MySql perfectly.

SELECT
        update_id
    FROM
        telegram;
Output:233

^This is the correct output.
Why is this happening? What changes should I make in my python code?


问:
Best method for storing a list of user IDs
I'm working on a PHP/MySQL rating system right now. For the user to be able to rate the user has to log in. Each user has a unique "UID". There will be multiple rating instances on the website (one for every game, in my case) and I need an efficient way of storing a list of UIDs in a MySQL row (one MySQL row in the ratings table for each instance of the rating system) to keep a tally of who has voted.

I've seen in other systems that the list is stored in a serialized PHP array. Every time a user votes, then serialized array has to extracted, unserialized, the new UID is inserted, the array is re-serialized, and the MySQL row is UPDATEd. Every time the page is loaded, that list has to once again be unserialized and checked to see if the user viewing the page has voted yet to make sure the user doesn't vote twice.

This seems kind of inefficient and cumbersome. Does MySQL have a built in list function to help this process be more efficient? Are there any more clever ways I could fix this problem?

I've considered one possible alternative which is forget the serializing and store the UIDs in a TEXT type field in the MySQL database. I would just append some non-numeric character after each UID (let's say a period [.]). To add a user entry I would just concatenate the UID onto the end of the TEXT field and then a period. When checking if the user has already voted I could just "SELECT * FROM table WHERE votes = '%$UID.%';". Would this work more efficiently or is there a more elegant way of getting the job done?

Follow-up post about the table structure... Efficient MySQL table structure for rating system

答:
It is inefficient.  What you have here in relational terms is a many-to-many relationship between users and games.  A user can vote on many games.  A game can be voted on by many users.  The solution for this is to have a join table:

```<code>USERS (uid, name, ...)
GAMES (gid, name, ...)
VOTES (id, uid, gid, ...)
</code>```

Where uid and gid are foreign keys back to their respective tables.

If someone votes, insert a record in VOTES.

To get a list of votes for a game:

```<code>$get = mysql_query("SELECT * FROM votes WHERE gid = $game_id");
...
</code>```

To get a list of the user's votes:

```<code>$get = mysql_query("SELECT * FROM votes WHERE uid = $user_id");
...
</code>```

and so on.

Don't join an array and store it in a single column.  You're right to avoid that.

ContentLicense: CC BY-SA 2.5

Body:
It is inefficient.  What you have here in relational terms is a many-to-many relationship between users and games.  A user can vote on many games.  A game can be voted on by many users.  The solution for this is to have a join table:

USERS (uid, name, ...)
GAMES (gid, name, ...)
VOTES (id, uid, gid, ...)

Where uid and gid are foreign keys back to their respective tables.

If someone votes, insert a record in VOTES.

To get a list of votes for a game:

$get = mysql_query("SELECT * FROM votes WHERE gid = $game_id");
...

To get a list of the user's votes:

$get = mysql_query("SELECT * FROM votes WHERE uid = $user_id");
...

and so on.

Don't join an array and store it in a single column.  You're right to avoid that.

OwnerDisplayName: cletus


问:
How to get raw key data from DHPublicKey?
I followed instructions for generating private/public keys from DH group in
https://cryptography.io/en/latest/hazmat/primitives/asymmetric/dh/ and I was able to get to this:

```<code>>>> p=0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF
>>> g=2
>>>
>>>
>>> pn = dh.DHParameterNumbers(p, g)
>>> params = pn.parameters(default_backend())
>>> priv = params.generate_private_key()
>>> pub = priv.public_key()
>>> pub.key_size
2048
>>> raw = pub.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
>>> len(raw)
552
</code>```

I expect key length 256 bytes (as pub.key_size suggests) but I can't find any way to get actual raw key data. As per docs public_bytes() accepts only SubjectPublicKeyInfo format for DHPublicKey.

How do I get actual key data with correct length?

答:
The example on the page you link shows you a superior way to generate a shared secret, but if you must get the raw public key bytes then

y = pub.public_numbers().y    # y is a python int
pub_bytes = y.to_bytes(2048 // 8, 'big')
```

will get them.

Body:
I followed instructions for generating private/public keys from DH group in
https://cryptography.io/en/latest/hazmat/primitives/asymmetric/dh/ and I was able to get to this:

>>> p=0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF
>>> g=2
>>>
>>>
>>> pn = dh.DHParameterNumbers(p, g)
>>> params = pn.parameters(default_backend())
>>> priv = params.generate_private_key()
>>> pub = priv.public_key()
>>> pub.key_size
2048
>>> raw = pub.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
>>> len(raw)
552

I expect key length 256 bytes (as pub.key_size suggests) but I can't find any way to get actual raw key data. As per docs public_bytes() accepts only SubjectPublicKeyInfo format for DHPublicKey.

How do I get actual key data with correct length?

Body:
The example on the page you link shows you a superior way to generate a shared secret, but if you must get the raw public key bytes then

y = pub.public_numbers().y    # y is a python int
pub_bytes = y.to_bytes(2048 // 8, 'big')

will get them.


问:
Ambiguous reference CS0104: 'Debug' is an ambiguous reference between'UnityEngine.Debug' and 'System.Diagnostics.Debug'
I am new to programming and need help to fix error pop-up, which appeared after writing if statement in code, 5 error codes for all Debug.Log lines, before if statement they were working fine.

```<code>    int max = 1000;
    int min = 1;

    Debug.Log("Welcome to number Wizard");
    Debug.Log("Pick a number");
    Debug.Log("Highest number is: " + max);
    Debug.Log("Lowest number is: " + min);
}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.UpArrow))
    {
        Debug.Log("Up Arrow key was pressed");
    }
}
</code>```

}

答:
If you don't need it on top of your file remove the

```<code>using System.Diagnostics;
</code>```

Otherwise either use the full namespace

```<code>UnityEngine.Debug.Log("some text");
</code>```

or add

```<code>using Debug = UnityEngine.Debug;
</code>```

at the top of your file.

Body:
I am new to programming and need help to fix error pop-up, which appeared after writing if statement in code, 5 error codes for all Debug.Log lines, before if statement they were working fine.

    int max = 1000;
    int min = 1;

    Debug.Log("Welcome to number Wizard");
    Debug.Log("Pick a number");
    Debug.Log("Highest number is: " + max);
    Debug.Log("Lowest number is: " + min);
}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.UpArrow))
    {
        Debug.Log("Up Arrow key was pressed");
    }
}

}

Body:
If you don't need it on top of your file remove the

using System.Diagnostics;

Otherwise either use the full namespace

UnityEngine.Debug.Log("some text");

or add

using Debug = UnityEngine.Debug;

at the top of your file.


问:
How generate OAuth for azure vm
I installed Grafana on my Azure virtual machine. Now I want to set OAuth.
In defaults.ini  I set the

```<code>name = my app
enabled = true
allow_sign_up = true
client_id = with my id
client_secret = with my client_secret
scopes = openid email name
auth_url =
token_url =
api_url =
team_ids =
allowed_organizations =
</code>```

And this not work.  Can anyone have some idea where I wrong.

答:
Do not edit defaults.ini!
Use the following link to create or locate grafana.ini or custom.ini depending on your OS:
https://grafana.com/docs/grafana/latest/installation/configuration/

I would recommend that you copy the block of code for the OAuth provider you want to use to grafana.ini/custom.ini and then edit it to suit your need.

You may have to edit the URL under the [server] settings to allow for the correct redirect when using external OAuth

Title: How generate OAuth for azure vm

Body:
I installed Grafana on my Azure virtual machine. Now I want to set OAuth.
In defaults.ini  I set the

name = my app
enabled = true
allow_sign_up = true
client_id = with my id
client_secret = with my client_secret
scopes = openid email name
auth_url =
token_url =
api_url =
team_ids =
allowed_organizations =

And this not work.  Can anyone have some idea where I wrong.


问:
Possible PHP bug around static:: in PHP 5.3.3
I was working on some PHP around the "static::" keyword, and encountered an issue where too many static calls result in confusion as to where a method resides. It's easier to show by example:

```<code>class Class1
{
    function Test()
    {
        return Class2::Test();
    }
}

class Class2
{
    function Test()
    {
        return static::Test2();
    }

    function Test2()
    {
        return true;
    }
}

/* test 1: calling Class1::Test() statically results in expected call to Class2::Test2() */
echo "test 1: " . Class1::Test() . "\n";

/* test 2: instantiating the class causes Class1::Test2() to be called, which does not exist */
$Class1 = new Class1();
echo "test 2: " . $Class1->Test() . "\n";
</code>```

I wanted to reach out and get opinions of PHP experts who can tell me whether this might be a genuine bug or simple misuse of the language.

I realize the setup may be odd with all the static calls, but it represents actual code that I came across.

Please let me know if any more information or clarification is needed. Thanks for any help in advance!

答:
The PHP docs on late static bindings answer your question.

"late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced by self::, parent::, static::" ...

Your test 1 is a static call, so when Class2::Test() is called, it stores Class2. The static test2 call refers to the correct place in Class2.

Your test 2 is a non static call, so it uses the class of the object in all cases, and since it is a Class1, it can't find the method Test2.

Body:
I was working on some PHP around the "static::" keyword, and encountered an issue where too many static calls result in confusion as to where a method resides. It's easier to show by example:

class Class1
{
    function Test()
    {
        return Class2::Test();
    }
}

class Class2
{
    function Test()
    {
        return static::Test2();
    }

    function Test2()
    {
        return true;
    }
}

/* test 1: calling Class1::Test() statically results in expected call to Class2::Test2() */
echo "test 1: " . Class1::Test() . "\n";

/* test 2: instantiating the class causes Class1::Test2() to be called, which does not exist */
$Class1 = new Class1();
echo "test 2: " . $Class1->Test() . "\n";

I wanted to reach out and get opinions of PHP experts who can tell me whether this might be a genuine bug or simple misuse of the language.

I realize the setup may be odd with all the static calls, but it represents actual code that I came across.

Please let me know if any more information or clarification is needed. Thanks for any help in advance!