问:
Convert curl command into RestTemplate
I have the following curl expression:

```<code>curl --data 'api_key=API_Key' --data-urlencode 'event=[{"user_id":"12345", "event_type":"buy_song"}]' https://someapi
</code>```

which should be converted into RestTemplate.postForEntity call. I do conversion this way:

```<code>HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("api_key", "API_Key");
params.add("event", URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8"));

// send
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
ResponseEntity<String> response = restTemplate.postForEntity("https://someapi", request, String.class);
</code>```

Server returns 400 Bad request

I confirm that Jackson's objectmapper serializes the object correctly objectMapper.writeValueAsString(Collections.singletonList(e))

I suspect that I cannot correctly handle the mix of --data and --data-urlencode from example curl in RestTemplate.

Could you please suggest what am I doing wrong?

答:
I think the only problem is MediaType, Data which you are sending is not form Data (APPLICATION_FORM_URLENCODED)

It's json data so you need to use MediaType.APPLICATION_JSON Something like this

```<code>HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

// converting form variable to Map
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("api_key", "API_Key");
map.add("event", URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8"));

// finally build Request
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity(
  apiUrl, request , String.class);
</code>```

Refer this for more detail on RestTemplate

Title: Convert curl command into RestTemplate

Body:
I have the following curl expression:

curl --data 'api_key=API_Key' --data-urlencode 'event=[{"user_id":"12345", "event_type":"buy_song"}]' https://someapi

which should be converted into RestTemplate.postForEntity call. I do conversion this way:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("api_key", "API_Key");
params.add("event", URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8"));

// send
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
ResponseEntity<String> response = restTemplate.postForEntity("https://someapi", request, String.class);

Server returns 400 Bad request

I confirm that Jackson's objectmapper serializes the object correctly objectMapper.writeValueAsString(Collections.singletonList(e))

I suspect that I cannot correctly handle the mix of --data and --data-urlencode from example curl in RestTemplate.

Could you please suggest what am I doing wrong?

Body:
I think the only problem is MediaType, Data which you are sending is not form Data (APPLICATION_FORM_URLENCODED)

It's json data so you need to use MediaType.APPLICATION_JSON Something like this

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

// converting form variable to Map
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("api_key", "API_Key");
map.add("event", URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8"));

// finally build Request
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity(
  apiUrl, request , String.class);

Refer this for more detail on RestTemplate


来源: stackexchange

问:
Linq Query to Search "Many" in one to many relationship
Hey guys I have EF classes of Book and Comments.

A book can have many comments.

How can I search for a book with any comment that contains my search text?

My method looks like this as of now...

```<code>public IEnumerable<Book> Search(string commentText)
{

     IQueryable<Book> books = _context.Books;

     books.Where() //need to filter by commentText here

     return books;

}
</code>```

答:
Try this:</p>

```<code>books.Where(a=>a.Comments.Any(b=>b.CommentText.Contains(commentText)));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hey guys I have EF classes of Book and Comments.

A book can have many comments.

How can I search for a book with any comment that contains my search text?

My method looks like this as of now...

public IEnumerable<Book> Search(string commentText)
{

     IQueryable<Book> books = _context.Books;

     books.Where() //need to filter by commentText here

     return books;

}

Body:
Try this:

books.Where(a=>a.Comments.Any(b=>b.CommentText.Contains(commentText)));


问:
How can I escape braces in string to be fed to sub process
```<code>    import subprocess
    profile_val = 'ishan'
    cmd = 'instaloader --post-metadata-txt="{likes} likes, {comments} comments, {caption}" --login=blabla_id --fast-update' + ' ' + profile_val)
    subprocess.call(cmd.split())
</code>```

It not escaping braces in {likes} and treats like as separate part command and fails.

答:
Stephane Chazelas gives the best solution but if you have to split shell-like command you can use shlex.

import subprocess
import shlex
profile_val = 'ishan'
cmd = 'instaloader --post-metadata-txt="{likes} likes, {comments} comments, {caption}" --login=blabla_id --fast-update "' + profile_val + '"'
subprocess.call(shlex.split(cmd))
```

ContentLicense: CC BY-SA 4.0

Body:
    import subprocess
    profile_val = 'ishan'
    cmd = 'instaloader --post-metadata-txt="{likes} likes, {comments} comments, {caption}" --login=blabla_id --fast-update' + ' ' + profile_val)
    subprocess.call(cmd.split())

It not escaping braces in {likes} and treats like as separate part command and fails.


问:
How to create an upload folder for a web app in Kubernetes?
we're experimenting Kubernetes and thinking about migrating our webapp, currently hosted in a classic public cloud with vps and load balancing.

I'd like to know how to manage an upload folder (with write/read privileged) inside our dockerized app in which  files uploaded by our users are stored.

As we use lot of file uploading in our apps, would it be possible to have a persistent data storage in which the webapp can upload files in and manage them via webapp? Do I have to change the code of my app and save files to external object storages or there's a faster way to do it via local filesystem?

Thank you !

答:
As the comment mentions, persistent voulmes is an option. You can create a AWS volume, and attach it to the pod. This post describes how to do that.

However, there is a problem you might face. That you can't scale the number of instance. I think, kubernetes doesn't allow a single elb to be shared among replicas. This issue is highlighted here. As mentioned there, its better to switch to object storage like s3. Though it might require code changes, that would be the optimal solution.


问:
Using web component without registering as a custom element?
Is it possible to instantiate a web component without registering it to the  CustomElementRegistry? consider a simple component:

```<code>export class MyCustomElm extends HTMLElement {

  constructor() {
    super();

    this.attachShadow({ mode: 'open' });
  }

  connectedCallback() {
    this.shadowRoot!.innerHTML = `
      <div>Hello world</div>
    `;
  }
}

// Is it really required?
customElements.define('my-custom-elm', MyCustomElm);
</code>```

I am using storybook for building a library of web-component. All the examples/demos are web components. The code will always use constructor syntax, i.e. new MyCustomElm() to initialize the component. It will never be used via plain HTML.

I tried to not register the element but it doesn't seem to work. It throws an exception if a constructor is invoked without registering a component. Since there are lots of demo components, it quickly becomes unwieldy to come up with unique names.

Alternately, is there any way to use storybook for web-components without having to set up extra web components for stories? (I tried DOM manipulations but it also spirals out of hand.)

答:
Yes if you want to instantiate a Custom Element with new, you'll need to define it first with customElements.define().

It's because your custom element derives from HTMLElement, so it must part of the Custom Elements Registry when super() is called from the constructor() method.

If you remove the extends HTMLElement and super() code parts from your class definition, you'll be able to instantiate it with new but it will a standard Javascript object, not a custom HTML element.

Body:
Is it possible to instantiate a web component without registering it to the  CustomElementRegistry? consider a simple component:

export class MyCustomElm extends HTMLElement {

  constructor() {
    super();

    this.attachShadow({ mode: 'open' });
  }

  connectedCallback() {
    this.shadowRoot!.innerHTML = `

Hello world

    `;
  }
}

// Is it really required?
customElements.define('my-custom-elm', MyCustomElm);

I am using storybook for building a library of web-component. All the examples/demos are web components. The code will always use constructor syntax, i.e. new MyCustomElm() to initialize the component. It will never be used via plain HTML.

I tried to not register the element but it doesn't seem to work. It throws an exception if a constructor is invoked without registering a component. Since there are lots of demo components, it quickly becomes unwieldy to come up with unique names.

Alternately, is there any way to use storybook for web-components without having to set up extra web components for stories? (I tried DOM manipulations but it also spirals out of hand.)


问:
Stripping out HTML tags from a string
How do I remove HTML tags from a string so that I can output clean text?</p>

```<code>let str = string.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
print(str)
</code>```

答:
Updated for Swift 4:

guard let htmlStringData = htmlString.data(using: .unicode) else { fatalError() }

let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
                .documentType: NSAttributedString.DocumentType.html
                .characterEncoding: String.Encoding.unicode.rawValue
             ]

let attributedHTMLString = try! NSAttributedString(data: htmlStringData, options: options, documentAttributes: nil)
let string = attributedHTMLString.string
```

Title: Stripping out HTML tags from a string

Body:
How do I remove HTML tags from a string so that I can output clean text?

let str = string.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
print(str)


问:
How to output a link in an input field via a prompt?
I am struggling with this and can't get it to work. I am using jQuery to click on a link that will open me a prompt. In this prompt, I want the user to add a URL to link it to some other websites. That works fine, but I can't get the value of the prompt to be shown properly in the input field.

The error I am getting after adding my text in the prompt is the fact
  that it outputs it like [Object object].

I do know how to do this in plain JS, but not in jQuery and I need jQuery.

This is my code:

```<code>    $(".html-button").on("click", function () {
    var urls = prompt("Add a link", "http://");
    var setText = $("#post-text").val().append('<a href="'+ urls + '"</a>');
// Adding prompt text into my input field
    $("#post-text").val(setText);
                            });
</code>```

I thought I could do this by using append instead of innerHTML, which I would use in plain JS... Can someone help please?

PS: preferably I would not want to output the anchor already in my input field, but only after submitting the post, but this is a nice to have.

Edit: Fiddle link

答:
You seem to have mixed up some variables here. You are assigning the value of the prompt response to var urls, but then expecting it to be in an undefined var person (guessing you've used the example for this from the W3 Schools Tutorial (https://www.w3schools.com/jsref/met_win_prompt.asp)).

Assuming that your input element has an id of post-text - then you would do this:

```<code>$("#post-text").val(urls);
</code>```

I am working on the assumption here that you're writing the URL into an input field, as you suggest. If you want those a tags in the input field as well then it would be:

```<code> $("#post-text").val('<a href="' + urls + '"</a>');
</code>```

If your intention is to output it as a link somewhere including the HTML 'a' tags so it can be clicked, then you'd need to append it to an appropriate element (not a input field) in the right place in the DOM/on the page.

Lastly, if you want to write the value into the field after the form as been submitted (for whatever reason) you could either store it in a variable and write it on submit, or perhaps in a hidden field. I am unsure why you would want to do this though.

Hope this helps.

Body:
I am struggling with this and can't get it to work. I am using jQuery to click on a link that will open me a prompt. In this prompt, I want the user to add a URL to link it to some other websites. That works fine, but I can't get the value of the prompt to be shown properly in the input field.

The error I am getting after adding my text in the prompt is the fact
  that it outputs it like [Object object].

I do know how to do this in plain JS, but not in jQuery and I need jQuery.

This is my code:

    $(".html-button").on("click", function () {
    var urls = prompt("Add a link", "http://");
    var setText = $("#post-text").val().append('<a href="'+ urls + '"');
// Adding prompt text into my input field
    $("#post-text").val(setText);
                            });

I thought I could do this by using append instead of innerHTML, which I would use in plain JS... Can someone help please?

PS: preferably I would not want to output the anchor already in my input field, but only after submitting the post, but this is a nice to have.

Edit: Fiddle link

Body:
You seem to have mixed up some variables here. You are assigning the value of the prompt response to var urls, but then expecting it to be in an undefined var person (guessing you've used the example for this from the W3 Schools Tutorial (https://www.w3schools.com/jsref/met_win_prompt.asp)).

Assuming that your input element has an id of post-text - then you would do this:

$("#post-text").val(urls);

I am working on the assumption here that you're writing the URL into an input field, as you suggest. If you want those a tags in the input field as well then it would be:

 $("#post-text").val('<a href="' + urls + '"</a>');

If your intention is to output it as a link somewhere including the HTML 'a' tags so it can be clicked, then you'd need to append it to an appropriate element (not a input field) in the right place in the DOM/on the page.

Lastly, if you want to write the value into the field after the form as been submitted (for whatever reason) you could either store it in a variable and write it on submit, or perhaps in a hidden field. I am unsure why you would want to do this though.

Hope this helps.


问:
Scraping each image from a craigslist search
I'm trying to pull each image url from a craigslist search, but can't seem to drill down to the URL itself.  When I try soup.find_all("a", { "class":"result-image gallery"} )[0].img, it doesn't return anything.

Specifically, the page I am trying to scrape is https://raleigh.craigslist.org/search/rea?query=duplex&sort=date&availabilityMode=0&sale_date=all+dates.

I'm trying to get the image at the following src: https://images.craigslist.org/00j0j_cC4PhAMdHLj_300x300.jpg

The super frustrating thing is that I was able to successfully do this yesterday, but didn't commit that working code to Github at the time.  I have since accidentally deleted it and can't figure out what I had originally done to make this work :(

答:
It seems you are trying to get only the first image url. Therefore, you can just use find instead of find_all.

Also, to get the URL, you need to get the src attribute from img as well.

soup.find("a", { "class":"result-image gallery"} ).img["src"]
```


问:
How to redirect inside jquery tab using javascript?
I've just got this jquery form working, it's based inside a jquery tab, and on clicking the submit button, it submits to a mySQL database without leaving the page or anything. Now, though, I want it to redirect the user, without making them leave the tab, to a different page inside the same tab once they've submitted their details.

Does anyone know the Javascript code to do this?

Thanks!

答:
If you're trying to load a new page into the DIV where your form was, simply call </p>

```<code>$('#idOfDivWithForm').load('newpage.php');
</code>```

Body:
If you're trying to load a new page into the DIV where your form was, simply call

$('#idOfDivWithForm').load('newpage.php');


问:
How to spread tab items evenly?
I'm developing new administration page. On that registration page I need to have a menu with five tabs for each administration section. We are using ant for angular and for tab menu we are using component from ant library.

I have tried to override style for ant tabs as described here:

How To Evenly Space Tabs Across the Whole Tab Bar

and here

https://github.com/NG-ZORRO/ng-zorro-antd/issues/2242

None of those articles helped.

Here is code example

```<code>    <nz-tab nzTitle="LAN STATUS">
      Content of Tab Pane 1
    </nz-tab>
    <nz-tab nzTitle="DHCP">
      Content of Tab Pane 2
    </nz-tab>
    <nz-tab nzTitle="DNS">
        Content of Tab Pane 2
      </nz-tab>
      <nz-tab nzTitle="USERS">
          Content of Tab Pane 2
      </nz-tab>
      <nz-tab nzTitle="AMAZON SERVICES">
          Content of Tab Pane 2
      </nz-tab>
  </nz-tabset>
</code>```

I would like to have a evenly spaced  element inside

答:
Angular have encapsulation components so you should use deep or disable that encapsulation (I prefer use deep).

@Component({
  selector: 'second-cmp',
  template: `<div class="cmp">Second Component</div>`,
  styles: ['.cmp { border: green 2px solid; }'],
  encapsulation: ViewEncapsulation.None  // Use to disable CSS Encapsulation for this component
})
```

<p>or</p>

```:host ::ng-deep nz-tab X{
    color: red;
}
```

You can read more here https://coryrylan.com/blog/css-encapsulation-with-angular-components
https://blog.angular-university.io/angular-host-context/

Title: How to spread tab items evenly?

Body:
I'm developing new administration page. On that registration page I need to have a menu with five tabs for each administration section. We are using ant for angular and for tab menu we are using component from ant library.

I have tried to override style for ant tabs as described here:

How To Evenly Space Tabs Across the Whole Tab Bar

and here

https://github.com/NG-ZORRO/ng-zorro-antd/issues/2242

None of those articles helped.

Here is code example

    <nz-tab nzTitle="LAN STATUS">
      Content of Tab Pane 1
    </nz-tab>
    <nz-tab nzTitle="DHCP">
      Content of Tab Pane 2
    </nz-tab>
    <nz-tab nzTitle="DNS">
        Content of Tab Pane 2
      </nz-tab>
      <nz-tab nzTitle="USERS">
          Content of Tab Pane 2
      </nz-tab>
      <nz-tab nzTitle="AMAZON SERVICES">
          Content of Tab Pane 2
      </nz-tab>
  </nz-tabset>

I would like to have a evenly spaced  element inside

Body:
Angular have encapsulation components so you should use deep or disable that encapsulation (I prefer use deep).

@Component({
  selector: 'second-cmp',
  template: `<div class="cmp">Second Component</div>`,
  styles: ['.cmp { border: green 2px solid; }'],
  encapsulation: ViewEncapsulation.None  // Use to disable CSS Encapsulation for this component
})

or

:host ::ng-deep nz-tab X{
    color: red;
}

You can read more here https://coryrylan.com/blog/css-encapsulation-with-angular-components
https://blog.angular-university.io/angular-host-context/


问:
Ansible copy or move files only on remote host
This should work but doesn't and gives the following error (below).

I've read a couple of posts on stackoverflow here and here but there doesn't seem to be a good answer that works in this case.  I'm really hoping I'm just missing something dumb and I have been at this for hours so please don't mind my snark but I need to vent.

Since ansible, 2.3.0, can't do something as simple as copy/move/rename files ONLY on the remote host, I'm mean who would want to do that?  And it also can't act on globs (*) (say when you don't know what files to act on), a 2 step approach seems to be the only way (that I know of) to move some files (only on the remote host).  But not even this works.

migrate_rhel2centos.yml

```<code>---
- hosts: RedHat
  become: true
  become_user: root
  become_method: sudo
  vars:
    repo_dir: /etc/yum.repos.d
  tasks:
  - name: create directory
    file: path=/etc/yum.repos.d/bak/ state=directory

  - name: get repo files
    shell: "ls {{ repo_dir }}/*.repo"
    register: repo_list

 - debug: var=repo_list.stdout_lines

 - name: move repo files
   command: "/bin/mv -f {{ item }} bak"
   args:
     chdir: "{{repo_dir}}"
   with_items: repo_list.stdout_lines

#################################

TASK [get repo files]

**********************************************************************
changed: [myhost]

TASK [debug]
**********************************************************************
ok: [myhost] => {
     "repo_list.stdout_lines": [
     "/etc/yum.repos.d/centric.repo",
     "/etc/yum.repos.d/redhat.repo",
     "/etc/yum.repos.d/rhel-source.repo"
   ]
}

TASK [move repo files]
*******************************************************************
failed: [myhost] (item=repo_list.stdout_lines) => {"changed": true,    "cmd": ["/bin/mv", "-f", "repo_list.stdout_lines", "bak"], "delta": "0:00:00.001945", "end": "2016-12-13 15:07:14.103823", "failed": true, "item": "repo_list.stdout_lines", "rc": 1, "start": "2016-12-13 15:07:14.101878", "stderr": "/bin/mv: cannot stat `repo_list.stdout_lines': No such file or directory", "stdout": "", "stdout_lines": [], "warnings": []}
to retry, use: --limit @/home/jimm/.ansible/migrate_rhel2centos.retry

PLAY RECAP
********************************
myhost : ok=5    changed=1    unreachable=0    failed=1
</code>```

答:
Copy has the flag
remote_src

If no, it will search for src at originating/master machine.

If yes it will go to the remote/target machine for the src. Default is no.

edit: https://docs.ansible.com/ansible/latest/collections/ansible/builtin/copy_module.html

Does now support recursive copying.

Body:
This should work but doesn't and gives the following error (below).

I've read a couple of posts on stackoverflow here and here but there doesn't seem to be a good answer that works in this case.  I'm really hoping I'm just missing something dumb and I have been at this for hours so please don't mind my snark but I need to vent.

Since ansible, 2.3.0, can't do something as simple as copy/move/rename files ONLY on the remote host, I'm mean who would want to do that?  And it also can't act on globs (*) (say when you don't know what files to act on), a 2 step approach seems to be the only way (that I know of) to move some files (only on the remote host).  But not even this works.

migrate_rhel2centos.yml

---
- hosts: RedHat
  become: true
  become_user: root
  become_method: sudo
  vars:
    repo_dir: /etc/yum.repos.d
  tasks:
  - name: create directory
    file: path=/etc/yum.repos.d/bak/ state=directory

  - name: get repo files
    shell: "ls {{ repo_dir }}/*.repo"
    register: repo_list

 - debug: var=repo_list.stdout_lines

 - name: move repo files
   command: "/bin/mv -f {{ item }} bak"
   args:
     chdir: "{{repo_dir}}"
   with_items: repo_list.stdout_lines

#################################

TASK [get repo files]

**********************************************************************
changed: [myhost]

TASK [debug]
**********************************************************************
ok: [myhost] => {
     "repo_list.stdout_lines": [
     "/etc/yum.repos.d/centric.repo",
     "/etc/yum.repos.d/redhat.repo",
     "/etc/yum.repos.d/rhel-source.repo"
   ]
}

TASK [move repo files]
*******************************************************************
failed: [myhost] (item=repo_list.stdout_lines) => {"changed": true,    "cmd": ["/bin/mv", "-f", "repo_list.stdout_lines", "bak"], "delta": "0:00:00.001945", "end": "2016-12-13 15:07:14.103823", "failed": true, "item": "repo_list.stdout_lines", "rc": 1, "start": "2016-12-13 15:07:14.101878", "stderr": "/bin/mv: cannot stat `repo_list.stdout_lines': No such file or directory", "stdout": "", "stdout_lines": [], "warnings": []}
to retry, use: --limit @/home/jimm/.ansible/migrate_rhel2centos.retry

PLAY RECAP
********************************
myhost : ok=5    changed=1    unreachable=0    failed=1


问:
 not working in firefox and chrome
break line tag is not working in firefox, neither in chrome. When i see the source of my page i get:

```<code><p>Zugang zu Testaccount:</br></br>peter petrelli </br></br>sein Standardpwd.</br></br>peter.heroes.com</p>
</code>```

However when i do view selected source, i get:

```<code><p>Zugang zu Testaccount: peter petrelli  sein Standardpwd. peter.heroes.com</p>
</code>```

It seems firefox is filtering break line tags out.

It works in IE7 fine.

答: If you are using struts set escapeXml="false"

OwnerDisplayName: Sergio del Amo

ContentLicense: CC BY-SA 2.5

Title: </br> not working in firefox and chrome

Body:
break line tag is not working in firefox, neither in chrome. When i see the source of my page i get:

Zugang zu Testaccount:

peter petrelli

sein Standardpwd.

peter.heroes.com

However when i do view selected source, i get:

Zugang zu Testaccount: peter petrelli  sein Standardpwd. peter.heroes.com

It seems firefox is filtering break line tags out.

It works in IE7 fine.

LastEditorDisplayName: Dana


问:
Module not found: Error: Can't resolve 'X\node_modules\ng-zorro-antd\src\ng-zorro-antd.less'
i using angular 6.0.1 . when i need to use ng-zorro-antd it show me this error :

ERROR in multi ../node_modules/ng-zorro-antd/src/ng-zorro-antd.less ./src/styles.css
            Module not found: Error: Can't resolve 'E:\AngularTraning\node_modules\ng-zorro-antd\src\ng-zorro-antd.less' in 'E:\AngularTraning\Authorize'

i install ng-zorro-antd with this command : npm install ng-zorro-antd --save

and import this :

```<code>   BrowserModule,
FormsModule,
HttpClientModule,
BrowserAnimationsModule,
NgZorroAntdModule.forRoot()
</code>```

add ng-zorro-antd.less in angular.json :

```<code>"styles": [
          "../node_modules/ng-zorro-antd/src/ng-zorro-antd.less",
          "src/styles.css"
        ],
</code>```

whats the problem ? how can solve that ?

答:
EDIT:

Your path seems wrong. Replace .. with ./

ORIGINAL ANSWER:

Firstly, is your Angular project running on SASS/SCSS OR LESS ? You cant have both preprocessors in the same project. Chances are you are having the Sassy CSS (SCSS) preprocessor with your Angular project.

SOLUTION 1: Replace it with the .min.css

```<code>"./node_modules/ng-zorro-antd/ng-zorro-antd.min.css"
</code>```

SOLUTION 2: Replace the line with {"input": }

If this has to work,  you have to make sure your project is using LESS preprocessor and NOT SCSS

```<code>{"input": "../node_modules/ng-zorro-antd/src/ng-zorro-antd.less"}
</code>```

Body:
i using angular 6.0.1 . when i need to use ng-zorro-antd it show me this error :

ERROR in multi ../node_modules/ng-zorro-antd/src/ng-zorro-antd.less ./src/styles.css
            Module not found: Error: Can't resolve 'E:\AngularTraning\node_modules\ng-zorro-antd\src\ng-zorro-antd.less' in 'E:\AngularTraning\Authorize'

i install ng-zorro-antd with this command : npm install ng-zorro-antd --save

and import this :

   BrowserModule,
FormsModule,
HttpClientModule,
BrowserAnimationsModule,
NgZorroAntdModule.forRoot()

add ng-zorro-antd.less in angular.json :

"styles": [
          "../node_modules/ng-zorro-antd/src/ng-zorro-antd.less",
          "src/styles.css"
        ],

whats the problem ? how can solve that ?

Body:
EDIT:

Your path seems wrong. Replace .. with ./

ORIGINAL ANSWER:

Firstly, is your Angular project running on SASS/SCSS OR LESS ? You cant have both preprocessors in the same project. Chances are you are having the Sassy CSS (SCSS) preprocessor with your Angular project.

SOLUTION 1: Replace it with the .min.css

"./node_modules/ng-zorro-antd/ng-zorro-antd.min.css"

SOLUTION 2: Replace the line with {"input": }

If this has to work,  you have to make sure your project is using LESS preprocessor and NOT SCSS

{"input": "../node_modules/ng-zorro-antd/src/ng-zorro-antd.less"}


问:
How to implement process execution as reactive `Observable[String]
I want represent external process execution as Observable[String], where String - line from process output. Here example what I do, it's worked:

```<code>import monix.eval.Task
import monix.execution.Scheduler.Implicits.global
import monix.reactive.Observable

object TestSo {

  def main(args: Array[String]): Unit = {

    val lineStream = scala.sys.process.Process("python3 test.py").lineStream

    val lineStreamO: Observable[String] = Observable.fromIterator(Task(lineStream.iterator))
      .doOnNext(l => Task(println(l))) //logging
      .guarantee(Task(println("clean resources")))

    println(lineStreamO.toListL.runSyncUnsafe())
  }

}
</code>```

You can see, that process emits new line every second. But it does not matter. Just provide full example, test.py:

```<code>from time import sleep
print(0, flush=True)
sleep(1)
print(1, flush=True)
sleep(1)
print(2, flush=True)
sleep(1)
print(3, flush=True)
sleep(1)
print(4, flush=True)
</code>```

Output:

```<code>0
1
2
3
4
5
clean resources
List(0, 1, 2, 3, 4, 5)
</code>```

Problem:

I want to have timeout - if process freezes (for example sleep 100000) process should be killed after timeout. Also if process compelted or fail, some resources should be cleaned (guarantee in example). NonZero exit code should represent failure.

How to implement process execution as Observable[String] with propper error handling? rx-java solutions are welcome.

答:
I implemened process execution as reactive rxjava2 Observable in small library, that wraps NuProcess in reactive way. For example:

```<code>PreparedStreams streams = builder.asStdInOut();

Single<NuProcess> started = streams.started();
Single<Exit> done = streams.waitDone();
Observable<byte[]> stdout = streams.stdOut();
Observer<byte[]> stdin = streams.stdIn();

done.subscribe();
</code>```

Body:
I want represent external process execution as Observable[String], where String - line from process output. Here example what I do, it's worked:

import monix.eval.Task
import monix.execution.Scheduler.Implicits.global
import monix.reactive.Observable

object TestSo {

  def main(args: Array[String]): Unit = {

    val lineStream = scala.sys.process.Process("python3 test.py").lineStream

    val lineStreamO: Observable[String] = Observable.fromIterator(Task(lineStream.iterator))
      .doOnNext(l => Task(println(l))) //logging
      .guarantee(Task(println("clean resources")))

    println(lineStreamO.toListL.runSyncUnsafe())
  }

}

You can see, that process emits new line every second. But it does not matter. Just provide full example, test.py:

from time import sleep
print(0, flush=True)
sleep(1)
print(1, flush=True)
sleep(1)
print(2, flush=True)
sleep(1)
print(3, flush=True)
sleep(1)
print(4, flush=True)

Output:

0
1
2
3
4
5
clean resources
List(0, 1, 2, 3, 4, 5)

Problem:

I want to have timeout - if process freezes (for example sleep 100000) process should be killed after timeout. Also if process compelted or fail, some resources should be cleaned (guarantee in example). NonZero exit code should represent failure.

How to implement process execution as Observable[String] with propper error handling? rx-java solutions are welcome.

Body:
I implemened process execution as reactive rxjava2 Observable in small library, that wraps NuProcess in reactive way. For example:

PreparedStreams streams = builder.asStdInOut();

Single<NuProcess> started = streams.started();
Single<Exit> done = streams.waitDone();
Observable<byte[]> stdout = streams.stdOut();
Observer<byte[]> stdin = streams.stdIn();

done.subscribe();


问:
Android - problems with JNI
I have the following code (stored as .c file) in my Android project:

```<code>static void convert(unsigned int &c, const float &temp1, const float &temp2, const float &temp3) {
    if ( (temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3) * 100);

    else if ((temp3 * 2) < 1) c = (unsigned int) (temp1 * 100);

    else if ((temp3 * 3) < 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.66666 - temp3) * 6) * 100);

    else c = (unsigned int) (temp2 * 100);

    return;
}
</code>```

During the code it gets called like this:

```<code>convert(r, temp1, temp2, temp3);
</code>```

But when I compile it with the ndk-build command from the command line, then I get the following errors:

Android NDK: APP_PLATFORM not set. Defaulting to minimum supported
  version android-16.     [arm64-v8a] Compile        :
  com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor
  <=
  com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c
  jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:193:47:
  error:
        expected ')' static void convert(unsigned int &c, const float &temp1, const float ...
                                                ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:193:33:
  note:
        to match this '(' static void convert(unsigned int &c, const float &temp1, const float ...
                                  ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:193:47:
  error:
        parameter name omitted static void convert(unsigned int &c, const float &temp1, const float ...
                                                ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:194:11:
  error:
        use of undeclared identifier 'temp3'
      if ( (temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3...
            ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:194:27:
  error:
        use of undeclared identifier 'c'
      if ( (temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3...
                            ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:194:57:
  error:
        use of undeclared identifier 'temp1'
      if ( (temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3...
                                                          ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:194:65:
  error:
        use of undeclared identifier 'temp2'
      if ( (temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3) * ...
                                                                  ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:194:48:
  error:
        use of undeclared identifier 'temp2'
      if ( (temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3...
                                                 ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:194:78:
  error:
        use of undeclared identifier 'temp3'   ...(temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3) * 100);
                                                                           ^
  jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:196:15:
  error:
        use of undeclared identifier 'temp3'
      else if ((temp3 * 2) < 1) c = (unsigned int) (temp1 * 100);
                ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:196:31:
  error:
        use of undeclared identifier 'c'
      else if ((temp3 * 2) < 1) c = (unsigned int) (temp1 * 100);
                                ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:196:51:
  error:
        use of undeclared identifier 'temp1'
      else if ((temp3 * 2) < 1) c = (unsigned int) (temp1 * 100);
                                                    ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:198:15:
  error:
        use of undeclared identifier 'temp3'
      else if ((temp3 * 3) < 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.666...
                ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:198:31:
  error:
        use of undeclared identifier 'c'
      else if ((temp3 * 3) < 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.666...
                                ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:198:61:
  error:
        use of undeclared identifier 'temp1'
      else if ((temp3 * 3) < 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.666...
                                                              ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:198:69:
  error:
        use of undeclared identifier 'temp2'   ...if ((temp3 * 3) < 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.66666 - temp...
                                                                  ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:198:52:
  error:
        use of undeclared identifier 'temp2'
      else if ((temp3 * 3) < 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.666...
                                                     ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:198:88:
  error:
        use of undeclared identifier 'temp3'   ...< 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.66666 - temp3) * 6) * 100);
                                                                     ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:200:10:
  error:
        use of undeclared identifier 'c'
      else c = (unsigned int) (temp2 * 100);
           ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:200:30:
  error:
        use of undeclared identifier 'temp2'
      else c = (unsigned int) (temp2 * 100);

I got that code from a .cpp file. When I delete the address operator (&) in the signature, then everything is fine (no errors) but I do not know if then the algorithm would work.

Can anybody help ?

答: In C++ unsigned int &c is a reference parameter and & is not "the address operator" in that case. However, references don't exist in C, which is why you get errors when compiling this C++ code in a .c file instead of .cpp

Title: Android - problems with JNI

Body:
I have the following code (stored as .c file) in my Android project:

static void convert(unsigned int &c, const float &temp1, const float &temp2, const float &temp3) {
    if ( (temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3) * 100);

    else if ((temp3 * 2) < 1) c = (unsigned int) (temp1 * 100);

    else if ((temp3 * 3) < 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.66666 - temp3) * 6) * 100);

    else c = (unsigned int) (temp2 * 100);

    return;
}

During the code it gets called like this:

convert(r, temp1, temp2, temp3);

But when I compile it with the ndk-build command from the command line, then I get the following errors:

Android NDK: APP_PLATFORM not set. Defaulting to minimum supported
  version android-16.     [arm64-v8a] Compile        :
  com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor
  <=
  com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c
  jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:193:47:
  error:
        expected ')' static void convert(unsigned int &c, const float &temp1, const float ...
                                                ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:193:33:
  note:
        to match this '(' static void convert(unsigned int &c, const float &temp1, const float ...
                                  ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:193:47:
  error:
        parameter name omitted static void convert(unsigned int &c, const float &temp1, const float ...
                                                ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:194:11:
  error:
        use of undeclared identifier 'temp3'
      if ( (temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3...
            ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:194:27:
  error:
        use of undeclared identifier 'c'
      if ( (temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3...
                            ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:194:57:
  error:
        use of undeclared identifier 'temp1'
      if ( (temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3...
                                                          ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:194:65:
  error:
        use of undeclared identifier 'temp2'
      if ( (temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3) * ...
                                                                  ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:194:48:
  error:
        use of undeclared identifier 'temp2'
      if ( (temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3...
                                                 ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:194:78:
  error:
        use of undeclared identifier 'temp3'   ...(temp3 * 6) < 1) c = (unsigned int) ((temp2 + (temp1 - temp2) * 6 * temp3) * 100);
                                                                           ^
  jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:196:15:
  error:
        use of undeclared identifier 'temp3'
      else if ((temp3 * 2) < 1) c = (unsigned int) (temp1 * 100);
                ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:196:31:
  error:
        use of undeclared identifier 'c'
      else if ((temp3 * 2) < 1) c = (unsigned int) (temp1 * 100);
                                ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:196:51:
  error:
        use of undeclared identifier 'temp1'
      else if ((temp3 * 2) < 1) c = (unsigned int) (temp1 * 100);
                                                    ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:198:15:
  error:
        use of undeclared identifier 'temp3'
      else if ((temp3 * 3) < 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.666...
                ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:198:31:
  error:
        use of undeclared identifier 'c'
      else if ((temp3 * 3) < 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.666...
                                ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:198:61:
  error:
        use of undeclared identifier 'temp1'
      else if ((temp3 * 3) < 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.666...
                                                              ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:198:69:
  error:
        use of undeclared identifier 'temp2'   ...if ((temp3 * 3) < 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.66666 - temp...
                                                                  ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:198:52:
  error:
        use of undeclared identifier 'temp2'
      else if ((temp3 * 3) < 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.666...
                                                     ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:198:88:
  error:
        use of undeclared identifier 'temp3'   ...< 2) c = (unsigned int) ((temp2 + (temp1 - temp2) * (.66666 - temp3) * 6) * 100);
                                                                     ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:200:10:
  error:
        use of undeclared identifier 'c'
      else c = (unsigned int) (temp2 * 100);
           ^ jni/com_celik_abdullah_imageprocessingpart_processors_NativeImageProcessor.c:200:30:
  error:
        use of undeclared identifier 'temp2'
      else c = (unsigned int) (temp2 * 100);

I got that code from a .cpp file. When I delete the address operator (&) in the signature, then everything is fine (no errors) but I do not know if then the algorithm would work.

Can anybody help ?


问:
How to prevent My apk from decompiling
Hi
As you now the apk is a zip file, and can be extracted, and the classes.dex can also decompiled, please How to pervent my apk from extracting or decompiling??
Thanks alot</p>

答:
Use

ProGuard

Title: How to prevent My apk from decompiling

Body:
Use

ProGuard


问:
How can I position my progress bar at the bottom of a button?
I am facing a bit of an issue and I can't seem to figure it out.

I am trying to create a button and add a bootstrap progress bar at the bottom of it, but I cant seem to figure out how to get it to do just that.

Here's my current setup. https://jsfiddle.net/bob_mosh/7qeazm9w/3/

HTML:

```<code><button id="sample_button" type="button" class="soundButton">
<label class="buttonTitle">Bird Song</label>
<label class="buttonDescription">A nice bird song.</label>
<div class="progress volume-slider">
<div class="progress-bar" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</button>
</code>```

CSS:

```<code>.soundButton {
    display: table-cell;
    background-color: rgba(255, 255, 255, 0.650);
    margin: 4px;
    padding: 8px;
    width: 250px;
    height: 120px !important;
    border-radius: 8px;
    border: none !important;
    float: left !important;
}

.soundButton label {
    color: rgba(37, 38, 43, 1.00) !important;
}

body {
  background-color: rgba(37, 38, 43, 1.00)
}

.buttonTitle {
    font-weight: 700;
    font-size: 1.5em;
    display: block;
}

.volume-slider {
    bottom:0;
    height: 8px !important;
}
</code>```

This is the current state on the right and the way I am envisioning it on the left.

For some reason I cant get the absolute positioning to work. Every time I try to set the position of the progress bar to absolute, it completely disappears. Can anyone help me figure this out?

答:
All you need to do is add position: relative; to your .soundButton class then copy this to your .volume-slider

```<code>.volume-slider {
  position: absolute;
  bottom: 0;
  right: 0;
  left: 0;
  height: 8px !important;
}
</code>```

Working sample fiddle HERE

Body:
I am facing a bit of an issue and I can't seem to figure it out.

I am trying to create a button and add a bootstrap progress bar at the bottom of it, but I cant seem to figure out how to get it to do just that.

Here's my current setup. https://jsfiddle.net/bob_mosh/7qeazm9w/3/

HTML:

<button id="sample_button" type="button" class="soundButton">
Bird Song
A nice bird song.

</button>

CSS:

.soundButton {
    display: table-cell;
    background-color: rgba(255, 255, 255, 0.650);
    margin: 4px;
    padding: 8px;
    width: 250px;
    height: 120px !important;
    border-radius: 8px;
    border: none !important;
    float: left !important;
}

.soundButton label {
    color: rgba(37, 38, 43, 1.00) !important;
}

body {
  background-color: rgba(37, 38, 43, 1.00)
}

.buttonTitle {
    font-weight: 700;
    font-size: 1.5em;
    display: block;
}

.volume-slider {
    bottom:0;
    height: 8px !important;
}

This is the current state on the right and the way I am envisioning it on the left.

For some reason I cant get the absolute positioning to work. Every time I try to set the position of the progress bar to absolute, it completely disappears. Can anyone help me figure this out?

Body:
All you need to do is add position: relative; to your .soundButton class then copy this to your .volume-slider

.volume-slider {
  position: absolute;
  bottom: 0;
  right: 0;
  left: 0;
  height: 8px !important;
}

Working sample fiddle HERE


问:
Why method that calls another one which throws RuntimeException needs return statement?
Why unreachable statement is not identified by javac ?</p>

```<code>public int directThrow(){
     throw new RuntimeException();
    //Compiles fine
}

public int indirectThrow(){
    directThrow();
    // Missing Return Statement error
}
</code>```

答:
The compiler simply isn't designed to analyse your code that deeply.

For directThrow, the compiler looks at it and says, "I see you have a throw statement, so the method will terminate abruptly here, no need for a return statement then!"

For indirectThrow, the compiler looks at it and says, "I only see a method call. Hey programmer! You need a return statement here!"

The compiler doesn't look at what directThrow actually does. I think this is quite reasonable, because the benefit of analysing what every method you call does is really small, compared to the cost of increased compilation time. Think about what the compiler needs to check to make sure that directThrow will always throw an exception. The most important thing being, is it overridden by anything? Can you even check that? Can you even make sure that no class in the future will subclass your class and override that method (give your class and directThrow are both non-final)?

If you have some complicated exception-throwing logic that you want to extract into a method, you can extract it into a method that returns the Exception:

```<code>private Exception someComplicatedLogicThatGivesAnException() { ... }

public void foo() {
    if (...) {
        throw someComplicatedLogicThatGivesAnException();
    }
}
</code>```

Body:
Why unreachable statement is not identified by javac ?

public int directThrow(){
     throw new RuntimeException();
    //Compiles fine
}

public int indirectThrow(){
    directThrow();
    // Missing Return Statement error
}

Body:
The compiler simply isn't designed to analyse your code that deeply.

For directThrow, the compiler looks at it and says, "I see you have a throw statement, so the method will terminate abruptly here, no need for a return statement then!"

For indirectThrow, the compiler looks at it and says, "I only see a method call. Hey programmer! You need a return statement here!"

The compiler doesn't look at what directThrow actually does. I think this is quite reasonable, because the benefit of analysing what every method you call does is really small, compared to the cost of increased compilation time. Think about what the compiler needs to check to make sure that directThrow will always throw an exception. The most important thing being, is it overridden by anything? Can you even check that? Can you even make sure that no class in the future will subclass your class and override that method (give your class and directThrow are both non-final)?

If you have some complicated exception-throwing logic that you want to extract into a method, you can extract it into a method that returns the Exception:

private Exception someComplicatedLogicThatGivesAnException() { ... }

public void foo() {
    if (...) {
        throw someComplicatedLogicThatGivesAnException();
    }
}


问:
React.js - passing props to children from hoc
I have been trying to pass some props from my HOC to children. the HOC wraps react router switch and route. The props are missing in the child component. I make use of React.CloneElement to add the props to the children but do not seem to work

```<code><BrowserRouter>
<Layout>
        <React.Suspense fallback={loading()}>
          <Switch>
            <Route exact path="/" component={Login} />
            <Route path="/dashboard" component={Home} />
            <Route path="/tickets" component={Tickets} />

          </Switch>
        </React.Suspense>
      </Layout>
    </BrowserRouter>
</code>```

this is the HOC(layout)

```<code>class Layout extends React.Component {
   .....

    render() {
        const children = this.props.children && React.cloneElement(this.props.children, { data: 'ok' })
...
</code>```

the child component do no get the data prop, I get just this

```<code>{history: {…}, location: {…}, match: {…}, staticContext: undefined}
</code>```

答:
this.props.children is a collection of elements/components.  So, you have to map before calling cloneElement:

```<code>return React.Children.map(this.props.children, el => (
    React.cloneElement(el, { data: 'ok' });
);
</code>```

Body:
I have been trying to pass some props from my HOC to children. the HOC wraps react router switch and route. The props are missing in the child component. I make use of React.CloneElement to add the props to the children but do not seem to work

<BrowserRouter>
<Layout>
        <React.Suspense fallback={loading()}>
          <Switch>
            <Route exact path="/" component={Login} />
            <Route path="/dashboard" component={Home} />
            <Route path="/tickets" component={Tickets} />

          </Switch>
        </React.Suspense>
      </Layout>
    </BrowserRouter>

this is the HOC(layout)

class Layout extends React.Component {
   .....

    render() {
        const children = this.props.children && React.cloneElement(this.props.children, { data: 'ok' })
...

the child component do no get the data prop, I get just this

{history: {…}, location: {…}, match: {…}, staticContext: undefined}

Body:
this.props.children is a collection of elements/components.  So, you have to map before calling cloneElement:

return React.Children.map(this.props.children, el => (
    React.cloneElement(el, { data: 'ok' });
);


问:
WPF DataGrid disable a row but allow one cell
I have a DataGrid in WPF.
The most left cell in every row is a CheckBox, which sets an Enabled property on the row's model (through a RowViewModel).

When the CheckBoxis unchecked on a certain row that row in the DataGrid should be disabled so all controls in the other columns of the row should be disabled, but not the CheckBox cell.

How can I easiest achieve that, still allowing the CheckBox cell to be enabled so the user can click the CheckBox in the most left cell in the row (so the user could still enable the object again hence making the complete row enabled as well)

答:
You could define a cell style that with a trigger that binds to the source property of the CheckBox and sets the IsEnabled property of the cell to false when the source property returns false or true:

```<code><Style x:Key="cellStyle" TargetType="DataGridCell">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Enabled}" Value="False">
            <Setter Property="IsEnabled" Value="False" />
        </DataTrigger>
    </Style.Triggers>
</Style>
</code>```

You then set the CellStyle property of all columns except the one with the CheckBox to this style:

```<code><DataGridTextColumn ... CellStyle="{StaticResource cellStyle}">
</code>```

Body:
You could define a cell style that with a trigger that binds to the source property of the CheckBox and sets the IsEnabled property of the cell to false when the source property returns false or true:

<Style x:Key="cellStyle" TargetType="DataGridCell">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Enabled}" Value="False">
            <Setter Property="IsEnabled" Value="False" />
        </DataTrigger>
    </Style.Triggers>
</Style>

You then set the CellStyle property of all columns except the one with the CheckBox to this style:

<DataGridTextColumn ... CellStyle="{StaticResource cellStyle}">


问:
How to convert DWORD to string in Python
I am working on a C++ SDK using Python. One of the APIs looks like this

API

```<code>DWORD NET_DVR_GetSDKVersion(
);
</code>```

Documentation

2 higher bytes mean the major version, 2 lower bytes mean the minor version, e.g. 0x00030000 means version 3.0.

It returns a DWORD value. I did some research and it seems like DWORD equals to ctypes.c_ulong in Python.

However, all I get from the API is an integer 393216 that does not make much sense.

Code

```<code>sdk = cdll.LoadLibrary("sdk.so")
sdk.NET_DVR_GetSDKVersion.restype = ctypes.c_long
result = sdk.NET_DVR_GetSDKVersion()
</code>```

I have setting the return value type using c_char_p and several other types but results don't really make much sense.

答:
2 higher bytes mean the major version, 2 lower bytes mean the minor version, e.g. 0x00030000 means version 3.0.

As you can see in the example, the number is in the hex format (0x prefix). In hex format you can easily see the bytes - 2 hex digits=1 byte (because 16*16 is 256).

You need to convert your number to hex using hex(your_value_here) and cut it into 2 parts for major and minor version.

In your case hex(393216) returns '0x60000' - that is 0x0 as 2 lower bytes (minor version) and 0x6 as higher bytes (major version), giving version 6.0

EDIT:

You can also extract your version using binary operations. Use your_number_here>>16 to move your number 16 bits (2 bytes) right, i.e. removing the lower 2.

So it's your_number>>16 for major, your_number - (your_number>>16<<16) for minor.

Body:
I am working on a C++ SDK using Python. One of the APIs looks like this

API

DWORD NET_DVR_GetSDKVersion(
);

Documentation

2 higher bytes mean the major version, 2 lower bytes mean the minor version, e.g. 0x00030000 means version 3.0.

It returns a DWORD value. I did some research and it seems like DWORD equals to ctypes.c_ulong in Python.

However, all I get from the API is an integer 393216 that does not make much sense.

Code

sdk = cdll.LoadLibrary("sdk.so")
sdk.NET_DVR_GetSDKVersion.restype = ctypes.c_long
result = sdk.NET_DVR_GetSDKVersion()

I have setting the return value type using c_char_p and several other types but results don't really make much sense.


问:
How to scroll to an element on a page when click a link in a separate Angular 7 mat-toolbar component
I have an Angular 7 project with a mat-tool bar at the top of the page containing links. Below it is a long view made up of various sections. Each section is its own component. I achieved this by creating one component - Home - and then placed the component selectors for each section one under the other in home template. As such:

```<code>// Home component template
<app-intro></app-intro>
<app-ourservices></app-ourservices>
<app-ourwork></app-ourwork>
<app-contact></app-contact>
</code>```

I want to be able to click a link in the mat-toolbar (which is its own component) and have the home page scroll to a relevant section WITH animation.

The following works, but it causes the view to jump to the section.

```<code><a href="home#servicesSection">Services</a>
</code>```

I am also aware of using a click event combined with .scrollIntoView:

```<code>scroll(element: HTMLElement) {
    element.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }
</code>```

But this only seems to work when everything (id tags, and click events) are contained within the same component (i.e on the same page).

How can I achieve what I am trying to do but still keep things separated into components? I am new to Angular so might be structuring things incorrectly.

答:
In your HTML - Give the elements reference variables #nameHere

```<code><div #intro>
    <app-intro></app-intro>
</div>
<div #ourservices>
    <app-ourservices></app-ourservices>
<div #ourwork>
    <app-ourwork></app-ourwork>
</div>
<div #contact>
    <app-contact></app-contact>
</div>
</code>```

In your .ts file - Use @ViewChild to get  reference to the element using the reference variables, then use the navtiveElement with scrollIntoView()

```<code>import { ... ViewChild } from "@angular/core";

....

@ViewChild('intro') intro: ElementRef;
@ViewChild('ourserivces') ourservices: ElementRef;
@ViewChild('ourwork') ourwork: ElementRef;
@ViewChild('contact') contact: ElementRef;

contstructor(....)

public scrollToIntro() {
    this.intro.nativeElement.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest'
    });
}

public scrollToOurServices() {
    this.ourserivces.nativeElement.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest'
    })
}

public scrollToOurWork() {
    this.ourwork.nativeElement.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest'
    })
}

public scrollToContact() {
    this.contect.nativeElement.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest'
    })
}
</code>```

Usage - in your HTML

```<code><div (click)="scrollToIntro()">Intro</div>
<div (click)="scrollToOurServices()">Services</div>
<div (click)="scrollToOurWork()">Our Work</div>
<div (click)="scrollToContact()">Contact</div>
</code>```

Body:
I have an Angular 7 project with a mat-tool bar at the top of the page containing links. Below it is a long view made up of various sections. Each section is its own component. I achieved this by creating one component - Home - and then placed the component selectors for each section one under the other in home template. As such:

// Home component template
<app-intro></app-intro>
<app-ourservices></app-ourservices>
<app-ourwork></app-ourwork>
<app-contact></app-contact>

I want to be able to click a link in the mat-toolbar (which is its own component) and have the home page scroll to a relevant section WITH animation.

The following works, but it causes the view to jump to the section.

Services

I am also aware of using a click event combined with .scrollIntoView:

scroll(element: HTMLElement) {
    element.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }

But this only seems to work when everything (id tags, and click events) are contained within the same component (i.e on the same page).

How can I achieve what I am trying to do but still keep things separated into components? I am new to Angular so might be structuring things incorrectly.

Body:
In your HTML - Give the elements reference variables #nameHere

<div #intro>
    <app-intro></app-intro>
</div>
<div #ourservices>
    <app-ourservices></app-ourservices>
<div #ourwork>
    <app-ourwork></app-ourwork>
</div>
<div #contact>
    <app-contact></app-contact>
</div>

In your .ts file - Use @ViewChild to get  reference to the element using the reference variables, then use the navtiveElement with scrollIntoView()

import { ... ViewChild } from "@angular/core";

....

@ViewChild('intro') intro: ElementRef;
@ViewChild('ourserivces') ourservices: ElementRef;
@ViewChild('ourwork') ourwork: ElementRef;
@ViewChild('contact') contact: ElementRef;

contstructor(....)

public scrollToIntro() {
    this.intro.nativeElement.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest'
    });
}

public scrollToOurServices() {
    this.ourserivces.nativeElement.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest'
    })
}

public scrollToOurWork() {
    this.ourwork.nativeElement.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest'
    })
}

public scrollToContact() {
    this.contect.nativeElement.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest'
    })
}

Usage - in your HTML

<div (click)="scrollToIntro()">Intro</div>
<div (click)="scrollToOurServices()">Services</div>
<div (click)="scrollToOurWork()">Our Work</div>
<div (click)="scrollToContact()">Contact</div>


问:
How to continuously deploy from jenkins to Kubernetes
i have a Maven project on my local machine and a docker image in my repo and im using gitlab and jenkins to automate builds, and now with current setup I want to continously deploy to Kubernetes. I have no idea on how this is done. Any input will be appreciated.

my yaml file looks like this

apiVersion: v1
kind: Pod
metadata:
  name: client-pod
  labels:
    component: web
spec:
  containers:
    - name: client
      image: <image>
      ports:
        - containerPort: 3000```

答:
You can use this exemplary jenkins pipeline, to build and deploy your dockerized maven-app to Kubernetes with helm. It consists of following steps:

Git clone and setup

Build and local tests

Publish Docker and Helm

Deploy to dev and test

Deploy to staging and test

Optionally deploy to production and test

It think it's a nice starting point to realize CI/CD with Jenkins & Kubernets.


问:
Next Previous Post in wordpress
How can i show the content in next previous post of wordpress. For example. For the next post link with title is to be there, Is it possible to show the content of that post (100 Words).

```<code>       <div class="alignleftfp">
        <?php next_post_link('%link', '%title'); ?>
<?php get_next_post();?>
        </div>
        <div class="alignrightfp">
        <?php previous_post_link('%link', '%title'); ?>
<?php get_previous_post();?>
        </div>
</code>```

Much appreciated if any response. . .

答:
```<code><div class="post-navigation">
        <div class="prev-post">
            <?php $greenres_prev_post = get_previous_post();
            if($greenres_prev_post):
                ?>
                <h3 class="post-title"><a href="<?php echo get_the_permalink($greenres_prev_post);
                    ?>"><?php echo get_the_title($greenres_prev_post); ?></a></h3>
            <?php endif; ?>
        </div>
        <div class="next-post">
            <?php $greenres_next_post = get_next_post();
            if($greenres_next_post):
            ?>
            <h3 class="post-title"><a href="<?php echo get_the_permalink($greenres_next_post);
                ?>"><?php echo get_the_title($greenres_next_post); ?></a></h3>

            <?php endif; ?>
        </div>
    </div>
</code>```

Title: Next Previous Post in wordpress

Body:
How can i show the content in next previous post of wordpress. For example. For the next post link with title is to be there, Is it possible to show the content of that post (100 Words).

        <?php next_post_link('%link', '%title'); ?>
<?php get_next_post();?>

        <?php previous_post_link('%link', '%title'); ?>
<?php get_previous_post();?>

Much appreciated if any response. . .


问:
How do you balance working for a living and contributing to open source projects?
I have been a working programmer since the turn of the century and I have always been fascinated by the open source world. I have wanted to contribute to these projects but I find it difficult to find the time that I think these projects would require.

I find professional software development to be a huge time sink. Almost every project I have worked on has a familiar litany inflexible deadlines and inevitable round the clock last minute pushes that eat up your nights and weekends and everything else in sight. Even in the project that don't have this - the typical work day is 10 to 12 hours and after that one has errands and chores, reading up on the latest stuff, etc...

Since this happens with a fair amount of regularity - I am hesitant to join projects since I can't promise to devote a regular number of hours every week.

My question is how do you people do it?

Do you work at open source companies? Am I exaggerating the amount of time I need to spend (I am thinking a couple of hours everyday)? Am I way off base and simply not managing my time efficiently? How do you manage your time?

答: spend less time on stackoverflow.com, more time with family</p>

OwnerDisplayName: Nikhil

OwnerDisplayName: Steven A. Lowe


问:
SSH connection with python from a device (not computer)
I'm using a Digi 3G router that can be programmed with python, and I want it to make periodic SSH connections to another device. I've read everything about paramiko, but don't know how to install it in the router.
I want to know if there is any other way of including paramiko into a device, apart from installing (i.e. including some library), or if it exist another possibility apart from paramiko for this particular case.

Thanks in advance.

答:
The description for the Digi 3G states that it is capable of python scripting, using a custom development environment.  To make this work, you would have to use the python source code from paramiko; the executable would not be installable directly on the router (since the executable is designed to be run on a computer, not a router).

The source code would probably have to be  modified, since the APIs for this sort of thing are most likely different than those in a computer, and the router would have to be capable of what you are asking of it.


问:
how to get the column name of the greatest value by using greatest function postgresql?
I have four columns in my table which are col1,col2,col3,col4.
I can find the greatest value by using

```<code>select greatest(col1,col2,col3,col4) from mytable;
</code>```

But I need to know the column name of the greatest value.

答:
With CASE:

```<code>select
  case greatest(col1,col2,col3,col4)
    when col1 then 'col1'
    when col2 then 'col2'
    when col3 then 'col3'
    when col4 then 'col4'
    else null
  end greatestcolumnname
from mytable;
</code>```

Body:
I have four columns in my table which are col1,col2,col3,col4.
I can find the greatest value by using

select greatest(col1,col2,col3,col4) from mytable;

But I need to know the column name of the greatest value.

Body:
With CASE:

select
  case greatest(col1,col2,col3,col4)
    when col1 then 'col1'
    when col2 then 'col2'
    when col3 then 'col3'
    when col4 then 'col4'
    else null
  end greatestcolumnname
from mytable;


问:
How to populate Hive Table with all timestamps(86400) in a day
I want a Hive Table with 4 Columns <date,key,Timestamp,count>. Here Keys can be multiple count should be numeric 0. I need a records for every second in the day for each key.
E.g. I have 2 Keys A and B. I want 86400 Records for each key in the table. From 00:00:00 till 23:59:59

I know about current_timestamp function. Not sure whether it will fit here.

```<code>Date, Key, Timestamp, Count
2019-05-31, A, 00:00:00, 0
2019-05-31, A, 00:00:01, 0
2019-05-31, A, 00:00:02, 0
.
.
.
2019-05-31, A, 23:59:59, 0
2019-05-31, B, 00:00:00, 0
2019-05-31, B, 00:00:01, 0
2019-05-31, B, 00:00:02, 0
.
.
.
2019-05-31, B, 23:59:59, 0
</code>```

答:
This query will produce timestamps required:

```<code> select from_unixtime(unix_timestamp('2019-05-31 00:00:00')+i) as ts
   from (select
               posexplode(split(space(86399),' ')) as (i,x)
        )s
</code>```

Explanation:

Subquery s generates rows with seconds. If you join with such subquery, for example using cross join (it depends on your initial dataset) you will get each row duplicated 86400 times

space(86399) - produces string of 86399 spaces
split() - produces array spaces
posexplode - explodes array and produces a table of position and element.
Position(i) is in the range 0 - 86399, we will use it as seconds to add to start timestamp

unix_timestamp('2019-05-31 00:00:00') - this gives start timestamp in seconds passed from unix epoch. We are adding seconds (i) to it and converting again to timestamp, in such way we get 1 second incremented timestamp for each row.

Join with it and if you need date and time separately, use substring.

Demo:

For example your initial table contains two rows with timestamps and two keys A and B, you can join it with seconds generating subquery:

```<code>with your_table as( --This is initial data example
select stack(2,
'2019-05-31 00:00:00', 'A',
'2019-05-31 00:00:00', 'B'
) as (ts, Key)
)

select min(ts), max(ts), key --aggregated result for the demo
from
(
select from_unixtime(unix_timestamp(t.ts)+i) as ts , t.key
  from your_table t
      cross join (select posexplode(split(space(86399),' ')) as (i,x))s
)s group by key
</code>```

Result (aggregation added, because it generates too many rows):

```<code>min                 max                 key
2019-05-31 00:00:00 2019-05-31 23:59:59 B
2019-05-31 00:00:00 2019-05-31 23:59:59 A
</code>```

Body:
I want a Hive Table with 4 Columns <date,key,Timestamp,count>. Here Keys can be multiple count should be numeric 0. I need a records for every second in the day for each key.
E.g. I have 2 Keys A and B. I want 86400 Records for each key in the table. From 00:00:00 till 23:59:59

I know about current_timestamp function. Not sure whether it will fit here.

Date, Key, Timestamp, Count
2019-05-31, A, 00:00:00, 0
2019-05-31, A, 00:00:01, 0
2019-05-31, A, 00:00:02, 0
.
.
.
2019-05-31, A, 23:59:59, 0
2019-05-31, B, 00:00:00, 0
2019-05-31, B, 00:00:01, 0
2019-05-31, B, 00:00:02, 0
.
.
.
2019-05-31, B, 23:59:59, 0

Body:
This query will produce timestamps required:

 select from_unixtime(unix_timestamp('2019-05-31 00:00:00')+i) as ts
   from (select
               posexplode(split(space(86399),' ')) as (i,x)
        )s

Explanation:

Subquery s generates rows with seconds. If you join with such subquery, for example using cross join (it depends on your initial dataset) you will get each row duplicated 86400 times

space(86399) - produces string of 86399 spaces
split() - produces array spaces
posexplode - explodes array and produces a table of position and element.
Position(i) is in the range 0 - 86399, we will use it as seconds to add to start timestamp

unix_timestamp('2019-05-31 00:00:00') - this gives start timestamp in seconds passed from unix epoch. We are adding seconds (i) to it and converting again to timestamp, in such way we get 1 second incremented timestamp for each row.

Join with it and if you need date and time separately, use substring.

Demo:

For example your initial table contains two rows with timestamps and two keys A and B, you can join it with seconds generating subquery:

with your_table as( --This is initial data example
select stack(2,
'2019-05-31 00:00:00', 'A',
'2019-05-31 00:00:00', 'B'
) as (ts, Key)
)

select min(ts), max(ts), key --aggregated result for the demo
from
(
select from_unixtime(unix_timestamp(t.ts)+i) as ts , t.key
  from your_table t
      cross join (select posexplode(split(space(86399),' ')) as (i,x))s
)s group by key

Result (aggregation added, because it generates too many rows):

min                 max                 key
2019-05-31 00:00:00 2019-05-31 23:59:59 B
2019-05-31 00:00:00 2019-05-31 23:59:59 A


问:
How to open a link in new windows
Good morning
how can I open the link called by the action "URLPAYPAL" in a new window? I tried with onclick = "window.open (); but it doesn't work</p>

```<code>echo "<a href=# class=\"btn btn-lg btn-block btn-inverse\" onclick=\"";
echo "formid = document.getElementById('gest');\n";
echo "document.getElementById('tabdati2').style.display='';\n";
echo "document.getElementById('tabdati1').style.display='none';\n";
echo "document.getElementById('gest').action='" . URLPAYPAL . "';\n";
echo "formid.email.style.backgroundColor ='#FFFFFF';\n";
echo "var ctrlerr = 0;\n";
echo "var regtel = /^(\d+)$/;\n";
echo "var regema =  /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/;\n";
echo "if ((formid.cli.value) != (formid.cli2.value)) {\n";
echo "formid.cli.style.backgroundColor ='#E55B3C';\n";
echo "alert ('Il numero di telefono non coincide!');\n";
echo "ctrlerr=1;\n";
echo "}\n";
echo "if ((formid.cli.value == '') || (formid.cli.value == 'Numero di telefono')) {\n";
echo "formid.cli.style.backgroundColor ='#E55B3C';\n";
echo "alert ('Scrivi il numero di telefono!');\n";
echo "ctrlerr=1;\n";
echo "}\n";
echo "if(!ctrlerr) {\n";
echo "formid.submit();\n";
echo "}\n";
echo "\"> Ricarica<span class=\"fui-arrow-right\"></span> </a>\n";
</code>```

答:
You can do something like this </p>

```<code>window.open(url, '_blank');
</code>```

Title: How to open a link in new windows

Body:
Good morning
how can I open the link called by the action "URLPAYPAL" in a new window? I tried with onclick = "window.open (); but it doesn't work

echo "<a href=# class=\"btn btn-lg btn-block btn-inverse\" onclick=\"";
echo "formid = document.getElementById('gest');\n";
echo "document.getElementById('tabdati2').style.display='';\n";
echo "document.getElementById('tabdati1').style.display='none';\n";
echo "document.getElementById('gest').action='" . URLPAYPAL . "';\n";
echo "formid.email.style.backgroundColor ='#FFFFFF';\n";
echo "var ctrlerr = 0;\n";
echo "var regtel = /^(\d+)$/;\n";
echo "var regema =  /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/;\n";
echo "if ((formid.cli.value) != (formid.cli2.value)) {\n";
echo "formid.cli.style.backgroundColor ='#E55B3C';\n";
echo "alert ('Il numero di telefono non coincide!');\n";
echo "ctrlerr=1;\n";
echo "}\n";
echo "if ((formid.cli.value == '') || (formid.cli.value == 'Numero di telefono')) {\n";
echo "formid.cli.style.backgroundColor ='#E55B3C';\n";
echo "alert ('Scrivi il numero di telefono!');\n";
echo "ctrlerr=1;\n";
echo "}\n";
echo "if(!ctrlerr) {\n";
echo "formid.submit();\n";
echo "}\n";
echo "\"> Ricarica \n";

Body:
You can do something like this

window.open(url, '_blank');


问:
Meteor: SSR necessary to secure admin part of application?
I have my extended user model in the Meteor.users collection, which I'm publishing most fields from to the client. Each user has an isAdmin field, set to false by default.

Now I have two concerns, which are linked:

How to make sure, components meant for admins can only be rendered, if the isAdmin field in the Meteor.users collection is set to true?

How to make sure, the isAdmin field on the Meteor.users collection cannot be modified from the clients console?

Concerning 1.

I'm hesitant to publish this field to the client and simply evaluate isAdmin on the client side.

I'm not sure if there is some hackish way through the console to simply change isAdmin in a way that would allow to render the component (or part of it) that is only meant for admins on the client. I could imagine that it is possible with Object.defineProperty() to do so, for example.

Should I use server-side rendering to secure the admin part of my UI?

Concerning 2.

Consider the first paragraph on Profile editing in this article about common mistakes. It suggests that isAdmin could easily be changed from the client by calling Meteor.users.update(Meteor.userId(), {$set: {'isAdmin': true}}) from the console.

When I run it, being logged in to my application, I get update failed: Access denied though.

But even the official documentation still suggests to add

```<code>// Deny all client-side updates on the Lists collection
Lists.deny({
  insert() { return true; },
  update() { return true; },
  remove() { return true; },
});
</code>```

at https://guide.meteor.com/security.html#allow-deny

There is an answer, suggesting that it's enough to simply check for the isAdmin property on the server side, if you make sure that the Meteor.methods are server-only. But it doesn't talk about allow-deny at all and it's 6 years old.

Can anyone tell, what truly is the case as of today?

答:
Can anyone tell, what truly is the case as of today?

I would not put too much effort to secure the admin ui on the client. A router level redirect when isAdmin is false should be sufficient.*

Way more important here is to secure methods and publications because these are the parts where users can mess around with your application. For those it can't be secure enough:

use ValidatedMethod from mdg:validated-methods for Methods

write a factory function to create Publications similar to mdg:validated-method to allow basic checks in a mixin-style

both: check if the arguments are valid

both: check if the user exists

both: check if the user has sufficient roles -> I recomment alanning:roles as it makes permission level checks more secure as it checks for id-match existence in a dedicated collection rather than checking for a flag in the user collection (plus it decouples the users from the roles!)

Throw fast and a lot: throw on any suspicious inconsistency, try to cover any undefined state with throwing errors.

rate limit using ddp-rate-limiter every method and publication

write a simple sanity check on startup that ensures all methods and publications are rate-limited, you can get all registered methods/publications on the server at Meteor.startup via Meteor.server.method_handlers and Meteor.server.publish_handlers

write test a lot, especially for the admin related methods and try any weird and crazy input you can think of to see if it gets rejected or causes any weird behavior (which you want to avoid)

As far as I understood your question you have currently not integrated ssr and if you follow the above steps you can secure your admin-area of the application a lot without including ssr into your app (which itself can cause a lot of headache due to additional config etc.).

*if you decide to use the recommended alanning:roles package you would be better to also use it on the client to check the user's roles.

Body:
I have my extended user model in the Meteor.users collection, which I'm publishing most fields from to the client. Each user has an isAdmin field, set to false by default.

Now I have two concerns, which are linked:

How to make sure, components meant for admins can only be rendered, if the isAdmin field in the Meteor.users collection is set to true?

How to make sure, the isAdmin field on the Meteor.users collection cannot be modified from the clients console?

Concerning 1.

I'm hesitant to publish this field to the client and simply evaluate isAdmin on the client side.

I'm not sure if there is some hackish way through the console to simply change isAdmin in a way that would allow to render the component (or part of it) that is only meant for admins on the client. I could imagine that it is possible with Object.defineProperty() to do so, for example.

Should I use server-side rendering to secure the admin part of my UI?

Concerning 2.

Consider the first paragraph on Profile editing in this article about common mistakes. It suggests that isAdmin could easily be changed from the client by calling Meteor.users.update(Meteor.userId(), {$set: {'isAdmin': true}}) from the console.

When I run it, being logged in to my application, I get update failed: Access denied though.

But even the official documentation still suggests to add

// Deny all client-side updates on the Lists collection
Lists.deny({
  insert() { return true; },
  update() { return true; },
  remove() { return true; },
});

at https://guide.meteor.com/security.html#allow-deny

There is an answer, suggesting that it's enough to simply check for the isAdmin property on the server side, if you make sure that the Meteor.methods are server-only. But it doesn't talk about allow-deny at all and it's 6 years old.

Can anyone tell, what truly is the case as of today?


问:
Batch file to add a line to multiple .txt files in folders and subfolders
Batch file to add a line to multiple .txt files in folders and subfolders.

I've got the code to work on a specific file if i replace (*.txt) with (specificname.txt) but it will only work in the folder the batch file is present in

```<code>@echo off

set "$New_line=Your text"

for %%a in (*.txt) do (

   echo %$New_line% > "New_%%a"

   type "%%a" >> "New_%%a"

   del "%%a" 2>nul

  ren "New_%%a" "%%a"

)
</code>```

I've got it to work in the folder the batch file is present in but needs extending to search for files within subfolders

expected result will add line to .txt files in both folder and subfolders

答:
There are some quirks in your code (taken from your comment):

ren doesn't support paths in the destination part - filename.ext only.

With for /r, %%a gives a Full Qualified File Name (drive,path,name,extension), so _new%%a results in an invalid FQFN (like _New_C:\folder\subfolder\file.txt)

You can get the needes substrings with modifiers (explained in for /?)

Minor improvements:

put quotes around any path or filename

swiched to another redirection syntax for the echo command to avoid trailing spaces.

```<code>@echo off
set "$New_line=Your text"
for /R "C:\folder\" %%A in (*.txt) do (
  > "%%~dpANew_%%~nxA" echo %$New_line%
  type "%%A" >> "%%~dpANew_%%~nxA"
  del "%%A" 2>nul
  ren "%%~dpANew_%%~nxA" "%%~nxA"
)
</code>```

Body:
Batch file to add a line to multiple .txt files in folders and subfolders.

I've got the code to work on a specific file if i replace (*.txt) with (specificname.txt) but it will only work in the folder the batch file is present in

@echo off

set "$New_line=Your text"

for %%a in (*.txt) do (

   echo %$New_line% > "New_%%a"

   type "%%a" >> "New_%%a"

   del "%%a" 2>nul

  ren "New_%%a" "%%a"

)

I've got it to work in the folder the batch file is present in but needs extending to search for files within subfolders

expected result will add line to .txt files in both folder and subfolders

Body:
There are some quirks in your code (taken from your comment):

ren doesn't support paths in the destination part - filename.ext only.

With for /r, %%a gives a Full Qualified File Name (drive,path,name,extension), so _new%%a results in an invalid FQFN (like _New_C:\folder\subfolder\file.txt)

You can get the needes substrings with modifiers (explained in for /?)

Minor improvements:

put quotes around any path or filename

swiched to another redirection syntax for the echo command to avoid trailing spaces.

@echo off
set "$New_line=Your text"
for /R "C:\folder\" %%A in (*.txt) do (
  > "%%~dpANew_%%~nxA" echo %$New_line%
  type "%%A" >> "%%~dpANew_%%~nxA"
  del "%%A" 2>nul
  ren "%%~dpANew_%%~nxA" "%%~nxA"
)


问:
filtering the keys and reducing into nested structure
I have a below data structure from it i need extract the columns which is an array an i need to build an object with key and actual label name.

Is there any better way to achieve this.

Any help appreciated

    let data = {
      "section1": {
        "forms": [
          {
            "fields": [
              {
                "columnName": "test1",
                "label": [
                  {
                    "actualLabel": "Test 1"
                  }
                ]
              },
              {
                "columnName": "test2",
                "label": [
                  {
                    "actualLabel": "Test 2"
                  }
                ]
              },
              {
                "columnName": "test0",
                "label": [
                  {
                    "actualLabel": "Test 0"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test6",
                "label": [
                  {
                    "actualLabel": "Test 6"
                  }
                ]
              },
              {
                "columnName": "test3",
                "label": [
                  {
                    "actualLabel": "Test 3"
                  }
                ]
              },
              {
                "columnName": "test10",
                "label": [
                  {
                    "actualLabel": "Test 10"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test15",
                "label": [
                  {
                    "actualLabel": "Test 15"
                  }
                ]
              },
              {
                "columnName": "test",
                "label": [
                  {
                    "actualLabel": "Test 6"
                  }
                ]
              },
              {
                "columnName": "test7",
                "label": [
                  {
                    "actualLabel": "Test 7"
                  }
                ]
              }
            ]
          }
        ]
      },
      "section2": {
        "forms": [
          {
            "fields": [
              {
                "columnName": "test1",
                "label": [
                  {
                    "actualLabel": "Test 1"
                  }
                ]
              },
              {
                "columnName": "test2",
                "label": [
                  {
                    "actualLabel": "Test 2"
                  }
                ]
              },
              {
                "columnName": "test0",
                "label": [
                  {
                    "actualLabel": "Test 0"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test3",
                "label": [
                  {
                    "actualLabel": "Test 3"
                  }
                ]
              },
              {
                "columnName": "test4",
                "label": [
                  {
                    "actualLabel": "Test 4"
                  }
                ]
              },
              {
                "columnName": "test10",
                "label": [
                  {
                    "actualLabel": "Test 10"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test5",
                "label": [
                  {
                    "actualLabel": "Test 5"
                  }
                ]
              },
              {
                "columnName": "test6",
                "label": [
                  {
                    "actualLabel": "Test 6"
                  }
                ]
              },
              {
                "columnName": "test7",
                "label": [
                  {
                    "actualLabel": "Test 7"
                  }
                ]
              }
            ]
          }
        ]
      },
      "section3": {
        "forms": [
          {
            "fields": [
              {
                "columnName": "test1",
                "label": [
                  {
                    "actualLabel": "Test 1"
                  }
                ]
              },
              {
                "columnName": "test2",
                "label": [
                  {
                    "actualLabel": "Test 2"
                  }
                ]
              },
              {
                "columnName": "test0",
                "label": [
                  {
                    "actualLabel": "Test 0"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test3",
                "label": [
                  {
                    "actualLabel": "Test 3"
                  }
                ]
              },
              {
                "columnName": "test 4",
                "label": [
                  {
                    "actualLabel": "Test 4"
                  }
                ]
              },
              {
                "columnName": "test10",
                "label": [
                  {
                    "actualLabel": "Test 10"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test15",
                "label": [
                  {
                    "actualLabel": "Test 15"
                  }
                ]
              },
              {
                "columnName": "test6",
                "label": [
                  {
                    "actualLabel": "Test 6"
                  }
                ]
              },
              {
                "columnName": "test7",
                "label": [
                  {
                    "actualLabel": "Test 7"
                  }
                ]
              }
            ]
          }
        ]
      }
    }

    let extractColumns = ['test1', 'test2', 'test7', 'test15']

   let result = Object.entries(data).reduce(
          (initial, [key, { forms }]) => {
            forms.forEach(({ fields }) => {
              fields.forEach(
                ({
                  columnName,
                  label: {
                    0: { actualLabel },
                  },
                }) => {
                  if (extractColumns.indexOf(columnName) > -1) {
                    initial[columnName] = {
                      actualLabel,
                    };
                  }
                },
              );
            });
            return initial;
          },
          {},
        );

console.log(result)```

答:
Another option is to get an array of fields using flatMap and then filter them to get the output. You could create a Set instead of an array of columns since Set#has is much faster than includes

let data={"section1":{"forms":[{"fields":[{"columnName":"test1","label":[{"actualLabel":"Test 1"}]},{"columnName":"test2","label":[{"actualLabel":"Test 2"}]},{"columnName":"test0","label":[{"actualLabel":"Test 0"}]}]},{"fields":[{"columnName":"test6","label":[{"actualLabel":"Test 6"}]},{"columnName":"test3","label":[{"actualLabel":"Test 3"}]},{"columnName":"test10","label":[{"actualLabel":"Test 10"}]}]},{"fields":[{"columnName":"test15","label":[{"actualLabel":"Test 15"}]},{"columnName":"test","label":[{"actualLabel":"Test 6"}]},{"columnName":"test7","label":[{"actualLabel":"Test 7"}]}]}]},"section2":{"forms":[{"fields":[{"columnName":"test1","label":[{"actualLabel":"Test 1"}]},{"columnName":"test2","label":[{"actualLabel":"Test 2"}]},{"columnName":"test0","label":[{"actualLabel":"Test 0"}]}]},{"fields":[{"columnName":"test3","label":[{"actualLabel":"Test 3"}]},{"columnName":"test4","label":[{"actualLabel":"Test 4"}]},{"columnName":"test10","label":[{"actualLabel":"Test 10"}]}]},{"fields":[{"columnName":"test5","label":[{"actualLabel":"Test 5"}]},{"columnName":"test6","label":[{"actualLabel":"Test 6"}]},{"columnName":"test7","label":[{"actualLabel":"Test 7"}]}]}]},"section3":{"forms":[{"fields":[{"columnName":"test1","label":[{"actualLabel":"Test 1"}]},{"columnName":"test2","label":[{"actualLabel":"Test 2"}]},{"columnName":"test0","label":[{"actualLabel":"Test 0"}]}]},{"fields":[{"columnName":"test3","label":[{"actualLabel":"Test 3"}]},{"columnName":"test 4","label":[{"actualLabel":"Test 4"}]},{"columnName":"test10","label":[{"actualLabel":"Test 10"}]}]},{"fields":[{"columnName":"test15","label":[{"actualLabel":"Test 15"}]},{"columnName":"test6","label":[{"actualLabel":"Test 6"}]},{"columnName":"test7","label":[{"actualLabel":"Test 7"}]}]}]}}

let extractColumns = new Set(['test1', 'test2', 'test7', 'test15'])

const output = Object.values(data).reduce((acc, { forms }) => {
  forms.flatMap(a => a.fields)
        .filter(f => extractColumns.has(f.columnName))
        .forEach(({ columnName, label: [o] }) => acc[columnName] = o)

  return acc;
}, {})

console.log(output)```

(I haven't checked if it's faster than what you already have)

Body:
Another option is to get an array of fields using flatMap and then filter them to get the output. You could create a Set instead of an array of columns since Set#has is much faster than includes

let data={"section1":{"forms":[{"fields":[{"columnName":"test1","label":[{"actualLabel":"Test 1"}]},{"columnName":"test2","label":[{"actualLabel":"Test 2"}]},{"columnName":"test0","label":[{"actualLabel":"Test 0"}]}]},{"fields":[{"columnName":"test6","label":[{"actualLabel":"Test 6"}]},{"columnName":"test3","label":[{"actualLabel":"Test 3"}]},{"columnName":"test10","label":[{"actualLabel":"Test 10"}]}]},{"fields":[{"columnName":"test15","label":[{"actualLabel":"Test 15"}]},{"columnName":"test","label":[{"actualLabel":"Test 6"}]},{"columnName":"test7","label":[{"actualLabel":"Test 7"}]}]}]},"section2":{"forms":[{"fields":[{"columnName":"test1","label":[{"actualLabel":"Test 1"}]},{"columnName":"test2","label":[{"actualLabel":"Test 2"}]},{"columnName":"test0","label":[{"actualLabel":"Test 0"}]}]},{"fields":[{"columnName":"test3","label":[{"actualLabel":"Test 3"}]},{"columnName":"test4","label":[{"actualLabel":"Test 4"}]},{"columnName":"test10","label":[{"actualLabel":"Test 10"}]}]},{"fields":[{"columnName":"test5","label":[{"actualLabel":"Test 5"}]},{"columnName":"test6","label":[{"actualLabel":"Test 6"}]},{"columnName":"test7","label":[{"actualLabel":"Test 7"}]}]}]},"section3":{"forms":[{"fields":[{"columnName":"test1","label":[{"actualLabel":"Test 1"}]},{"columnName":"test2","label":[{"actualLabel":"Test 2"}]},{"columnName":"test0","label":[{"actualLabel":"Test 0"}]}]},{"fields":[{"columnName":"test3","label":[{"actualLabel":"Test 3"}]},{"columnName":"test 4","label":[{"actualLabel":"Test 4"}]},{"columnName":"test10","label":[{"actualLabel":"Test 10"}]}]},{"fields":[{"columnName":"test15","label":[{"actualLabel":"Test 15"}]},{"columnName":"test6","label":[{"actualLabel":"Test 6"}]},{"columnName":"test7","label":[{"actualLabel":"Test 7"}]}]}]}}

let extractColumns = new Set(['test1', 'test2', 'test7', 'test15'])

const output = Object.values(data).reduce((acc, { forms }) => {
  forms.flatMap(a => a.fields)
        .filter(f => extractColumns.has(f.columnName))
        .forEach(({ columnName, label: [o] }) => acc[columnName] = o)

  return acc;
}, {})

console.log(output)

(I haven't checked if it's faster than what you already have)