问:
Calling a function from within v-bind:style doesn't trigger an update to the view
I have a list of images(like a gallery). A longpress(i'm using Nativescript-vue) on a picture will change the style of the image, and make it appear "selected". This is the image:

```<code><ListView layout="grid" ref="backedupImages" for="image in sortedBackedupImages">
      <v-template>
        <ImageComponent
          v-bind:style="{backgroundColor:isSelected(image.identifier) ? 'cyan' : 'white'}"
          :onLongPress="()=>{onLongPress(image.identifier)}"
          :onShortPress="()=>{onShortPress(image.identifier)}"
          :image="image"
        ></ImageComponent>
      </v-template>
    </ListView>
</code>```

As you can see, i'm calling some "isSelected" method, to check if the image is selected or not. The method sits in a mixin:

```<code>isSelected(identifier){
            const isSelected = this.selectedImages.includes(identifier);
            return isSelected
        }
</code>```

This is the onLongPress method, which toggles the image selection state:

```<code>onLongPress(identifier) {
            if(this.selectedImages.includes(identifier)){
                const index = this.selectedImages.indexOf(identifier);
                this.$delete(this.selectedImages,index);
            }else{
                const index = this.selectedImages.length;
                this.$set(this.selectedImages,index,identifier);
            }
        },
</code>```

The array manipulation seems to work, but i do not get any view reactivity. What could be the problem? Is there a better approach for this in Vue? I don't think i can use a computed property, being that i need to pass an argument to the "computation".

答:
The issue you're having is that a v-for loop on ListView will not behave as expected. This issue is described in the nativescript-vue documentation:

<ListView> does not loop through list items as you would expect when using a v-for loop. Instead <ListView> only creates the necessary views to display the currently visible items on the screen, and reuses the views that are already off-screen when scrolled. This concept is called view recycling and is commonly used in mobile apps to improve performance.

This is important because you can't rely on event listeners attached inside the v-template. Instead, you need to use the itemTap event which contains the index of the tapped item and the actual item from the list.

onItemTap(event) {

console.log(event.index)

console.log(event.item)

}

Body:
I have a list of images(like a gallery). A longpress(i'm using Nativescript-vue) on a picture will change the style of the image, and make it appear "selected". This is the image:

<ListView layout="grid" ref="backedupImages" for="image in sortedBackedupImages">
      <v-template>
        <ImageComponent
          v-bind:style="{backgroundColor:isSelected(image.identifier) ? 'cyan' : 'white'}"
          :onLongPress="()=>{onLongPress(image.identifier)}"
          :onShortPress="()=>{onShortPress(image.identifier)}"
          :image="image"
        ></ImageComponent>
      </v-template>
    </ListView>

As you can see, i'm calling some "isSelected" method, to check if the image is selected or not. The method sits in a mixin:

isSelected(identifier){
            const isSelected = this.selectedImages.includes(identifier);
            return isSelected
        }

This is the onLongPress method, which toggles the image selection state:

onLongPress(identifier) {
            if(this.selectedImages.includes(identifier)){
                const index = this.selectedImages.indexOf(identifier);
                this.$delete(this.selectedImages,index);
            }else{
                const index = this.selectedImages.length;
                this.$set(this.selectedImages,index,identifier);
            }
        },

The array manipulation seems to work, but i do not get any view reactivity. What could be the problem? Is there a better approach for this in Vue? I don't think i can use a computed property, being that i need to pass an argument to the "computation".


来源: stackexchange

问:
Why hover selector doesn't work with clases?
I have set the styles for  links (active, link, etc), but then I want to do a button with totally different styles so I tried something like this:

.r-button { padding: 4px 52px; display: inline-block; text-align: center; font-size: 16px; text-decoration: none !important; color: black !important; border-radius: 12px; border:1px inset #282c37;}

.r-button:hover { cursor: selector; color:ivory;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  Click button </code>```

But then I realized that :hover doesn't work with clases. Why is that? What others chances do I have to do the same?

答:
It does, your color: black !important; is overriding the hover and that selector isn't a valid cursor. Try pointer on hover.

```<code>.r-button:hover { cursor: pointer; }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have set the styles for  links (active, link, etc), but then I want to do a button with totally different styles so I tried something like this:

.r-button { padding: 4px 52px; display: inline-block; text-align: center; font-size: 16px; text-decoration: none !important; color: black !important; border-radius: 12px; border:1px inset #282c37;}

.r-button:hover { cursor: selector; color:ivory;}

  Click button

But then I realized that :hover doesn't work with clases. Why is that? What others chances do I have to do the same?

Body:
It does, your color: black !important; is overriding the hover and that selector isn't a valid cursor. Try pointer on hover.

.r-button:hover { cursor: pointer; }


问:
Failed to delete the state directory in IDE for Kafka Stream Application
I am developing a simple Kafka Stream application which extracting messages from a topic and put it into another topic after transformation. I am using Intelij for my development.

When I debug/run this application, it works perfect if my IDE and the Kafka Server sitting in the SAME machine

(i.e. with the BOOTSTRAP_SERVERS_CONFIG = localhost:9092 and
  SCHEMA_REGISTRY_URL_CONFIG = localhost:8081)

However, when I try to use another machine to do the development

(i.e. with the BOOTSTRAP_SERVERS_CONFIG = XXX.XXX.XXX:9092 and
  SCHEMA_REGISTRY_URL_CONFIG = XXX.XXX.XXX:8081 where XXX.XXX.XXX is the
  ip address of my Kafka),

the debug process run without problem at the 1st time. However, when I run 2nd time after resetting the offset, I received the following error:

```<code>ERROR stream-thread [main] Failed to delete the state directory. (org.apache.kafka.streams.processor.internals.StateDirectory:297)
java.nio.file.DirectoryNotEmptyException: \tmp\kafka-streams\my_application_id\0_0
Exception in thread "main" org.apache.kafka.streams.errors.StreamsException: java.nio.file.DirectoryNotEmptyException:
</code>```

If I changed my_application_id as my_application_id2, and run it, it works again at the 1st time but receiving error again if I run it again.

I have the following code in my last sentence in my application:

```<code>Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
</code>```

Any advice how to solve this problem?

UPDATE:

I have reviewed the state directory created in my development machine (Windows Platform) and if I delete these directory manually before running 2nd time, no error found. I have tried to run my IDE as Administrator because I think this could be something about the permission on the folder. However, this doesn't help.

Full stack for reference:

INFO Kafka version : 1.1.0 (org.apache.kafka.common.utils.AppInfoParser:109)
  INFO Kafka commitId : fdcf75ea326b8e07 (org.apache.kafka.common.utils.AppInfoParser:110)
  INFO stream-thread [main] Deleting state directory 0_0 for task 0_0 as user calling cleanup. (org.apache.kafka.streams.processor.internals.StateDirectory:281)
  Disconnected from the target VM, address: '127.0.0.1:16552', transport: 'socket'
  Exception in thread "main" org.apache.kafka.streams.errors.StreamsException: java.nio.file.DirectoryNotEmptyException: C:\workspace\bennychan\kafka-streams\my_application_001\0_0
      at org.apache.kafka.streams.processor.internals.StateDirectory.clean(StateDirectory.java:231)
      at org.apache.kafka.streams.KafkaStreams.cleanUp(KafkaStreams.java:931)
      at com.macroviewhk.financialreport.simpleStream.start(simpleStream.java:60)
      at com.macroviewhk.financialreport.simpleStream.main(simpleStream.java:45)
  Caused by: java.nio.file.DirectoryNotEmptyException: C:\workspace\bennychan\kafka-streams\my_application_001\0_0
      at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:266)
      at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103)
      at java.nio.file.Files.delete(Files.java:1126)
      at org.apache.kafka.common.utils.Utils$1.postVisitDirectory(Utils.java:651)
      at org.apache.kafka.common.utils.Utils$1.postVisitDirectory(Utils.java:634)
      at java.nio.file.Files.walkFileTree(Files.java:2688)
      at java.nio.file.Files.walkFileTree(Files.java:2742)
      at org.apache.kafka.common.utils.Utils.delete(Utils.java:634)
  ERROR stream-thread [main] Failed to delete the state directory. (org.apache.kafka.streams.processor.internals.StateDirectory:297)
      at org.apache.kafka.streams.processor.internals.StateDirectory.cleanRemovedTasks(StateDirectory.java:287)
  java.nio.file.DirectoryNotEmptyException: C:\workspace\bennychan\kafka-streams\my_application_001\0_0
      at org.apache.kafka.streams.processor.internals.StateDirectory.clean(StateDirectory.java:228)
      at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:266)
      ... 3 more
      at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103)
      at java.nio.file.Files.delete(Files.java:1126)
      at org.apache.kafka.common.utils.Utils$1.postVisitDirectory(Utils.java:651)
      at org.apache.kafka.common.utils.Utils$1.postVisitDirectory(Utils.java:634)
      at java.nio.file.Files.walkFileTree(Files.java:2688)
      at java.nio.file.Files.walkFileTree(Files.java:2742)
      at org.apache.kafka.common.utils.Utils.delete(Utils.java:634)
      at org.apache.kafka.streams.processor.internals.StateDirectory.cleanRemovedTasks(StateDirectory.java:287)
      at org.apache.kafka.streams.processor.internals.StateDirectory.clean(StateDirectory.java:228)
      at org.apache.kafka.streams.KafkaStreams.cleanUp(KafkaStreams.java:931)
      at com.macroviewhk.financialreport.simpleStream.start(simpleStream.java:60)
      at com.macroviewhk.financialreport.simpleStream.main(simpleStream.java:45)

UPDATE 2 :
After another detailed check, the line below throwing IOException

```<code>Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
</code>```

This line is located at kafka-clients-1.1.0.jar org.apache.kafka.common.utilsUtils.class

May be this is the problem with Windows system (sorry that I am not an experienced JAVA programmer).

答:
For googlers..

I'm currently using this Scala code for helping windows guys to handle deletion of state store.

```<code>if (System.getProperty("os.name").toLowerCase.contains("windows")) {
  logger.info("WINDOWS OS MODE - Cleanup state store.")
  try {
    FileUtils.deleteDirectory(new File("/tmp/kafka-streams/" + config.getProperty("application.id")))
    FileUtils.forceMkdir(new File("/tmp/kafka-streams/" + config.getProperty("application.id")))
  } catch {
    case e: Exception => logger.error(e.toString)
  }
}
else {
  streams.cleanUp()
}
</code>```

Body:
I am developing a simple Kafka Stream application which extracting messages from a topic and put it into another topic after transformation. I am using Intelij for my development.

When I debug/run this application, it works perfect if my IDE and the Kafka Server sitting in the SAME machine

(i.e. with the BOOTSTRAP_SERVERS_CONFIG = localhost:9092 and
  SCHEMA_REGISTRY_URL_CONFIG = localhost:8081)

However, when I try to use another machine to do the development

(i.e. with the BOOTSTRAP_SERVERS_CONFIG = XXX.XXX.XXX:9092 and
  SCHEMA_REGISTRY_URL_CONFIG = XXX.XXX.XXX:8081 where XXX.XXX.XXX is the
  ip address of my Kafka),

the debug process run without problem at the 1st time. However, when I run 2nd time after resetting the offset, I received the following error:

ERROR stream-thread [main] Failed to delete the state directory. (org.apache.kafka.streams.processor.internals.StateDirectory:297)
java.nio.file.DirectoryNotEmptyException: \tmp\kafka-streams\my_application_id\0_0
Exception in thread "main" org.apache.kafka.streams.errors.StreamsException: java.nio.file.DirectoryNotEmptyException:

If I changed my_application_id as my_application_id2, and run it, it works again at the 1st time but receiving error again if I run it again.

I have the following code in my last sentence in my application:

Runtime.getRuntime().addShutdownHook(new Thread(streams::close));

Any advice how to solve this problem?

UPDATE:

I have reviewed the state directory created in my development machine (Windows Platform) and if I delete these directory manually before running 2nd time, no error found. I have tried to run my IDE as Administrator because I think this could be something about the permission on the folder. However, this doesn't help.

Full stack for reference:

INFO Kafka version : 1.1.0 (org.apache.kafka.common.utils.AppInfoParser:109)
  INFO Kafka commitId : fdcf75ea326b8e07 (org.apache.kafka.common.utils.AppInfoParser:110)
  INFO stream-thread [main] Deleting state directory 0_0 for task 0_0 as user calling cleanup. (org.apache.kafka.streams.processor.internals.StateDirectory:281)
  Disconnected from the target VM, address: '127.0.0.1:16552', transport: 'socket'
  Exception in thread "main" org.apache.kafka.streams.errors.StreamsException: java.nio.file.DirectoryNotEmptyException: C:\workspace\bennychan\kafka-streams\my_application_001\0_0
      at org.apache.kafka.streams.processor.internals.StateDirectory.clean(StateDirectory.java:231)
      at org.apache.kafka.streams.KafkaStreams.cleanUp(KafkaStreams.java:931)
      at com.macroviewhk.financialreport.simpleStream.start(simpleStream.java:60)
      at com.macroviewhk.financialreport.simpleStream.main(simpleStream.java:45)
  Caused by: java.nio.file.DirectoryNotEmptyException: C:\workspace\bennychan\kafka-streams\my_application_001\0_0
      at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:266)
      at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103)
      at java.nio.file.Files.delete(Files.java:1126)
      at org.apache.kafka.common.utils.Utils$1.postVisitDirectory(Utils.java:651)
      at org.apache.kafka.common.utils.Utils$1.postVisitDirectory(Utils.java:634)
      at java.nio.file.Files.walkFileTree(Files.java:2688)
      at java.nio.file.Files.walkFileTree(Files.java:2742)
      at org.apache.kafka.common.utils.Utils.delete(Utils.java:634)
  ERROR stream-thread [main] Failed to delete the state directory. (org.apache.kafka.streams.processor.internals.StateDirectory:297)
      at org.apache.kafka.streams.processor.internals.StateDirectory.cleanRemovedTasks(StateDirectory.java:287)
  java.nio.file.DirectoryNotEmptyException: C:\workspace\bennychan\kafka-streams\my_application_001\0_0
      at org.apache.kafka.streams.processor.internals.StateDirectory.clean(StateDirectory.java:228)
      at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:266)
      ... 3 more
      at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103)
      at java.nio.file.Files.delete(Files.java:1126)
      at org.apache.kafka.common.utils.Utils$1.postVisitDirectory(Utils.java:651)
      at org.apache.kafka.common.utils.Utils$1.postVisitDirectory(Utils.java:634)
      at java.nio.file.Files.walkFileTree(Files.java:2688)
      at java.nio.file.Files.walkFileTree(Files.java:2742)
      at org.apache.kafka.common.utils.Utils.delete(Utils.java:634)
      at org.apache.kafka.streams.processor.internals.StateDirectory.cleanRemovedTasks(StateDirectory.java:287)
      at org.apache.kafka.streams.processor.internals.StateDirectory.clean(StateDirectory.java:228)
      at org.apache.kafka.streams.KafkaStreams.cleanUp(KafkaStreams.java:931)
      at com.macroviewhk.financialreport.simpleStream.start(simpleStream.java:60)
      at com.macroviewhk.financialreport.simpleStream.main(simpleStream.java:45)

UPDATE 2 :
After another detailed check, the line below throwing IOException

Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {

This line is located at kafka-clients-1.1.0.jar org.apache.kafka.common.utilsUtils.class

May be this is the problem with Windows system (sorry that I am not an experienced JAVA programmer).

Body:
For googlers..

I'm currently using this Scala code for helping windows guys to handle deletion of state store.

if (System.getProperty("os.name").toLowerCase.contains("windows")) {
  logger.info("WINDOWS OS MODE - Cleanup state store.")
  try {
    FileUtils.deleteDirectory(new File("/tmp/kafka-streams/" + config.getProperty("application.id")))
    FileUtils.forceMkdir(new File("/tmp/kafka-streams/" + config.getProperty("application.id")))
  } catch {
    case e: Exception => logger.error(e.toString)
  }
}
else {
  streams.cleanUp()
}


答:
You will need to either REMOVE !important from your color in .r-button or add it to .r-button:hover 's color

.r-button { padding: 4px 52px; display: inline-block; text-align: center; font-size: 16px; text-decoration: none !important; color: black !important; border-radius: 12px; border:1px inset #282c37;}

.r-button:hover { cursor: selector; color:ivory !important;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  Click button </code>```

Title: Why hover selector doesn't work with clases?

Body:
You will need to either REMOVE !important from your color in .r-button or add it to .r-button:hover 's color

.r-button { padding: 4px 52px; display: inline-block; text-align: center; font-size: 16px; text-decoration: none !important; color: black !important; border-radius: 12px; border:1px inset #282c37;}

.r-button:hover { cursor: selector; color:ivory !important;}

<a class="r-button" onclick="document.getElementById('menu').style.display='block'">  Click button </a>


问:
Prettier and eslint indents not working together
I traying setup my vim based typescript developing environment, but have an issue with indent management.

Probably 'eslint' says: indent: Expected indentation of 2 spaces but found 4. after prettier reformat.

My .eslintrc.js:

```<code>module.exports = {
  parser: '@typescript-eslint/parser', // Specifies the ESLint parser
  extends: [
    'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react
    'plugin:@typescript-eslint/recommended', // Uses the recommended rules from @typescript-eslint/eslint-plugin
    'prettier/@typescript-eslint',
    'plugin:prettier/recommended',
  ],
  parserOptions: {
    ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
    sourceType: 'module', // Allows for the use of imports
    ecmaFeatures: {
      jsx: true, // Allows for the parsing of JSX
      tsx: true, // Allows for the parsing of TSX ???
    },
  },
  rules: {
    indent: ['error', 2],
    quotes: ['error', 'single'],
    semi: ['error', 'never'],
    'sort-keys': ['error', 'asc', { caseSensitive: true, natural: false }],
  },
}
</code>```

My .prettierc:

```<code> module.exports = {
  semi: false,
  trailingComma: 'all',
  singleQuote: true,
  printWidth: 80,
  tabWidth: 2,
};
</code>```

答:
This should fix it https://github.com/prettier/eslint-config-prettier

It disables rules in eslint that conflict with prettier.

```<code>npm install --save-dev eslint-config-prettier
</code>```

in your .eslintrc.* file put last "prettier" to extends section

```<code>"extends": [
         //"some-other-config-you-use",
         "prettier"
      ],
</code>```

Body:
I traying setup my vim based typescript developing environment, but have an issue with indent management.

Probably 'eslint' says: indent: Expected indentation of 2 spaces but found 4. after prettier reformat.

My .eslintrc.js:

module.exports = {
  parser: '@typescript-eslint/parser', // Specifies the ESLint parser
  extends: [
    'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react
    'plugin:@typescript-eslint/recommended', // Uses the recommended rules from @typescript-eslint/eslint-plugin
    'prettier/@typescript-eslint',
    'plugin:prettier/recommended',
  ],
  parserOptions: {
    ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
    sourceType: 'module', // Allows for the use of imports
    ecmaFeatures: {
      jsx: true, // Allows for the parsing of JSX
      tsx: true, // Allows for the parsing of TSX ???
    },
  },
  rules: {
    indent: ['error', 2],
    quotes: ['error', 'single'],
    semi: ['error', 'never'],
    'sort-keys': ['error', 'asc', { caseSensitive: true, natural: false }],
  },
}

My .prettierc:

 module.exports = {
  semi: false,
  trailingComma: 'all',
  singleQuote: true,
  printWidth: 80,
  tabWidth: 2,
};

Body:
This should fix it https://github.com/prettier/eslint-config-prettier

It disables rules in eslint that conflict with prettier.

npm install --save-dev eslint-config-prettier

in your .eslintrc.* file put last "prettier" to extends section

"extends": [
         //"some-other-config-you-use",
         "prettier"
      ],


问:
RxJs - Can I use a BehaviorSubject to create a timer?
I created a time loader that I can stop and restart using observable interval:

```<code>   start(time) {

    this.max = time;
    this.intervalObs = Observable.interval(time)
      .takeWhile(_ => !this.isFinished)
      .do(i =>{this.current += 1 ; console.log(this.current);} )
     this.intervalSub$ = this.intervalObs.subscribe();
  }

  finish() {
    this.intervalSub$.unsubscribe();
  }
</code>```

and I want to do the exact same thing using behavior subjects. Is it possible and how ?

答:
If you have a subjected called finalise you can complete the observable with that</p>

```<code>finalise = new Subject();

this.intervalObs.pipe(takeUntil(this.finalise)).subscribe();

finish() {
  // When finalise emits the other observable completes
  this.finalise.next();
}
</code>```

Body:
I created a time loader that I can stop and restart using observable interval:

   start(time) {

    this.max = time;
    this.intervalObs = Observable.interval(time)
      .takeWhile(_ => !this.isFinished)
      .do(i =>{this.current += 1 ; console.log(this.current);} )
     this.intervalSub$ = this.intervalObs.subscribe();
  }

  finish() {
    this.intervalSub$.unsubscribe();
  }

and I want to do the exact same thing using behavior subjects. Is it possible and how ?

Body:
If you have a subjected called finalise you can complete the observable with that

finalise = new Subject();

this.intervalObs.pipe(takeUntil(this.finalise)).subscribe();

finish() {
  // When finalise emits the other observable completes
  this.finalise.next();
}


问:
Creating an XML file, via SimpleXML & simple_html_dom
Hope the title was OK.

My problem is that I want to generate an XML file, which contains all the ISO 4217 currencies, including their name, code and countries they are used in.

To do this I'm using simple_html_dom to grab the HTML, and select specific data from the page. Then using SimpleXML to construct the XML. I would like the output like so:

```<code><currency>
    <code>USD</code>
    <name>United States Dollars</name>
    <location>United States of America</location>
</currency>
</code>```

At the moment I can populate the code for all the codes, but cannot get the names or locations as well as the codes wrapped in currency

Here is the current code I have, the second for loop returns the names of the currency, but I can't figure out how to place this below the code tag within currency:

```<code><?php

//Source: simplehtmldom.sourceforge.net
require('simple_html_dom.php');

//177 currencies
//set URL to parse
$url = "http://en.wikipedia.org/wiki/ISO_4217";
$html = file_get_html($url);
//find all <td> elements that are nested within <table class="wikitable"><tr> and put them into an array
$content = $html->find('table.wikitable tr td');

$newsXML = new SimpleXMLElement("<currencies></currencies>");
$newsXML->addAttribute('type', 'ISO_4217');
Header('Content-type: text/xml');

//loop to add each currency code in <currency><code>HERE</code></currency>
//this loop gets all the codes of the currencies
for($i = 0; $i <= 885; $i += 5){
    $currency = $newsXML->addChild('currency');
    $code = $currency->addChild('code',strip_tags($content[$i]));
}
//this loop gets all the names of the currencies
for($n = 3; $n <= 531; $n += 5){
    $name = $currency->addChild('name',strip_tags($content[$n]));
}

//echo the XML
echo $newsXML->asXML();

?>
</code>```

I have only started learning PHP a month or so back, so would appreciate any advice, or a point in the correct direction.

(Hope the formatting/title naming convention is OK).

答:
Your problem is that the $currency in the second loop is static, resulting in something like

```<code><currency>
  <code>foo</code>
</currency>
<currency>
  <code>bar</code>
</currency>
<currency>
  <code>baz</code>
  <name>nfoo</name>
  <name>nbar</name>
  <name>nbaz</name>
</currency>
</code>```

You need to add both name and code to the same $currency object.

ContentLicense: CC BY-SA 2.5

Body:
Hope the title was OK.

My problem is that I want to generate an XML file, which contains all the ISO 4217 currencies, including their name, code and countries they are used in.

To do this I'm using simple_html_dom to grab the HTML, and select specific data from the page. Then using SimpleXML to construct the XML. I would like the output like so:

<currency>
    USD
    <name>United States Dollars</name>
    <location>United States of America</location>
</currency>

At the moment I can populate the code for all the codes, but cannot get the names or locations as well as the codes wrapped in currency

Here is the current code I have, the second for loop returns the names of the currency, but I can't figure out how to place this below the code tag within currency:

<?php

//Source: simplehtmldom.sourceforge.net
require('simple_html_dom.php');

//177 currencies
//set URL to parse
$url = "http://en.wikipedia.org/wiki/ISO_4217";
$html = file_get_html($url);
//find all  elements that are nested within

 and put them into an array
$content = $html->find('table.wikitable tr td');

$newsXML = new SimpleXMLElement("<currencies></currencies>");
$newsXML->addAttribute('type', 'ISO_4217');
Header('Content-type: text/xml');

//loop to add each currency code in <currency>HERE</currency>
//this loop gets all the codes of the currencies
for($i = 0; $i <= 885; $i += 5){
    $currency = $newsXML->addChild('currency');
    $code = $currency->addChild('code',strip_tags($content[$i]));
}
//this loop gets all the names of the currencies
for($n = 3; $n <= 531; $n += 5){
    $name = $currency->addChild('name',strip_tags($content[$n]));
}

//echo the XML
echo $newsXML->asXML();

?>

I have only started learning PHP a month or so back, so would appreciate any advice, or a point in the correct direction.

(Hope the formatting/title naming convention is OK).

Body:
Your problem is that the $currency in the second loop is static, resulting in something like

<currency>
  <code>foo</code>
</currency>
<currency>
  <code>bar</code>
</currency>
<currency>
  <code>baz</code>
  <name>nfoo</name>
  <name>nbar</name>
  <name>nbaz</name>
</currency>

You need to add both name and code to the same $currency object.

ContentLicense: CC BY-SA 3.0


问:
Performing an update on the path '_id' would modify the immutable field '_id'
I am trying to UPDATE fields in mongo database. However, I get the hollowing error.

MongoError: Performing an update on the path '_id' would modify the
  immutable field '_id'

My Code to update.

```<code>app.put("/api/inventory/:sku", (req, res, next) => {
  const inventory = new Inventory({
    _id: req.body.id,
    sku: req.body.sku,
    total_qty: req.body.total_qty,
    current_qty: req.body.current_qty
  });
  Inventory.updateOne({ sku: req.params.sku }, req.body).then(result => {
    res.status(200).json({ message: "Update successful!" });
  });
});
</code>```

答:
It seems you only need to update one Inventory record. You can simply do this:

```<code>app.put("/api/inventory/:sku", (req, res, next) => {
  return Inventory.updateOne(
    { sku: req.params.sku },  // <-- find stage
    { $set: {                // <-- set stage
       id: req.body.id,     // <-- id not _id
       sku: req.body.sku,
       total_qty: req.body.total_qty,
       current_qty: req.body.current_qty
      }
    }
  ).then(result => {
    res.status(200).json({ message: "Update successful!" });
  });
});
</code>```

There is no need to create new Inventory etc since all you need is to update an existing one based on sku

Here is more documentation on updateOne

Body:
I am trying to UPDATE fields in mongo database. However, I get the hollowing error.

MongoError: Performing an update on the path '_id' would modify the
  immutable field '_id'

My Code to update.

app.put("/api/inventory/:sku", (req, res, next) => {
  const inventory = new Inventory({
    _id: req.body.id,
    sku: req.body.sku,
    total_qty: req.body.total_qty,
    current_qty: req.body.current_qty
  });
  Inventory.updateOne({ sku: req.params.sku }, req.body).then(result => {
    res.status(200).json({ message: "Update successful!" });
  });
});

Body:
It seems you only need to update one Inventory record. You can simply do this:

app.put("/api/inventory/:sku", (req, res, next) => {
  return Inventory.updateOne(
    { sku: req.params.sku },  // <-- find stage
    { $set: {                // <-- set stage
       id: req.body.id,     // <-- id not _id
       sku: req.body.sku,
       total_qty: req.body.total_qty,
       current_qty: req.body.current_qty
      }
    }
  ).then(result => {
    res.status(200).json({ message: "Update successful!" });
  });
});

There is no need to create new Inventory etc since all you need is to update an existing one based on sku

Here is more documentation on updateOne


问:
What is the correct way to stop the setInterval in my function?
I want to implement a countdown in a game. Therefore I wrote some code but the setInterval is not stopping when it hits the number of 0.

Can somebody help me rewriting my code?

Below you can find the code.

```<code>secondsNum = 10;

{
setInterval(() => {
  console.log(secondsNum);
  secondsNum--;;
  if (secondsNum === 0) {
    clearInterval();
    console.log('Time is up');
  }

}, 1000);
</code>```

答:
You need to save the value returned from setInterval and pass it back to clearInterval when you want it to stop.  It might look like this:

```<code>secondsNum = 10;
var timerID = 0;

timerID = setInterval(() => {
    console.log(secondsNum);
    secondsNum--;
    if (secondsNum === 0) {
        clearInterval(timerID);
        console.log('Time is up');
    }
}, 1000);
</code>```

Body:
I want to implement a countdown in a game. Therefore I wrote some code but the setInterval is not stopping when it hits the number of 0.

Can somebody help me rewriting my code?

Below you can find the code.

secondsNum = 10;

{
setInterval(() => {
  console.log(secondsNum);
  secondsNum--;;
  if (secondsNum === 0) {
    clearInterval();
    console.log('Time is up');
  }

}, 1000);

Body:
You need to save the value returned from setInterval and pass it back to clearInterval when you want it to stop.  It might look like this:

secondsNum = 10;
var timerID = 0;

timerID = setInterval(() => {
    console.log(secondsNum);
    secondsNum--;
    if (secondsNum === 0) {
        clearInterval(timerID);
        console.log('Time is up');
    }
}, 1000);


问:
ORA-01461: can bind a LONG value
I'm setting up a test server and i get this problem ORA-01461: can bind a LONG value only for insert into a LONG column when i try execute Select from database, the error is when code call persist() of entitymanager

Im running glashfiss 4.1, Java 8, Oracle 9i and deploying throught Netbeans 8

I tried putting on persistence.xml oracle.jdbc.RetainV9LongBindBehavior","true"

答: I solved this downgrading the version of glassfish to 3.1 and java SE to 1.6</p>

Title: ORA-01461: can bind a LONG value


问:
Fopen function returns null when given an existing path
When trying to open a file with fopen(path, "2"); i get NULL on an existing path

iv'e tried to enter only the file name and it works but i want the program to write the file in the path...
Yes, i write the path with double backslashes "\\" when it's necesary.
Yes the path without doubt exists.

```<code>FILE* log;
char directory_path[PATH_LEN] = { 0 };
char directory_file[PATH_LEN] = { 0 };

//directory_path is the directory, entered by  the user
//LOG_NAME is the files name without the path - "log.txt"
//#define PATH_LEN 100

printf("Folder to scan:  ");
fgets(directory_path, PATH_LEN, stdin);
directory_path[strlen(directory_path) - 1] = 0;

//this section connects the path with the file name.
strcpy(directory_file, directory_path);
strcat(directory_file, "\\");
strcat(directory_file, LOG_NAME);

if ((log = fopen(directory_file, "w")) == NULL)
{
    printf("Error");
}
</code>```

My program worked until i tried to write into a file in order to create a log file. This means that the path is correct without doubt.

Can anyone tell me the problem here?

答:
You have several issues in your code:

For one, fopen(path, "2"); is not valid.
The mode argument needs to include one of a, r, and w and can optionally include b or +.

As another thing, directory_path[strlen(directory_path) - 1] = 0; may truncate the end of your path (if it's over PATH_LEN characters long).

There also may be a possible issue with buffer overflow due to the fact that you copy a string to a buffer of the same size and then concatenate two other strings to it. Therefore, you should change this line:

```<code>char directory_file[PATH_LEN] = { 0 };
</code>```

to this:

```<code>char directory_file[PATH_LEN+sizeof(LOG_NAME)+1] = { 0 };
</code>```

To debug this issue, you should print the string entered and ask for confirmation before using it (wrap this in #ifdef DEBUG).

Body:
When trying to open a file with fopen(path, "2"); i get NULL on an existing path

iv'e tried to enter only the file name and it works but i want the program to write the file in the path...
Yes, i write the path with double backslashes "\\" when it's necesary.
Yes the path without doubt exists.

FILE* log;
char directory_path[PATH_LEN] = { 0 };
char directory_file[PATH_LEN] = { 0 };

//directory_path is the directory, entered by  the user
//LOG_NAME is the files name without the path - "log.txt"
//#define PATH_LEN 100

printf("Folder to scan:  ");
fgets(directory_path, PATH_LEN, stdin);
directory_path[strlen(directory_path) - 1] = 0;

//this section connects the path with the file name.
strcpy(directory_file, directory_path);
strcat(directory_file, "\\");
strcat(directory_file, LOG_NAME);

if ((log = fopen(directory_file, "w")) == NULL)
{
    printf("Error");
}

My program worked until i tried to write into a file in order to create a log file. This means that the path is correct without doubt.

Can anyone tell me the problem here?

Body:
You have several issues in your code:

For one, fopen(path, "2"); is not valid.
The mode argument needs to include one of a, r, and w and can optionally include b or +.

As another thing, directory_path[strlen(directory_path) - 1] = 0; may truncate the end of your path (if it's over PATH_LEN characters long).

There also may be a possible issue with buffer overflow due to the fact that you copy a string to a buffer of the same size and then concatenate two other strings to it. Therefore, you should change this line:

char directory_file[PATH_LEN] = { 0 };

to this:

char directory_file[PATH_LEN+sizeof(LOG_NAME)+1] = { 0 };

To debug this issue, you should print the string entered and ask for confirmation before using it (wrap this in #ifdef DEBUG).


问:
How to create an EWS item (Calendar event or Contact) in the Deleted Items folder in Outlook?
I was trying to recreate the item into Deleted Items folder, but nothing happened, I got these errors "ErrorCannotCreateCalendarItemInNonCalendarFolder" or "ErrorCannotCreateContactInNonContactFolder". How to overcome this?

I used the request to POST with the body

```<code>    "<?xml version=\"1.0\" encoding=\"utf-8\"?> "
    "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" "
                   "xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" >"
      "<soap:Header> "
        "<t:RequestServerVersion Version=\"Exchange2013\" /> "
        "<t:ExchangeImpersonation> "
          "<t:ConnectingSID> "
            "<t:PrincipalName>%MAIL_BOX%</t:PrincipalName> "     // <<------- MAIL_BOX ---- FILLED IN BY A TEMPLATE PARAM
          "</t:ConnectingSID> "
        "</t:ExchangeImpersonation> "
      "</soap:Header> "
      "<soap:Body> "
        "<CreateItem xmlns=\"http://schemas.microsoft.com/exchange/services/2006/messages\" "
                    "MessageDisposition=\"SaveOnly\" "
                    "SendMeetingInvitations=\"SendToNone\"> "
          "<SavedItemFolderId>"
            "<t:FolderId Id=\"%FOLDER_ID%\"/>"                             // <<------- FOLDER_ID ---- FILLED IN BY A TEMPLATE PARAM
          "</SavedItemFolderId>"
          "<Items>"
            "%ITEMS_CONTENT%"                                              // <<------- ITEMS_CONTENT ---- FILLED IN BY A TEMPLATE PARAM
          "</Items>"
        "</CreateItem>"
      "</soap:Body>"
    "</soap:Envelope>";
</code>```

And got such the response:

```<code><?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
        <h:ServerVersionInfo MajorVersion="15" MinorVersion="20" MajorBuildNumber="1922" MinorBuildNumber="23" Version="V2018_01_08" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    </s:Header>
    <s:Body>
        <m:CreateItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
            <m:ResponseMessages>
                <m:CreateItemResponseMessage ResponseClass="Error">
                    <m:MessageText>Cannot create a calendar item in a non-calendar folder.</m:MessageText>
                    <m:ResponseCode>ErrorCannotCreateCalendarItemInNonCalendarFolder</m:ResponseCode>
                    <m:DescriptiveLinkKey>0</m:DescriptiveLinkKey>
                    <m:Items />
                </m:CreateItemResponseMessage>
            </m:ResponseMessages>
        </m:CreateItemResponse>
    </s:Body>
</s:Envelope>
</code>```

答: Because the Deleted Items Folder class is IPF.Note EWS restricts you from creating items that are Calendar or Contacts in these types of folder  hence the error message your receiving. A workaround is just create the Items in the normal Calendar or Contacts folder and then use the Move operation to move it after you have created it.</p>

Body:
I was trying to recreate the item into Deleted Items folder, but nothing happened, I got these errors "ErrorCannotCreateCalendarItemInNonCalendarFolder" or "ErrorCannotCreateContactInNonContactFolder". How to overcome this?

I used the request to POST with the body

    "<?xml version=\"1.0\" encoding=\"utf-8\"?> "
    "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" "
                   "xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" >"
      "<soap:Header> "
        "<t:RequestServerVersion Version=\"Exchange2013\" /> "
        "<t:ExchangeImpersonation> "
          "<t:ConnectingSID> "
            "<t:PrincipalName>%MAIL_BOX%</t:PrincipalName> "     // <<------- MAIL_BOX ---- FILLED IN BY A TEMPLATE PARAM
          "</t:ConnectingSID> "
        "</t:ExchangeImpersonation> "
      "</soap:Header> "
      "<soap:Body> "
        "<CreateItem xmlns=\"http://schemas.microsoft.com/exchange/services/2006/messages\" "
                    "MessageDisposition=\"SaveOnly\" "
                    "SendMeetingInvitations=\"SendToNone\"> "
          "<SavedItemFolderId>"
            "<t:FolderId Id=\"%FOLDER_ID%\"/>"                             // <<------- FOLDER_ID ---- FILLED IN BY A TEMPLATE PARAM
          "</SavedItemFolderId>"
          "<Items>"
            "%ITEMS_CONTENT%"                                              // <<------- ITEMS_CONTENT ---- FILLED IN BY A TEMPLATE PARAM
          "</Items>"
        "</CreateItem>"
      "</soap:Body>"
    "</soap:Envelope>";

And got such the response:

<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
        <h:ServerVersionInfo MajorVersion="15" MinorVersion="20" MajorBuildNumber="1922" MinorBuildNumber="23" Version="V2018_01_08" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    </s:Header>
    <s:Body>
        <m:CreateItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
            <m:ResponseMessages>
                <m:CreateItemResponseMessage ResponseClass="Error">
                    <m:MessageText>Cannot create a calendar item in a non-calendar folder.</m:MessageText>
                    <m:ResponseCode>ErrorCannotCreateCalendarItemInNonCalendarFolder</m:ResponseCode>
                    <m:DescriptiveLinkKey>0</m:DescriptiveLinkKey>
                    <m:Items />
                </m:CreateItemResponseMessage>
            </m:ResponseMessages>
        </m:CreateItemResponse>
    </s:Body>
</s:Envelope>


问:
How to store system-created to-do list items?
In a to-do list where users have both system-created items and their own items, how would you store the items?

A to-do list can have a mix of items. The system-created items can be modified and deleted just like user-created items. There difference is the titles and description text for the system-created items are initially pulled from a configuration. Many users can have the same system-created items. E.g. if two users want to paint rooms in their houses, they'd both get "buy paint" items.

Option 1

Save the full system-created items (including the title & text) with the user-created items.

Pros: Flexibility for user modifications since the items belong to the user and are not dependent on a central item configuration.

Cons: Lots of redundancy because there will be many users all with the same items.

Option 2

Save references to a configuration for system-created items with the user-created items.

Pros: Flexibility for system modifications since if we want to say "buy X-brand paint" instead of "buy paint", the change is easily reflected for all users with this item.

Cons: System-created items have to persist forever in the configuration even if the item is no longer relevant for new to-do lists because otherwise the user's reference will be broken.

Other options?

Thank you!

答:
I think the key here is whether you need to be able to modify a "system todo", and that change to be reflected in all the "user todos"...

If that's a requirement (it sounds sensible to me), your only option is Option 2 - the real con of Option 1 is once you copied the "system todo" as a "user todo", you cannot tell anymore whether they're related...

I'd go for a model similar to this, with 2 entities/tables:

```<code>ToDoTemplate
  Integer id
  String name
  String description
</code>```

```<code>ToDoItem
  Integer id
  ToDoTemplate template
  Boolean completed = false
  ?String name = null
  ?String description = null
</code>```

When you create a ToDoItem, you create it based on a ToDoTemplate (it may be a blank template), and you set the name and description as null, reusing the template name/description... Only if the user modifies their own ToDoItem is when you store that value... i.e.

```<code>String getName() {
  return this.name != null ? this.name : this.template.name;
}
</code>```

This is the most flexible of the approaches, and the only valid in many situations... Note the con you mention:

Cons: System-created items have to persist forever in the configuration even if the item is no longer relevant for new to-do lists because otherwise the user's reference will be broken.

This is not a con really - as long as there's one ToDoItem that uses a given ToDoTemplate, the template is still relevant, and of course there's no reason to remove it...

Body:
I think the key here is whether you need to be able to modify a "system todo", and that change to be reflected in all the "user todos"...

If that's a requirement (it sounds sensible to me), your only option is Option 2 - the real con of Option 1 is once you copied the "system todo" as a "user todo", you cannot tell anymore whether they're related...

I'd go for a model similar to this, with 2 entities/tables:

ToDoTemplate
  Integer id
  String name
  String description

ToDoItem
  Integer id
  ToDoTemplate template
  Boolean completed = false
  ?String name = null
  ?String description = null

When you create a ToDoItem, you create it based on a ToDoTemplate (it may be a blank template), and you set the name and description as null, reusing the template name/description... Only if the user modifies their own ToDoItem is when you store that value... i.e.

String getName() {
  return this.name != null ? this.name : this.template.name;
}

This is the most flexible of the approaches, and the only valid in many situations... Note the con you mention:

Cons: System-created items have to persist forever in the configuration even if the item is no longer relevant for new to-do lists because otherwise the user's reference will be broken.

This is not a con really - as long as there's one ToDoItem that uses a given ToDoTemplate, the template is still relevant, and of course there's no reason to remove it...


问:
cppyy - how to call a c++ function that accepts a set?
Suppose I have the following C++ function:

```<code>int summap(const map<int,int>& m) {
    ...
}
</code>```

I try to call it from Python using cppyy, by sending a dict:

```<code>import cppyy
cppyy.include("functions.hpp")
print(cppyy.gbl.summap({55:1,66:2,77:3}))
</code>```

I get an error:

```<code>TypeError: int ::summap(const map<int,int>& v) =>
    TypeError: could not convert argument 1
</code>```

How can I call this function?

答:
There is no relation between Python's dict and C++'s std::map (the two have completely different internal structure), so this requires a conversion, there is currently no automatic one in cppyy, so do something like this:

```<code>cppm = cppyy.gbl.std.map[int, int]()
for key, value in {55:1,66:2,77:3}.items():
    cppm[key] = value
</code>```

then pass cppm to summap.

Automatic support for python list/tuple -> std::vector is available, but there, too, it's no smarter than copying (likewise, b/c the internal structure is completely different), so any automatic std::map <-> python dict conversion would internally still have to do a copy like the above.

Body:
Suppose I have the following C++ function:

int summap(const map<int,int>& m) {
    ...
}

I try to call it from Python using cppyy, by sending a dict:

import cppyy
cppyy.include("functions.hpp")
print(cppyy.gbl.summap({55:1,66:2,77:3}))

I get an error:

TypeError: int ::summap(const map<int,int>& v) =>
    TypeError: could not convert argument 1

How can I call this function?

Body:
There is no relation between Python's dict and C++'s std::map (the two have completely different internal structure), so this requires a conversion, there is currently no automatic one in cppyy, so do something like this:

cppm = cppyy.gbl.std.map[int, int]()
for key, value in {55:1,66:2,77:3}.items():
    cppm[key] = value

then pass cppm to summap.

Automatic support for python list/tuple -> std::vector is available, but there, too, it's no smarter than copying (likewise, b/c the internal structure is completely different), so any automatic std::map <-> python dict conversion would internally still have to do a copy like the above.


问:
How to return results from stored procedure as a List?
Previously this worked well and recently the line stop working. This code uses the DB context to run a procedure and return it in List format. For some reason I am not seeing the error, I just see the action fail because it is not executing.

I ran the stored procedure in SQL Server and see the desired results, just not seeing it happening from the application layer.

```<code>[Http.Route("postsearch")]
public async Task<IHttpActionResult> PostSearch(SearchInputDTO srequest)
{
   var searchString = srequest.SearchValue.ToString();
   List<output> seResult = new List<output>(_output.searchLog(searchString)); /*This line stopped working*/
   return Ok(seResult);
}
</code>```

Stored procedure:

```<code>SET FMTONLY OFF
GO
SET NOCOUNT ON
GO

ALTER PROCEDURE [dbo].[searchLog]
    @searchValue VARCHAR(150)
AS
    SELECT *
    FROM [dbo].[output]
    WHERE CONTAINS (*, @searchValue)
</code>```

Implementation in Entity Framework

```<code>public virtual int searchLog(string searchValue)
{
    var searchValueParameter = searchValue != null ?
            new ObjectParameter("searchValue", searchValue) :
            new ObjectParameter("searchValue", typeof(string));

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("searchLog", searchValueParameter);
}
</code>```

This should return the rows from the query.

答:
Try removing the new instance of the list and just have it like this

```<code>List<output> seResult = _output.searchLog(searchString);
</code>```

Update stored proc to

```<code>@searchValue varchar(150)

AS

BEGIN

SELECT
  [ColumnName1]
  ,[ColumnName2] ...etc...
FROM [dbo].[output]
WHERE CONTAINS (*,@searchValue)

END
</code>```

Body:
Previously this worked well and recently the line stop working. This code uses the DB context to run a procedure and return it in List format. For some reason I am not seeing the error, I just see the action fail because it is not executing.

I ran the stored procedure in SQL Server and see the desired results, just not seeing it happening from the application layer.

[Http.Route("postsearch")]
public async Task<IHttpActionResult> PostSearch(SearchInputDTO srequest)
{
   var searchString = srequest.SearchValue.ToString();
   List<output> seResult = new List<output>(_output.searchLog(searchString)); /*This line stopped working*/
   return Ok(seResult);
}

Stored procedure:

SET FMTONLY OFF
GO
SET NOCOUNT ON
GO

ALTER PROCEDURE [dbo].[searchLog]
    @searchValue VARCHAR(150)
AS
    SELECT *
    FROM [dbo].[output]
    WHERE CONTAINS (*, @searchValue)

Implementation in Entity Framework

public virtual int searchLog(string searchValue)
{
    var searchValueParameter = searchValue != null ?
            new ObjectParameter("searchValue", searchValue) :
            new ObjectParameter("searchValue", typeof(string));

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("searchLog", searchValueParameter);
}

This should return the rows from the query.

Body:
Try removing the new instance of the list and just have it like this

List<output> seResult = _output.searchLog(searchString);

Update stored proc to

@searchValue varchar(150)

AS

BEGIN

SELECT
  [ColumnName1]
  ,[ColumnName2] ...etc...
FROM [dbo].[output]
WHERE CONTAINS (*,@searchValue)

END


问:
Malloc, free, and multiple pointers, how does it work?
I have multiple pointers pointing to dynamically allocated memory which was assigned using single malloc.

int *p1, *p2;
p1 = (int*)malloc(sizeof(int) * 10);
p2 = &p1[5];
free(p2);
p1[5] = 3;
p1[6] = 5;
```

Now my question is what does 'free(p2)' statement would do? Will it free memory ahead p1[5]? Is it safe to use memory ahead p1[5](i.e. p1[6], p1[7] , . .)

答:
You cannot predict the behavior of this function, as it is undefined behavior

From the reference:

Deallocates the space previously allocated by malloc(), calloc(), aligned_alloc, (since C11) or realloc().

If ptr is a null pointer, the function does nothing.

The behavior is undefined if the value of ptr does not equal a value returned earlier by malloc(), calloc(), realloc(), or aligned_alloc() (since C11).

—free, C++ Reference

Emphasis mine: your use of free in this context would involve freeing from a pointer that was not obtained from the use of any of those functions; it was obtained by transforming the pointer that was obtained from malloc, and thus is not valid.

My best guess at what might happen is a segmentation fault; but that's up to your compiler, and not something you or I can guarantee.

So do not do this.

Body:
I have multiple pointers pointing to dynamically allocated memory which was assigned using single malloc.

int *p1, *p2;
p1 = (int*)malloc(sizeof(int) * 10);
p2 = &p1[5];
free(p2);
p1[5] = 3;
p1[6] = 5;

Now my question is what does 'free(p2)' statement would do? Will it free memory ahead p1[5]? Is it safe to use memory ahead p1[5](i.e. p1[6], p1[7] , . .)


答:
Freeing a pointer that wasn't malloc/calloced is undefined behavior.
Some allocators such as glibc's can sometimes detect it and deterministically crash the program with a free(): invalid pointer error message, but technically you lose any and all guarantees about your program's behavior if you do it.

Title: Malloc, free, and multiple pointers, how does it work?


问:
How can I use Sidekiq to render large PDFs as a background process to avoid Heroku's 30 second timeout for HTTP requests?
I'm no expert, but my hours of googling and stack overflowing haven't given me an answer to my problem, so I decided to make my own question.

I'm using Ruby on Rails 5 which I'm tinkering with using the Cloud9 IDE on AWS. The app is deployed using Heroku which has a 30 second timeout for HTTP requests. I need to generate a PDF from an html.erb file that has a lot of logic and queries in it, so it usually takes around 100 seconds to complete, and, since it happens in the controller, it is considered an HTTP request and is required to either take less than 30 seconds or be completed as a background process. If you know of another way to get around the Heroku 30 second HTTP request timeout, PLEASE let me know.

I asked about this in another post and got the feedback to try using something like Sidekiq with rails to process the massive process instead of attempting it with an HTTP request. The idea here was to put it in a background request and let it do its thing for the full 100+ seconds, then return the PDF to the end user somehow (like having it download automatically for example). I decided to go for it, and got my code working to the point where I had the Redis server (required for Sidekiq), the Sidekiq server, and the usual rails server all running in unison to allow me to load and render the PDF from the Sidekiq worker instead of the controller.

My problem is that the 'render' method is not available in workers! I attempted to access it directly from the source by using
av = ActionView::Base.new()
 and then
av.render #pdf code here

but got the following error in my Sidekiq console:

"WARN: NameError: uninitialized constant PDFWorker::ActionView"

The code in my controller:

```<code># /app/controllers/recentgrad_controller.rb
require 'sidekiq'
require "redis"
class RecentgradController < ApplicationController
  def report
    # things that prepare the name of the pdf, etc. go here

    PDFWorker.perform_async(pdf_name, pdf_year)
    redirect_to emphs_path
  end
end
</code>```

The code in my worker:

```<code># /app/workers/pdf_worker.rb
Sidekiq.configure_client do |config|
  # config.redis = { db: 1 }
  config.redis = { url: 'redis://172.31.6.51:6379/0' }
end

Sidekiq.configure_server do |config|
  # config.redis = { db: 1 }
  config.redis = { url: 'redis://172.31.6.51:6379/0' }
end

class PDFWorker
  include Sidekiq::Worker
  sidekiq_options retry: false
  def perform(pdf_name, pdf_year)
    # create an instance of ActionView, so we can use the render method outside of a controller
    av = ActionView::Base.new() # THIS is where the error comes from
    av.view_paths = ActionController::Base.view_paths
    av.class_eval do
      include ActionController::UrlWriter
      include ApplicationHelper
    end

    av.render pdf: "mypdf",
      disposition: 'attachment',
      page_height: 1300,
         encoding: 'utf8',
        page_size:   'A4',
           footer: {html: {template: 'recent_grad/footer.html.erb'}, spacing: 0 },
           margin:  {   top:    10,                     # default 10 (mm)
                        bottom: 20,
                        left:   10,
                        right:  10 },
         template: "recent_grad/report.html.erb",
           locals: {start: @start, survey: @survey, years: @years, college: @college, department: @department, program: @program, emphasis: @emphasis, questions: @questions}
  end
end

</code>```

The error I get when I run the part of my program that generates a PDF:

WARN: NameError: uninitialized constant PDFWorker::ActionView

答:
It turned out to be much easier to use a job instead of a worker because jobs allow you to use the render function inherited from the ApplicationController

The real winner here is @unixmonkey who is the creator of wicked pdf for rails, and he set up a working app for me. You can see the question here: https://github.com/mileszs/wicked_pdf/issues/835

And the commit that really changed the way it worked can be viewed here:
https://github.com/unixmonkey/generate_pdf_async_example/commit/85e8dcd98fe6580a8692842fcc5316b931ce4eea

Enjoy!

Body:
I'm no expert, but my hours of googling and stack overflowing haven't given me an answer to my problem, so I decided to make my own question.

I'm using Ruby on Rails 5 which I'm tinkering with using the Cloud9 IDE on AWS. The app is deployed using Heroku which has a 30 second timeout for HTTP requests. I need to generate a PDF from an html.erb file that has a lot of logic and queries in it, so it usually takes around 100 seconds to complete, and, since it happens in the controller, it is considered an HTTP request and is required to either take less than 30 seconds or be completed as a background process. If you know of another way to get around the Heroku 30 second HTTP request timeout, PLEASE let me know.

I asked about this in another post and got the feedback to try using something like Sidekiq with rails to process the massive process instead of attempting it with an HTTP request. The idea here was to put it in a background request and let it do its thing for the full 100+ seconds, then return the PDF to the end user somehow (like having it download automatically for example). I decided to go for it, and got my code working to the point where I had the Redis server (required for Sidekiq), the Sidekiq server, and the usual rails server all running in unison to allow me to load and render the PDF from the Sidekiq worker instead of the controller.

My problem is that the 'render' method is not available in workers! I attempted to access it directly from the source by using
av = ActionView::Base.new()
 and then
av.render #pdf code here

but got the following error in my Sidekiq console:

"WARN: NameError: uninitialized constant PDFWorker::ActionView"

The code in my controller:

# /app/controllers/recentgrad_controller.rb
require 'sidekiq'
require "redis"
class RecentgradController < ApplicationController
  def report
    # things that prepare the name of the pdf, etc. go here

    PDFWorker.perform_async(pdf_name, pdf_year)
    redirect_to emphs_path
  end
end

The code in my worker:

# /app/workers/pdf_worker.rb
Sidekiq.configure_client do |config|
  # config.redis = { db: 1 }
  config.redis = { url: 'redis://172.31.6.51:6379/0' }
end

Sidekiq.configure_server do |config|
  # config.redis = { db: 1 }
  config.redis = { url: 'redis://172.31.6.51:6379/0' }
end

class PDFWorker
  include Sidekiq::Worker
  sidekiq_options retry: false
  def perform(pdf_name, pdf_year)
    # create an instance of ActionView, so we can use the render method outside of a controller
    av = ActionView::Base.new() # THIS is where the error comes from
    av.view_paths = ActionController::Base.view_paths
    av.class_eval do
      include ActionController::UrlWriter
      include ApplicationHelper
    end

    av.render pdf: "mypdf",
      disposition: 'attachment',
      page_height: 1300,
         encoding: 'utf8',
        page_size:   'A4',
           footer: {html: {template: 'recent_grad/footer.html.erb'}, spacing: 0 },
           margin:  {   top:    10,                     # default 10 (mm)
                        bottom: 20,
                        left:   10,
                        right:  10 },
         template: "recent_grad/report.html.erb",
           locals: {start: @start, survey: @survey, years: @years, college: @college, department: @department, program: @program, emphasis: @emphasis, questions: @questions}
  end
end

The error I get when I run the part of my program that generates a PDF:

WARN: NameError: uninitialized constant PDFWorker::ActionView


问:
How do I return array data from a foreach loop in Angular
I'm looping through a nested object to get a some data. This is working, but I can't seem to return the data and use it elsewhere.

I've tried putting the loop in a promise and couldn't get anywhere either. What am I doing wrong?

```<code>data: any = {
    '1234': {
        url: 'https://example1.com/',
        path: 'uploads',
        link: 'https://example1.com/uploads',
    },
    '5678': {
        url: 'https://example2.com/',
        path: 'uploads',
        link: 'https://example2.com/uploads',
    }
}

onSubmit(formData) {

    this.formdata = formData;

    Object.keys(this.data).forEach(key => {
        if (key == this.formdata.pin) {
            const url = this.data[key].url;
            // have also tried this.url to no avail
        }
    });

    // says undefined
    console.log(url);

    // set up headers, etc...

    // I need to use here
    this.http.post(url, body, head)
    ...
}
</code>```

答:
```<code>onSubmit(formData) {

this.formdata = formData;
let url; // Define here so that its accessible
Object.keys(this.data).forEach(key => {
    if (key === this.formdata.pin) {
         url = this.data[key].url;
        // have also tried this.url to no avail
    }
});

// Now url is in scope
console.log(url);

    ...
}
</code>```

Body:
I'm looping through a nested object to get a some data. This is working, but I can't seem to return the data and use it elsewhere.

I've tried putting the loop in a promise and couldn't get anywhere either. What am I doing wrong?

data: any = {
    '1234': {
        url: 'https://example1.com/',
        path: 'uploads',
        link: 'https://example1.com/uploads',
    },
    '5678': {
        url: 'https://example2.com/',
        path: 'uploads',
        link: 'https://example2.com/uploads',
    }
}

onSubmit(formData) {

    this.formdata = formData;

    Object.keys(this.data).forEach(key => {
        if (key == this.formdata.pin) {
            const url = this.data[key].url;
            // have also tried this.url to no avail
        }
    });

    // says undefined
    console.log(url);

    // set up headers, etc...

    // I need to use here
    this.http.post(url, body, head)
    ...
}


问:
Error parsing JSON with escaped quotes inside single quotes
I have a variable var jsonData = '{"Key":"query","Value":"dept=\"Human Resources*\"","ValueType":"Edm.String"}';

I'm trying to parse the variable with JSON.parse(jsonData), however, I'm getting an error "Unexpected token H in JSON at position 30." I can't change how the variable is returned, so here's what I think I understand about the problem:

The JSON.parse(jsonData) errors out because it's not recognizing the escaped double quotes as escaped since it is fully enclosed in single quotes

jsonData.replace(/\\"/g, "\\\\"") or other combinations that I've tried aren't finding the \" because javascript treats \" as just "

QUESTION How can I parse this properly, by either replacing the escaped quotes with something JSON.parse() can handle or using something else to parse this correctly? I'd like to stick with JSON.parse() on account of it's simplicity, but open to other options.

EDIT: Unfortunately I can't change the variable at this stage, it is just a small example of a larger JSON response. This is a temporary solution until the app is granted access to the API, but I needed the solution in the interim until that happens (IT dept can be slow). What I'm doing now its getting a large JSON response back by hitting the API address directly and the browser uses the cookies from the user OAuth for authentication. I then copy and paste the JSON response into my application so I can work with the data. The response is riddled with the escaped quotes and manually editing the text would be laborious and I'm trying to avoid copying into text processor before copying into the variable.

答:
You should escape the backslash character in your code by prefixing it with another backslash. So the code becomes:

var jsonData = '{"Key":"query","Value":"dept=\\"Human Resources*\\"","ValueType":"Edm.String"}';
```

The first backslash is so that JS puts the second backslash in the string, which must be in the string so that the json parser knows that it should ignore the quote character.

Body:
You should escape the backslash character in your code by prefixing it with another backslash. So the code becomes:

var jsonData = '{"Key":"query","Value":"dept=\\"Human Resources*\\"","ValueType":"Edm.String"}';

The first backslash is so that JS puts the second backslash in the string, which must be in the string so that the json parser knows that it should ignore the quote character.


问:
Can someone help explain why it returns a different sum?
var x = 10 + Number("1"+"6");
console.log(x);

returns: 26

var y = 10 + 1 + 6;
console.log(y);

returns: 17

答:
In your first example Number("1"+"6"), "1" and "6" evaluate as strings (because of the quotes). When JS adds strings it concatenates them, so "1" + "6" becomes "16" the same way that "Hello " + "world" becomes "Hello world".

In your second example all of the numbers are treated as numbers, so they are added as you expect.


问:
How to fix "ord() expected a character, but string of length 0 found" error in Python
My program must encode input messages using a Caesar Cipher. I tried to split my string to many letters by putting "/" between them. Then everything, in fact, worked(as I think). Eventually, when a message gets closer to chr(ord(ch)+ 2) an error pops out. How can I fix with this? </p>

```<code>def main():

    print("This program will encode your messages using a Caesar Cipher")

    message = input("Enter the message: ")

    load = ("")

    codedMessage = ("")

    for i in message:

        load = load + i + "/"

        ''.join(load)

    for ch in load.split("/"):

        codedMessage = codedMessage + chr(ord(ch)+ 2)

    print("The coded message is:", codedMessage)

main()
</code>```

答:
In your first for loop you always append a / character to the end of the string, meaning that you have a trailing / at the end of your final string. When you do a load.split('/') the string at the end gets split to the right, leaving you with an empty string at the end, which throws an error since you're trying to get the ord of nothing:

Here's a code example of what I'm talking about:

```<code>>>> "o/".split('/')
['o', '']
</code>```

The last '' is what is giving you the error. There are a bunch of ways you could go about fixing it, but I think skipping the / delimiters and just using the input string like a couple of other people are saying is probably your best bet.

Body:
My program must encode input messages using a Caesar Cipher. I tried to split my string to many letters by putting "/" between them. Then everything, in fact, worked(as I think). Eventually, when a message gets closer to chr(ord(ch)+ 2) an error pops out. How can I fix with this?

def main():

    print("This program will encode your messages using a Caesar Cipher")

    message = input("Enter the message: ")

    load = ("")

    codedMessage = ("")

    for i in message:

        load = load + i + "/"

        ''.join(load)

    for ch in load.split("/"):

        codedMessage = codedMessage + chr(ord(ch)+ 2)

    print("The coded message is:", codedMessage)

main()

Body:
In your first for loop you always append a / character to the end of the string, meaning that you have a trailing / at the end of your final string. When you do a load.split('/') the string at the end gets split to the right, leaving you with an empty string at the end, which throws an error since you're trying to get the ord of nothing:

Here's a code example of what I'm talking about:

>>> "o/".split('/')
['o', '']

The last '' is what is giving you the error. There are a bunch of ways you could go about fixing it, but I think skipping the / delimiters and just using the input string like a couple of other people are saying is probably your best bet.


问:
How to perform a VLOOKUP in R?
I am replicating a CSV file in R (originally created in excel), that is compiled using various data sources. When i made this CSV in excel i used a vlookup to populate certain columns based on another data source/other spreadsheet.

How can i populate a column in R using something similar to a VLOOKUP? i.e. looking for a variable in an external source and matching it with another column in the df?

For example, the formula in the excel version is =
=VLOOKUP('[Spreadsheet1]Tab1'!A22,'[Spreadsheet2]Tab2'!$A$6:$B$500,2,FALSE)

How can i make this same formula in R code?

答:
dplyr::left_join() should do the trick:

```<code>myData <- data.frame(
  x = c('a', 'b', 'b', 'c')
)

lookUpData <- data.frame(
  key = c('a', 'b', 'c'),
  value = c(1, 2, 3)
)

library(dplyr)

myData %>%
  left_join(lookUpData, by = c(x = 'key')) %>%
  rename(newCol = value)

  x newCol
1 a      1
2 b      2
3 b      2
4 c      3
</code>```

Title: How to perform a VLOOKUP in R?

Body:
dplyr::left_join() should do the trick:

myData <- data.frame(
  x = c('a', 'b', 'b', 'c')
)

lookUpData <- data.frame(
  key = c('a', 'b', 'c'),
  value = c(1, 2, 3)
)

library(dplyr)

myData %>%
  left_join(lookUpData, by = c(x = 'key')) %>%
  rename(newCol = value)

  x newCol
1 a      1
2 b      2
3 b      2
4 c      3


问:
How to size Android components according to image size using XML
I have created a custom icon bar in Android using the XML layout creator, using a RadioGroup within a LinearLayout (XML included below).  Each RadioButton within the RadioGroup has a custom drawable (with checked and unchecked states) as its android:button attribute.

The Linear layout is itself within a RelativeLayout so that it can appear at an arbitrary position on the screen (as a side bar, in this instance).

The drawables are 55 pixels wide, and the android:layout\_width attribute of all these views is wrap\_content.

When I make this component visible, aligned to the bottom-left of the screen, only about three-quarters of the RadioButton image widths are visible.  Setting the layout\_width of the RelativeLayout to fill\_parent  rectifies this and causes the full button to appear.

However this means that the button group consumes click events across the entire width of the screen.

How can I make the entire button appear, and have only the area of the button respond to clicks?  Hard-coding the width of the drawable is not a particularly desirable solution.

```<code><RelativeLayout android:id="@+id/RelativeLayout01" android:layout_width="wrap_content" android:layout_height="wrap_content">
    <LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_below="@+id/LinearLayout01" android:visibility="invisible">
        <RadioGroup android:id="@+id/RadioGroup01" android:layout_height="wrap_content" android:checkedButton="@+id/RB01" android:layout_width="fill_parent">
            <RadioButton android:id="@+id/RB01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:button="@drawable/DR01"/>
            <RadioButton android:id="@+id/RB02" android:layout_width="fill_parent" android:layout_height="wrap_content" android:button="@drawable/DR02"/>
            <RadioButton android:id="@+id/RB03" android:layout_width="fill_parent" android:layout_height="wrap_content" android:button="@drawable/DR03"/>
            <RadioButton android:id="@+id/RB04" android:layout_width="fill_parent" android:layout_height="wrap_content" android:button="@drawable/DR04"/>
        </RadioGroup>
    </LinearLayout>
    </RelativeLayout>
</code>```

答:
Setting the width of the LinearLayout, RadioGroup, or RadioButton in dp's (density indpendent pixels) might work for you.  Based on what youve said above I think it would have to be the Layout's width.  The dimensions are "hardcoded" but they'll scale with the size of your screen.

So the xml could look like:

```<code>android:layout_width="55dp"
</code>```

The official documentation for dps is here

Body:
I have created a custom icon bar in Android using the XML layout creator, using a RadioGroup within a LinearLayout (XML included below).  Each RadioButton within the RadioGroup has a custom drawable (with checked and unchecked states) as its android:button attribute.

The Linear layout is itself within a RelativeLayout so that it can appear at an arbitrary position on the screen (as a side bar, in this instance).

The drawables are 55 pixels wide, and the android:layout\_width attribute of all these views is wrap\_content.

When I make this component visible, aligned to the bottom-left of the screen, only about three-quarters of the RadioButton image widths are visible.  Setting the layout\_width of the RelativeLayout to fill\_parent  rectifies this and causes the full button to appear.

However this means that the button group consumes click events across the entire width of the screen.

How can I make the entire button appear, and have only the area of the button respond to clicks?  Hard-coding the width of the drawable is not a particularly desirable solution.

<RelativeLayout android:id="@+id/RelativeLayout01" android:layout_width="wrap_content" android:layout_height="wrap_content">
    <LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_below="@+id/LinearLayout01" android:visibility="invisible">
        <RadioGroup android:id="@+id/RadioGroup01" android:layout_height="wrap_content" android:checkedButton="@+id/RB01" android:layout_width="fill_parent">
            <RadioButton android:id="@+id/RB01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:button="@drawable/DR01"/>
            <RadioButton android:id="@+id/RB02" android:layout_width="fill_parent" android:layout_height="wrap_content" android:button="@drawable/DR02"/>
            <RadioButton android:id="@+id/RB03" android:layout_width="fill_parent" android:layout_height="wrap_content" android:button="@drawable/DR03"/>
            <RadioButton android:id="@+id/RB04" android:layout_width="fill_parent" android:layout_height="wrap_content" android:button="@drawable/DR04"/>
        </RadioGroup>
    </LinearLayout>
    </RelativeLayout>

Body:
Setting the width of the LinearLayout, RadioGroup, or RadioButton in dp's (density indpendent pixels) might work for you.  Based on what youve said above I think it would have to be the Layout's width.  The dimensions are "hardcoded" but they'll scale with the size of your screen.

So the xml could look like:

android:layout_width="55dp"

The official documentation for dps is here

OwnerDisplayName: Will


问:
how do i set a dynamic object in JS?
I want to keep a value from a form by a js function
with document.getElementById("form1")

but in the form there are dynamic inputs amount1 , amount2 ect... (i dont know how many - its from database)

how do i reach form1.amount (p)

when p is the index of the amount ?

thanks

答:
Ioannis is pretty much there. To get the value of the ith amount input, use:

```<code>var value = document.forms['form1'].elements['amount' + i].value;
</code>```

A little more robustly:

```<code>function getIthAmount(i) {
  var o = document.forms['form1'];
  o = o && o.elements['amount' + i];

  if (o) {
    return o.value;
  }
}
</code>```

Title: how do i set a dynamic object in JS?

Body:
Ioannis is pretty much there. To get the value of the ith amount input, use:

var value = document.forms['form1'].elements['amount' + i].value;

A little more robustly:

function getIthAmount(i) {
  var o = document.forms['form1'];
  o = o && o.elements['amount' + i];

  if (o) {
    return o.value;
  }
}


问:
Order files numerically in specific folder
I have a folder which contains only .txt files. I want my output to have a certain order.

The first 2 digit of every filename is its unique ID. I want to order the files numerically in that order

I've researched multiple questions that seem similar to this like
Getting all file names from a folder using C#

but none has helped me accomplish this goal. What is the easiest way for me to get my desired output?

```<code>        string folder = @"C:\Testing\";
        var txtFiles = Directory.GetFiles(folder, "*.txt")
                                 .Select(Path.GetFileName)
                                 .ToList();
        foreach(var f in txtFiles)
        {
            Console.WriteLine(f);
        }
        Console.ReadKey();
</code>```

Windows Explore

Console Output

答:
Easier alternative can be to use padding :</p>

```<code>var txtFiles = Directory.EnumerateFiles(folder, "*.txt")
                        .Select(Path.GetFileName)
                        .OrderBy(s => s.PadLeft(11));
</code>```

Body:
I have a folder which contains only .txt files. I want my output to have a certain order.

The first 2 digit of every filename is its unique ID. I want to order the files numerically in that order

I've researched multiple questions that seem similar to this like
Getting all file names from a folder using C#

but none has helped me accomplish this goal. What is the easiest way for me to get my desired output?

        string folder = @"C:\Testing\";
        var txtFiles = Directory.GetFiles(folder, "*.txt")
                                 .Select(Path.GetFileName)
                                 .ToList();
        foreach(var f in txtFiles)
        {
            Console.WriteLine(f);
        }
        Console.ReadKey();

Windows Explore

Console Output

Body:
Easier alternative can be to use padding :

var txtFiles = Directory.EnumerateFiles(folder, "*.txt")
                        .Select(Path.GetFileName)
                        .OrderBy(s => s.PadLeft(11));


问:
readFileSync: Why only first character of string being returned?
Why does the code only return the first character of the string?

Text for the first 6 rows is:

1-800-FLOWERS.COM, INC.

1ST SOURCE

1ST SOURCE CORP

3D SYSTEMS

8X8, INC.

A.H. BELO

Have reviewed every post here related to the same issue, none directly provide a solution.

```<code>    const searchkeywords = fs.readFileSync('kwords.csv','utf-8');
        for (let kword of searchkeywords) {
    console.log(`Search Keyword: ${kword}`);
</code>```

Hoping a solution to retrieve the entire row text string from the CSV file.

答:
Found simple answer, parse.

```<code>function readKeyWords(path) {
    return fs.readFileSync(path, 'utf-8')
        .split('\n');
}
</code>```

then

```<code>    const searchkeywords = readKeyWords('kwords.csv','utf-8');
    for (let kword of searchkeywords) {
    console.log(`Search Keyword: (${kword})`);
</code>```

for anyone whom has the same question.

Body:
Why does the code only return the first character of the string?

Text for the first 6 rows is:

1-800-FLOWERS.COM, INC.

1ST SOURCE

1ST SOURCE CORP

3D SYSTEMS

8X8, INC.

A.H. BELO

Have reviewed every post here related to the same issue, none directly provide a solution.

    const searchkeywords = fs.readFileSync('kwords.csv','utf-8');
        for (let kword of searchkeywords) {
    console.log(`Search Keyword: ${kword}`);

Hoping a solution to retrieve the entire row text string from the CSV file.

Body:
Found simple answer, parse.

function readKeyWords(path) {
    return fs.readFileSync(path, 'utf-8')
        .split('\n');
}

then

    const searchkeywords = readKeyWords('kwords.csv','utf-8');
    for (let kword of searchkeywords) {
    console.log(`Search Keyword: (${kword})`);

for anyone whom has the same question.


问:
Why hover selector doesn't work with clases?
I have set the styles for  links (active, link, etc), but then I want to do a button with totally different styles so I tried something like this:

.r-button { padding: 4px 52px; display: inline-block; text-align: center; font-size: 16px; text-decoration: none !important; color: black !important; border-radius: 12px; border:1px inset #282c37;}

.r-button:hover { cursor: selector; color:ivory;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  Click button </code>```

But then I realized that :hover doesn't work with clases. Why is that? What others chances do I have to do the same?

答:
Your :hover pseudo element was being overwritten with !important. Avoid using !important rules within your default class.

Bonus tip! Remove cursor: pointer for anchor tags, and simply have an empty href="#" attribute for better accessibility.

.r-button {
  padding: 4px 52px;
  display: inline-block;
  text-align: center;
  font-size: 16px;
  text-decoration: none;
  color: black;
  border-radius: 12px;
  border: 1px inset #282c37;
}
.r-button:hover {
  background-color: #282c37;
  color: ivory;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Click button</code>```

Body:
I have set the styles for  links (active, link, etc), but then I want to do a button with totally different styles so I tried something like this:

.r-button { padding: 4px 52px; display: inline-block; text-align: center; font-size: 16px; text-decoration: none !important; color: black !important; border-radius: 12px; border:1px inset #282c37;}

.r-button:hover { cursor: selector; color:ivory;}

  Click button

But then I realized that :hover doesn't work with clases. Why is that? What others chances do I have to do the same?

Body:
Your :hover pseudo element was being overwritten with !important. Avoid using !important rules within your default class.

Bonus tip! Remove cursor: pointer for anchor tags, and simply have an empty href="#" attribute for better accessibility.

.r-button {
  padding: 4px 52px;
  display: inline-block;
  text-align: center;
  font-size: 16px;
  text-decoration: none;
  color: black;
  border-radius: 12px;
  border: 1px inset #282c37;
}
.r-button:hover {
  background-color: #282c37;
  color: ivory;
}

<a class="r-button" href="#" onclick="document.getElementById('menu').style.display='block'">Click button</a>


问:
Resize tables based on number of records in SSRS
I have two table having data like below:

```<code>            SELECT *
              FROM [dbo].[TestTable_1]
            ID  Value
            ----------
            1   gjha
            2   dc
            3   d
            4   ds
            5   dg
            6   hn
</code>```

2nd table:

```<code>            SELECT *
              FROM [dbo].[TestTable_2]
            Value
            -----
            jklsa
            dfv
            b
            grt
            trj
            h
            muik
            rg
            kuu
            wd
            gb
            nm
            wef
</code>```

I'm fetching the data in SSRS report as below:

Question is:

How can I maintain the table size same? That is, if small table in SSRS report has 6 records (which is in this case),
the bigger one should adjust same size as small and the extra (/more) records that are coming in the large table should shift to right.

Here is the expected output from SSRS

```<code>            Value           Value
            --------  -----------------
            gjha      jklsa |muik | wef
            dc        dfv   |rg   |
            d         b     |kuu  |
            ds        grt   |wd   |
            dg        trj   |gb   |
            hn        h     |nm   |
</code>```

Note: The above details are just example, however, the number of records are really dynamic.

答:
I just answered a similar question here: https://stackoverflow.com/a/56350614/2033717

You can adapt this solution to your situation by replacing the 3 in the expressions with:

```<code>=Floor(Count(Fields!ColumnName.Value, "Dataset1") / Count(Fields!ColumnName.Value, "Dataset1"))
</code>```

In other words, you're determining how many columns you need. And then grouping each row of the dataset into rows and columns of the matrix. This will work if you know the second table can be bigger than the first, but I'm not sure if it will work both ways without some additional conditions on the expressions.

Body:
I have two table having data like below:

            SELECT *
              FROM [dbo].[TestTable_1]
            ID  Value
            ----------
            1   gjha
            2   dc
            3   d
            4   ds
            5   dg
            6   hn

2nd table:

            SELECT *
              FROM [dbo].[TestTable_2]
            Value
            -----
            jklsa
            dfv
            b
            grt
            trj
            h
            muik
            rg
            kuu
            wd
            gb
            nm
            wef

I'm fetching the data in SSRS report as below:

Question is:

How can I maintain the table size same? That is, if small table in SSRS report has 6 records (which is in this case),
the bigger one should adjust same size as small and the extra (/more) records that are coming in the large table should shift to right.

Here is the expected output from SSRS

            Value           Value
            --------  -----------------
            gjha      jklsa |muik | wef
            dc        dfv   |rg   |
            d         b     |kuu  |
            ds        grt   |wd   |
            dg        trj   |gb   |
            hn        h     |nm   |

Note: The above details are just example, however, the number of records are really dynamic.

Body:
I just answered a similar question here: https://stackoverflow.com/a/56350614/2033717

You can adapt this solution to your situation by replacing the 3 in the expressions with:

=Floor(Count(Fields!ColumnName.Value, "Dataset1") / Count(Fields!ColumnName.Value, "Dataset1"))

In other words, you're determining how many columns you need. And then grouping each row of the dataset into rows and columns of the matrix. This will work if you know the second table can be bigger than the first, but I'm not sure if it will work both ways without some additional conditions on the expressions.


问:
What naming to use for interpreted languages?
What kind of naming convention should I use for variables in uncompiled code like PHP that is holding values for passwords?

Obviously naming something “loginPassword” isn’t good- so what do people use instead?

答:
Generally, best practice is for variable names and functions that are descriptive of their purpose.

Thus:

```<code> $loginPassword = $_POST['loginPassword'];
</code>```

is fine. It tells you exactly what this code is and how it will be used. As an addendum,

```<code> $loginPassword = hash($AlgoChoice, $_POST['loginPassword'].$salt);
</code>```

might be a good idea so you only ever have to handle the salted and hashed password. That would give you a variable ready to use in an SQL SELECT statement.

As PHP is run on the server side, the end user should not see the code. Nevertheless, it is wise to write code as if your enemies can see a copy. See and know there is no point attacking it.

Body:
Generally, best practice is for variable names and functions that are descriptive of their purpose.

Thus:

 $loginPassword = $_POST['loginPassword'];

is fine. It tells you exactly what this code is and how it will be used. As an addendum,

 $loginPassword = hash($AlgoChoice, $_POST['loginPassword'].$salt);

might be a good idea so you only ever have to handle the salted and hashed password. That would give you a variable ready to use in an SQL SELECT statement.

As PHP is run on the server side, the end user should not see the code. Nevertheless, it is wise to write code as if your enemies can see a copy. See and know there is no point attacking it.


问:
Mediawiki extension that produces cryptographic hash value of the input string?
I'm looking for an extension, probably a parser function, that takes an input string (could be any wikitext, and probably needs to support wikitext parsing in the call) and produces the cryptographic hash of the input.

Examples (with Semantic Mediawiki query) usage:

{{#hash: sha1|{{#show: SomeTestingPage|?SomeValue# -}} }}

{{#hash: md5|{{#ask: [[Category: Boats]] [[Displacement::>100000]] [[Purpose::Freighter]]|?format=list|link=none|headers=hide}} }}

Is there anything like this in Mediawiki?

Important: Don't confuse this with the HashTables extension, which implements hash table lookup but doesn't actually produce cryptographic hash values at the page level.

答:
Beyond the fact that the cryptographic value of md5 and sha1 is questionable at this point, I'm not aware of an already existing extension that does this. Creating one should be rather easy though, including it being able to parse wikitext.

https://www.mediawiki.org/wiki/Manual:Parser_functions this manual gives you a basic example of how this would work, it should be fairly easy to follow.


问:
Is this class Threadsafe?
Hi

Is the class below threadsafe?

```<code>class ImmutablePossiblyThreadsafeClass<K, V> {

    private final Map<K, V> map;

    public ImmutablePossiblyThreadsafeClass(final Map<K, V> map) {
        this.map = new HashMap<K, V>();

        for (Entry<K, V> entry : map.entrySet()) {
            this.map.put(entry.getKey(), entry.getValue());
        }
    }

    public V get(K key) {
        return this.map.get(key);
    }
}
</code>```

答:
Yes, it is thread-safe. It is immutable so no thread can make any changes that will interfere with the results for another thread.

Note: If the map is modified during construction, you won't get the contents you thought you passed, but when accessing the map afterwards, it will be thread-safe.

Title: Is this class Threadsafe?

Body:
Hi

Is the class below threadsafe?

class ImmutablePossiblyThreadsafeClass<K, V> {

    private final Map<K, V> map;

    public ImmutablePossiblyThreadsafeClass(final Map<K, V> map) {
        this.map = new HashMap<K, V>();

        for (Entry<K, V> entry : map.entrySet()) {
            this.map.put(entry.getKey(), entry.getValue());
        }
    }

    public V get(K key) {
        return this.map.get(key);
    }
}