问:
how is it possible to display continuously calculated values of functions from a class?
I want the program to run continuously and output the values from the methods (func1 - func4) as soon as a signal gradient is detected on the pins.

This is just a test code to understand how I can access the values, because I have written a "program" with a surface that shows uninterrupted values from a machine where I use ONLY global variables and I don't want to post that here because it's embarrassing...
and i want to get rid of all the global variables

A raspberry pi is connected to the machine with which I intercept 4 signals over the gpio.

```<code>cavity = 2
count = 0
scrap = 0
uptime = datetime.timedelta(0)
downtime = datetime.timedelta(0)

def func1(channel):
    if GPIO.input(7) == 0:
        while True:
            uptime = uptime + datetime.timedelta(0,1)
            time.sleep(1)
            if GPIO.input(7) == 1 or GPIO.input(37) == 0:
                break

def func2(channel):
    scrap = scrap + cavity

def func3(channel):
    count = count + cavity

def func4(channel):
    if GPIO.input(37) == 0:
        while True:
            downtime = downtime + datetime.timedelta(0,1)
            if GPIO.inpu(37) == 1:
                break

GPIO.add_event_detect(7, GPIO.RISING, callback = func1, bouncetime = 100)           #Run
GPIO.add_event_detect(29, GPIO.RISING, callback = func2, bouncetime = 100)          #Scrap
GPIO.add_event_detect(13, GPIO.RISING, callback = func3, bouncetime = 100)          #Count
GPIO.add_event_detect(37, GPIO.RISING, callback = func4, bouncetime = 100)          #Alarm

class Output(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.show()

    def show(self):
        print('ich werde aufgerufen')
        while True:
            print(uptime)
            print(scrap)
            print(count)
            print(downtime)
            print('############################')
            time.sleep(5)

thread2 = Output()
thread2.start()
</code>```

only zeros are output this was to be expected but how do i get access to the variables so that on signal detection the values increase

答:
Your code written as two classes:</p>

```<code>class Events:
    def __init__(self):
        GPIO.add_event_detect(7, GPIO.RISING, callback = self.func1, bouncetime = 100)           #Run
        GPIO.add_event_detect(29, GPIO.RISING, callback = self.func2, bouncetime = 100)          #Scrap
        GPIO.add_event_detect(13, GPIO.RISING, callback = self.func3, bouncetime = 100)          #Count
        GPIO.add_event_detect(37, GPIO.RISING, callback = self.func4, bouncetime = 100)          #Alarm

        self.cavity = 2
        self.count = 0
        self.scrap = 0
        self.uptime = datetime.timedelta(0)
        self.downtime = datetime.timedelta(0)

    def func1(self, channel):
        if GPIO.input(7) == 0:
            while True:
                self.uptime = self.uptime + datetime.timedelta(0,1)
                time.sleep(1)
                if GPIO.input(7) == 1 or GPIO.input(37) == 0:
                    break

    def func2(self, channel):
        self.scrap = self.scrap + cavity

    def func3(self, channel):
        self.count = self.count + cavity

    def func4(self, channel):
        if GPIO.input(37) == 0:
            while True:
                self.downtime = self.downtime + datetime.timedelta(0,1)
                if GPIO.inpu(37) == 1:
                    break

class Output(threading.Thread):
    def __init__(self, events):
        threading.Thread.__init__(self)
        self.events = events
        self.show()

    def show(self):
        print('ich werde aufgerufen')
        while True:
            print(self.events.uptime)
            print(self.events.scrap)
            print(self.events.count)
            print(self.events.downtime)
            print('############################')
            time.sleep(5)

events = Events()
thread2 = Output(events)
thread2.start()
</code>```

Body:
I want the program to run continuously and output the values from the methods (func1 - func4) as soon as a signal gradient is detected on the pins.

This is just a test code to understand how I can access the values, because I have written a "program" with a surface that shows uninterrupted values from a machine where I use ONLY global variables and I don't want to post that here because it's embarrassing...
and i want to get rid of all the global variables

A raspberry pi is connected to the machine with which I intercept 4 signals over the gpio.

cavity = 2
count = 0
scrap = 0
uptime = datetime.timedelta(0)
downtime = datetime.timedelta(0)

def func1(channel):
    if GPIO.input(7) == 0:
        while True:
            uptime = uptime + datetime.timedelta(0,1)
            time.sleep(1)
            if GPIO.input(7) == 1 or GPIO.input(37) == 0:
                break

def func2(channel):
    scrap = scrap + cavity

def func3(channel):
    count = count + cavity

def func4(channel):
    if GPIO.input(37) == 0:
        while True:
            downtime = downtime + datetime.timedelta(0,1)
            if GPIO.inpu(37) == 1:
                break

GPIO.add_event_detect(7, GPIO.RISING, callback = func1, bouncetime = 100)           #Run
GPIO.add_event_detect(29, GPIO.RISING, callback = func2, bouncetime = 100)          #Scrap
GPIO.add_event_detect(13, GPIO.RISING, callback = func3, bouncetime = 100)          #Count
GPIO.add_event_detect(37, GPIO.RISING, callback = func4, bouncetime = 100)          #Alarm

class Output(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.show()

    def show(self):
        print('ich werde aufgerufen')
        while True:
            print(uptime)
            print(scrap)
            print(count)
            print(downtime)
            print('############################')
            time.sleep(5)

thread2 = Output()
thread2.start()

only zeros are output this was to be expected but how do i get access to the variables so that on signal detection the values increase

Body:
Your code written as two classes:

class Events:
    def __init__(self):
        GPIO.add_event_detect(7, GPIO.RISING, callback = self.func1, bouncetime = 100)           #Run
        GPIO.add_event_detect(29, GPIO.RISING, callback = self.func2, bouncetime = 100)          #Scrap
        GPIO.add_event_detect(13, GPIO.RISING, callback = self.func3, bouncetime = 100)          #Count
        GPIO.add_event_detect(37, GPIO.RISING, callback = self.func4, bouncetime = 100)          #Alarm

        self.cavity = 2
        self.count = 0
        self.scrap = 0
        self.uptime = datetime.timedelta(0)
        self.downtime = datetime.timedelta(0)

    def func1(self, channel):
        if GPIO.input(7) == 0:
            while True:
                self.uptime = self.uptime + datetime.timedelta(0,1)
                time.sleep(1)
                if GPIO.input(7) == 1 or GPIO.input(37) == 0:
                    break

    def func2(self, channel):
        self.scrap = self.scrap + cavity

    def func3(self, channel):
        self.count = self.count + cavity

    def func4(self, channel):
        if GPIO.input(37) == 0:
            while True:
                self.downtime = self.downtime + datetime.timedelta(0,1)
                if GPIO.inpu(37) == 1:
                    break

class Output(threading.Thread):
    def __init__(self, events):
        threading.Thread.__init__(self)
        self.events = events
        self.show()

    def show(self):
        print('ich werde aufgerufen')
        while True:
            print(self.events.uptime)
            print(self.events.scrap)
            print(self.events.count)
            print(self.events.downtime)
            print('############################')
            time.sleep(5)

events = Events()
thread2 = Output(events)
thread2.start()


来源: stackexchange

问:
the issue is probably caused by a circular import
i'm trying to runserver for a django project and it shows me this error :
The included URLconf 'Smartfarmer.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

eventhough the same project works fine in another envirenement

i've tried to check if there are any mistakes in urls but i believe everything is fine

my urls file of the project :
smartfarmer.urls:

from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

from main_app import views

urlpatterns = [
    url(r'^admin/',admin.site.urls),
    url(r'^',
        include('main_app.urls')),
     url(r'^detect/',
        include('detect.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

```

<p>my urls for my apps :</p>

<p>main_app.urls:</p>

<pre class="lang-py prettyprint-override"><code>from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^$', views.index),
]
</code>```

detect.urls:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^result/$', views.result, name='result'),
]
```

答:
First way:

smartfarmer.urls:

```<code>from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('main_app.urls', namespace="main")),
    url(r'^detect/', include('detect.urls', namespace="detect")),
]
</code>```

main_app.urls:

```<code>from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name="index"),
]
</code>```

Second way:

main_app.urls:

```<code>from django.conf.urls import url
from . import views

app_name = "main"
urlpatterns = [
    url(r'^$', views.index, name="index"),
]
</code>```

detect.urls:

```<code>from django.conf.urls import url
from . import views

app_name = "detect"
urlpatterns = [
    url(r'^result/$', views.result, name='result'),
]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i'm trying to runserver for a django project and it shows me this error :
The included URLconf 'Smartfarmer.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

eventhough the same project works fine in another envirenement

i've tried to check if there are any mistakes in urls but i believe everything is fine

my urls file of the project :
smartfarmer.urls:

from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

from main_app import views

urlpatterns = [
    url(r'^admin/',admin.site.urls),
    url(r'^',
        include('main_app.urls')),
     url(r'^detect/',
        include('detect.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

my urls for my apps :

main_app.urls:

from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^$', views.index),
]

detect.urls:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^result/$', views.result, name='result'),
]

Body:
First way:

smartfarmer.urls:

from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('main_app.urls', namespace="main")),
    url(r'^detect/', include('detect.urls', namespace="detect")),
]

main_app.urls:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name="index"),
]

Second way:

main_app.urls:

from django.conf.urls import url
from . import views

app_name = "main"
urlpatterns = [
    url(r'^$', views.index, name="index"),
]

detect.urls:

from django.conf.urls import url
from . import views

app_name = "detect"
urlpatterns = [
    url(r'^result/$', views.result, name='result'),
]


问:
How is the sintaxis to use ignore_dup_key?
I am trying to ignore duplicates when I insert rows in a many to many relationship table, but all the examples that I find is modifying the key in the table.

I would like to know if there is some way to set this only for the inserts that I want to do, something like that:

```<code>insert into Table(IDA, IDB) VALUES(1,2) ignore_dup_key = ON;
</code>```

Thanks.

答:
"ignore_dup_key = ON" is a property that you define when creating an index. It is not a query hint.</p>

```<code>CREATE UNIQUE NONCLUSTERED INDEX ix_table
    ON dbo.Table (KeyColumn)
    WITH (IGNORE_DUP_KEY = ON) ON [PRIMARY];
</code>```

Body:
I am trying to ignore duplicates when I insert rows in a many to many relationship table, but all the examples that I find is modifying the key in the table.

I would like to know if there is some way to set this only for the inserts that I want to do, something like that:

insert into Table(IDA, IDB) VALUES(1,2) ignore_dup_key = ON;

Thanks.

Body:
"ignore_dup_key = ON" is a property that you define when creating an index. It is not a query hint.

CREATE UNIQUE NONCLUSTERED INDEX ix_table
    ON dbo.Table (KeyColumn)
    WITH (IGNORE_DUP_KEY = ON) ON [PRIMARY];


问:
How to configure TestRestTemplate to use a Keystore?
My project has a series of integration tests that use TestRestTemplate and MockMvc.  These had been passing successfully.

I have now added Spring Boot Starter Security and Spring Security OAuth2 Autoconfigure dependencies to my project.  I have added a custom class that extends WebSecurityConfigurerAdapter to allow open access (for the moment) to my applicaiton.  Here is the class

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .authorizeRequests()
            .anyRequest()
            .permitAll();
    }

    @Override
    public void configure(WebSecurity webSecurity) {
        webSecurity
            .ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**");
    }
}
</code>```

The application also needs to act as an OAuth2 Resource Server so I have also annotated my main class with @EnableResourceServer.  I provide the path to the trusted key store as run parameters when running the application.  -Djavax.net.ssl.trustStore=<where the cert is stored locally> -Djavax.net.ssl.trustStorePassword=<the password>

The application works fine but now all of the integration tests are failing.  Here is an example of the error common to all the tests that use the TestRestTemplate

```<code>Could not fetch user details: class org.springframework.web.client.ResourceAccessException, I/O error on GET request for <the path to my userinfo URL>:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

It seems that the TestRestTemplate I am using for my tests needs to be instructed to use the same keystore that the application does.  Is it possible to do this?  How would it work for MockMvc?

答:
Thank you, the first link you posted was very useful. This is my working code for a RestTemplate that accepts any cert, if anyone else finds it useful. It's still dependent on valid tokens being provided but that's another story.</p>

```<code>private RestTemplate buildRestTemplate() throws Exception {
    SSLContext sslContext = new SSLContextBuilder()
        .loadTrustMaterial(
            new TrustSelfSignedStrategy()
        ).build();
    SSLConnectionSocketFactory socketFactory =
        new SSLConnectionSocketFactory(sslContext);
    HttpClient httpClient = HttpClients.custom()
        .setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory factory =
        new HttpComponentsClientHttpRequestFactory(httpClient);
    return new RestTemplate(factory);
}
</code>```

Body:
My project has a series of integration tests that use TestRestTemplate and MockMvc.  These had been passing successfully.

I have now added Spring Boot Starter Security and Spring Security OAuth2 Autoconfigure dependencies to my project.  I have added a custom class that extends WebSecurityConfigurerAdapter to allow open access (for the moment) to my applicaiton.  Here is the class

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .authorizeRequests()
            .anyRequest()
            .permitAll();
    }

    @Override
    public void configure(WebSecurity webSecurity) {
        webSecurity
            .ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**");
    }
}

The application also needs to act as an OAuth2 Resource Server so I have also annotated my main class with @EnableResourceServer.  I provide the path to the trusted key store as run parameters when running the application.  -Djavax.net.ssl.trustStore=<where the cert is stored locally> -Djavax.net.ssl.trustStorePassword=<the password>

The application works fine but now all of the integration tests are failing.  Here is an example of the error common to all the tests that use the TestRestTemplate

Could not fetch user details: class org.springframework.web.client.ResourceAccessException, I/O error on GET request for <the path to my userinfo URL>:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

It seems that the TestRestTemplate I am using for my tests needs to be instructed to use the same keystore that the application does.  Is it possible to do this?  How would it work for MockMvc?

Body:
Thank you, the first link you posted was very useful. This is my working code for a RestTemplate that accepts any cert, if anyone else finds it useful. It's still dependent on valid tokens being provided but that's another story.

private RestTemplate buildRestTemplate() throws Exception {
    SSLContext sslContext = new SSLContextBuilder()
        .loadTrustMaterial(
            new TrustSelfSignedStrategy()
        ).build();
    SSLConnectionSocketFactory socketFactory =
        new SSLConnectionSocketFactory(sslContext);
    HttpClient httpClient = HttpClients.custom()
        .setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory factory =
        new HttpComponentsClientHttpRequestFactory(httpClient);
    return new RestTemplate(factory);
}


问:
How to show a PDF page by page using horizontal swipe in iphone?
I would like to add to my app a pdf viewer which can scroll horizontally. Anyone know how to do it? I'm making several attempts but without success. Thanks. Matteo</p>

答:
Use UIWebViewController in landscape orientation and this piece of code can give you an idea about how to display pdfs:</p>

```<code> UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake( 0, 0, 320, 480 )];
 NSString *path = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"pdf"];
 NSURL *targetURL = [NSURL fileURLWithPath:path];
 NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
 [webView loadRequest:request];
 webView.scalesPageToFit = YES;
 [self.view addSubview:webView];
 [webView release];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use UIWebViewController in landscape orientation and this piece of code can give you an idea about how to display pdfs:

 UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake( 0, 0, 320, 480 )];
 NSString *path = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"pdf"];
 NSURL *targetURL = [NSURL fileURLWithPath:path];
 NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
 [webView loadRequest:request];
 webView.scalesPageToFit = YES;
 [self.view addSubview:webView];
 [webView release];


问:
Angular Modal undefined nativeElement
I'm getting the following error when trying to close my modal:

cannot read property nativeElement of undefined

The element has been rendered by time i'm trying to close it so I'm not sure what else it could be.

Modal code:

```<code><div class="modal" id="myModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
        </div>
        <div class="modal-body">
          <button type="button" class="btn btn-primary" (click)="close()">Close</button>
        </div>
        <div class="modal-footer">
        </div>
      </div>
    </div>
  </div>
  </div>
</div>
</code>```

Typescript:

```<code>import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {

  constructor() { }

  @ViewChild('myModal') closeModal: ElementRef;

  ngOnInit() {
  }

  close() {
    this.closeModal.nativeElement.click();
  }
}
</code>```

答:
ViewChild uses a template reference variable, not the id, to refer to the element. You should set the variable myModal on the target element in the template markup:

```<code><div class="modal" #myModal ...>
</code>```

so that you can refer to that element with ViewChild:

```<code>@ViewChild('myModal') closeModal: ElementRef;
</code>```

Title: Angular Modal undefined nativeElement

Body:
I'm getting the following error when trying to close my modal:

cannot read property nativeElement of undefined

The element has been rendered by time i'm trying to close it so I'm not sure what else it could be.

Modal code:

          <button type="button" class="btn btn-primary" (click)="close()">Close</button>

Typescript:

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {

  constructor() { }

  @ViewChild('myModal') closeModal: ElementRef;

  ngOnInit() {
  }

  close() {
    this.closeModal.nativeElement.click();
  }
}

Body:
ViewChild uses a template reference variable, not the id, to refer to the element. You should set the variable myModal on the target element in the template markup:

<div class="modal" #myModal ...>

so that you can refer to that element with ViewChild:

@ViewChild('myModal') closeModal: ElementRef;


问:
ServiceStack: Adding Blazor support?
I have tried adding ServiceStack-references to a client-side Blazor project, but I run into problems after adding ServiceStack.HttpClient via NuGet.

Currently, VS2019 will tell me that:

Cannot find declaration of exported type 'System.Threading'

and when ask/look around, they say that:

Blazor is built using mono-wasm as the base .NET framework
  implementation, and in this case I believe it's a missing method in
  mono-wasm that's the issue.

and

at present Mono WASM has no support for threading; check the repo
  https://github.com/lrz/mono-wasm-mono for more info

Am I getting it correctly:

ServiceStack requires System.Threading

WebAssembly and thus Blazor does not support references to System.Threading

Meaning that ServiceStack cannot be used in a Blazor app

答:
ServiceStack's Blazor WASM Template is being maintained by Sebastian Faltoni at https://github.com/nukedbit/blazor-wasm-servicestack

Which can be installed with the x dotnet tool:

```<code>$ dotnet tool install -g x
</code>```

and created with:

```<code>$ x new nukedbit/blazor-wasm-servicestack ProjectName
</code>```

Or for an installation-free alternative use ServiceStack's online project template builder:
https://servicestack.net/start#community

It includes integration with a Blazor Service Client which can be created at:

```<code>var client =  BlazorClient.Create("https://localhost:5001")
</code>```

It currently returns a pre-configured JsonHttpClient that removes all HttpClient features that Blazor WASM doesn't support. Over time we'll include more features as they're supported in Blazor.

@Issac is incorrect about ServiceStack using Web Sockets, ServiceStack doesn't use Web Sockets in any of its libraries and BlazorClient is a Service Client using .NET's HttpClient which Blazor WASM does support.

Title: ServiceStack: Adding Blazor support?

Body:
ServiceStack's Blazor WASM Template is being maintained by Sebastian Faltoni at https://github.com/nukedbit/blazor-wasm-servicestack

Which can be installed with the x dotnet tool:

$ dotnet tool install -g x

and created with:

$ x new nukedbit/blazor-wasm-servicestack ProjectName

Or for an installation-free alternative use ServiceStack's online project template builder:
https://servicestack.net/start#community

It includes integration with a Blazor Service Client which can be created at:

var client =  BlazorClient.Create("https://localhost:5001")

It currently returns a pre-configured JsonHttpClient that removes all HttpClient features that Blazor WASM doesn't support. Over time we'll include more features as they're supported in Blazor.

@Issac is incorrect about ServiceStack using Web Sockets, ServiceStack doesn't use Web Sockets in any of its libraries and BlazorClient is a Service Client using .NET's HttpClient which Blazor WASM does support.


问:
CURL can not run with Domain name on local Server
i'm trying to use curl to run a local php file inside my centOs7 shared server, but i can not use curl method for my local files.
here are my example files :

```<code>--bg/
------back.php
------curl.php
</code>```

here is curl.php codes:

```<code><?php
function run_curl($data){
    //url-ify the data for the POST
    $fields_string = '';
    //foreach($data as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    $fields_string = http_build_query($data);
    //open connection
    $ch = curl_init();
    //set the url, number of POST vars, POST data
    //curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: ' . $content_type]);
    curl_setopt($ch, CURLOPT_POST,true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json'
        )
    );
    curl_setopt($ch,CURLOPT_URL,'https://taskdan.com/bg/back.php');
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,50); # timeout after 10 seconds, you can increase it
    //curl_setopt($ch,CURLOPT_HEADER,false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  # Set curl to return the data instead of printing it to the browser.
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); # Some server may refuse your request if you dont pass user agent
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //execute post
    $result = curl_exec($ch);
    //print_r($result);
    //print_r((curl_getinfo($ch)));
    //error_log($result);
    //close connection
    curl_close($ch);
    return ($result);
}
echo " Output : </br>";
echo run_curl( [
    "ab" => "test"
]);
?>
</code>```

and the below my back.php codes:

```<code><?php
header("Content-Type:application/json");
echo json_encode([
    "a" => "test"
])
?>
</code>```

When I run this code, it looks like it converts my domain name to the server's public  IP address. Curl is working fine for outside of server scripts.

when i run curl with using SSH, i get this:

```<code>[root@??? ~]# curl https://taskdan.com -k
<html>Apache is functioning normally</html>
[root@??? ~]# curl http://171.22.27.118 -k
<html>Apache is functioning normally</html>
</code>```

i want to run some scripts in background, Are there any way to run a local php file with POST parameters by CURL?

答:
Your /etc/hosts file should look like this:

```<code>127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
</code>```

Change it to look like this:

```<code>127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4 taskdan.com
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6 taskdan.com
</code>```

Or, just change your code.

```<code>curl_setopt($ch,CURLOPT_URL,'http://127.0.0.1/bg/back.php');
</code>```

And configure Apache accordingly.

Body:
i'm trying to use curl to run a local php file inside my centOs7 shared server, but i can not use curl method for my local files.
here are my example files :

--bg/
------back.php
------curl.php

here is curl.php codes:

<?php
function run_curl($data){
    //url-ify the data for the POST
    $fields_string = '';
    //foreach($data as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    $fields_string = http_build_query($data);
    //open connection
    $ch = curl_init();
    //set the url, number of POST vars, POST data
    //curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: ' . $content_type]);
    curl_setopt($ch, CURLOPT_POST,true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json'
        )
    );
    curl_setopt($ch,CURLOPT_URL,'https://taskdan.com/bg/back.php');
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,50); # timeout after 10 seconds, you can increase it
    //curl_setopt($ch,CURLOPT_HEADER,false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  # Set curl to return the data instead of printing it to the browser.
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); # Some server may refuse your request if you dont pass user agent
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //execute post
    $result = curl_exec($ch);
    //print_r($result);
    //print_r((curl_getinfo($ch)));
    //error_log($result);
    //close connection
    curl_close($ch);
    return ($result);
}
echo " Output :
";
echo run_curl( [
    "ab" => "test"
]);
?>

and the below my back.php codes:

<?php
header("Content-Type:application/json");
echo json_encode([
    "a" => "test"
])
?>

When I run this code, it looks like it converts my domain name to the server's public  IP address. Curl is working fine for outside of server scripts.

when i run curl with using SSH, i get this:

[root@??? ~]# curl https://taskdan.com -k
Apache is functioning normally
[root@??? ~]# curl http://171.22.27.118 -k
Apache is functioning normally

i want to run some scripts in background, Are there any way to run a local php file with POST parameters by CURL?

Body:
Your /etc/hosts file should look like this:

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

Change it to look like this:

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4 taskdan.com
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6 taskdan.com

Or, just change your code.

curl_setopt($ch,CURLOPT_URL,'http://127.0.0.1/bg/back.php');

And configure Apache accordingly.


问:
I2C, DCMI stops working after waking up from STOP mode in stm32f4
The I2C and DCMI stops working on my custom board after wake up from STOP mode. I deinitialize GPIO's before going into STOP mode. After wake up from STOP for I2C I always get HAL_BUSY for both read and write while for camera on DCMI I get some random data instead of jpeg image. But if I don't deinitialize GPIO's then everything works fine without any problem but there is higher power consumption in STOP mode. Following is my code for GPIO's deinitialization

```<code>void MX_GPIO_Deinit()
{
    GPIO_InitTypeDef GPIO_InitStruct;
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();
    __HAL_RCC_GPIOC_CLK_ENABLE();
    __HAL_RCC_GPIOH_CLK_ENABLE();

    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Pin = GPIO_PIN_All;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
    HAL_GPIO_Init(GPIOH, &GPIO_InitStruct);

    /* Disable GPIOs clock */
    __HAL_RCC_GPIOA_CLK_DISABLE();
    __HAL_RCC_GPIOB_CLK_DISABLE();
    __HAL_RCC_GPIOC_CLK_DISABLE();
    __HAL_RCC_GPIOH_CLK_DISABLE();
}
</code>```

Is there any to reset I2C and DCMI properly after waking from STOP mode? Calling functions MX_I2C2_Init() and MX_DCMI_Init() doesn't work. What is the proper way for handling this and make I2C and DCMI work?

答:
Peripherals can be reset using the RCC (Reset and Clock Control).

Find the bits corresponding to the peripherals to be reset in the RCC...RSTR registers, set them to 1, and clear them to 0. E.g. for DCMI, it would be

```<code>RCC->AHB2RSTR |= RCC_AHB2RSTR_DCMIRST;
RCC->AHB2RSTR &= ~RCC_AHB2RSTR_DCMIRST;
</code>```

HAL provides some macros that save you the need to look up the register names, like

```<code>__HAL_RCC_DCMI_FORCE_RESET();
__HAL_RCC_DCMI_RELEASE_RESET();
</code>```

You can find the register bits and the macros for the I2C peripheral in the Reference Manual, or in the HAL headers.

Body:
The I2C and DCMI stops working on my custom board after wake up from STOP mode. I deinitialize GPIO's before going into STOP mode. After wake up from STOP for I2C I always get HAL_BUSY for both read and write while for camera on DCMI I get some random data instead of jpeg image. But if I don't deinitialize GPIO's then everything works fine without any problem but there is higher power consumption in STOP mode. Following is my code for GPIO's deinitialization

void MX_GPIO_Deinit()
{
    GPIO_InitTypeDef GPIO_InitStruct;
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();
    __HAL_RCC_GPIOC_CLK_ENABLE();
    __HAL_RCC_GPIOH_CLK_ENABLE();

    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Pin = GPIO_PIN_All;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
    HAL_GPIO_Init(GPIOH, &GPIO_InitStruct);

    /* Disable GPIOs clock */
    __HAL_RCC_GPIOA_CLK_DISABLE();
    __HAL_RCC_GPIOB_CLK_DISABLE();
    __HAL_RCC_GPIOC_CLK_DISABLE();
    __HAL_RCC_GPIOH_CLK_DISABLE();
}

Is there any to reset I2C and DCMI properly after waking from STOP mode? Calling functions MX_I2C2_Init() and MX_DCMI_Init() doesn't work. What is the proper way for handling this and make I2C and DCMI work?

Body:
Peripherals can be reset using the RCC (Reset and Clock Control).

Find the bits corresponding to the peripherals to be reset in the RCC...RSTR registers, set them to 1, and clear them to 0. E.g. for DCMI, it would be

RCC->AHB2RSTR |= RCC_AHB2RSTR_DCMIRST;
RCC->AHB2RSTR &= ~RCC_AHB2RSTR_DCMIRST;

HAL provides some macros that save you the need to look up the register names, like

__HAL_RCC_DCMI_FORCE_RESET();
__HAL_RCC_DCMI_RELEASE_RESET();

You can find the register bits and the macros for the I2C peripheral in the Reference Manual, or in the HAL headers.


问:
Actionlink in MVC RC/Beta from codeplex preview 5
In Preview 5, here are the actionlinks that worked fine:

```<code>            listing is the controller and about is the action
</code>```

2.

var values = new RouteValueDictionary();

```<code>            text and actionname are both strings
</code>```

Html.ActionLink(text, actionName, values);

What would I convert these to get unblocked on the RC release?

答:
Nope using this in RC generates this error;

Method not found: 'System.String System.Web.Mvc.Html.LinkExtensions.RouteLink(System.Web.Mvc.HtmlHelper, System.String, System.Web.Routing.RouteValueDictionary, System.Web.Routing.RouteValueDictionary)'.

OwnerDisplayName: Joe

ContentLicense: CC BY-SA 2.5

Body:
In Preview 5, here are the actionlinks that worked fine:

            listing is the controller and about is the action

2.

var values = new RouteValueDictionary();

            text and actionname are both strings

Html.ActionLink(text, actionName, values);

What would I convert these to get unblocked on the RC release?

OwnerDisplayName: Tolik


问:
How to install Symfony framework on shared hosting account?
I have a questions while install Symfony framework on my shared hosting account.(hostmonster)

I can access SSH now, but I can not access httpd file.

so, I do not know how to set below setting using command line.

**

```<code><Directory "/$data_dir/symfony/web/sf">

 AllowOverride All

 Allow from All

</Directory>

<VirtualHost *:80>

  ServerName myapp.example.com

  DocumentRoot "/home/steve/myproject/web"

  DirectoryIndex index.php

  Alias /sf /$data_dir/symfony/web/sf

  <Directory "/home/steve/myproject/web">

   AllowOverride All

   Allow from All

  </Directory>

</VirtualHost>
</code>```

**

,

I tried this,

**

```<code>chmod 777 /home1/myaccount/php/data/symfony/web

chmod 777 /home1/myaccount/public_html/symfony/web
</code>```

**

But nothing changed.

when access mydomain.com, it show like this

```<code>#!/usr/bin/env php
<?php

/*
 * This file is part of the symfony package.
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

chdir(dirname(__FILE__));
require_once(dirname(__FILE__).'/config/ProjectConfiguration.class.php');
include(sfCoreAutoload::getInstance()->getBaseDir().'/command/cli.php');
</code>```

Please advice me how should I do .?

Thanks!

答:
If you are seeing

```<code> #!/usr/bin/env php
<?php

/*
 * This file is part of the symfony package.
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

chdir(dirname(__FILE__));
require_once(dirname(__FILE__).'/config/ProjectConfiguration.class.php');
include(sfCoreAutoload::getInstance()->getBaseDir().'/command/cli.php');
</code>```

when you head to yourdomain.com, you simply do not have PHP enabled. You may not even have it installed. A quick check is to create a file called info.php and put the following as it's contents

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

Upload info.php and navigate to yourdomain.com/info.php. If you are seeing the code you just entered you do not have php installed or enabled on your server. If you see a massive list of configuration items than I'm wrong.

Body:
I have a questions while install Symfony framework on my shared hosting account.(hostmonster)

I can access SSH now, but I can not access httpd file.

so, I do not know how to set below setting using command line.

**

<Directory "/$data_dir/symfony/web/sf">

 AllowOverride All

 Allow from All

</Directory>

<VirtualHost *:80>

  ServerName myapp.example.com

  DocumentRoot "/home/steve/myproject/web"

  DirectoryIndex index.php

  Alias /sf /$data_dir/symfony/web/sf

  <Directory "/home/steve/myproject/web">

   AllowOverride All

   Allow from All

  </Directory>

</VirtualHost>

**

,

I tried this,

**

chmod 777 /home1/myaccount/php/data/symfony/web

chmod 777 /home1/myaccount/public_html/symfony/web

**

But nothing changed.

when access mydomain.com, it show like this

#!/usr/bin/env php
<?php

/*
 * This file is part of the symfony package.
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

chdir(dirname(__FILE__));
require_once(dirname(__FILE__).'/config/ProjectConfiguration.class.php');
include(sfCoreAutoload::getInstance()->getBaseDir().'/command/cli.php');

Please advice me how should I do .?

Thanks!

Body:
If you are seeing

 #!/usr/bin/env php
<?php

/*
 * This file is part of the symfony package.
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

chdir(dirname(__FILE__));
require_once(dirname(__FILE__).'/config/ProjectConfiguration.class.php');
include(sfCoreAutoload::getInstance()->getBaseDir().'/command/cli.php');

when you head to yourdomain.com, you simply do not have PHP enabled. You may not even have it installed. A quick check is to create a file called info.php and put the following as it's contents

<?php phpinfo(); ?>

Upload info.php and navigate to yourdomain.com/info.php. If you are seeing the code you just entered you do not have php installed or enabled on your server. If you see a massive list of configuration items than I'm wrong.


问:
Display subchildren by signed user
Hello I am new in firebase and I need help with display subchildren of firebase which contain the same userID as signed user

 here is users and edu1 full show of user
I need display just subchildren of signed user

and here is my code
 private FirebaseAuth fAuth;

```<code>private DatabaseReference fNotesDatabase;
ArrayAdapter adapter;
ListView listView;
ArrayList<String> arraylist = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_education);
    fAuth = FirebaseAuth.getInstance();
    listView = findViewById(R.id.listview);
    fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");

    fNotesDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for(DataSnapshot datas: dataSnapshot.getChildren()){
                String values = datas.getKey();
                arraylist.add(values);
                adapter = new ArrayAdapter(Education.this, android.R.layout.simple_list_item_single_choice, arraylist);
                listView.setAdapter(adapter);

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

答:
Can you try this code and see if it is working with you :</p>

```<code>FirebaseAuth mAuth = FirebaseAuth.getInstance();
 // get the current user-id to read data easly
String  currentUserId = mAuth.getCurrentUser().getUid();
DatabaseReference userRef = FirebaseDatabase.getInstance()
   .getReference().child("notes").child("education");
 // get data to them
userRef.child(currentUserId).addValueEventListener(
            new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
      if(dataSnapshot.exists()){
         for(DataSnapshot datas: dataSnapshot.getChildren()){
            String values = datas.getKey();
            arraylist.add(values);
            adapter = new ArrayAdapter(Education.this,
             android.R.layout.simple_list_item_single_choice,
             arraylist);
            listView.setAdapter(adapter);

         }
      }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

        }
});
</code>```

Title: Display subchildren by signed user

Body:
Hello I am new in firebase and I need help with display subchildren of firebase which contain the same userID as signed user

 here is users and edu1 full show of user
I need display just subchildren of signed user

and here is my code
 private FirebaseAuth fAuth;

private DatabaseReference fNotesDatabase;
ArrayAdapter adapter;
ListView listView;
ArrayList<String> arraylist = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_education);
    fAuth = FirebaseAuth.getInstance();
    listView = findViewById(R.id.listview);
    fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");

    fNotesDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for(DataSnapshot datas: dataSnapshot.getChildren()){
                String values = datas.getKey();
                arraylist.add(values);
                adapter = new ArrayAdapter(Education.this, android.R.layout.simple_list_item_single_choice, arraylist);
                listView.setAdapter(adapter);

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Body:
Can you try this code and see if it is working with you :

FirebaseAuth mAuth = FirebaseAuth.getInstance();
 // get the current user-id to read data easly
String  currentUserId = mAuth.getCurrentUser().getUid();
DatabaseReference userRef = FirebaseDatabase.getInstance()
   .getReference().child("notes").child("education");
 // get data to them
userRef.child(currentUserId).addValueEventListener(
            new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
      if(dataSnapshot.exists()){
         for(DataSnapshot datas: dataSnapshot.getChildren()){
            String values = datas.getKey();
            arraylist.add(values);
            adapter = new ArrayAdapter(Education.this,
             android.R.layout.simple_list_item_single_choice,
             arraylist);
            listView.setAdapter(adapter);

         }
      }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

        }
});


问:
Django UpdateView - get initial data from many-to-many field and add them when saving form
I'm using Django class based generic view. In my models.py I have a model called MyModel with many-to-many field called m2m. I have multiple groups of users they can edit the m2m field. Each group of users can only see and add their portion to the field - using get_form to set what they can see in the m2m field. The problem I'm having is that when one user enter his record it will delete the initial records in the m2m field. I need to somehow get the initial values from the m2m field save them and then add them to the new ones when the form is submitted. Here is my views.py:</p>

```<code>class MyModelUpdate(UpdateView):
    model = MyModel
    fields = ['m2m']

    def get_initial(self):
        return initials

    def get_form(self, form_class=None):
        form = super(MyModelUpdate, self).get_form(form_class)
        form.fields["m2m"].queryset = DiffModel.objects.filter(user = self.request.user)
        return form

    def form_valid(self, form):
        form.instance.m2m.add( ??? add the initial values)
        return super(MyModelUpdate, self).form_valid(form)

    def get_success_url(self):
        ...
</code>```

答:
I'm adding this answer to offer a simplified explanation of this kind of problem, and also because the OP switches from an UpdateView to a function based view in his solution, which might not be what some users are looking for.

If you are using UpdateView for a model that has a ManyToMany field, but you are not displaying it to the user because you just want this data to be left alone, after saving the form all the m2m values will be erased.

That's obviously because Django expects this field to be included in the form, and not including it is the same as just sending it empty, therefore, to tell Django to delete all ManyToMany relationships.

In that simple case, you don't need to define the form_valid and then retrieve the original values and so on, you just need to tell Django not to expect this field.

So, if that's you view:

```<code>class ProjectFormView(generic.UpdateView):
    model = Project
    form_class = ProjectForm
    template_name = 'project.html'
</code>```

In your form, exclude the m2m field:

```<code>class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = '__all__'
        exclude = ['many_to_many_field']
</code>```

Body:
I'm using Django class based generic view. In my models.py I have a model called MyModel with many-to-many field called m2m. I have multiple groups of users they can edit the m2m field. Each group of users can only see and add their portion to the field - using get_form to set what they can see in the m2m field. The problem I'm having is that when one user enter his record it will delete the initial records in the m2m field. I need to somehow get the initial values from the m2m field save them and then add them to the new ones when the form is submitted. Here is my views.py:

class MyModelUpdate(UpdateView):
    model = MyModel
    fields = ['m2m']

    def get_initial(self):
        return initials

    def get_form(self, form_class=None):
        form = super(MyModelUpdate, self).get_form(form_class)
        form.fields["m2m"].queryset = DiffModel.objects.filter(user = self.request.user)
        return form

    def form_valid(self, form):
        form.instance.m2m.add( ??? add the initial values)
        return super(MyModelUpdate, self).form_valid(form)

    def get_success_url(self):
        ...

Body:
I'm adding this answer to offer a simplified explanation of this kind of problem, and also because the OP switches from an UpdateView to a function based view in his solution, which might not be what some users are looking for.

If you are using UpdateView for a model that has a ManyToMany field, but you are not displaying it to the user because you just want this data to be left alone, after saving the form all the m2m values will be erased.

That's obviously because Django expects this field to be included in the form, and not including it is the same as just sending it empty, therefore, to tell Django to delete all ManyToMany relationships.

In that simple case, you don't need to define the form_valid and then retrieve the original values and so on, you just need to tell Django not to expect this field.

So, if that's you view:

class ProjectFormView(generic.UpdateView):
    model = Project
    form_class = ProjectForm
    template_name = 'project.html'

In your form, exclude the m2m field:

class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = '__all__'
        exclude = ['many_to_many_field']


问:
Putting values into an inner Map
I have a ConcurrentHashMap that looks like this:

```<code>private Map<String,Map<String,Set<PublicKey>>> instancePairs = new ConcurrentHashMap<>();
</code>```

And a method that is supposed to fill this hashmap up.

But i can't figure out how to put the values in the map

Currently i have:

```<code>instancePairs.putIfAbsent(inMemoryInstance.getUsername(), inMemoryInstance.getId() , publicKeySet);
</code>```

Intellij Idea is giving me this error:

答:
As mentioned by "DDovzhenko", you'd need to do something along the following lines.</p>

```<code>//Get the map containing the ID as keys, if it doesn't exist, then create one.
Map mapValuesForName = instancePairs.getOrDefault(inMemoryInstance.getUsername(), new ConcurrentHashMap<String,Set<PublicKey>>());

//Put the publicKeySet based on the Id.
mapValuesForName.putIfAbsent(inMemoryInstance.getId(), publicKeySet);

//Store the potentially changed/new value back in original map.
instancePairs.put(mapValuesForName);
</code>```

Title: Putting values into an inner Map

Body:
I have a ConcurrentHashMap that looks like this:

private Map<String,Map<String,Set<PublicKey>>> instancePairs = new ConcurrentHashMap<>();

And a method that is supposed to fill this hashmap up.

But i can't figure out how to put the values in the map

Currently i have:

instancePairs.putIfAbsent(inMemoryInstance.getUsername(), inMemoryInstance.getId() , publicKeySet);

Intellij Idea is giving me this error:

Body:
As mentioned by "DDovzhenko", you'd need to do something along the following lines.

//Get the map containing the ID as keys, if it doesn't exist, then create one.
Map mapValuesForName = instancePairs.getOrDefault(inMemoryInstance.getUsername(), new ConcurrentHashMap<String,Set<PublicKey>>());

//Put the publicKeySet based on the Id.
mapValuesForName.putIfAbsent(inMemoryInstance.getId(), publicKeySet);

//Store the potentially changed/new value back in original map.
instancePairs.put(mapValuesForName);


问:
Ansible: compare two arrays by specific field
I have two arrays with applications descriptions:

```<code>source_array:
  - status: Active
    AppName": "Application 1"
    version: "0.1.1"
    metadata: ""
  - status": "Active"
    AppName: "Application 2"
    version: "0.2.2"
    metadata: "ID123"
  - status: "Active"
    AppName: "Application 3"
    version: "0.3.3"
    metadata: ""
</code>```

And:

```<code>target_array:
  - status: "Active"
    AppName: "Application 1"
    version: "0.1.1"
    metadata: ""
  - status: "Active"
    AppName: "Application 2"
    version: "0.2.2"
    metadata: "ID321"
  - status: "Active",
    AppName: "Application 3"
    version: "0.3.0"
    metadata: ""
</code>```

I need to compare these two arrays based on the version field.
So, for example, the desired result should be:

```<code>[{
    "status": "Active",
    "AppName": "Application 3",
    "version": "0.3.0",
    "metadata": ""
}]
</code>```

I've tried to use difference filter but it returns also the secondf element - as it has different metadata

```<code>- name: Comparing arrays
  set_fact:
    delta: "{{ source_array | difference(target_array) }}"
</code>```

And i've got incorrect result:

```<code>[{
    "status": "Active",
    "AppName": "Application 2",
    "version": "0.2.2",
    "metadata": "ID123"
},
{
    "status": "Active",
    "AppName": "Application 3",
    "version": "0.3.3",
    "metadata": ""
},
{
    "status": "Active",
    "AppName": "Application 2",
    "version": "0.2.2",
    "metadata": "ID321"
},
{
    "status": "Active",
    "AppName": "Application 3",
    "version": "0.3.0",
    "metadata": ""
}]
</code>```

Any help will be highly appreciated!

答:
This not trivial indeed. You don't provide much context but I suspect what you want to do is something like check if an application has been or should be updated. Right ?

Here is one way:

```<code>- hosts: localhost
  vars:
    array1:
      - status: "Active"
        AppName: "Application 1"
        version: "0.1.1"
        metadata: ""
      - status: "Active"
        AppName: "Application 2"
        version: "0.2.2"
        metadata: "ID321"
      - status: "Active"
        AppName: "Application 3"
        version: "0.3.3"
        metadata: ""
    array2:
      - status: "Active"
        AppName: "Application 1"
        version: "0.1.1"
        metadata: ""
      - status: "Active"
        AppName: "Application 2"
        version: "0.2.2"
        metadata: "ID321"
      - status: "Active"
        AppName: "Application 3"
        version: "0.3.0"
        metadata: ""

  tasks:
    - name: "Show matching pattern"
      debug:
        msg: "{{'^' + (array1|map(attribute='version'))|difference(array2|map(attribute='version'))|join('|') + '$'}}"

    - name: "Compare arrays"
      debug:
        msg: "{{ array1 | selectattr('version', 'match', '^' + (array1|map(attribute='version'))|difference(array2|map(attribute='version'))|join('|') + '$') | list }}"
</code>```

It works by first finding the "newer versions", then screening the original list based on those. But it is a bit brittle cause:

it assumes you now, a priori which array contains  the "newer" data (here all newer version are in array1).

if you have two or more elements in your array with identical versions it would retain both, not knowing which to chose.

Maybe you should consider a different data structure, like a mapping (dict). See the current_state variable below:

```<code>- hosts: localhost
  vars:
    current_state:
      "Application 1":
        status: "Active"
        version: "0.1.1"
        metadata: ""
      "Application 2":
        status: "Active"
        version: "0.2.2"
        metadata: "ID321"
      "Application 3":
        status: "Active"
        version: "0.3.0"
        metadata: ""
    new_applications:
      - status: "Active"
        AppName: "Application 1"
        version: "0.1.1"
        metadata: ""
      - status: "Active"
        AppName: "Application 2"
        version: "0.2.2"
        metadata: "ID321"
      - status: "Active"
        AppName: "Application 3"
        version: "0.3.3"
        metadata: ""
      - status: "Active"
        AppName: "Application 4"
        version: "0.1.0"
        metadata: ""
  tasks:
    - name: "Different appraoch"
      debug:
         msg: "{{ item.0 }} -- {{ item.1 }} -- Should update: {{ item.1.version is version((current_state[item.0]|default({'version': '0.0.0'}))['version'], '>') }}"
      loop: "{{ new_applications|map(attribute='AppName')|zip(new_applications)|list }}"

    - name: "Build 'current_state' from a list (if not available as is)"
      # There might be a smarter way using items2dict...
      set_fact:
        dict_from_list: "{{ dict_from_list|default({})|combine({item[0]: item[1]})}}"
      loop: "{{ new_applications|map(attribute='AppName')|zip(new_applications)|list }}"

    - debug:
        var: dict_from_list
</code>```

This version fixes the last of the two issues mentioned above. It is also more robust in case the order of the two arrays are not the same, or the array do not have the same length.

The first issue I chose to ignore because, though your question lead to believe array1 and array2 to be interchangeable, I am assuming they are in fact not, within a given context.

Body:
I have two arrays with applications descriptions:

source_array:
  - status: Active
    AppName": "Application 1"
    version: "0.1.1"
    metadata: ""
  - status": "Active"
    AppName: "Application 2"
    version: "0.2.2"
    metadata: "ID123"
  - status: "Active"
    AppName: "Application 3"
    version: "0.3.3"
    metadata: ""

And:

target_array:
  - status: "Active"
    AppName: "Application 1"
    version: "0.1.1"
    metadata: ""
  - status: "Active"
    AppName: "Application 2"
    version: "0.2.2"
    metadata: "ID321"
  - status: "Active",
    AppName: "Application 3"
    version: "0.3.0"
    metadata: ""

I need to compare these two arrays based on the version field.
So, for example, the desired result should be:

[{
    "status": "Active",
    "AppName": "Application 3",
    "version": "0.3.0",
    "metadata": ""
}]

I've tried to use difference filter but it returns also the secondf element - as it has different metadata

- name: Comparing arrays
  set_fact:
    delta: "{{ source_array | difference(target_array) }}"

And i've got incorrect result:

[{
    "status": "Active",
    "AppName": "Application 2",
    "version": "0.2.2",
    "metadata": "ID123"
},
{
    "status": "Active",
    "AppName": "Application 3",
    "version": "0.3.3",
    "metadata": ""
},
{
    "status": "Active",
    "AppName": "Application 2",
    "version": "0.2.2",
    "metadata": "ID321"
},
{
    "status": "Active",
    "AppName": "Application 3",
    "version": "0.3.0",
    "metadata": ""
}]

Any help will be highly appreciated!

Body:
This not trivial indeed. You don't provide much context but I suspect what you want to do is something like check if an application has been or should be updated. Right ?

Here is one way:

- hosts: localhost
  vars:
    array1:
      - status: "Active"
        AppName: "Application 1"
        version: "0.1.1"
        metadata: ""
      - status: "Active"
        AppName: "Application 2"
        version: "0.2.2"
        metadata: "ID321"
      - status: "Active"
        AppName: "Application 3"
        version: "0.3.3"
        metadata: ""
    array2:
      - status: "Active"
        AppName: "Application 1"
        version: "0.1.1"
        metadata: ""
      - status: "Active"
        AppName: "Application 2"
        version: "0.2.2"
        metadata: "ID321"
      - status: "Active"
        AppName: "Application 3"
        version: "0.3.0"
        metadata: ""

  tasks:
    - name: "Show matching pattern"
      debug:
        msg: "{{'^' + (array1|map(attribute='version'))|difference(array2|map(attribute='version'))|join('|') + '$'}}"

    - name: "Compare arrays"
      debug:
        msg: "{{ array1 | selectattr('version', 'match', '^' + (array1|map(attribute='version'))|difference(array2|map(attribute='version'))|join('|') + '$') | list }}"

It works by first finding the "newer versions", then screening the original list based on those. But it is a bit brittle cause:

it assumes you now, a priori which array contains  the "newer" data (here all newer version are in array1).

if you have two or more elements in your array with identical versions it would retain both, not knowing which to chose.

Maybe you should consider a different data structure, like a mapping (dict). See the current_state variable below:

- hosts: localhost
  vars:
    current_state:
      "Application 1":
        status: "Active"
        version: "0.1.1"
        metadata: ""
      "Application 2":
        status: "Active"
        version: "0.2.2"
        metadata: "ID321"
      "Application 3":
        status: "Active"
        version: "0.3.0"
        metadata: ""
    new_applications:
      - status: "Active"
        AppName: "Application 1"
        version: "0.1.1"
        metadata: ""
      - status: "Active"
        AppName: "Application 2"
        version: "0.2.2"
        metadata: "ID321"
      - status: "Active"
        AppName: "Application 3"
        version: "0.3.3"
        metadata: ""
      - status: "Active"
        AppName: "Application 4"
        version: "0.1.0"
        metadata: ""
  tasks:
    - name: "Different appraoch"
      debug:
         msg: "{{ item.0 }} -- {{ item.1 }} -- Should update: {{ item.1.version is version((current_state[item.0]|default({'version': '0.0.0'}))['version'], '>') }}"
      loop: "{{ new_applications|map(attribute='AppName')|zip(new_applications)|list }}"

    - name: "Build 'current_state' from a list (if not available as is)"
      # There might be a smarter way using items2dict...
      set_fact:
        dict_from_list: "{{ dict_from_list|default({})|combine({item[0]: item[1]})}}"
      loop: "{{ new_applications|map(attribute='AppName')|zip(new_applications)|list }}"

    - debug:
        var: dict_from_list

This version fixes the last of the two issues mentioned above. It is also more robust in case the order of the two arrays are not the same, or the array do not have the same length.

The first issue I chose to ignore because, though your question lead to believe array1 and array2 to be interchangeable, I am assuming they are in fact not, within a given context.


问:
How to close a ChildWindow with Cancel button using MVVM Light Toolkit
I'm new to MVVM and trying to figure out how to close a ChildWindow with the traditional Cancel button using MVVM Light Toolkit.

In my ChildWindow (StoreDetail.xaml), I have :

```<code><Button x:Name="CancelButton" Content="Cancel" Command="{Binding CancelCommand}" />
</code>```

In my ViewModel (ViewModelStoreDetail.cs), I have :

```<code>public ICommand CancelCommand { get; private set; }

public ViewModelStoreDetail()
{
    CancelCommand = new RelayCommand(CancelEval);
}

private void CancelEval()
{
    //Not sure if Messenger is the way to go here...
    //Messenger.Default.Send<string>("ClosePostEventChildWindow", "ClosePostEventChildWindow");
}
</code>```

答:
Have a look at this articleon MSDN. About half way down there is an approach on how to do this. Basically it uses either uses a WorkspaceViewModel or you implements an interface that exposes and event RequestClose

You then inside the Window's DataContext (if you are setting the ViewModel to it) you can attach to the event.

This is an excerpt from the article (Figure 7). You can adjust it to suit your needs.

```<code>// In App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);

MainWindow window = new MainWindow();

// Create the ViewModel to which
// the main window binds.
string path = "Data/customers.xml";
var viewModel = new MainWindowViewModel(path);

// When the ViewModel asks to be closed,
// close the window.
viewModel.RequestClose += delegate
{
    window.Close();
};

// Allow all controls in the window to
// bind to the ViewModel by setting the
// DataContext, which propagates down
// the element tree.
window.DataContext = viewModel;

window.Show();
}
</code>```

Body:
I'm new to MVVM and trying to figure out how to close a ChildWindow with the traditional Cancel button using MVVM Light Toolkit.

In my ChildWindow (StoreDetail.xaml), I have :

<Button x:Name="CancelButton" Content="Cancel" Command="{Binding CancelCommand}" />

In my ViewModel (ViewModelStoreDetail.cs), I have :

public ICommand CancelCommand { get; private set; }

public ViewModelStoreDetail()
{
    CancelCommand = new RelayCommand(CancelEval);
}

private void CancelEval()
{
    //Not sure if Messenger is the way to go here...
    //Messenger.Default.Send<string>("ClosePostEventChildWindow", "ClosePostEventChildWindow");
}

Body:
Have a look at this articleon MSDN. About half way down there is an approach on how to do this. Basically it uses either uses a WorkspaceViewModel or you implements an interface that exposes and event RequestClose

You then inside the Window's DataContext (if you are setting the ViewModel to it) you can attach to the event.

This is an excerpt from the article (Figure 7). You can adjust it to suit your needs.

// In App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);

MainWindow window = new MainWindow();

// Create the ViewModel to which
// the main window binds.
string path = "Data/customers.xml";
var viewModel = new MainWindowViewModel(path);

// When the ViewModel asks to be closed,
// close the window.
viewModel.RequestClose += delegate
{
    window.Close();
};

// Allow all controls in the window to
// bind to the ViewModel by setting the
// DataContext, which propagates down
// the element tree.
window.DataContext = viewModel;

window.Show();
}


问:
How to connect my Google Assistant app to my own server
I'm creating an actions on google smart home app. I need to use a server that lets me make external (to Google) calls. I've already tried it with Firebase, but it's not possible unless you upgrade your account. What platform could I use to accomplish this task?

I have already searched for alternatives to Firebase, and came up with platforms such us parse, back4app or horizon, but I don't actually know if they are suitable for my purpose. Does anyone know which one could I use and how can I link it with my actions on google app?

答:
There are many different ways you could go.

Upgrade to the pay-as-you-go Blaze plan. You can look at the pricing for the tier and see if it makes sense.

As Actions on Google has fulfillment that is at its core a REST API call, you can host the fulfillment directly on your server and respond using one of the libraries or directly through JSON.

As the platform is basically a REST API call, you can use any server / cloud function service to generate calls. I don't know anything about the three suggestions you make, but as long as you can run code on them they should work.


问:
Dropping duplicate records ignoring case
I have a data frame with with several columns, one of which is company_name. I'm trying to remove duplicate records based on them having the same company_name, but I'm at a loss on how to do this while maintaining the original case of the company_name.

I've tried converting all names to lowercase and then removing duplicates, but as mentioned before I would like to maintain the original case.

```<code>df = pd.DataFrame({'company_name': ['Apple', 'apple', 'BlackBerry', 'blackberry','Blackberry'])
df['company_name'] = df['company_name'].str.strip()
df['company_name'] = df['company_name'].str.lower()
input_records.drop_duplicates(subset=['company_id'], inplace=True,
   keep="first")
</code>```

this code gets rid of duplicates, but stores the company name in all lowercase.

Desired result

```<code>company_name
Apple
BlackBerry
</code>```

Actual result

```<code>company_name
apple
blackberry
</code>```

答:
How about using duplicated

```<code>yourdf=df[~df.company_name.str.strip().str.lower().duplicated(keep='first')]
yourdf
Out[415]:
  company_name
0        Apple
2   BlackBerry
</code>```

Body:
I have a data frame with with several columns, one of which is company_name. I'm trying to remove duplicate records based on them having the same company_name, but I'm at a loss on how to do this while maintaining the original case of the company_name.

I've tried converting all names to lowercase and then removing duplicates, but as mentioned before I would like to maintain the original case.

df = pd.DataFrame({'company_name': ['Apple', 'apple', 'BlackBerry', 'blackberry','Blackberry'])
df['company_name'] = df['company_name'].str.strip()
df['company_name'] = df['company_name'].str.lower()
input_records.drop_duplicates(subset=['company_id'], inplace=True,
   keep="first")

this code gets rid of duplicates, but stores the company name in all lowercase.

Desired result

company_name
Apple
BlackBerry

Actual result

company_name
apple
blackberry

Body:
How about using duplicated

yourdf=df[~df.company_name.str.strip().str.lower().duplicated(keep='first')]
yourdf
Out[415]:
  company_name
0        Apple
2   BlackBerry


问:
C#, why I can't add domain user into local group?
Why this code doesn work ? What I want to do is add domain user into local group.

```<code>DirectorySearcher srch = new DirectorySearcher(new DirectoryEntry("LDAP://" + "AD1.test.it/DC=test,DC=it"));
srch.Filter = "(&(objectClass=user)(sAMAccountName=testUser))";
SearchResultCollection results = srch.FindAll();
DirectoryEntry de = new DirectoryEntry(results[0].Path);

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry dComUsersGrp = localMachine.Children.Find("Distributed COM Users", "group");
dComUsersGrp.Invoke("Add", new object[] { de.Path.ToString() });
</code>```

I get this error: "Exception has been thrown by the target of an invocation."

Simillar code works for adding local user into a local group.

```<code>DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry de = localMachine.Children.Find("testUser", "user");

DirectoryEntry dComUsersGrp = localMachine.Children.Find("Distributed COM Users", "group");
dComUsersGrp.Invoke("Add", new object[] { de.Path.ToString() });
</code>```

Thank you very much for any help.

答:
```<code>string userPath = string.Format("WinNT://{0}/{1},user", domain, user);
string groupPath = string.Format("WinNT://{0}/{1},group", Environment.MachineName, group);
using (DirectoryEntry group = new DirectoryEntry(groupPath))
{
    group.Invoke("Add", userPath);
    group.CommitChanges();
}
</code>```

You need to use WinNT:// ADSI namespace.

Body:
Why this code doesn work ? What I want to do is add domain user into local group.

DirectorySearcher srch = new DirectorySearcher(new DirectoryEntry("LDAP://" + "AD1.test.it/DC=test,DC=it"));
srch.Filter = "(&(objectClass=user)(sAMAccountName=testUser))";
SearchResultCollection results = srch.FindAll();
DirectoryEntry de = new DirectoryEntry(results[0].Path);

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry dComUsersGrp = localMachine.Children.Find("Distributed COM Users", "group");
dComUsersGrp.Invoke("Add", new object[] { de.Path.ToString() });

I get this error: "Exception has been thrown by the target of an invocation."

Simillar code works for adding local user into a local group.

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry de = localMachine.Children.Find("testUser", "user");

DirectoryEntry dComUsersGrp = localMachine.Children.Find("Distributed COM Users", "group");
dComUsersGrp.Invoke("Add", new object[] { de.Path.ToString() });

Thank you very much for any help.

Body:
string userPath = string.Format("WinNT://{0}/{1},user", domain, user);
string groupPath = string.Format("WinNT://{0}/{1},group", Environment.MachineName, group);
using (DirectoryEntry group = new DirectoryEntry(groupPath))
{
    group.Invoke("Add", userPath);
    group.CommitChanges();
}

You need to use WinNT:// ADSI namespace.


问:
Alert Dialog on selection of particular drop down item
I have made a Spinner of city selection. I have some particular cities shown there (specified in my project) and the last item in the dropDownList is "others". I want that when the users select "others", either a dialog comes with a TextInputLayout asking for the user to type in the city, or in any other way. I just want that after selecting others, I ask the user to enter the city and that city is shown on the spinner field. I am new to Android Studio and can't seem to solve the condition.

Here is what I have done so far.
spinner layout in my activity_main.xml

<Spinner
    android:id="@+id/citySpinner"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:spinnerMode="dialog" />
```

<p>Layout for styling the selected text shown in the spinner field </p>

<pre class="lang-java prettyprint-override"><code><TextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fontFamily="@font/ubuntu_bold"
    android:textColor="@color/Blue"
    android:textSize="16sp">
</TextView>
</code>```

Layout for the drop down items

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="@color/Blue"
    android:paddingBottom="12dp"
    android:paddingTop="12dp"
    android:paddingStart="12dp"
    android:fontFamily="@font/ubuntu_medium">
</TextView>
```

<p>and My main activity</p>

<pre class="lang-java prettyprint-override"><code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Spinner citySpinner = findViewById(R.id.citySpinner);
        List<String> cityList = new ArrayList<String>();
        cityList.add("Select a City");
        cityList.add("Banglore");
        cityList.add("Pune");
        cityList.add("Mumbai");
        cityList.add("Noida/Ghaziabad");
        cityList.add("Other");

        ArrayAdapter<String> cityDataAdapter = new ArrayAdapter<String>(this,
        R.layout.city_spinner_selected_item, cityList);
        cityDataAdapter.setDropDownViewResource(R.layout.support_simple_
        spinner_dropdown_item);
        cityDataAdapter.setDropDownViewResource(R.layout.register_dropd
        own_item);
        citySpinner.setAdapter(cityDataAdapter);

}
</code>```

Now, how do I set an alert dialog on others?

答:
First create an OnItemSelectedListener and with position == 5 you know, when others is clicked.

```<code>citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    if(position == 5){
        //show your dialog
    }
}

});
</code>```

Then you create a dialog with an EditText.

```<code>AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter City");

EditText editText = new EditText(this);
alert.setView(editText);

alert.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
       //Here you set the text of your EditText to your TextView
       yourtextview.setText(editText.getText().toString());
    }
});

alert.show();
</code>```

Then you just put it in your OnItemSelectedListener.

```<code> citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    if(position == 5){

AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
    alert.setTitle("Enter City");

    EditText editText = new EditText(this);
    alert.setView(editText);

    alert.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
           //Here you set the text of your EditText to your TextView
           yourtextview.setText(editText.getText().toString());
        }
    });

    alert.show();
    }
    }

    });
</code>```

Body:
I have made a Spinner of city selection. I have some particular cities shown there (specified in my project) and the last item in the dropDownList is "others". I want that when the users select "others", either a dialog comes with a TextInputLayout asking for the user to type in the city, or in any other way. I just want that after selecting others, I ask the user to enter the city and that city is shown on the spinner field. I am new to Android Studio and can't seem to solve the condition.

Here is what I have done so far.
spinner layout in my activity_main.xml

<Spinner
    android:id="@+id/citySpinner"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:spinnerMode="dialog" />

Layout for styling the selected text shown in the spinner field

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fontFamily="@font/ubuntu_bold"
    android:textColor="@color/Blue"
    android:textSize="16sp">
</TextView>

Layout for the drop down items

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="@color/Blue"
    android:paddingBottom="12dp"
    android:paddingTop="12dp"
    android:paddingStart="12dp"
    android:fontFamily="@font/ubuntu_medium">
</TextView>

and My main activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Spinner citySpinner = findViewById(R.id.citySpinner);
        List<String> cityList = new ArrayList<String>();
        cityList.add("Select a City");
        cityList.add("Banglore");
        cityList.add("Pune");
        cityList.add("Mumbai");
        cityList.add("Noida/Ghaziabad");
        cityList.add("Other");

        ArrayAdapter<String> cityDataAdapter = new ArrayAdapter<String>(this,
        R.layout.city_spinner_selected_item, cityList);
        cityDataAdapter.setDropDownViewResource(R.layout.support_simple_
        spinner_dropdown_item);
        cityDataAdapter.setDropDownViewResource(R.layout.register_dropd
        own_item);
        citySpinner.setAdapter(cityDataAdapter);

}

Now, how do I set an alert dialog on others?

Body:
First create an OnItemSelectedListener and with position == 5 you know, when others is clicked.

citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    if(position == 5){
        //show your dialog
    }
}

});

Then you create a dialog with an EditText.

AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter City");

EditText editText = new EditText(this);
alert.setView(editText);

alert.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
       //Here you set the text of your EditText to your TextView
       yourtextview.setText(editText.getText().toString());
    }
});

alert.show();

Then you just put it in your OnItemSelectedListener.

 citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    if(position == 5){

AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
    alert.setTitle("Enter City");

    EditText editText = new EditText(this);
    alert.setView(editText);

    alert.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
           //Here you set the text of your EditText to your TextView
           yourtextview.setText(editText.getText().toString());
        }
    });

    alert.show();
    }
    }

    });


问:
python split string by delimiter only it is outside of quotes
My string has the following format:

```<code>string = 'token1 -token2 +"token 3"'
</code>```

I want to extract the tokens and fields as follows:

```<code>result = [
    'token1',
    '-token2',
    '+token 3'
]
</code>```

I am using the csv module for that but unsuccessfully getting the last token as '+"token', '3"'

```<code># for Python 2.x
try: from StringIO import StringIO
# for Python 3.x
except ImportError: from io import StringIO
import csv

f = StringIO('token1 -token2 +"token 3"')

tokens = csv.reader(f, delimiter=' ', doublequote=False, quotechar='"', quoting=csv.QUOTE_NONE)

for t in tokens: print(t)
# > ['token1', '-token2', '+"token', '3"']
</code>```

答:
csv isn't recognizing +"token 3" as a single value because the quotes don't surround the whole thing. So ensure that they do:

```<code>line = line.replace('+"', '"+')
</code>```

and change csv.QUOTE_NONE to csv.QUOTE_MINIMAL (or just drop the quoting arg).

Body:
My string has the following format:

string = 'token1 -token2 +"token 3"'

I want to extract the tokens and fields as follows:

result = [
    'token1',
    '-token2',
    '+token 3'
]

I am using the csv module for that but unsuccessfully getting the last token as '+"token', '3"'

# for Python 2.x
try: from StringIO import StringIO
# for Python 3.x
except ImportError: from io import StringIO
import csv

f = StringIO('token1 -token2 +"token 3"')

tokens = csv.reader(f, delimiter=' ', doublequote=False, quotechar='"', quoting=csv.QUOTE_NONE)

for t in tokens: print(t)
# > ['token1', '-token2', '+"token', '3"']

Body:
csv isn't recognizing +"token 3" as a single value because the quotes don't surround the whole thing. So ensure that they do:

line = line.replace('+"', '"+')

and change csv.QUOTE_NONE to csv.QUOTE_MINIMAL (or just drop the quoting arg).


问:
Getting error with basic trim() function in U-SQL script
I want to apply .trim() function on a column but getting the error.
Sample data:
Product_ID,Product_Name
1,   Office Supplies
2,Personal Care

I have to do some data manipulation but can't get the basic trim() function right.

```<code>@productlog =
EXTRACT Product_ID string,
    Prduct_Name string
FROM "/Staging/Products.csv"
USING Extractors.Csv();
@output = Select Product_ID, Product_Name.trim() from @productlog;
OUTPUT @output
TO "/Output/Products.csv"
USING Outputters.Csv();
</code>```

Error:
Activity U-SQL1 failed: Error Id: E_CSC_USER_SYNTAXERROR, Error Message: syntax error. Expected one of: '.' ALL ANTISEMIJOIN ANY AS BEGIN BROADCASTLEFT BROADCASTRIGHT CROSS DISTINCT EXCEPT FULL FULLCROSS GROUP HASH HAVING INDEXLOOKUP INNER INTERSECT JOIN LEFT LOOP MERGE ON OPTION ORDER OUTER OUTER UNION PAIR PIVOT PRESORT PRODUCE READONLY REQUIRED RIGHT SAMPLE SEMIJOIN SERIAL TO UNIFORM UNION UNIVERSE UNPIVOT USING WHERE WITH ';' '(' ')' ',' .

答:
Got it right finally, in case someone else face the same issue. U-SQL is more like C# so it will be a bit tricky for people like me, coming from pure SQL background.

Code:

```<code>@productlog =
EXTRACT Product_ID string,
    Prduct_Name string
FROM "/Staging/Products.csv"
USING Extractors.Csv();

@output =
        SELECT
            T.Product_ID,
            T.Prduct_Name.ToUpper().Trim() AS Prduct_Name
        FROM @productlog AS T;

OUTPUT @output
TO "/Output/Products.csv"
USING Outputters.Csv();
</code>```

Body:
I want to apply .trim() function on a column but getting the error.
Sample data:
Product_ID,Product_Name
1,   Office Supplies
2,Personal Care

I have to do some data manipulation but can't get the basic trim() function right.

@productlog =
EXTRACT Product_ID string,
    Prduct_Name string
FROM "/Staging/Products.csv"
USING Extractors.Csv();
@output = Select Product_ID, Product_Name.trim() from @productlog;
OUTPUT @output
TO "/Output/Products.csv"
USING Outputters.Csv();

Error:
Activity U-SQL1 failed: Error Id: E_CSC_USER_SYNTAXERROR, Error Message: syntax error. Expected one of: '.' ALL ANTISEMIJOIN ANY AS BEGIN BROADCASTLEFT BROADCASTRIGHT CROSS DISTINCT EXCEPT FULL FULLCROSS GROUP HASH HAVING INDEXLOOKUP INNER INTERSECT JOIN LEFT LOOP MERGE ON OPTION ORDER OUTER OUTER UNION PAIR PIVOT PRESORT PRODUCE READONLY REQUIRED RIGHT SAMPLE SEMIJOIN SERIAL TO UNIFORM UNION UNIVERSE UNPIVOT USING WHERE WITH ';' '(' ')' ',' .

Body:
Got it right finally, in case someone else face the same issue. U-SQL is more like C# so it will be a bit tricky for people like me, coming from pure SQL background.

Code:

@productlog =
EXTRACT Product_ID string,
    Prduct_Name string
FROM "/Staging/Products.csv"
USING Extractors.Csv();

@output =
        SELECT
            T.Product_ID,
            T.Prduct_Name.ToUpper().Trim() AS Prduct_Name
        FROM @productlog AS T;

OUTPUT @output
TO "/Output/Products.csv"
USING Outputters.Csv();


问:
Android Stetho-Realm : FATAL EXCEPTION: StethoWorker-main-5
I am using Realm gradle plugin 5.11.0 and stetho realm 2.1.0 , but when I connect to chrome it crashed app and I am not able to inspect db. I am getting below exception</p>

```<code>E/AndroidRuntime: FATAL EXCEPTION: StethoWorker-main-5
Process: kt.esense.com.realmsample, PID: 2201
java.lang.NoClassDefFoundError: io.realm.internal.LinkView
    at libcore.reflect.InternalNames.getClass(InternalNames.java:55)
    at java.lang.Class.getDexCacheType(Class.java:2551)
    at java.lang.reflect.AbstractMethod.getParameterTypes(AbstractMethod.java:169)
    at java.lang.reflect.Method.getParameterTypes(Method.java:193)
    at java.lang.Class.getDeclaredMethods(Class.java:1812)
    at com.facebook.stetho.inspector.MethodDispatcher.buildDispatchTable(MethodDispatcher.java:115)
    at com.facebook.stetho.inspector.MethodDispatcher.findMethodDispatcher(MethodDispatcher.java:53)
    at com.facebook.stetho.inspector.MethodDispatcher.dispatch(MethodDispatcher.java:60)
    at com.facebook.stetho.inspector.ChromeDevtoolsServer.handleRemoteRequest(ChromeDevtoolsServer.java:129)
    at com.facebook.stetho.inspector.ChromeDevtoolsServer.handleRemoteMessage(ChromeDevtoolsServer.java:111)
    at com.facebook.stetho.inspector.ChromeDevtoolsServer.onMessage(ChromeDevtoolsServer.java:87)
    at com.facebook.stetho.websocket.WebSocketSession$1.handleTextFrame(WebSocketSession.java:176)
    at com.facebook.stetho.websocket.WebSocketSession$1.onCompleteFrame(WebSocketSession.java:136)
    at com.facebook.stetho.websocket.ReadHandler.readLoop(ReadHandler.java:44)
    at com.facebook.stetho.websocket.WebSocketSession.handle(WebSocketSession.java:45)
    at com.facebook.stetho.websocket.WebSocketHandler.doUpgrade(WebSocketHandler.java:117)
    at com.facebook.stetho.websocket.WebSocketHandler.handleRequest(WebSocketHandler.java:83)
    at com.facebook.stetho.server.http.LightHttpServer.dispatchToHandler(LightHttpServer.java:84)
    at com.facebook.stetho.server.http.LightHttpServer.serve(LightHttpServer.java:61)
    at com.facebook.stetho.inspector.DevtoolsSocketHandler.onAccepted(DevtoolsSocketHandler.java:52)
    at com.facebook.stetho.server.ProtocolDetectingSocketHandler.onSecured(ProtocolDetectingSocketHandler.java:63)
    at com.facebook.stetho.server.SecureSocketHandler.onAccepted(SecureSocketHandler.java:33)
    at com.facebook.stetho.server.LazySocketHandler.onAccepted(LazySocketHandler.java:36)
    at com.facebook.stetho.server.LocalSocketServer$WorkerThread.run(LocalSocketServer.java:167)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "io.realm.internal.LinkView" on path: DexPathList[[zip file "/data/app/kt.com.realmsample-1/base.apk"],nativeLibraryDirectories=[/data/app/kt.com.realmsample-1/lib/arm64, /data/app/kt.com.realmsample-1/base.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:74)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at libcore.reflect.InternalNames.getClass(InternalNames.java:53)
</code>```

答:
For Realm 3.7.1-3.7.2, Stetho-Realm won't work at all (unless you fork it and fix it for the code)

For Realm 4.0.0+ (that includes your version Realm 5.11.0), you need to use WickeDev's fork that supports Realm 4.0+.

```<code>repositories {
    maven { url 'https://github.com/WickeDev/stetho-realm/raw/master/maven-repo' }
}

dependencies {
    implementation 'com.uphyca:stetho_realm:2.3.0'
}
</code>```

Body:
I am using Realm gradle plugin 5.11.0 and stetho realm 2.1.0 , but when I connect to chrome it crashed app and I am not able to inspect db. I am getting below exception

E/AndroidRuntime: FATAL EXCEPTION: StethoWorker-main-5
Process: kt.esense.com.realmsample, PID: 2201
java.lang.NoClassDefFoundError: io.realm.internal.LinkView
    at libcore.reflect.InternalNames.getClass(InternalNames.java:55)
    at java.lang.Class.getDexCacheType(Class.java:2551)
    at java.lang.reflect.AbstractMethod.getParameterTypes(AbstractMethod.java:169)
    at java.lang.reflect.Method.getParameterTypes(Method.java:193)
    at java.lang.Class.getDeclaredMethods(Class.java:1812)
    at com.facebook.stetho.inspector.MethodDispatcher.buildDispatchTable(MethodDispatcher.java:115)
    at com.facebook.stetho.inspector.MethodDispatcher.findMethodDispatcher(MethodDispatcher.java:53)
    at com.facebook.stetho.inspector.MethodDispatcher.dispatch(MethodDispatcher.java:60)
    at com.facebook.stetho.inspector.ChromeDevtoolsServer.handleRemoteRequest(ChromeDevtoolsServer.java:129)
    at com.facebook.stetho.inspector.ChromeDevtoolsServer.handleRemoteMessage(ChromeDevtoolsServer.java:111)
    at com.facebook.stetho.inspector.ChromeDevtoolsServer.onMessage(ChromeDevtoolsServer.java:87)
    at com.facebook.stetho.websocket.WebSocketSession$1.handleTextFrame(WebSocketSession.java:176)
    at com.facebook.stetho.websocket.WebSocketSession$1.onCompleteFrame(WebSocketSession.java:136)
    at com.facebook.stetho.websocket.ReadHandler.readLoop(ReadHandler.java:44)
    at com.facebook.stetho.websocket.WebSocketSession.handle(WebSocketSession.java:45)
    at com.facebook.stetho.websocket.WebSocketHandler.doUpgrade(WebSocketHandler.java:117)
    at com.facebook.stetho.websocket.WebSocketHandler.handleRequest(WebSocketHandler.java:83)
    at com.facebook.stetho.server.http.LightHttpServer.dispatchToHandler(LightHttpServer.java:84)
    at com.facebook.stetho.server.http.LightHttpServer.serve(LightHttpServer.java:61)
    at com.facebook.stetho.inspector.DevtoolsSocketHandler.onAccepted(DevtoolsSocketHandler.java:52)
    at com.facebook.stetho.server.ProtocolDetectingSocketHandler.onSecured(ProtocolDetectingSocketHandler.java:63)
    at com.facebook.stetho.server.SecureSocketHandler.onAccepted(SecureSocketHandler.java:33)
    at com.facebook.stetho.server.LazySocketHandler.onAccepted(LazySocketHandler.java:36)
    at com.facebook.stetho.server.LocalSocketServer$WorkerThread.run(LocalSocketServer.java:167)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "io.realm.internal.LinkView" on path: DexPathList[[zip file "/data/app/kt.com.realmsample-1/base.apk"],nativeLibraryDirectories=[/data/app/kt.com.realmsample-1/lib/arm64, /data/app/kt.com.realmsample-1/base.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:74)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at libcore.reflect.InternalNames.getClass(InternalNames.java:53)

Body:
For Realm 3.7.1-3.7.2, Stetho-Realm won't work at all (unless you fork it and fix it for the code)

For Realm 4.0.0+ (that includes your version Realm 5.11.0), you need to use WickeDev's fork that supports Realm 4.0+.

repositories {
    maven { url 'https://github.com/WickeDev/stetho-realm/raw/master/maven-repo' }
}

dependencies {
    implementation 'com.uphyca:stetho_realm:2.3.0'
}


问:
Deploying multiple divs based on number input
I'm trying to display multiple divs based on what on the user's number input. For example if user picks 3 then 3 divs are displayed.

I managed to get it working but I need to set IDs for each div dynamically for the returned values, and to set number next to the word car for example Car 1 Car 2 Car 3.

```<code>        <div class="col-md-12">
            <div id="content"></div>
            <script>
                function myFunction(){
                var n = Number(document.getElementById("nbchambre").value);
                var content = document.getElementById('content');
                content.innerHTML="";
                for(var count = 1; count < n+1; count++){
                var div = document.createElement('div');
                div.innerHTML = 'Car : <input type="date" name="bday">';
                content.appendChild(div);
                    }
                }
            </script>
        </div>
</code>```

Out come should be if user puts 3
car 1:
car 2:
car 3:

答:
You just need to concatenate count in to the string, assigning it to the id attribute and the text.

function myFunction() {
  var n = Number(document.getElementById("nbchambre").value);
  var content = document.getElementById('content');
  content.innerHTML = "";

  for (var count = 1; count < n + 1; count++) {
    var div = document.createElement('div');
    div.innerHTML = 'Car ' + count + ': <input type="date" name="bday" id="car' + count + '">';
    content.appendChild(div);
  }
}

myFunction();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-12">
  <div id="content"></div>
</div>

<input type="text" id="nbchambre" value="5" /></code>```

Body:
I'm trying to display multiple divs based on what on the user's number input. For example if user picks 3 then 3 divs are displayed.

I managed to get it working but I need to set IDs for each div dynamically for the returned values, and to set number next to the word car for example Car 1 Car 2 Car 3.

Out come should be if user puts 3
car 1:
car 2:
car 3:

Body:
You just need to concatenate count in to the string, assigning it to the id attribute and the text.

function myFunction() {
  var n = Number(document.getElementById("nbchambre").value);
  var content = document.getElementById('content');
  content.innerHTML = "";

  for (var count = 1; count < n + 1; count++) {
    var div = document.createElement('div');
    div.innerHTML = 'Car ' + count + ': <input type="date" name="bday" id="car' + count + '">';
    content.appendChild(div);
  }
}

myFunction();

<div class="col-md-12">
  <div id="content"></div>
</div>

<input type="text" id="nbchambre" value="5" />