问:
python regular expression to pick up first instance of " target = x"
I have a line "blabla somehing something target = 4, hjieei, target = 8, abcd ef", I want to have a python regular expression to give me the output of 4, which is the number after the 1st "target = ".

I have tried re.search('.*target = ([0-9.]+)’, line), it always give me value of 8 (Not 4).
I have tried below code, and it doss not work either.
Would you pls help.

```<code>line = "target = 4, hjieei, target = 8, abcd ef"
while line:
    target_1 = re.search('/[^target = ([0-9.]+)]*/)', line)
    if target_1 and target_1.groups():
        print("found: ", target_1.group(1))'
    break
</code>```

答:
If you are sure that there is always target = [number] at start of your string then you might do:

```<code>import re
txt = "target = 4, hjieei, target = 8, abcd ef"
number = re.findall(r'^target = (\d+)',txt)[0]
print(number) #prints 4
</code>```

Note raw string (r before ') usage so I can use single \ without need of escaping it and \d which is equivalent to [0-9]

Body:
I have a line "blabla somehing something target = 4, hjieei, target = 8, abcd ef", I want to have a python regular expression to give me the output of 4, which is the number after the 1st "target = ".

I have tried re.search('.*target = ([0-9.]+)’, line), it always give me value of 8 (Not 4).
I have tried below code, and it doss not work either.
Would you pls help.

line = "target = 4, hjieei, target = 8, abcd ef"
while line:
    target_1 = re.search('/[^target = ([0-9.]+)]*/)', line)
    if target_1 and target_1.groups():
        print("found: ", target_1.group(1))'
    break

Body:
If you are sure that there is always target = [number] at start of your string then you might do:

import re
txt = "target = 4, hjieei, target = 8, abcd ef"
number = re.findall(r'^target = (\d+)',txt)[0]
print(number) #prints 4

Note raw string (r before ') usage so I can use single \ without need of escaping it and \d which is equivalent to [0-9]


来源: stackexchange

问:
Spring Boot 2.0 Hibernate 5 EhCache 3 with JCache
I'm trying to setup Hibernate with EhCache as the second level cache but the TTL is not working.

Here are my dependencies:

```<code><dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-jcache</artifactId>
</dependency>

<dependency>
  <groupId>org.ehcache</groupId>
  <artifactId>ehcache</artifactId>
</dependency>

<dependency>
  <groupId>javax.cache</groupId>
  <artifactId>cache-api</artifactId>
</dependency>
</code>```

Here's my YAML configuration:

```<code>spring:
  jpa:
    show-sql: true
    properties:
      hibernate:
        dialect: Dialect
        cache:
          use_second_level_cache: true
          region.factory_class: org.hibernate.cache.jcache.JCacheRegionFactory
          use_query_cache: true
  cache:
    jcache:
      config: classpath:ehcache.xml
</code>```

Here's how my Entity class is configured:

```<code>@Entity
@javax.persistence.Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class PersonEntity {
  //
}
</code>```

And the JpaRepository for the entity:

```<code>public interface PersonRepository extends JpaRepository<PersonEntity, Integer> {
  @org.springframework.data.jpa.repository.QueryHints({
      @javax.persistence.QueryHint(name = "org.hibernate.cacheable", value = "true")
  })
  List<PersonEntity> findByName(String name);
}
</code>```

I've configured the cache to expire in 2 seconds, but calling findByName still uses the cache (there are no SQL Queries printed after the first one).

Here's the ehcache.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://www.ehcache.org/v3">

  <cache-template name="simple">
    <expiry>
      <ttl>2</ttl>
    </expiry>
    <heap>100</heap>
  </cache-template>

  <cache alias="com.sample.PersonEntity" uses-template="simple"/>

</config>
</code>```

EDIT:
I've done some debugging. I've added a break point in org.ehcache.jsr107.ExpiryPolicyToEhcacheExpiry:

```<code>javax.cache.expiry.Duration duration = this.expiryPolicy.getExpiryForCreation();
</code>```

This duration is INFINITE for some reason. So maybe the configuration is not set properly? I know the xml is being read because when I invalidate it (by removing heap tag for example) I get an error.

答:
When you set your @Cacheable annotation on top of your entity it creates a region where the KEY is the ID of the entity and the Value is the entity. The above mean that you will hit the cache if you access by key which is the ID.  If you use spring data and findById it will hit the cache. If you create a method findByName the access will not be by key trerefore it will not hit the cache region defined by your Cacheable annotation. On the other hand it will hit the query cache, but the query cache is in entirely different region. And judging from your configuration you have not configured query cache at all.For this method to hit any cache at all you need to add it using this property:

```<code>spring:jpa:properties:hibernate:cache:use_query_cache: true
</code>```

Alternativly you can specify @Cacheable on top of the repository method this way define a new region.

You can configigure default cache, this should capture the StandardQueryCahache.

```<code><defaultCache
    maxElementsInMemory="10000"
    eternal="false"
    timeToIdleSeconds="3600"
    timeToLiveSeconds="3600">
  </defaultCache>
</code>```

In EhCache2 you can configure the standard query cache through this element:

```<code>  <cache
name="org.hibernate.cache.internal.StandardQueryCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="3600">
</code>```

Not sure how it is in ehcache 3 though. I believe it should be the same, because the StandartQueryCache class is part of the hibernate package and not part of the ehcache package.

I also think you need to set

hibernate.javax.cache.provider = org.ehcache.jsr107.EhcacheCachingProvider

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to setup Hibernate with EhCache as the second level cache but the TTL is not working.

Here are my dependencies:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-jcache</artifactId>
</dependency>

<dependency>
  <groupId>org.ehcache</groupId>
  <artifactId>ehcache</artifactId>
</dependency>

<dependency>
  <groupId>javax.cache</groupId>
  <artifactId>cache-api</artifactId>
</dependency>

Here's my YAML configuration:

spring:
  jpa:
    show-sql: true
    properties:
      hibernate:
        dialect: Dialect
        cache:
          use_second_level_cache: true
          region.factory_class: org.hibernate.cache.jcache.JCacheRegionFactory
          use_query_cache: true
  cache:
    jcache:
      config: classpath:ehcache.xml

Here's how my Entity class is configured:

@Entity
@javax.persistence.Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class PersonEntity {
  //
}

And the JpaRepository for the entity:

public interface PersonRepository extends JpaRepository<PersonEntity, Integer> {
  @org.springframework.data.jpa.repository.QueryHints({
      @javax.persistence.QueryHint(name = "org.hibernate.cacheable", value = "true")
  })
  List<PersonEntity> findByName(String name);
}

I've configured the cache to expire in 2 seconds, but calling findByName still uses the cache (there are no SQL Queries printed after the first one).

Here's the ehcache.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://www.ehcache.org/v3">

  <cache-template name="simple">
    <expiry>
      <ttl>2</ttl>
    </expiry>
    <heap>100</heap>
  </cache-template>

  <cache alias="com.sample.PersonEntity" uses-template="simple"/>

</config>

EDIT:
I've done some debugging. I've added a break point in org.ehcache.jsr107.ExpiryPolicyToEhcacheExpiry:

javax.cache.expiry.Duration duration = this.expiryPolicy.getExpiryForCreation();

This duration is INFINITE for some reason. So maybe the configuration is not set properly? I know the xml is being read because when I invalidate it (by removing heap tag for example) I get an error.

Body:
When you set your @Cacheable annotation on top of your entity it creates a region where the KEY is the ID of the entity and the Value is the entity. The above mean that you will hit the cache if you access by key which is the ID.  If you use spring data and findById it will hit the cache. If you create a method findByName the access will not be by key trerefore it will not hit the cache region defined by your Cacheable annotation. On the other hand it will hit the query cache, but the query cache is in entirely different region. And judging from your configuration you have not configured query cache at all.For this method to hit any cache at all you need to add it using this property:

spring:jpa:properties:hibernate:cache:use_query_cache: true

Alternativly you can specify @Cacheable on top of the repository method this way define a new region.

You can configigure default cache, this should capture the StandardQueryCahache.

<defaultCache
    maxElementsInMemory="10000"
    eternal="false"
    timeToIdleSeconds="3600"
    timeToLiveSeconds="3600">
  </defaultCache>

In EhCache2 you can configure the standard query cache through this element:

  <cache
name="org.hibernate.cache.internal.StandardQueryCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="3600">

Not sure how it is in ehcache 3 though. I believe it should be the same, because the StandartQueryCache class is part of the hibernate package and not part of the ehcache package.

I also think you need to set

hibernate.javax.cache.provider = org.ehcache.jsr107.EhcacheCachingProvider


问:
Soap Service Upload Attachment Using Angular
I am using soap services, In soap services, I pass XML and along with file attachment. In SoapUI tool its work fine. But in my case, I want to achieve through Angular6. Here my Xml code.</p>

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsdl="http://service.wsvc.mhb.crimsonlogic.com/wsdl">
 <soapenv:Header><wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><wsse:UsernameToken wsu:Id="UsernameToken-4C616D2C88CB4E2F9915586128832798"><wsse:Username>this.userName</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest"> token.getPasswordDigest()  </wsse:Password><wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"> token.getNonceBase64() </wsse:Nonce><wsu:Created> token.getCreated() </wsu:Created></wsse:UsernameToken></wsse:Security>
     </soapenv:Header>
      <soapenv:Body>
      <wsdl:SubmitMessageRequest>
      <wsdl:DocumentType> document </wsdl:DocumentType>
       <wsdl:Subject>this.fileName</wsdl:Subject>
       <wsdl:PayloadName>
        <wsdl:href>cid: this.fileName</wsdl:href>
        </wsdl:PayloadName>
       <wsdl:AttachmentFile>
        <wsdl:href>?</wsdl:href>
         </wsdl:AttachmentFile>
         </wsdl:SubmitMessageRequest>
        </wsdl:MessageSubmission>
      </soapenv:Body>
      </soapenv:Envelope>
</code>```

答:
SOAP services are using HTTP protocol so it's possible. In order to communicate with SOAP services, you can use ngx-soap angular module. Inside the body of SOAP request, you need to put the file you want to upload as binary data.

Template file

```<code><input
  style="display: none"
  type="file" (change)="onFileChanged($event)"
  #fileInput>
<button (click)="fileInput.click()">Select File</button>
<button (click)="onUpload()">Upload!</button>
</code>```

Component file

```<code>export class MyFileUploadComponent {
  selectedFile: File
  client: Client;

  constructor(private soap: NgxSoapService) {
     this.soap.createClient('assets/fileuploader.wsdl').subscribe(client => this.client = client);
  }

  onFileChanged(event) {
    this.selectedFile = event.target.files[0]
  }

  onUpload() {
    // upload code goes here
    const body = {
          file: this.selectedFile
    };
    (<any>this.client).Add(body).subscribe((res: ISoapMethodResponse) => this.message = res.result.AddResult);
  }
}
</code>```

Body:
I am using soap services, In soap services, I pass XML and along with file attachment. In SoapUI tool its work fine. But in my case, I want to achieve through Angular6. Here my Xml code.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsdl="http://service.wsvc.mhb.crimsonlogic.com/wsdl">
 <soapenv:Header><wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><wsse:UsernameToken wsu:Id="UsernameToken-4C616D2C88CB4E2F9915586128832798"><wsse:Username>this.userName</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest"> token.getPasswordDigest()  </wsse:Password><wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"> token.getNonceBase64() </wsse:Nonce><wsu:Created> token.getCreated() </wsu:Created></wsse:UsernameToken></wsse:Security>
     </soapenv:Header>
      <soapenv:Body>
      <wsdl:SubmitMessageRequest>
      <wsdl:DocumentType> document </wsdl:DocumentType>
       <wsdl:Subject>this.fileName</wsdl:Subject>
       <wsdl:PayloadName>
        <wsdl:href>cid: this.fileName</wsdl:href>
        </wsdl:PayloadName>
       <wsdl:AttachmentFile>
        <wsdl:href>?</wsdl:href>
         </wsdl:AttachmentFile>
         </wsdl:SubmitMessageRequest>
        </wsdl:MessageSubmission>
      </soapenv:Body>
      </soapenv:Envelope>

Body:
SOAP services are using HTTP protocol so it's possible. In order to communicate with SOAP services, you can use ngx-soap angular module. Inside the body of SOAP request, you need to put the file you want to upload as binary data.

Template file

<input
  style="display: none"
  type="file" (change)="onFileChanged($event)"
  #fileInput>
<button (click)="fileInput.click()">Select File</button>
<button (click)="onUpload()">Upload!</button>

Component file

export class MyFileUploadComponent {
  selectedFile: File
  client: Client;

  constructor(private soap: NgxSoapService) {
     this.soap.createClient('assets/fileuploader.wsdl').subscribe(client => this.client = client);
  }

  onFileChanged(event) {
    this.selectedFile = event.target.files[0]
  }

  onUpload() {
    // upload code goes here
    const body = {
          file: this.selectedFile
    };
    (<any>this.client).Add(body).subscribe((res: ISoapMethodResponse) => this.message = res.result.AddResult);
  }
}


问:
How to detect a link click with JavaScript/jQuery in a iFrame?
How can I detect a link click inside a iFrame?

The Frame source changes a lot of times and I need to detect all link click inside the iFrame.

I try that already: Javascript - click link in iframe

JS:

```<code>$("#Source a").click();
</code>```

HTML:

```<code><iframe src="" name="Source" id="Source" scrolling="" frameborder="0" title="Anzeigebereich"></iframe>
</code>```

答:
you need to use .contents() http://api.jquery.com/contents/</p>

```<code>$('#Source').on('load', function(){
    $(this).contents().find('body').on('click', 'a', function(e){
        e.preventDefault(e);//stop normal navigation
        //your code here
    });
});
</code>```

Body:
How can I detect a link click inside a iFrame?

The Frame source changes a lot of times and I need to detect all link click inside the iFrame.

I try that already: Javascript - click link in iframe

JS:

$("#Source a").click();

HTML:

Body:
you need to use .contents() http://api.jquery.com/contents/

$('#Source').on('load', function(){
    $(this).contents().find('body').on('click', 'a', function(e){
        e.preventDefault(e);//stop normal navigation
        //your code here
    });
});


问:
Django deserialize to model instance without saving to DB
I want to serialize an object to Json, then deserialize it as the object, without save it to DB (it's already saved). The reason is that the current state of the model may be different from the state when I serialized it.

This is how I currently serialize the object:

```<code>ser_obj = serializers.serialize("json", [self.instance])
</code>```

Now, as I understand, in order to deserialize I can do something like:

```<code>for obj in serializers.deserialize("json", ser_obj):
    obj.save()
</code>```

But that will save the object to DB, which I don't want to.
I guess I can also do something like:

```<code>MyModel(field1 = ser_obj['field1'],
        field2 = ser_obj['field2']
       )
</code>```

But it seems wrong.
So any idea how can I deserialize json object into Django model without saving to DB?

I did notice that if I use the 'save()', I can then use the obj.object to get the object.

答:
You can deserialise without saving to the database.

```<code>for obj in serializers.deserialize("json", ser_obj):
    do_something_with(obj)
</code>```

This will return DeserializedObject instances. You can find more info in the Django docs

Body:
I want to serialize an object to Json, then deserialize it as the object, without save it to DB (it's already saved). The reason is that the current state of the model may be different from the state when I serialized it.

This is how I currently serialize the object:

ser_obj = serializers.serialize("json", [self.instance])

Now, as I understand, in order to deserialize I can do something like:

for obj in serializers.deserialize("json", ser_obj):
    obj.save()

But that will save the object to DB, which I don't want to.
I guess I can also do something like:

MyModel(field1 = ser_obj['field1'],
        field2 = ser_obj['field2']
       )

But it seems wrong.
So any idea how can I deserialize json object into Django model without saving to DB?

I did notice that if I use the 'save()', I can then use the obj.object to get the object.

Body:
You can deserialise without saving to the database.

for obj in serializers.deserialize("json", ser_obj):
    do_something_with(obj)

This will return DeserializedObject instances. You can find more info in the Django docs


问:
Init the CGPDFDocumentRef with Custom contents return from my PHP Server
I want to display the PDF in iPhone using the PDF Contents return by my PHP Server. How to do this one?</p>

答:
You can use UIWebView sample code is below....

```<code>NSURL *url = [NSURL fileURLWithPath:@"your pdf path"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[obj_WebView loadRequest:request];
</code>```

please check it. I think it's helpful to you.

ContentLicense: CC BY-SA 3.0

Body:
You can use UIWebView sample code is below....

NSURL *url = [NSURL fileURLWithPath:@"your pdf path"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[obj_WebView loadRequest:request];

please check it. I think it's helpful to you.


问:
BottomSheetDialogFragment theme with skins
How to combine BottomSheetDialogFragment theme with other themes?

My app has skins which are made using  themes. BottomSheetDialogFragment should have rounded corners, and I achieve this using:

```<code> override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme) /* hack to make background transparent */
 }
</code>```

Then in styles.xml:

```<code><style name="CustomBottomSheetStyle" parent="Widget.Design.BottomSheet.Modal">
    <item name="android:background">@android:color/transparent</item>
</style>

<style name="CustomBottomSheetDialogTheme" parent="Theme.MaterialComponents.Light.BottomSheetDialog">
    <item name="bottomSheetStyle">@style/CustomBottomSheetStyle</item>
</style>
</code>```

But If I extend from the Theme.MaterialComponents.Light.BottomSheetDialog I do not get the color scheme which I have defined in the skin theme.

So the question is: How to define Dialog theme inside the skin theme?

答:
```<code>override fun onCreateDialog(@Nullable savedInstanceState: Bundle?): Dialog
val dialog = BottomSheetDialog(context!!,R.style.FullScreenBottomSheet)

<style name="FullScreenBottomSheet"
parent="Theme.MaterialComponents.Light.BottomSheetDialog">
<item name="android:windowFullscreen">false</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowBackground">@color/transparent</item>
<item name="android:statusBarColor">@color/transparent</item>
</style>
</code>```

Body:
How to combine BottomSheetDialogFragment theme with other themes?

My app has skins which are made using  themes. BottomSheetDialogFragment should have rounded corners, and I achieve this using:

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme) /* hack to make background transparent */
 }

Then in styles.xml:

But If I extend from the Theme.MaterialComponents.Light.BottomSheetDialog I do not get the color scheme which I have defined in the skin theme.

So the question is: How to define Dialog theme inside the skin theme?


问:
Warning for explicit-shape array reshaping
Let all routines be inside modules.

If I pass the array real*8 aa(5,3) to a routine

```<code>subroutine sub(bb)
real*8, intent(in) :: bb(2,5)
...
end subroutine
</code>```

with the statement call sub(aa) this will compile without a warning and the first 2 columns of aa will fill the bb array. The elements of the arrays aa and bb are aligned very differently.

If instead the routine is written

```<code>subroutine sub(bb)
real*8, intent(in) :: bb(:,:)
...
end subroutine
</code>```

then bb would have the same shape and storage order as aa.

Q: The first behavior is quite dangerous if one forgets that there are explicit-size declarations in a routine. Can I make the compiler warn when explicit-shape arrays change shape/alignment?

答: I am not aware of a compiler option to warn about this as it is a perfectly legitimate practise using the storage association - we have several questions and answers about this concept. It can be quite useful.

Body:
Let all routines be inside modules.

If I pass the array real*8 aa(5,3) to a routine

subroutine sub(bb)
real*8, intent(in) :: bb(2,5)
...
end subroutine

with the statement call sub(aa) this will compile without a warning and the first 2 columns of aa will fill the bb array. The elements of the arrays aa and bb are aligned very differently.

If instead the routine is written

subroutine sub(bb)
real*8, intent(in) :: bb(:,:)
...
end subroutine

then bb would have the same shape and storage order as aa.

Q: The first behavior is quite dangerous if one forgets that there are explicit-size declarations in a routine. Can I make the compiler warn when explicit-shape arrays change shape/alignment?


问:
Is `ng serve` command suitable for production?
I'm building a small project using Angular 7.  When you run

```<code>ng serve
</code>```

and a NodeJS server is spun up to handle requests, does each request block until processing is complete?  We are trying to evaluate how effective using this in production would be as opposed to using a more traditional application server.

答:
ng serve runs a webpack development server behind the hood.

a development server.

It's made to mimic the production build and see your final application in an esay way.

If you didn't have that command, you would need to run a command like simplehttpserver after rebuilding all of your application on every change.

This is a convenience tool provided by the CLI to ease your development, in no case it's suited for production mode. This is a server without security, without optimization, without performance, without ... Well, without anything that makes a server, a server. By default, it deosn't even make your application accessible outside of your localhost. Not so useful for a production mode ...

So, never, I repeat, never, use this command for your production server.

Body:
I'm building a small project using Angular 7.  When you run

ng serve

and a NodeJS server is spun up to handle requests, does each request block until processing is complete?  We are trying to evaluate how effective using this in production would be as opposed to using a more traditional application server.


问:
How do I respond with a message to a user when they trigger an error on my Discord bot?
I'm trying to make my Discord bot reply to a user letting them know that there was an error if one occurred when they ran a command. I'm unsure of how I'm supposed to get my message variable from the command message in my index file from the command.

I've already tried using the message variable in a function that is running in my index.js file from the command file, but when it runs it says that 'message' is not defined. I suspect that it may be where I've put my .catch(). Here is the code that I am using.

```<code>//This is the area in my index that handles errors
bot.on('error', (err, message) => {
  console.error();
  message.reply("error here, possibly a rich presence");
});

//Heres the function with the .catch()
http.request(options, function(res) {
    var body = '';

    res.on('data', function (chunk) {
        body+= chunk;
    });

    res.on('end', function() {
       var jsondata = JSON.parse(body);
       var converteddate = new Date(jsondata.toTimestamp*1000)
       console.log(converteddate)
       var hours = converteddate.getHours();
       var minutes = "0" + converteddate.getMinutes();
       var finishedtime = hours + ':' + minutes.substr(-2);
        message.reply(finishedtime + " EST.")
})
}).end()
.catch(err => bot.emit('error', err, message));
}
</code>```

The expected output of this is to run the command and if there are any errors, notify the user of them. Thanks for the help!

答:
You can access the message because in the http.request isn't close properly. Make sure you run a linter and bveautify your code to easily spot extra or unclosed sections in your code.

as for replying to the user you could simply do:

```<code>message.author.send("There was an error: "+err);
</code>```

I would try something like this:

```<code>http.request(options, (res) => {
    let body = '';
    res.on('data', (chunk) => {
        body+= chunk;
    });
    res.on('end', () => {
       const jsondata = JSON.parse(body);
       const converteddate = new Date(jsondata.toTimestamp*1000)
       console.log(converteddate)
       const hours = converteddate.getHours();
       const minutes = "0" + converteddate.getMinutes();
       const finishedtime = hours + ':' + minutes.substr(-2);
        message.reply(finishedtime + " EST.")
    })
}).catch(err => message.author.send("There was an error: "+err.toString()));
</code>```

If you want to do a more global approach I would create a errorHandler and import it. However I do not see any particular reason to have a generic one since you do not do any specific actions with it.

Body:
I'm trying to make my Discord bot reply to a user letting them know that there was an error if one occurred when they ran a command. I'm unsure of how I'm supposed to get my message variable from the command message in my index file from the command.

I've already tried using the message variable in a function that is running in my index.js file from the command file, but when it runs it says that 'message' is not defined. I suspect that it may be where I've put my .catch(). Here is the code that I am using.

//This is the area in my index that handles errors
bot.on('error', (err, message) => {
  console.error();
  message.reply("error here, possibly a rich presence");
});

//Heres the function with the .catch()
http.request(options, function(res) {
    var body = '';

    res.on('data', function (chunk) {
        body+= chunk;
    });

    res.on('end', function() {
       var jsondata = JSON.parse(body);
       var converteddate = new Date(jsondata.toTimestamp*1000)
       console.log(converteddate)
       var hours = converteddate.getHours();
       var minutes = "0" + converteddate.getMinutes();
       var finishedtime = hours + ':' + minutes.substr(-2);
        message.reply(finishedtime + " EST.")
})
}).end()
.catch(err => bot.emit('error', err, message));
}

The expected output of this is to run the command and if there are any errors, notify the user of them. Thanks for the help!

Body:
You can access the message because in the http.request isn't close properly. Make sure you run a linter and bveautify your code to easily spot extra or unclosed sections in your code.

as for replying to the user you could simply do:

message.author.send("There was an error: "+err);

I would try something like this:

http.request(options, (res) => {
    let body = '';
    res.on('data', (chunk) => {
        body+= chunk;
    });
    res.on('end', () => {
       const jsondata = JSON.parse(body);
       const converteddate = new Date(jsondata.toTimestamp*1000)
       console.log(converteddate)
       const hours = converteddate.getHours();
       const minutes = "0" + converteddate.getMinutes();
       const finishedtime = hours + ':' + minutes.substr(-2);
        message.reply(finishedtime + " EST.")
    })
}).catch(err => message.author.send("There was an error: "+err.toString()));

If you want to do a more global approach I would create a errorHandler and import it. However I do not see any particular reason to have a generic one since you do not do any specific actions with it.


问:
MongoError: connect ECONNREFUSED 127.0.0.1:27017
I'm using NodeJS wih MongoDB using mongodb package. When I run mongod command it works fine and gives "waiting for connection on port 27017". So, mongod seems to be working. But MongoClient does not work and gives error when I run node index.js command-

```<code>MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
</code>```

I have install mongo db 3.4 and my code is-

```<code>var MongoClient = require('mongodb').MongoClient;
var dburl       =   "mongodb://localhost:27017/test";
MongoClient.connect(dburl, function(err, db) {
  if (err) {
    throw err;
  }
  console.log('db connected');
  db.close();
});
</code>```

I have created data/db directories on root and given write permissions.
mongod.conf file takes db path as-

storage:
dbPath: /var/lib/mongo

But it seems that it is actually taking db path as data/db and not var/lib/mongo

It working earlier but suddenly stopped.

答:
This happened probably because the MongoDB service isn't started. Follow the below steps to start it:

Press the Windows + R keys on your keyboard to open the Run
window. Type services.msc and hit Enter on your keyboard or
click/tap the OK button. A new window opens up.

Search MongoDB.exe. Right click on it and select Start.

The server will start. Now execute npm start again and the code might work this time.

Body:
I'm using NodeJS wih MongoDB using mongodb package. When I run mongod command it works fine and gives "waiting for connection on port 27017". So, mongod seems to be working. But MongoClient does not work and gives error when I run node index.js command-

MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]

I have install mongo db 3.4 and my code is-

var MongoClient = require('mongodb').MongoClient;
var dburl       =   "mongodb://localhost:27017/test";
MongoClient.connect(dburl, function(err, db) {
  if (err) {
    throw err;
  }
  console.log('db connected');
  db.close();
});

I have created data/db directories on root and given write permissions.
mongod.conf file takes db path as-

storage:
dbPath: /var/lib/mongo

But it seems that it is actually taking db path as data/db and not var/lib/mongo

It working earlier but suddenly stopped.


问:
Can I treat this pointer in virtual function as this pointer of derived class
```<code>class Base{
 public:
  virtual void show(){
      cout<<" In Base \n";
   }
};

class Derived: public Base
{
    int x;
   public:
       void show() {
             this->x = 10;
             this->printX();
         }

        void printX(){
           cout<<x;
       }
};

int main(void)
{
    Base *bp = new Derived;
    bp->show();  // RUN-TIME POLYMORPHISM
    return 0;
}
</code>```

My Question:

```<code>         this->x = 10;
         this->printX();
</code>```

since this is of type (Base *) can I treat it as (Derived *) and call/change Derived class specific members?

答:
since this is of type (Base *) can I treat it as (Derived *) and call/change Derived class specific members?

It is not a Base*. You are in the scope of Derived::show. In this scope its static type can only be a Derived*. Overriding Base::show or not doesn't affect that.

Accessing any member of Derived in Derived::show is therefore perfectly legitimate. This is how an overriding class is supposed to customize a behavior, by using its class specific members..

Body:
class Base{
 public:
  virtual void show(){
      cout<<" In Base \n";
   }
};

class Derived: public Base
{
    int x;
   public:
       void show() {
             this->x = 10;
             this->printX();
         }

        void printX(){
           cout<<x;
       }
};

int main(void)
{
    Base *bp = new Derived;
    bp->show();  // RUN-TIME POLYMORPHISM
    return 0;
}

My Question:

         this->x = 10;
         this->printX();

since this is of type (Base *) can I treat it as (Derived *) and call/change Derived class specific members?


问:
Window shell - Output log if found text in files
To find text in file, you can use following code

```<code>findstr /MIC:"string to find" "path of file"
</code>```

Problem

How can I output different string if found/not found text. Something like below.

```<code>if (find "string" "path") (
echo "Found" >> log.txt
) else (
echo "Not Found" >> log.txt
)
</code>```

Specific Problem

I have batch of text files (*.html) which may contains one of the following text

```<code>...
<div class="status_item">This feature has been configured and is functioning properly. All status tests have passed.</div>
...
</code>```

OR

```<code>...
<div class="status_item">This feature failed to configured and not working properly. Please contact your administrator.</div>
...
</code>```

I need to run a shell script periodically to check the status and output the result to a log file (log.txt). Example shown below.

```<code>....
Wed 05/29/2019 foo.html 10:00:00.00 Normal
Wed 05/29/2019 bar.html 10:01:00.00 Normal
Wed 05/29/2019 bar.html 10:02:00.00 Abnormal
Wed 05/29/2019 foo.html 10:03:00.00 Normal
Wed 05/29/2019 foo.html 10:04:00.00 Normal
...
</code>```

Specific Solution

```<code>@echo off
(for %%A in (*.html) do findStr /MIC:"functioning properly" "%%A">Nul&&(
echo %date% %time% %%A Normal) || echo %date% %time% %%A Abnormal) >> log.txt
</code>```

答:
Here is the solution I found.

If you don't need to echo out filename

```<code>@echo off
(findstr /MIC:"string to find" *.txt>Nul && (
echo "Found") || echo "Not found") >> log.txt
</code>```

If you need to echo out filename

```<code>@echo off
(for %%A in (*.txt) do findstr /MIC:"string to find" "%%A">Nul&&(
echo %%A "Found") || echo %%A "Not found") >> log.txt
</code>```

Body:
To find text in file, you can use following code

findstr /MIC:"string to find" "path of file"

Problem

How can I output different string if found/not found text. Something like below.

if (find "string" "path") (
echo "Found" >> log.txt
) else (
echo "Not Found" >> log.txt
)

Specific Problem

I have batch of text files (*.html) which may contains one of the following text

...

This feature has been configured and is functioning properly. All status tests have passed.

...

OR

...

This feature failed to configured and not working properly. Please contact your administrator.

...

I need to run a shell script periodically to check the status and output the result to a log file (log.txt). Example shown below.

....
Wed 05/29/2019 foo.html 10:00:00.00 Normal
Wed 05/29/2019 bar.html 10:01:00.00 Normal
Wed 05/29/2019 bar.html 10:02:00.00 Abnormal
Wed 05/29/2019 foo.html 10:03:00.00 Normal
Wed 05/29/2019 foo.html 10:04:00.00 Normal
...

Specific Solution

@echo off
(for %%A in (*.html) do findStr /MIC:"functioning properly" "%%A">Nul&&(
echo %date% %time% %%A Normal) || echo %date% %time% %%A Abnormal) >> log.txt

Body:
Here is the solution I found.

If you don't need to echo out filename

@echo off
(findstr /MIC:"string to find" *.txt>Nul && (
echo "Found") || echo "Not found") >> log.txt

If you need to echo out filename

@echo off
(for %%A in (*.txt) do findstr /MIC:"string to find" "%%A">Nul&&(
echo %%A "Found") || echo %%A "Not found") >> log.txt


问:
How to restrict merge from specific branches
I would like only specific branches merge to specific branches.

Some example: I want to do master branch accept pull requests only from test branch, and test branch accept only from development branch.

How can I do this restriction on TFS/Git?

We have some policies about reviewers and build validation.

答:
I solved my problem via 3rd party web hook integration.

I developed nodejs expressapp and host it different server and i created integration rule which triggered when the pull request created. And i check source and target branches in my node app.

After that i added this integration to merge policies.

So cool , so easy. Thanks to everyone.


问:
Best way to generate MBeans for managing an XML File
I have an XML file defined by an XML Schema. I need to manipulate it with Java code. I also need to enable remote clients to manipulate it via JMX.

Anyone got any good suggestions?

答:
This sounds like an XML file used for configuration.

Use JAXB to generate Java bindings

Use some appropriate tool to expose the Java objects generated in 1) as JMX MBeans (Spring JMX, Model MBeans, etc)


问:
Go 1.5 to 1.6: import cycle not allowed
I'm trying to migrate from Go 1.5.3 to Go 1.6 and for some packages I encounter "import cycle not allowed" error, when I'm trying to build them for 1.6 .

e.g for building the golint tool I'm getting:

```<code>import cycle not allowed
package github.com/golang/lint/golint
    imports flag
    imports errors
    imports runtime
    imports runtime/internal/atomic
    imports runtime
</code>```

Is there eny problem in my local env or is there any way how to fix this?

```<code>go env
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/radek/Projekty/Go"
GORACE=""
GOROOT="/home/radek/Software/Go/go1.6"
GOTOOLDIR="/home/radek/Software/Go/go1.6/pkg/tool/linux_amd64"
GO15VENDOREXPERIMENT=""
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
</code>```

答: Compare the output of readlink -f $(which go) and echo $GOROOT and if they are different, you should set $GOROOT to point to the root directory of the go binary you are running or vice versa.

Title: Go 1.5 to 1.6: import cycle not allowed

Body:
I'm trying to migrate from Go 1.5.3 to Go 1.6 and for some packages I encounter "import cycle not allowed" error, when I'm trying to build them for 1.6 .

e.g for building the golint tool I'm getting:

import cycle not allowed
package github.com/golang/lint/golint
    imports flag
    imports errors
    imports runtime
    imports runtime/internal/atomic
    imports runtime

Is there eny problem in my local env or is there any way how to fix this?

go env
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/radek/Projekty/Go"
GORACE=""
GOROOT="/home/radek/Software/Go/go1.6"
GOTOOLDIR="/home/radek/Software/Go/go1.6/pkg/tool/linux_amd64"
GO15VENDOREXPERIMENT=""
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"


问:
postDelayed blocking ui thread
What I want: The user keeps the button clicked for 1900ms. If he picks his finger before 1900ms the phone stops vibrating. While if he keeps his finger on the button for more than 1900 sec, calculate() method runs.
I am using: postDelayed as I read it does not interfere with ui thread.
I was trying to check if 1900 sec has passed user has not picked his finger, even than calculate method runs.
Error Happening: If the user picks his finger before 1900 seconds or just he touches and immediately picks, the phone keeps vibrating. Although it should not happen as I am checking it with MotionEvent.ACTION_UP. Please help !!

```<code>  int flag = 0;
  int aborted_flag = 0;
 @Override
public boolean onTouch(View v, MotionEvent event) {

    Handler mHandler = new Handler();

    if(event.getAction()==MotionEvent.ACTION_DOWN){
        scanning();
        t1 = System.currentTimeMillis();
        vibrator.vibrate(1900);

        mHandler.postDelayed(new Runnable() {
            public void run() {
               check();
            }
        }, 1901);
    }

    if(event.getAction()==MotionEvent.ACTION_UP){
        if(flag == 0){
            t2 = System.currentTimeMillis();
            vibrator.cancel();
            calculate();
            aborted_flag = 1;
        }
    }

    return true;
}

private void check() {
    t2 = System.currentTimeMillis();
    Log.e("Hello","Inside Check");
    Log.e("Hello",""+aborted_flag);
    vibrator.cancel();
    if(aborted_flag==0){
        calculate();
        flag = 1;
    }
}

private void scanning() {
    textView.setText("Scanning");
}

private void calculate() {
    Log.e("t2-t1 ", t2-t1+"");

    if(t2-t1>=1900){
        Random r = new Random();
        int k = r.nextInt((5 - 0) + 1) + 0;
        textView.setText(str[k]);

        ////////////animation library code/////////////
        YoYo.with(Techniques.StandUp)
                .duration(700)
                .playOn(findViewById(R.id.text_view));
        ////////////////////////////////////////

        changeBackgroundColor(k);

        //textView.setTextColor(Color.parseColor("#00ff00"));
         flag = 0;
    }
    else{
        textView.setText("Aborted\n Try Again");
        relativeLayout.setBackgroundResource(R.color.red);
    }
}
public void changeBackgroundColor(final int k) {
    runOnUiThread(new Runnable(){
        public void run() {
            switch(k){
                case 0: relativeLayout.setBackgroundResource(R.color.blue);
                    break;
                case 1: relativeLayout.setBackgroundResource(R.color.pink);
                    break;
                case 2:;
                case 3: relativeLayout.setBackgroundResource(R.color.green);
                    break;
                default:relativeLayout.setBackgroundResource(R.color.yellow);
            }
        }
    });
}
</code>```

答:
You can create a HandlerThread and use it's looper to create a handler and then post stuff to it either post or postdelayed

```<code>public class myActivity extends Activity
{
    private HandlerThread loaderThread;
    private Handler loader;

    @override
    public void onResume()
    {
        super.onResume();

        if (loaderThread == null)
        {
            loaderThread = new HandlerThread("MyActivitySeparateThread");
            loaderThread.start();
            loader = new Handler(loaderThread.getLooper());
        }
    }

    @override
    public void onDestroy()
    {
        //Stop and release handler
        try {
            loader.removeCallbacksAndMessages(null);
            loader.dispose();
        } finally {
            loader = null;
        }

        //Stop and release Thread
        try {
            loaderThread.quit();
            loaderThread.dispose();
        } finally {
            loaderThread = null;
        }

        super.onDestroy();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        switch(event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                {
                    scanning();
                    t1 = System.currentTimeMillis();
                    vibrator.vibrate(1900);

                    loader.postDelayed(new Runnable()
                    {
                        public void run()
                        {
                            check();
                        }
                    }, 1901);
                    break;
                }
            case MotionEvent.ACTION_UP:
                {
                    if (flag == 0)
                    {
                        t2 = System.currentTimeMillis();
                        vibrator.cancel();
                        calculate();
                        aborted_flag = 1;
                    }
                    break;
                }
        }

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

Title: postDelayed blocking ui thread

Body:
What I want: The user keeps the button clicked for 1900ms. If he picks his finger before 1900ms the phone stops vibrating. While if he keeps his finger on the button for more than 1900 sec, calculate() method runs.
I am using: postDelayed as I read it does not interfere with ui thread.
I was trying to check if 1900 sec has passed user has not picked his finger, even than calculate method runs.
Error Happening: If the user picks his finger before 1900 seconds or just he touches and immediately picks, the phone keeps vibrating. Although it should not happen as I am checking it with MotionEvent.ACTION_UP. Please help !!

  int flag = 0;
  int aborted_flag = 0;
 @Override
public boolean onTouch(View v, MotionEvent event) {

    Handler mHandler = new Handler();

    if(event.getAction()==MotionEvent.ACTION_DOWN){
        scanning();
        t1 = System.currentTimeMillis();
        vibrator.vibrate(1900);

        mHandler.postDelayed(new Runnable() {
            public void run() {
               check();
            }
        }, 1901);
    }

    if(event.getAction()==MotionEvent.ACTION_UP){
        if(flag == 0){
            t2 = System.currentTimeMillis();
            vibrator.cancel();
            calculate();
            aborted_flag = 1;
        }
    }

    return true;
}

private void check() {
    t2 = System.currentTimeMillis();
    Log.e("Hello","Inside Check");
    Log.e("Hello",""+aborted_flag);
    vibrator.cancel();
    if(aborted_flag==0){
        calculate();
        flag = 1;
    }
}

private void scanning() {
    textView.setText("Scanning");
}

private void calculate() {
    Log.e("t2-t1 ", t2-t1+"");

    if(t2-t1>=1900){
        Random r = new Random();
        int k = r.nextInt((5 - 0) + 1) + 0;
        textView.setText(str[k]);

        ////////////animation library code/////////////
        YoYo.with(Techniques.StandUp)
                .duration(700)
                .playOn(findViewById(R.id.text_view));
        ////////////////////////////////////////

        changeBackgroundColor(k);

        //textView.setTextColor(Color.parseColor("#00ff00"));
         flag = 0;
    }
    else{
        textView.setText("Aborted\n Try Again");
        relativeLayout.setBackgroundResource(R.color.red);
    }
}
public void changeBackgroundColor(final int k) {
    runOnUiThread(new Runnable(){
        public void run() {
            switch(k){
                case 0: relativeLayout.setBackgroundResource(R.color.blue);
                    break;
                case 1: relativeLayout.setBackgroundResource(R.color.pink);
                    break;
                case 2:;
                case 3: relativeLayout.setBackgroundResource(R.color.green);
                    break;
                default:relativeLayout.setBackgroundResource(R.color.yellow);
            }
        }
    });
}

Body:
You can create a HandlerThread and use it's looper to create a handler and then post stuff to it either post or postdelayed

public class myActivity extends Activity
{
    private HandlerThread loaderThread;
    private Handler loader;

    @override
    public void onResume()
    {
        super.onResume();

        if (loaderThread == null)
        {
            loaderThread = new HandlerThread("MyActivitySeparateThread");
            loaderThread.start();
            loader = new Handler(loaderThread.getLooper());
        }
    }

    @override
    public void onDestroy()
    {
        //Stop and release handler
        try {
            loader.removeCallbacksAndMessages(null);
            loader.dispose();
        } finally {
            loader = null;
        }

        //Stop and release Thread
        try {
            loaderThread.quit();
            loaderThread.dispose();
        } finally {
            loaderThread = null;
        }

        super.onDestroy();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        switch(event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                {
                    scanning();
                    t1 = System.currentTimeMillis();
                    vibrator.vibrate(1900);

                    loader.postDelayed(new Runnable()
                    {
                        public void run()
                        {
                            check();
                        }
                    }, 1901);
                    break;
                }
            case MotionEvent.ACTION_UP:
                {
                    if (flag == 0)
                    {
                        t2 = System.currentTimeMillis();
                        vibrator.cancel();
                        calculate();
                        aborted_flag = 1;
                    }
                    break;
                }
        }

        return true;
    }
}


问:
Get result of array elements which are not matched into a single array
I am new to Javascript. I have the following Mongodb Result Array

```<code>Result = [
          {
            "userId": "5cecfab4219aca350421b063",
            "providers": [
              "1689736266",
              "1598763690",
              "1528069614",
              "1831364272",
              "1548463045",
              "1245301159",
              "1386616399",
              "1790775971",
              "1629462130",
              "1992169783"
            ],
            "countByType": {
              "doctors": 6,
              "labs": 0,
              "hospitals": 0,
              "imagingCenters": 0,
              "other": 4
            },
            "id": "5cecfab4219aca350421b066"
          }
         ]
</code>```

I have another Array

```<code>newArray = [1689736266, 1831364272, 123456789, 235695654 ];
</code>```

how to get the array value in newArray which are not in MongoDBResult providers Array.

Eg: anotherArray = [123456789, 235695654];

Also how can I get the providers Array result using Javascript.

答:
You can use filter() on the newArray and check if its present in providers array of Result using includes()

const Result = [ { "userId": "5cecfab4219aca350421b063", "providers": [ "1689736266", "1598763690", "1528069614", "1831364272", "1548463045", "1245301159", "1386616399", "1790775971", "1629462130", "1992169783" ], "countByType": { "doctors": 6, "labs": 0, "hospitals": 0, "imagingCenters": 0, "other": 4 }, "id": "5cecfab4219aca350421b066" } ]

const newArray = [1689736266, 1831364272, 123456789, 235695654 ];
const anotherArray = newArray.filter(x => !Result[0].providers.includes(String(x)))

console.log(anotherArray)```

Body:
I am new to Javascript. I have the following Mongodb Result Array

Result = [
          {
            "userId": "5cecfab4219aca350421b063",
            "providers": [
              "1689736266",
              "1598763690",
              "1528069614",
              "1831364272",
              "1548463045",
              "1245301159",
              "1386616399",
              "1790775971",
              "1629462130",
              "1992169783"
            ],
            "countByType": {
              "doctors": 6,
              "labs": 0,
              "hospitals": 0,
              "imagingCenters": 0,
              "other": 4
            },
            "id": "5cecfab4219aca350421b066"
          }
         ]

I have another Array

newArray = [1689736266, 1831364272, 123456789, 235695654 ];

how to get the array value in newArray which are not in MongoDBResult providers Array.

Eg: anotherArray = [123456789, 235695654];

Also how can I get the providers Array result using Javascript.


问:
Android Room Database: How to handle Arraylist in an Entity?
I just implemented Room for offline data saving. But in an Entity class, I am getting the following error:

```<code>Error:(27, 30) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
</code>```

And the class is as following:

```<code>@Entity(tableName = "firstPageData")
public class MainActivityData {

    @PrimaryKey
    private String userId;

    @ColumnInfo(name = "item1_id")
    private String itemOneId;

    @ColumnInfo(name = "item2_id")
    private String itemTwoId;

    // THIS IS CAUSING THE ERROR... BASICALLY IT ISN'T READING ARRAYS
    @ColumnInfo(name = "mylist_array")
    private ArrayList<MyListItems> myListItems;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public ArrayList<MyListItems> getMyListItems() {
        return myListItems;
    }

    public void setCheckListItems(ArrayList<MyListItems> myListItems) {
        this.myListItems = myListItems;
    }

}
</code>```

So basically I want to save the ArrayList in the database but I was not able to find anything relevant to it. Can you guide me regarding how to save an Array using Room?

NOTE: MyListItems Pojo class contains 2 Strings (as of now)

答:
Json conversions don't scale well in terms of memory allocation.I'd rather go for something similar to responses above with some nullability.

```<code>class Converters {
    @TypeConverter
    fun stringAsStringList(strings: String?): List<String> {
        val list = mutableListOf<String>()
        strings
            ?.split(",")
            ?.forEach {
                list.add(it)
            }

        return list
    }

    @TypeConverter
    fun stringListAsString(strings: List<String>?): String {
        var result = ""
        strings?.forEach { element ->
            result += "$element,"
        }
        return result.removeSuffix(",")
    }
}
</code>```

For simple data types the above can be used, otherwise for complex datatypes Room provides Embedded

Body:
I just implemented Room for offline data saving. But in an Entity class, I am getting the following error:

Error:(27, 30) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

And the class is as following:

@Entity(tableName = "firstPageData")
public class MainActivityData {

    @PrimaryKey
    private String userId;

    @ColumnInfo(name = "item1_id")
    private String itemOneId;

    @ColumnInfo(name = "item2_id")
    private String itemTwoId;

    // THIS IS CAUSING THE ERROR... BASICALLY IT ISN'T READING ARRAYS
    @ColumnInfo(name = "mylist_array")
    private ArrayList<MyListItems> myListItems;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public ArrayList<MyListItems> getMyListItems() {
        return myListItems;
    }

    public void setCheckListItems(ArrayList<MyListItems> myListItems) {
        this.myListItems = myListItems;
    }

}

So basically I want to save the ArrayList in the database but I was not able to find anything relevant to it. Can you guide me regarding how to save an Array using Room?

NOTE: MyListItems Pojo class contains 2 Strings (as of now)

Body:
Json conversions don't scale well in terms of memory allocation.I'd rather go for something similar to responses above with some nullability.

class Converters {
    @TypeConverter
    fun stringAsStringList(strings: String?): List<String> {
        val list = mutableListOf<String>()
        strings
            ?.split(",")
            ?.forEach {
                list.add(it)
            }

        return list
    }

    @TypeConverter
    fun stringListAsString(strings: List<String>?): String {
        var result = ""
        strings?.forEach { element ->
            result += "$element,"
        }
        return result.removeSuffix(",")
    }
}

For simple data types the above can be used, otherwise for complex datatypes Room provides Embedded


问:
Character Ellipsis when multiple textblocks are present in parent container in WPF
I have 2 textblocks in a parent container and I want ellipse to be shown after second textblock content when  container size is reduced.</p>

答:
You can use a grid:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Column="0" Text="This is the first TextBlock. " />
    <TextBlock Grid.Column="1" Text="This is the second TextBlock. " TextTrimming="CharacterEllipsis" />
</Grid>
</code>```

Result:

Body:
You can use a grid:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Column="0" Text="This is the first TextBlock. " />
    <TextBlock Grid.Column="1" Text="This is the second TextBlock. " TextTrimming="CharacterEllipsis" />
</Grid>

Result:


问:
How do I prevent handheld devices from opening the keyboard when using a canvas signature pad?
I have a little confirmation window in my app where the user has to enter a name and message, then put their signature. My problem is that when a user enters a name, the focus of the application doesn't do a away the moment someone uses the signature pad, causing the virtual keyboard to pup up the moment the user releases their finger from the touch screen. This focus problem only seems to occur on mobile devices and happens on both android and apple devices.

I've tried using JQuery and Javascript and even Knockout solutions like focus.blur and .focus() but nothing seems to work. It's like clicking on the HTML5 canvas on mobile devices doesn't take away focus.

```<code><div class="row">
    <div class="col-md-6">
        <form-group params="value: NameSignatory, attr: {'data-test-id':'name'}"></form-group>
        <form-group params="value: EmailSignatory, attr: {'data-test-id':'email'}"></form-group>
        <form-group params="value: SignatoryComment, attr: {'data-test-id':'comment'}"></form-group>

        <div> </div>
        <div> </div>
        <div> </div>
    </div>
    <div class="col-md-6">
        <div class="form-group has-feedback" data-bind="validationElement: SignatureJson">
            <label class="large">Put your signature here:</label>
            <em class="help-block" data-bind="validationMessage: SignatureJson"></em>
            <signature-pad-v2 params="json: SignatureJson, imageUrl: ImageFileUrl"></signature-pad-v2>

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

Script:

```<code>define([
    "knockout",
    "jquery",
    "szimek-signature-pad",
    "text!./signature-pad-v2.html"
], function (ko, $, SignaturePad, template) {

    return {
        template: template,
        viewModel: {
            createViewModel: function (params, componentInfo) {
                var canvas,
                    signaturePad,
                    clearButton,
                    $element = $(componentInfo.element),
                    imageUrl = params.imageUrl ? params.imageUrl : ko.observable(),
                    json = params.json ? params.json : ko.observable(),
                    variableBorder = params.variableBorder ? params.variableBorder : ko.observable(1)
                    ;

                var callbacks = {
                    regenerateFromJson: function (data) {
                        signaturePad.fromData(data);
                    },
                    regenerateFromDataUrl: function (data) {
                        signaturePad.fromDataURL(data);
                    }
                };

                if (params.context) {
                    params.context(callbacks);
                }

                return {
                    init: function () {
                        console.log('signature-pad-v2 started', $element);
                        canvas = $element.find("canvas").get(0);
                        signaturePad = new SignaturePad(canvas,
                            {
                                minWidth: 1,
                                maxWidth: 2,
                                penColor: "rgb(51,97,155)",
                                backgroundColor: "rgb(255,255,255)",
                                onEnd: function () {
                                    json(signaturePad.toData());
                                    imageUrl(signaturePad.toDataURL());
                                }
                            });

                        document.getElementById("signature-pad-v2").style.border = ko.unwrap(variableBorder) + "px solid #c0c0c0";

                        clearButton = $element.find(".clearButton a");

                        clearButton.bind("click", function (evt) {
                            evt.preventDefault();
                            signaturePad.clear();
                            return true;
                        });

                        if (imageUrl()) {
                            signaturePad.fromDataURL(imageUrl());
                        }
                        else {
                            if (json()) {
                                signaturePad.fromData(json());
                            }
                        }

                        if (params.context) {
                            params.context(callbacks);
                        }

                    }
                };

            }
        }
    };

});
</code>```

When the user puts their signature on a mobile device, focus doesn't get removed from the text fields and the keyboard will pop up once they release their finger. An annoying little inconvenience.

答:
I believe that to remove the focus from an element it is necessary for another element to take focus. Have you tried to make the component 'focusable'?

Try adding the attribute tabindex="0" to your signature-pad-v2, or to sub-element generated by your component.

Body:
I have a little confirmation window in my app where the user has to enter a name and message, then put their signature. My problem is that when a user enters a name, the focus of the application doesn't do a away the moment someone uses the signature pad, causing the virtual keyboard to pup up the moment the user releases their finger from the touch screen. This focus problem only seems to occur on mobile devices and happens on both android and apple devices.

I've tried using JQuery and Javascript and even Knockout solutions like focus.blur and .focus() but nothing seems to work. It's like clicking on the HTML5 canvas on mobile devices doesn't take away focus.

        <form-group params="value: NameSignatory, attr: {'data-test-id':'name'}"></form-group>
        <form-group params="value: EmailSignatory, attr: {'data-test-id':'email'}"></form-group>
        <form-group params="value: SignatoryComment, attr: {'data-test-id':'comment'}"></form-group>

            Put your signature here:

            <signature-pad-v2 params="json: SignatureJson, imageUrl: ImageFileUrl"></signature-pad-v2>

Script:

define([
    "knockout",
    "jquery",
    "szimek-signature-pad",
    "text!./signature-pad-v2.html"
], function (ko, $, SignaturePad, template) {

    return {
        template: template,
        viewModel: {
            createViewModel: function (params, componentInfo) {
                var canvas,
                    signaturePad,
                    clearButton,
                    $element = $(componentInfo.element),
                    imageUrl = params.imageUrl ? params.imageUrl : ko.observable(),
                    json = params.json ? params.json : ko.observable(),
                    variableBorder = params.variableBorder ? params.variableBorder : ko.observable(1)
                    ;

                var callbacks = {
                    regenerateFromJson: function (data) {
                        signaturePad.fromData(data);
                    },
                    regenerateFromDataUrl: function (data) {
                        signaturePad.fromDataURL(data);
                    }
                };

                if (params.context) {
                    params.context(callbacks);
                }

                return {
                    init: function () {
                        console.log('signature-pad-v2 started', $element);
                        canvas = $element.find("canvas").get(0);
                        signaturePad = new SignaturePad(canvas,
                            {
                                minWidth: 1,
                                maxWidth: 2,
                                penColor: "rgb(51,97,155)",
                                backgroundColor: "rgb(255,255,255)",
                                onEnd: function () {
                                    json(signaturePad.toData());
                                    imageUrl(signaturePad.toDataURL());
                                }
                            });

                        document.getElementById("signature-pad-v2").style.border = ko.unwrap(variableBorder) + "px solid #c0c0c0";

                        clearButton = $element.find(".clearButton a");

                        clearButton.bind("click", function (evt) {
                            evt.preventDefault();
                            signaturePad.clear();
                            return true;
                        });

                        if (imageUrl()) {
                            signaturePad.fromDataURL(imageUrl());
                        }
                        else {
                            if (json()) {
                                signaturePad.fromData(json());
                            }
                        }

                        if (params.context) {
                            params.context(callbacks);
                        }

                    }
                };

            }
        }
    };

});

When the user puts their signature on a mobile device, focus doesn't get removed from the text fields and the keyboard will pop up once they release their finger. An annoying little inconvenience.


问:
How to convert object to MySQLi in this below code?
Hi I am trying to replace all old mysql query in this CMS to mysqli for PHP 7. But I am getting this below error on every page.

PHP Warning:  mysqli_query() expects parameter 1 to be mysqli, object given in ..

In this CMS a db class file is included on every page but I can't convert the object to mysqli for the mysqli_query

Code For DB.php

```<code>class db {

    var $query;
    var $db;
    var $queryArray = array();
    var $showError = true;

    function __construct() {
        global $glob;

        $this->db = mysqli_connect($glob['dbhost'], $glob['dbusername'], $glob['dbpassword']) or die(mysqli_error());
        if (!$this->db) die($this->debug(true));

        $selectdb = mysqli_select_db($this->db,$glob['dbdatabase']);
        if (!$selectdb) die ($this->debug());

    }
</code>```

Code For the page which I am trying to open

```<code><?php
        $instance = new db();
    $query = mysqli_query($instance,"SELECT * FROM adam_docs WHERE doc_id = '24' ORDER BY doc_name ASC");

    //echo $query; exit;
    $num_row = mysqli_num_rows($query);
    if($num_row > 0){
    $results = mysqli_fetch_array($query);
  ?>
</code>```

答:
Your db class is not an instance of MySQLi. It does not inherit, instead it has a public property called $db. You should use this property in mysqli_query. However the keyword var should be replaced with public.

```<code>$query = mysqli_query($instance->db, "SELECT * FROM adam_docs WHERE doc_id = '24' ORDER BY doc_name ASC");
</code>```

Body:
Hi I am trying to replace all old mysql query in this CMS to mysqli for PHP 7. But I am getting this below error on every page.

PHP Warning:  mysqli_query() expects parameter 1 to be mysqli, object given in ..

In this CMS a db class file is included on every page but I can't convert the object to mysqli for the mysqli_query

Code For DB.php

class db {

    var $query;
    var $db;
    var $queryArray = array();
    var $showError = true;

    function __construct() {
        global $glob;

        $this->db = mysqli_connect($glob['dbhost'], $glob['dbusername'], $glob['dbpassword']) or die(mysqli_error());
        if (!$this->db) die($this->debug(true));

        $selectdb = mysqli_select_db($this->db,$glob['dbdatabase']);
        if (!$selectdb) die ($this->debug());

    }

Code For the page which I am trying to open

<?php
        $instance = new db();
    $query = mysqli_query($instance,"SELECT * FROM adam_docs WHERE doc_id = '24' ORDER BY doc_name ASC");

    //echo $query; exit;
    $num_row = mysqli_num_rows($query);
    if($num_row > 0){
    $results = mysqli_fetch_array($query);
  ?>

Body:
Your db class is not an instance of MySQLi. It does not inherit, instead it has a public property called $db. You should use this property in mysqli_query. However the keyword var should be replaced with public.

$query = mysqli_query($instance->db, "SELECT * FROM adam_docs WHERE doc_id = '24' ORDER BY doc_name ASC");


问:
UNNotificationAction Handler on Low Power Mode
I am using Local Notifications with UNNotificationAction, when the user triggers the action I need to send an API request to the server.

When the device is on Low power mode and Background App Refresh is turned off and the app is killed, I get a weird behaviour on the action handler.

After the user taps the selected action on the notification - App Delegate didFinishLaunchingWithOptions() start to process but never finish.

It seems like the process is suspended in the middle of this function.

This behaviour also stops the handler function of the Notification Action.

After monitoring with logs (debugging from Xcode it always works), I see the state of the application is background on startup.

Also, I could not see any logs that indicate crush or process suspension

I could not find any documentation of handling such a case.

答: This is quite a long shot, and I don't know if it will solve your issue, but remember that there are limitations regarding what can you do inside the didFinishLaunchingWithOptions method. IIRC, if that method takes more than 10 seconds to execute, the application gets killed (the system thinks something went reeeally ballistic). So, if you need to trigger something heavy through that method, make sure you run it asynchronously.


问:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'transaction_sell_lines.name' in 'field list'

DataTables warning: table id=product_sell_report_table - Exception Message:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'transaction_sell_lines.name' in 'field list'

Controller

```<code>$brands=DB::table('products')
    ->select('brands.name')
    ->join('brands','brands.id','=','products.brand_id')
    ->join('transaction_sell_lines','products.brand_id','=','transaction_sell_lines.product_id')
    ->get();

'transaction_sell_lines.name as brand',

jQuery {data: 'brands',name:'transaction_sell_lines.brand'},
</code>```

答:
You need to give DB::raw to fetch such data

```<code>DB::raw('transaction_sell_lines.name as brand'),
</code>```

Like above.

Now check again.

Body:
DataTables warning: table id=product_sell_report_table - Exception Message:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'transaction_sell_lines.name' in 'field list'

Controller

$brands=DB::table('products')
    ->select('brands.name')
    ->join('brands','brands.id','=','products.brand_id')
    ->join('transaction_sell_lines','products.brand_id','=','transaction_sell_lines.product_id')
    ->get();

'transaction_sell_lines.name as brand',

jQuery {data: 'brands',name:'transaction_sell_lines.brand'},

Body:
You need to give DB::raw to fetch such data

DB::raw('transaction_sell_lines.name as brand'),

Like above.

Now check again.


问:
Multiple Azure Functions in one Timer trigger class
We have to write multiple triggers. I was hoping to create separate functions, based on the trigger types. So if I need 5 timer triggers, that will run at different times, I would create one Timer trigger function class and name the functions like [TimerTrigger1], [TimerTrigger2], [TimerTrigger3] ... and so forth. After I added the code I am not sure if I can do that anymore.

Can someone suggest how I can go about adding multiple triggers? I can't have two Run functions under one class.

public static class TimerTrigger
{
    [FunctionName("InsertTimerTrigger1")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
    {
         // Do task 1
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    }

    [FunctionName("InsertTimerTrigger2")]
    public static void Run([TimerTrigger("0 */15 * * * *")]TimerInfo myTimer, ILogger log)
    {
        //Do Task 2
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    }
}
```

答:
You can create multiple functions in Single Class. You can change Run Method name.

```<code>public static class Function1
{
    [FunctionName("Function1")]
    public static void Method1([TimerTrigger("0 */2 * * * *")]TimerInfo myTimer, TraceWriter log)
    {
        log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
    }

    [FunctionName("Function2")]
    public static void Method2([TimerTrigger("0 */3 * * * *")]TimerInfo myTimer, TraceWriter log)
    {
        log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
    }
}
</code>```

But I will recommend, Create multiple functions will help you (5 in your case).

If you are using common business logic, you can put in a common class and inject in all function.

You can independently Enable/Disable/Delete function from FunctionApp Instance.

You can monitor each function independently (from Function Monitor section)

Body:
You can create multiple functions in Single Class. You can change Run Method name.

public static class Function1
{
    [FunctionName("Function1")]
    public static void Method1([TimerTrigger("0 */2 * * * *")]TimerInfo myTimer, TraceWriter log)
    {
        log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
    }

    [FunctionName("Function2")]
    public static void Method2([TimerTrigger("0 */3 * * * *")]TimerInfo myTimer, TraceWriter log)
    {
        log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
    }
}

But I will recommend, Create multiple functions will help you (5 in your case).

If you are using common business logic, you can put in a common class and inject in all function.

You can independently Enable/Disable/Delete function from FunctionApp Instance.

You can monitor each function independently (from Function Monitor section)


问:
How to properly highlight text in React Native?
I would like to highlight a multiline text in a React Native app by changing the text's background color. The problem is that the background color changes in the whole text area, not just under the words.

```<code>class Example extends Component {
  render() {
    const text = '...';

    return (
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>
          {text}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  textContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    width: 200,
  },
  textStyle: {
    backgroundColor: 'red',
  },
});
</code>```

The code above results in something that looks like this:

But I would like it to look like this:

I can get that result by splitting the text and adding the background color to the individual words:

```<code>class Example extends Component {
  render() {
    const text = '...';

    const brokenText = text.split(' ').map(word => (
      <Text style={styles.textStyle}>{word} </Text>
    ));

    return (
      <View style={styles.textContainer}>
        {brokenText}
      </View>
    );
  }
}
</code>```

But splitting the text into individual words doesn't seem like the best solution, and has a huge performance cost. Is there any cleaner way to do it?

答:
Try using

react-highlight-words library which can meet your need or use react-native-highlight-words library.

Both of these libraries are derived from the node package highlight-words-core

Body:
I would like to highlight a multiline text in a React Native app by changing the text's background color. The problem is that the background color changes in the whole text area, not just under the words.

class Example extends Component {
  render() {
    const text = '...';

    return (
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>
          {text}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  textContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    width: 200,
  },
  textStyle: {
    backgroundColor: 'red',
  },
});

The code above results in something that looks like this:

But I would like it to look like this:

I can get that result by splitting the text and adding the background color to the individual words:

class Example extends Component {
  render() {
    const text = '...';

    const brokenText = text.split(' ').map(word => (
      <Text style={styles.textStyle}>{word} </Text>
    ));

    return (
      <View style={styles.textContainer}>
        {brokenText}
      </View>
    );
  }
}

But splitting the text into individual words doesn't seem like the best solution, and has a huge performance cost. Is there any cleaner way to do it?


问:
How do I make the width of each character the same?
I'm using a custom font. The design doesn't allow me to change font.

While the number change, the content after it got pushed around due to the different width of digits.

Is there a way to make all the digits same width? I don't want to assign the width of the span component because I need this to be inline and the width should be determined by the number of digits it has.

const numberDom = document.querySelector('.number');
let number = 0;

function tick() {
  number += 1;
  numberDom.innerText = number;
}

setInterval(tick, 50);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  font-size: 1rem;
}

.number {
  font-family: 'Carter One', cursive;
  font-size: 1.5rem;
  color: #365;
}

.number::after {
  content: 'pt';
  font-size: 0.75em;
  margin-left: 0.1em;
  color: #587;
}</code>```

<link href="https://fonts.googleapis.com/css?family=Carter+One&display=swap" rel="stylesheet">

You got , good job!
```

答:
Okay so first I made a function that it changes the looks of your
. after that the only solution I could find to stop the jiggling was to put the number in an inline-block.

Here is my fiddle

Edit

I made a script that changes the width of the inline-block. It's an if statement that if your number is 1000 or higher the width will change.

Fiddle

You can always make an else if with over 10000 et cetera.

Body:
I'm using a custom font. The design doesn't allow me to change font.

While the number change, the content after it got pushed around due to the different width of digits.

Is there a way to make all the digits same width? I don't want to assign the width of the span component because I need this to be inline and the width should be determined by the number of digits it has.

const numberDom = document.querySelector('.number');
let number = 0;

function tick() {
  number += 1;
  numberDom.innerText = number;
}

setInterval(tick, 50);

p {
  font-size: 1rem;
}

.number {
  font-family: 'Carter One', cursive;
  font-size: 1.5rem;
  color: #365;
}

.number::after {
  content: 'pt';
  font-size: 0.75em;
  margin-left: 0.1em;
  color: #587;
}

<link href="https://fonts.googleapis.com/css?family=Carter+One&display=swap" rel="stylesheet">

You got , good job!

Body:
Okay so first I made a function that it changes the looks of your <p>. after that the only solution I could find to stop the jiggling was to put the number in an inline-block.

Here is my fiddle

Edit

I made a script that changes the width of the inline-block. It's an if statement that if your number is 1000 or higher the width will change.

Fiddle

You can always make an else if with over 10000 et cetera.


问:
Change color of single li on hover
I am struggling to change the font color of that particular li when hover over. My code is not working properly when mouse is pointed to li from white to black color.

.tags-list li{display:inline-block;background-color:#253b5d;    padding: 1px 10px !important;
    text-transform: lowercase;
    font-weight: normal;
    font-size: 14px;
    transition: all 1s linear;
    }
.tags-list li:hover{background-color: #aebdd5;}
.tags-list li a{transition: all 1s linear;color:white;}
.tags-list ul li a:hover{color:black;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="tags-list">
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
</ul></code>```

答:
.tags-list ul li a:hover{color:black;} // this line replace by
.tags-list li:hover a{color:black;}

Title: Change color of single li on hover

Body:
I am struggling to change the font color of that particular li when hover over. My code is not working properly when mouse is pointed to li from white to black color.

.tags-list li{display:inline-block;background-color:#253b5d;    padding: 1px 10px !important;
    text-transform: lowercase;
    font-weight: normal;
    font-size: 14px;
    transition: all 1s linear;
    }
.tags-list li:hover{background-color: #aebdd5;}
.tags-list li a{transition: all 1s linear;color:white;}
.tags-list ul li a:hover{color:black;}

Testing

Testing

Testing

Testing

Testing

Testing


问:
Cannot connect to Azure SQL DataWarehouse from RStudio using Active Directory Authentication
I am trying to connect to Azure SQL Datawarehouse using RStudio. The only Authentication that is setup on the warehouse is Active Directory Password Authentication. I tried using the below connection string.

connectionString="Data Source = abc.database.secure.windows.net;   Authentication=Active Directory Password;
  Initial Catalog=dbo; UID='UserName';
   PWD=  ;

It fails with "neither DSN nor SERVER keywork supplied" . And I dont want to set up a DSN as I am building a front end app and it must be portable.

I tried RODBC too ..but couldn't get much help with Active Dir Authentication.

答:
I finally got to the bottom of this after a few deadends. A key step is updating your ODBC driver to ODBC Driver 17. The following works using Azure Active Directory authentication, which is slightly different to a consumer key/consumer secret but may achieve the same outcome (i.e. authentication without a SQL password).

library(DBI)
server <- "yourserver.database.windows.net"
database = "database-name"
con <- DBI::dbConnect(odbc::odbc(),
                 UID = rstudioapi::askForPassword("username"),
                 Driver="ODBC Driver 17 for SQL Server",
                 Server = server, Database = database,
                 Authentication = "ActiveDirectoryInteractive")

```


问:
How to change the format of JSON in the front-end in React
I have JSON called by fetch request that looks like this:

```<code>[{
    "type": "1",
    "First": {
      "Id": "123456"
    }
  },
  {
    "type": "2",
    "Second": [{
        "Id": "13333"
      },
      {
        "Id": "255555"
      },
      {
        "Id": "37777"
      },
      {
        "Id": "48888"
      }
    ]
  }
]
</code>```

What I did is that I find object with type 1 and add it to object which type 2 and splice my array to just have an object which type 2. Now it looks like this:

```<code>[{
  "type": "2",
  "First": {
    "Id": "123456"
  },
  "Second": [{
      "Id": "13333"
    },
    {
      "Id": "255555"
    },
    {
      "Id": "37777"
    },
    {
      "Id": "48888"
    }
  ]
}]
</code>```

I have two problems. First I want to add obeject type 1 to every objects of array second, like this:

```<code>[{
  "type": "2",
  "Second": [{
      "Id": "13333",
      "First": {
        "Id": "123456"
      }
    },
    {
      "Id": "255555",
      "First": {
        "Id": "123456"
      }
    },
    {
      "Id": "37777",
      "First": {
        "Id": "123456"
      }
    },
    {
      "Id": "48888",
      "First": {
        "Id": "123456"
      }
    }
  ]
}]
</code>```

Secondly I want my JSON to just included Second array, like this:

```<code>[{
    "Id": "13333",
    "First": {
      "Id": "123456"
    }
  },
  {
    "Id": "255555",
    "First": {
      "Id": "123456"
    }
  },
  {
    "Id": "37777",
    "First": {
      "Id": "123456"
    }
  },
  {
    "Id": "48888",
    "First": {
      "Id": "123456"
    }
  }
]
</code>```

How can I solve these two issues? Here is a piece of my code:

```<code>class App extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        data: [],
        library: null,
        perPage: 20,
        currentPage: 1,
        maxPage: null,

    }
}
componentDidMount() {
    fetch('/json.bc', {
        method: 'get',
    })
        .then(response => response.text())
        .then(text => {
            const Maindata = JSON.parse(text.replace(/\'/g, '"'))
            const type1 = Maindata.find(({ type }) => type === '1');
            const MergedData = Maindata.map(item => item.type === '1' ? item : { ...type1, ...item });
            const MergedData2 = MergedData.splice(1)

            this.setState(state => ({
                ...state,
                data: MergedData2
            }), () => {
                this.reorganiseLibrary()
            })
        }).catch(error => console.error(error))

}

reorganiseLibrary = () => {
    const { perPage, data } = this.state;
    let library = data;
    library = _.chunk(library, perPage);
    this.setState({
        library,
        currentPage: 1,
        maxPage: library.length === 0 ? 1 : library.length
    })
}

previousPage = event => {
    this.setState({
        currentPage: this.state.currentPage - 1
    })
}

nextPage = event => {
    this.setState({
        currentPage: this.state.currentPage + 1
    })
}

handlePerPage = (evt) =>
    this.setState({
        perPage: evt.target.value
    }, () => this.reorganiseLibrary());

renderLibrary = () => {
    const { library, currentPage } = this.state;
    if (!library || (library && library.length === 0)) {
        return <div>NOResult</div>
    }
    return library[currentPage - 1].map((item, i) => (
        <div className="Wrapper">{item.id}</div>
    ))
}

render() {
    const { library, currentPage, perPage, maxPage } = this.state;
    return (
        <div>
            {this.renderLibrary()}
            <ul id="page-numbers">
                <li>
                    {currentPage !== 1 && (
                        <button onClick={this.previousPage}></button>
                    )}
                </li>
                <li>{this.state.currentPage}</li>
                <li>{this.state.maxPage}</li>
                <li>
                    {(currentPage < maxPage) && (
                        <button onClick={this.nextPage}></button>
                    )}
                </li>
            </ul>
        </div>
    )
}
}
ReactDOM.render(<App />, document.getElementById('Result'))
</code>```

答:
You could get the First from an item with type: 1 using find. Then filter the type: 2 items and create an new array of objects with First nested in every object in Second

const input=[{"type":"1","First":{"Id":"123456"}},{"type":"2","Second":[{"Id":"13333"},{"Id":"255555"},{"Id":"37777"},{"Id":"48888"}]}]

const { First } = input.find(a => a.type === "1") || {}

const output1 = input.filter(a => a.type === "2")
                      .map(a => {
                          const Second = a.Second.map(b => ({ ...b, First }))
                          return { ...a, Second }
                      })

console.log(JSON.stringify(output1, null, 3))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

You can easily get the second output like output1[0].Second. Depends on how many items with type: 2 will be there in the array.

Body:
I have JSON called by fetch request that looks like this:

[{
    "type": "1",
    "First": {
      "Id": "123456"
    }
  },
  {
    "type": "2",
    "Second": [{
        "Id": "13333"
      },
      {
        "Id": "255555"
      },
      {
        "Id": "37777"
      },
      {
        "Id": "48888"
      }
    ]
  }
]

What I did is that I find object with type 1 and add it to object which type 2 and splice my array to just have an object which type 2. Now it looks like this:

[{
  "type": "2",
  "First": {
    "Id": "123456"
  },
  "Second": [{
      "Id": "13333"
    },
    {
      "Id": "255555"
    },
    {
      "Id": "37777"
    },
    {
      "Id": "48888"
    }
  ]
}]

I have two problems. First I want to add obeject type 1 to every objects of array second, like this:

[{
  "type": "2",
  "Second": [{
      "Id": "13333",
      "First": {
        "Id": "123456"
      }
    },
    {
      "Id": "255555",
      "First": {
        "Id": "123456"
      }
    },
    {
      "Id": "37777",
      "First": {
        "Id": "123456"
      }
    },
    {
      "Id": "48888",
      "First": {
        "Id": "123456"
      }
    }
  ]
}]

Secondly I want my JSON to just included Second array, like this:

[{
    "Id": "13333",
    "First": {
      "Id": "123456"
    }
  },
  {
    "Id": "255555",
    "First": {
      "Id": "123456"
    }
  },
  {
    "Id": "37777",
    "First": {
      "Id": "123456"
    }
  },
  {
    "Id": "48888",
    "First": {
      "Id": "123456"
    }
  }
]

How can I solve these two issues? Here is a piece of my code:

class App extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        data: [],
        library: null,
        perPage: 20,
        currentPage: 1,
        maxPage: null,

    }
}
componentDidMount() {
    fetch('/json.bc', {
        method: 'get',
    })
        .then(response => response.text())
        .then(text => {
            const Maindata = JSON.parse(text.replace(/\'/g, '"'))
            const type1 = Maindata.find(({ type }) => type === '1');
            const MergedData = Maindata.map(item => item.type === '1' ? item : { ...type1, ...item });
            const MergedData2 = MergedData.splice(1)

            this.setState(state => ({
                ...state,
                data: MergedData2
            }), () => {
                this.reorganiseLibrary()
            })
        }).catch(error => console.error(error))

}

reorganiseLibrary = () => {
    const { perPage, data } = this.state;
    let library = data;
    library = _.chunk(library, perPage);
    this.setState({
        library,
        currentPage: 1,
        maxPage: library.length === 0 ? 1 : library.length
    })
}

previousPage = event => {
    this.setState({
        currentPage: this.state.currentPage - 1
    })
}

nextPage = event => {
    this.setState({
        currentPage: this.state.currentPage + 1
    })
}

handlePerPage = (evt) =>
    this.setState({
        perPage: evt.target.value
    }, () => this.reorganiseLibrary());

renderLibrary = () => {
    const { library, currentPage } = this.state;
    if (!library || (library && library.length === 0)) {
        return
NOResult

    }
    return library[currentPage - 1].map((item, i) => (

{item.id}

    ))
}

render() {
    const { library, currentPage, perPage, maxPage } = this.state;
    return (

            {this.renderLibrary()}

                    {currentPage !== 1 && (
                        <button onClick={this.previousPage}></button>
                    )}

{this.state.currentPage}

{this.state.maxPage}

                    {(currentPage < maxPage) && (
                        <button onClick={this.nextPage}></button>
                    )}

    )
}
}
ReactDOM.render(<App />, document.getElementById('Result'))

Body:
You could get the First from an item with type: 1 using find. Then filter the type: 2 items and create an new array of objects with First nested in every object in Second

const input=[{"type":"1","First":{"Id":"123456"}},{"type":"2","Second":[{"Id":"13333"},{"Id":"255555"},{"Id":"37777"},{"Id":"48888"}]}]

const { First } = input.find(a => a.type === "1") || {}

const output1 = input.filter(a => a.type === "2")
                      .map(a => {
                          const Second = a.Second.map(b => ({ ...b, First }))
                          return { ...a, Second }
                      })

console.log(JSON.stringify(output1, null, 3))

.as-console-wrapper { max-height: 100% !important; top: 0; }

You can easily get the second output like output1[0].Second. Depends on how many items with type: 2 will be there in the array.