问:
Selecting a dropdown from a web site
This is first time I am trying to extract an excel report from a webpage. Sequence of how my code should work is as under:

Initial URL - brings home page of the website (userid and password saved in browser to autologin) - image1

Click on "Reports"

New page appears (image2)

select from dropdown_module.

Select appropriate from dropdown_reports.

selection in dropdown_reports creates a new dropdown_project.

select from dropdown_project

click on drownload reports (image3)

give path for downloading.

image41
image12
image23
image34

I am able to reach upto point 3, but not able to proceed ahead.
On using inspect element on dropdown_module i get the code (image4)

My using so far is as under:

```<code>Set IE = CreateObject("InternetExplorer.Application")
URL = Range("hr_url").Value
IE.Visible = True
IE.navigate URL
Application.StatusBar = " is loading. Please wait..."
Do While IE.readyState = 4: DoEvents: Loop
Do Until IE.readyState = 4: DoEvents: Loop
Application.StatusBar = " Loaded"

Set doc = IE.document
For Each element In doc.all
    If InStr(element.ID, "08191") > 0 Then
        If InStr(element.ID, "AppPress:12") Then
            element.Focus
            element.Click
        End If
    End If
Next element

Application.Wait (5)

Do
DoEvents
Loop Until IE.readyState <> 4

Set doc = IE.document
For Each element In doc.all
    If InStr(element.ID, "0261") > 0 Then
        If InStr(element.ID, "AppPress:6") Then
          MsgBox "element is found"
          element.Options(0).Selected = True
        End If
    End If
Next element
</code>```

The code isnt able to find the dropdown element and select the 0 index required. Can anyone suggest what is wrong here?

答:
I was not aware that scraping was posible with VBA. (Scraping is the way the technique of extracting info from the web with software is called)

You should find this question useful:

Scraping data from website using vba

I am not aware of the posibilities off doing this with VBA that might be limited to internet explorer among other limitations. The little things I've done for that have been with python and a library called beautifulSoup, that is amazing!

https://www.crummy.com/software/BeautifulSoup/bs4/doc/

If you feel curious enough you might want to dive into it, as it is quite simple, and googling what you want to do might take you very far, also if you want to create an excel file with the info you extract.

Hope that helps

Title: Selecting a dropdown from a web site

Body:
This is first time I am trying to extract an excel report from a webpage. Sequence of how my code should work is as under:

Initial URL - brings home page of the website (userid and password saved in browser to autologin) - image1

Click on "Reports"

New page appears (image2)

select from dropdown_module.

Select appropriate from dropdown_reports.

selection in dropdown_reports creates a new dropdown_project.

select from dropdown_project

click on drownload reports (image3)

give path for downloading.

image41
image12
image23
image34

I am able to reach upto point 3, but not able to proceed ahead.
On using inspect element on dropdown_module i get the code (image4)

My using so far is as under:

Set IE = CreateObject("InternetExplorer.Application")
URL = Range("hr_url").Value
IE.Visible = True
IE.navigate URL
Application.StatusBar = " is loading. Please wait..."
Do While IE.readyState = 4: DoEvents: Loop
Do Until IE.readyState = 4: DoEvents: Loop
Application.StatusBar = " Loaded"

Set doc = IE.document
For Each element In doc.all
    If InStr(element.ID, "08191") > 0 Then
        If InStr(element.ID, "AppPress:12") Then
            element.Focus
            element.Click
        End If
    End If
Next element

Application.Wait (5)

Do
DoEvents
Loop Until IE.readyState <> 4

Set doc = IE.document
For Each element In doc.all
    If InStr(element.ID, "0261") > 0 Then
        If InStr(element.ID, "AppPress:6") Then
          MsgBox "element is found"
          element.Options(0).Selected = True
        End If
    End If
Next element

The code isnt able to find the dropdown element and select the 0 index required. Can anyone suggest what is wrong here?


来源: stackexchange

问:
How to programmatically get latest offset per Kafka topic partition in Python
I'm new to Kafka, and want to get the position of a Kafka topic, per partition.
I see in the documentation - https://kafka-python.readthedocs.io/en/master/apidoc/KafkaAdminClient.html#kafkaadminclient - that the offset is available via the function KafkaAdminClient.list_consumer_group_offsets,
but I don't see such a method for the position there.

Does anybody know how I can get it?

答:
Using confluent-kafka-python

You can use position:

Retrieve current positions (offsets) for the list of partitions.

```<code>from confluent_kafka import Consumer, TopicPartition

consumer = Consumer({"bootstrap.servers": "localhost:9092"})
topic = consumer.list_topics(topic='topicName')
partitions = [TopicPartition('topicName', partition) for partition in list(topic.topics['topicName'].partitions.keys())]

offset_per_partition = consumer.position(partitions)
</code>```

Alternatively, you can also use get_watermark_offsets but you'd have to pass one partition at a time and thus it requires multiple calls:

Retrieve low and high offsets for partition.

```<code>from confluent_kafka import Consumer, TopicPartition

consumer = Consumer({"bootstrap.servers": "localhost:9092"})
topic = consumer.list_topics(topic='topicName')
partitions = [TopicPartition('topicName', partition) for partition in list(topic.topics['topicName'].partitions.keys())]

for p in partitions:
    low_offset, high_offset = consumer.get_watermark_offsets(p)
    print(f"Latest offset for partition {f}: {high_offset}")
</code>```

Using kafka-python

You can use end_offsets:

Get the last offset for the given partitions. The last offset of a
  partition is the offset of the upcoming message, i.e. the offset of
  the last available message + 1.

This method does not change the current consumer position of the
  partitions.

```<code>from kafka import TopicPartition
from kafka.consumer import KafkaConsumer

consumer = KafkaConsumer(bootstrap_servers = "localhost:9092" )
partitions= = [TopicPartition('myTopic', p) for p in consumer.partitions_for_topic('myTopic')]
last_offset_per_partition = consumer.end_offsets(partitions)
</code>```

If you want to iterate through all topics, the following will do the trick:

```<code>from kafka import TopicPartition
from kafka.consumer import KafkaConsumer

kafka_topics = consumer.topics()
for topic in kafka_topics:
    partitions= = [TopicPartition(topic, p) for p in consumer.partitions_for_topic(topic)]
    last_offset_per_partition = consumer.end_offsets(partitions)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using confluent-kafka-python

You can use position:

Retrieve current positions (offsets) for the list of partitions.

from confluent_kafka import Consumer, TopicPartition

consumer = Consumer({"bootstrap.servers": "localhost:9092"})
topic = consumer.list_topics(topic='topicName')
partitions = [TopicPartition('topicName', partition) for partition in list(topic.topics['topicName'].partitions.keys())]

offset_per_partition = consumer.position(partitions)

Alternatively, you can also use get_watermark_offsets but you'd have to pass one partition at a time and thus it requires multiple calls:

Retrieve low and high offsets for partition.

from confluent_kafka import Consumer, TopicPartition

consumer = Consumer({"bootstrap.servers": "localhost:9092"})
topic = consumer.list_topics(topic='topicName')
partitions = [TopicPartition('topicName', partition) for partition in list(topic.topics['topicName'].partitions.keys())]

for p in partitions:
    low_offset, high_offset = consumer.get_watermark_offsets(p)
    print(f"Latest offset for partition {f}: {high_offset}")

Using kafka-python

You can use end_offsets:

Get the last offset for the given partitions. The last offset of a
  partition is the offset of the upcoming message, i.e. the offset of
  the last available message + 1.

This method does not change the current consumer position of the
  partitions.

from kafka import TopicPartition
from kafka.consumer import KafkaConsumer

consumer = KafkaConsumer(bootstrap_servers = "localhost:9092" )
partitions= = [TopicPartition('myTopic', p) for p in consumer.partitions_for_topic('myTopic')]
last_offset_per_partition = consumer.end_offsets(partitions)

If you want to iterate through all topics, the following will do the trick:

from kafka import TopicPartition
from kafka.consumer import KafkaConsumer

kafka_topics = consumer.topics()
for topic in kafka_topics:
    partitions= = [TopicPartition(topic, p) for p in consumer.partitions_for_topic(topic)]
    last_offset_per_partition = consumer.end_offsets(partitions)


问:
simplify nested Objects and find sum of particular property
I have a nested Objects like below. I want to simplify the nested Objects to one Object and find sum of a particular property of all the children of the particular parent Object.

Current Object

```<code>let obj = {
Myanmar: [
    {
        trk1: {
            mou: 0.0,
            ca: 1.0,
            ccs: 0.0,
            ccc: 0.0,
        },
    }
],
Gibraltar: [
    {
        trk1: {
            mou: 12.850000381469727,
            ca: 1.0,
            ccs: 1.0,
            ccc: 3.0,
        },
    }
],
Cyprus: [
    {
        trk1: {
            mou: 36.25,
            ca: 3.0,
            ccs: 2.0,
            ccc: 7.0,
        },
        trk2: {
            mou: 27.299999237060547,
            ca: 1.0,
            ccs: 1.0,
            ccc: 6.0,
        },
        trk3: {
            mou: 80.59999752044678,
            ca: 4.0,
            ccs: 4.0,
            ccc: 14.0,
        },
        trk4: {
            mou: 26.716670513153076,
            ca: 4.0,
            ccs: 4.0,
            ccc: 6.0,
        }
    }
]};
</code>```

Expected Object

```<code>{
Myanmar: {
    mou: "(trk1-mou+trk2-mou+trk3-mou)",
    ca: "(trk1-ca+trk2-ca+trk3-ca)"
}};
</code>```

I want to perform the sum of properties over a nested object.
i am not able to continue after getting the object.keys
please help.

Body:
I have a nested Objects like below. I want to simplify the nested Objects to one Object and find sum of a particular property of all the children of the particular parent Object.

Current Object

let obj = {
Myanmar: [
    {
        trk1: {
            mou: 0.0,
            ca: 1.0,
            ccs: 0.0,
            ccc: 0.0,
        },
    }
],
Gibraltar: [
    {
        trk1: {
            mou: 12.850000381469727,
            ca: 1.0,
            ccs: 1.0,
            ccc: 3.0,
        },
    }
],
Cyprus: [
    {
        trk1: {
            mou: 36.25,
            ca: 3.0,
            ccs: 2.0,
            ccc: 7.0,
        },
        trk2: {
            mou: 27.299999237060547,
            ca: 1.0,
            ccs: 1.0,
            ccc: 6.0,
        },
        trk3: {
            mou: 80.59999752044678,
            ca: 4.0,
            ccs: 4.0,
            ccc: 14.0,
        },
        trk4: {
            mou: 26.716670513153076,
            ca: 4.0,
            ccs: 4.0,
            ccc: 6.0,
        }
    }
]};

Expected Object

{
Myanmar: {
    mou: "(trk1-mou+trk2-mou+trk3-mou)",
    ca: "(trk1-ca+trk2-ca+trk3-ca)"
}};

I want to perform the sum of properties over a nested object.
i am not able to continue after getting the object.keys
please help.

Body:
var obj={"Myanmar": [{ "trk1": { "mou": 0.0, "ca": 1.0, "ccs": 0.0, "ccc": 0.0 }}],"Gibraltar": [{ "trk1": { "mou": 12.850000381469727, "ca": 1.0, "ccs": 1.0, "ccc": 3.0 }}],"Cyprus": [{ "trk1": { "mou": 36.25, "ca": 3.0, "ccs": 2.0, "ccc": 7.0 }, "trk2": { "mou": 27.299999237060547, "ca": 1.0, "ccs": 1.0, "ccc": 6.0 }, "trk3": { "mou": 80.59999752044678, "ca": 4.0, "ccs": 4.0, "ccc": 14.0 }, "trk4": { "mou": 26.716670513153076, "ca": 4.0, "ccs": 4.0, "ccc": 6.0 }}]}

let reqObj={};
let arr = Object.keys(obj);
for(var i=0;i<=arr.length-1;i++){
 let inObj = obj[arr[i]][0];
 reqObj[arr[i]] = Object.keys(inObj).reduce((acc,ele,index)=>{
     let keyArr = Object.keys(inObj[ele]);
     for(var j=0;j<=keyArr.length-1;j++){
       acc = {...acc,...{[keyArr[j]] : (keyArr[j] in acc)   ? acc[keyArr[j]] + inObj[ele][keyArr[j]]   : inObj[ele][keyArr[j]]}}
     }
     return acc;
  },{})
}
  console.log(reqObj)


问:
YouTube JavaScript API, onStateChange not firing, no autoplay
I have a training program where I'm trying to display a YouTube video in an iFrame, automatically play it, and advance to the next page when the video completes.  I can get the onYouTubeIframeAPIReady function to fire, but none of the other events will.  Actually, I'm only interested in state change.

```<code>    var tag = document.createElement('script');
    tag.src = 'https://www.youtube.com/iframe_api';
    tag.id = 'apiScript';
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</code>```

...

```<code>    //function onYouTubeIframeAPIReady() {  //tried this too but no change
    window.onYouTubeIframeAPIReady = function() {
        player = new YT.Player('externalComponent', {
        events: {
            'onReady': onPlayerReady,
            'onError': onPlayerError,
            'onStateChange': onPlayerStateChange
            }
        });
        console.log('api ready');
    }

    function onPlayerStateChange(event) {
        console.log('onStateChange');
        console.log(YT.PlayerState);
    }
</code>```

When it runs, you can see "api  ready" in the console but nothing else.  iFrame looks like:

```<code>    <iframe id="externalComponent" src="https://youtube.com/embed/_S_Bg9qfa8o?enablejsapi=1&controls=0&autoplay=1" width="1024" height="576" allow="autoplay" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</code>```

What is stopping onStateChange from working and not automatically playing?  The controls do not show.

答:
I was unable to get it to work as I've posted.  I had to change the code to use a div rather than an iframe, add a video ID and other parameters in the playerVars.  Once I did that, the video played automatically, showed no controls, and fired the state change event.

```<code>  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      playerVars: {
                autoplay: 1,
                controls: 0,
                showinfo: 0,
                autohide: 1
                },
      videoId: '_S_Bg9qfa8o',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }
</code>```

...

```<code><div id="player"></div>
</code>```

Body:
I have a training program where I'm trying to display a YouTube video in an iFrame, automatically play it, and advance to the next page when the video completes.  I can get the onYouTubeIframeAPIReady function to fire, but none of the other events will.  Actually, I'm only interested in state change.

    var tag = document.createElement('script');
    tag.src = 'https://www.youtube.com/iframe_api';
    tag.id = 'apiScript';
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

...

    //function onYouTubeIframeAPIReady() {  //tried this too but no change
    window.onYouTubeIframeAPIReady = function() {
        player = new YT.Player('externalComponent', {
        events: {
            'onReady': onPlayerReady,
            'onError': onPlayerError,
            'onStateChange': onPlayerStateChange
            }
        });
        console.log('api ready');
    }

    function onPlayerStateChange(event) {
        console.log('onStateChange');
        console.log(YT.PlayerState);
    }

When it runs, you can see "api  ready" in the console but nothing else.  iFrame looks like:

What is stopping onStateChange from working and not automatically playing?  The controls do not show.

Body:
I was unable to get it to work as I've posted.  I had to change the code to use a div rather than an iframe, add a video ID and other parameters in the playerVars.  Once I did that, the video played automatically, showed no controls, and fired the state change event.

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      playerVars: {
                autoplay: 1,
                controls: 0,
                showinfo: 0,
                autohide: 1
                },
      videoId: '_S_Bg9qfa8o',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

...

<div id="player"></div>


问:
High response time with active storage
I am using active_storage to store and retrieve three plots on a web page on Heroku.  The code to retrieve the plot is

```<code>image_tag plot.variant(resize: '500x500'), class: 'r_plot'
</code>```

Each plot is fairly small, around 500 KByte.  I frequently see the following error from the Logentries heroku add-on:

```<code>High Response Time: Heroku/Syslog drain
    2020-05-30 21:39:37.733
    671 <158>1 2020-05-30T21:39:35.184905+00:00 heroku router - - at=info method=GET path="/rails/active_storage/representations/long_token/-tmp-plotsPlotname" host=cvd-tracker.herokuapp.com request_id=some_id fwd="ip_address" dyno=web.1 connect=0ms service=5015ms status=302 bytes=1679 protocol=https
</code>```

Why is it taking so long to retrieve these plots?

答:
Could be a few things:

The variants are created on demand by the server, so the first time it is called it can take some time and a decent amount of resources to complete.

Heroku has an ephemeral filesystem, meaning if you're storing these variants locally then after every new deployment or other event causing a dyno change, the previously created variant will be destroyed so the next time it is called you will have to go through the previous step again.

If you aren't storing the variants locally then perhaps your dyno is too small, meaning the server is running out of memory and having to use swap space to complete the variant processing?

Does it sound like any of these apply to your situation?

EDIT - Background Processing:

It appears that the actual processing is triggered when processed is called so you could do something like this in your rake task:

```<code>upload = Upload.find(upload_id)
variant = upload.image.variant(options)
was_processed = variant.processed
Rails.logger.info "Processed variant for #{upload.id}" if was_processed
</code>```

I found the above along with some other tips here.

Title: High response time with active storage

Body:
I am using active_storage to store and retrieve three plots on a web page on Heroku.  The code to retrieve the plot is

image_tag plot.variant(resize: '500x500'), class: 'r_plot'

Each plot is fairly small, around 500 KByte.  I frequently see the following error from the Logentries heroku add-on:

High Response Time: Heroku/Syslog drain
    2020-05-30 21:39:37.733
    671 <158>1 2020-05-30T21:39:35.184905+00:00 heroku router - - at=info method=GET path="/rails/active_storage/representations/long_token/-tmp-plotsPlotname" host=cvd-tracker.herokuapp.com request_id=some_id fwd="ip_address" dyno=web.1 connect=0ms service=5015ms status=302 bytes=1679 protocol=https

Why is it taking so long to retrieve these plots?

Body:
Could be a few things:

The variants are created on demand by the server, so the first time it is called it can take some time and a decent amount of resources to complete.

Heroku has an ephemeral filesystem, meaning if you're storing these variants locally then after every new deployment or other event causing a dyno change, the previously created variant will be destroyed so the next time it is called you will have to go through the previous step again.

If you aren't storing the variants locally then perhaps your dyno is too small, meaning the server is running out of memory and having to use swap space to complete the variant processing?

Does it sound like any of these apply to your situation?

EDIT - Background Processing:

It appears that the actual processing is triggered when processed is called so you could do something like this in your rake task:

upload = Upload.find(upload_id)
variant = upload.image.variant(options)
was_processed = variant.processed
Rails.logger.info "Processed variant for #{upload.id}" if was_processed

I found the above along with some other tips here.


问:
How to link (AWS) RDS Microsoft SQL Server to front end (react native)
I am doing a project to create a login and create an account page and also store different sorts of data that needs to be securely stored in the database.

I am using react native and amazon web service. I am confused about how to use the RDS(AWS) Microsoft SQL Server and to connect with the front end. Do I use AWS amplify?

I saw a post that mentioned

Amplify is at the moment tied to dynamoDB in a very strong way. But you can use graphQL queries sent to AppSync (the backend layer of amplify) to trigger lambda functions. From there you can target any type of database you want

Is there a better or shorter process of connecting the front end with the SQL database. Please give me some tips as it is my first time working with AWS and react native.

答:
There are many ways to accomplish this with AWS. You essentially need a backend web server component in your architecture. The classical solution would be to setup an EC2 and have this server handle REST or GraphQL requests that query your RDS.

A more modern "serverless" option would be to route your front-end traffic to an API Gateway that invokes a lambda function. This lambda function can utilize IAM permissions to query your database. There are many resources for this pattern; here's an AWS blog post about it.

I'm not familiar with the specifics of Amplify, but if you can be flexible switching datastore it seems convenient just to use a datastore that Amplify plays nicely with. I'd highly recommend trying to get Amplify working if you are not familiar with backend web software and don't have time / care to dig into the complexities of it.


问:
Getting InnerHits Result from SearchHits Class at Spring Data Elastic Search 4.0.0
I am currently doing migration from spring data elastic search 3.2.X to 4.0.0.

I had been relying on obtaining inner hits result through raw SearchResponse class by utilizing the now deprecated low level function org.springframework.data.elasticsearch.core.ElasticsearchOperations.query(SearchQuery query, ResultsExtractor resultsExtractor);

https://docs.spring.io/spring-data/elasticsearch/docs/4.0.0.RELEASE/reference/html/#elasticsearch-migration-guide-3.2-4.0

Basically what I did was creating custom resultExtractor which will expose the low level SearchResponse so that I could then extract the inner hits result.

Now with version 4.0.0 that functionality is no longer there, Both ElasticSearchOperations and ElasticSearchRestTemplate utilize new result class called SearchHits which AFAIK does not store inner hits information.

The workaround I could think of besides using the restHighLevelClient directly (which of course is undesirable since I'd lose the object mapping and stuff) is to extend ElasticSearchRestTemplate and basically creating new implementation of search(Query query, Class clazz, IndexCoordinates index) which will return SearchHits and the raw search response (similar to what my custom ResultExtractor used to do).

Afterwards, since all api returning page instance has been deprecated, I would now have to rely on SearchHitSupport.searchPageFor(SearchHits searchHits, @Nullable Pageable pageable) to get the usual paging functionalities.

I felt that this is not very straightforward and clean solution and certainly felt more like a workaround. Would there be any more straightforward way to obtain innerHitsResult and map result content to page at version 4.0.0?

答:
There is an open issue about inner_hits. Returning the inner_hits should be done in the SearchHit<T> class and not by exposing internal Elasticsearch data.

As for the paging: When you have a SearchHits<T> object as the result of a query that use a Pageable, you can call

```<code>SearchHits<Entity> searchHits = operations.search(query, Entity.class);
SearchPage<Entity> page = SearchHitSupport.searchPageFor(searchHits, query.getPageable)
</code>```

SearchPage implements the Page interface.

Edit:

The issue is fixed, inner hits are returned from the next version (4.1) on.

Body:
There is an open issue about inner_hits. Returning the inner_hits should be done in the SearchHit<T> class and not by exposing internal Elasticsearch data.

As for the paging: When you have a SearchHits<T> object as the result of a query that use a Pageable, you can call

SearchHits<Entity> searchHits = operations.search(query, Entity.class);
SearchPage<Entity> page = SearchHitSupport.searchPageFor(searchHits, query.getPageable)

SearchPage implements the Page interface.

Edit:

The issue is fixed, inner hits are returned from the next version (4.1) on.


问:
Scraping hover over figure using Python and Selenium
I am trying to scrape the data from http://fuelinsights.gasbuddy.com/Charts using Python and Selenium.  The difficult part is that the data only appear when a point on the line graph is hovered over.  Currently, my issue is an inability to create a list of all the hover over objects.  My code so far is below:

```<code>from selenium import webdriver as web
from selenium.webdriver.common.action_chains import ActionChains

driver = web.Chrome('driver path')

driver.get('http://fuelinsights.gasbuddy.com/Charts')

test= driver.find_elements_by_xpath('//*[@class="highcharts-markers"]')

print(test)
</code>```

`

which gives me test=[].  Previously, I have used beautifulsoup for all of my scraping projects, but I have redone some of my previous projects to make sure that I understand how Selenium works and haven't had issues.

If anyone can help me solve this issue so I can create a list of the items that I can use ActionChains to hover over and extract the price and date from it would be much appreciated.

Thank you!

****EDIT****
To clarify, I have looked over numerous other posts concerning SVG and g elements and Highcharts, but I am still short on a solution to this problem.  I have tried numerous Xpaths (and other find_elements_by options), but have only been able to come to two results: (1) the Xpath is valid, but does not contain any elements, or (2) InvalidSelectorException indicating that I was unable to locate an element with the xpath expression.  I believe this comes down to simply incorrectly specifying my Xpath, but I am at a loss for how to find the correct Xpath.

答:
Thanks You ! 2 years later, i'm facing to an equivalent project and used your example to learn how to get the job done with python & Firefox.
Perhaps the following code will be useful to some people.

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Firefox(executable_path=r'path\to\the\geckodriver.exe')
driver.get('http://fuelinsights.gasbuddy.com/Charts')
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "highcharts-markers")))
test = driver.find_elements_by_xpath("//*[name()='svg']//*[name()='g' and @class='highcharts-markers']/*[name()='path']")

res = []
for el in test:
    hover = ActionChains(driver).move_to_element(el)
    hover.perform()
    date = driver.find_elements_by_css_selector(".highcharts-tooltip > text:nth-child(5) > tspan:nth-child(1)")
    price = driver.find_elements_by_css_selector(".highcharts-tooltip > text:nth-child(5) > tspan:nth-child(4)")
    res.append((date[0].text, price[0].text))
</code>```

"res" contains :

```<code>('Saturday, May 30, 2020', '1.978 $/gal')
('Friday, May 29, 2020', '1.979 $/gal')
('Thursday, May 28, 2020', '1.977 $/gal')
('Wednesday, May 27, 2020', '1.972 $/gal')
('Tuesday, May 26, 2020', '1.965 $/gal')
.......
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to scrape the data from http://fuelinsights.gasbuddy.com/Charts using Python and Selenium.  The difficult part is that the data only appear when a point on the line graph is hovered over.  Currently, my issue is an inability to create a list of all the hover over objects.  My code so far is below:

from selenium import webdriver as web
from selenium.webdriver.common.action_chains import ActionChains

driver = web.Chrome('driver path')

driver.get('http://fuelinsights.gasbuddy.com/Charts')

test= driver.find_elements_by_xpath('//*[@class="highcharts-markers"]')

print(test)

`

which gives me test=[].  Previously, I have used beautifulsoup for all of my scraping projects, but I have redone some of my previous projects to make sure that I understand how Selenium works and haven't had issues.

If anyone can help me solve this issue so I can create a list of the items that I can use ActionChains to hover over and extract the price and date from it would be much appreciated.

Thank you!

****EDIT****
To clarify, I have looked over numerous other posts concerning SVG and g elements and Highcharts, but I am still short on a solution to this problem.  I have tried numerous Xpaths (and other find_elements_by options), but have only been able to come to two results: (1) the Xpath is valid, but does not contain any elements, or (2) InvalidSelectorException indicating that I was unable to locate an element with the xpath expression.  I believe this comes down to simply incorrectly specifying my Xpath, but I am at a loss for how to find the correct Xpath.

Body:
Thanks You ! 2 years later, i'm facing to an equivalent project and used your example to learn how to get the job done with python & Firefox.
Perhaps the following code will be useful to some people.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Firefox(executable_path=r'path\to\the\geckodriver.exe')
driver.get('http://fuelinsights.gasbuddy.com/Charts')
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "highcharts-markers")))
test = driver.find_elements_by_xpath("//*[name()='svg']//*[name()='g' and @class='highcharts-markers']/*[name()='path']")

res = []
for el in test:
    hover = ActionChains(driver).move_to_element(el)
    hover.perform()
    date = driver.find_elements_by_css_selector(".highcharts-tooltip > text:nth-child(5) > tspan:nth-child(1)")
    price = driver.find_elements_by_css_selector(".highcharts-tooltip > text:nth-child(5) > tspan:nth-child(4)")
    res.append((date[0].text, price[0].text))

"res" contains :

('Saturday, May 30, 2020', '1.978 $/gal')
('Friday, May 29, 2020', '1.979 $/gal')
('Thursday, May 28, 2020', '1.977 $/gal')
('Wednesday, May 27, 2020', '1.972 $/gal')
('Tuesday, May 26, 2020', '1.965 $/gal')
.......


问:
OpenCV throws errors after applying numpy transformations
I've run into a curious error. After applying np.flip, cv2.rectangle is throwing an error. Here's a minimal reproducible example:

```<code>image = np.random.choice(255,(50,50,3)).astype(np.uint8)
image_180 = np.flip(image.copy())
x1,y1,x2,y2 = 20,20,30,30
cv2.rectangle(image,(x1,y1),(x2,y2),(0,255,0),1)
cv2.rectangle(image_180,(x1,y1),(x2,y2),(0,255,0),1)
</code>```

Both image and image_180 are of the type numpy.ndarray, and are of dtype np.uint8. However, the second call to rectangle throws the following error:

```<code>TypeError: an integer is required (got type tuple)
</code>```

Which makes no sense. I'm assuming this is a bug or something with a lazy fix.

答:
Indeed, this error message is very confusing.

According to the official NumPy documentation, np.flip() returns a view of the input array. Presumably, this causes problems for OpenCV.

A simple fix is to pass a deep copy of the returned view, i.e.:

```<code>r = cv2.rectangle(image_180.copy(), (x1, y1), (x2, y2), (0, 255, 0), 1)
</code>```

Strangely enough, cv2.rectangle() does sometimes work with views, e.g.:

```<code>r = cv2.rectangle(image[:10], (x1, y1), (x2, y2), (0, 255, 0), 1)
</code>```

This suggests to me there is some kind of a bug in either NumPy or OpenCV. Either way, using .copy() on your array will fix your issue.

Body:
I've run into a curious error. After applying np.flip, cv2.rectangle is throwing an error. Here's a minimal reproducible example:

image = np.random.choice(255,(50,50,3)).astype(np.uint8)
image_180 = np.flip(image.copy())
x1,y1,x2,y2 = 20,20,30,30
cv2.rectangle(image,(x1,y1),(x2,y2),(0,255,0),1)
cv2.rectangle(image_180,(x1,y1),(x2,y2),(0,255,0),1)

Both image and image_180 are of the type numpy.ndarray, and are of dtype np.uint8. However, the second call to rectangle throws the following error:

TypeError: an integer is required (got type tuple)

Which makes no sense. I'm assuming this is a bug or something with a lazy fix.

Body:
Indeed, this error message is very confusing.

According to the official NumPy documentation, np.flip() returns a view of the input array. Presumably, this causes problems for OpenCV.

A simple fix is to pass a deep copy of the returned view, i.e.:

r = cv2.rectangle(image_180.copy(), (x1, y1), (x2, y2), (0, 255, 0), 1)

Strangely enough, cv2.rectangle() does sometimes work with views, e.g.:

r = cv2.rectangle(image[:10], (x1, y1), (x2, y2), (0, 255, 0), 1)

This suggests to me there is some kind of a bug in either NumPy or OpenCV. Either way, using .copy() on your array will fix your issue.


问:
Automatic update from database
I'm developing in WPF and want my DataGrid to automatically refresh when there's a change in the DB, and vice versa.

Today I'm using Timers and simple Selects to perform the updates.
Is there something in .Net that provides that functionality ?

答: Unfortunately Database are "pull" data sources and doesn't provide any "Push" data model to make your code notify about the changes, until you implement pseudo push which is basically what you have mentioned i.e timers polling the database. Other option may be to implement a Trigger which calls a CLR SP and this SP is able to send the data to your code through remoting or something like that.</p>

Title: Automatic update from database


问:
How can I sort the columns of a large data frame based on specific criteria?
I would like to sort the columns of a large dataframe (around 14000 variables) based on a specific rationale.

The column names have the following structure (Condition_Sleepstage_Parameter_Electrode_Nightpart):

```<code> [1] "Adapt_N2_negLengthLoc_C3_firstHour"          "Adapt_N3_negLengthLoc_C3_firstHour"
  [3] "Adapt_NREM_negLengthLoc_C3_firstHour"        "Book_N2_negLengthLoc_C3_firstHour"
  [5] "Book_N3_negLengthLoc_C3_firstHour"           "Book_NREM_negLengthLoc_C3_firstHour"
</code>```

R has the columns ordered in a purely alphabetical structure but I would like to have them in a logical order based on the following system:

First, variables should be presented in blocks per parameter. (order: "negLengthLoc", "posLength", "wholeLength", "negPeak", "nbnegPeaks", "initialMeannegSlope", "finalMeannegSlope", "initialMaxnegslope", "finalMaxnegslope", "posPeak", "nbposPeaks", "initialMeannposSlope", "finalMeanposSlope", "initialMaxposSlope", "PeaktoPeak", "Number", "Density")

Within these blocks, the highest order hierarchy should be due to Condition. (order: "Adapt", "NoFilter", "Filter", "Book").

Thereafter, the next hierarchy should be defined by Electrode. (order: "F3", "Fz", "F4", "C3", "Cz", "C4", "P3", "Pz", "P4", "O1", "O2").

Thereafter by Nightpart (order:"firstHour", "firstQuarter", "secondQuarter", "thirdQuarter", "fourthQuarter", "wholeNight") and lastly by Sleepstage ("order: "N2", "N3", "NREM").

The resulting order should look like:

```<code>[1] "Adapt_N2_negLengthLoc_F3_firstHour"          "Adapt_N3_negLengthLoc_F3_firstHour"
[3] "Adapt_NREM_negLengthLoc_F3_firstHour"          "Adapt_N2_negLengthLoc_F3_firstQuarter"
[5] "Adapt_N3_negLengthLoc_F3_firstQuarter"          "Adapt_NREM_negLengthLoc_F3_firstQuarter"
[7] "Adapt_N2_negLengthLoc_F3_secondQuarter"          "Adapt_N3_negLengthLoc_F3_secondQuarter"
[9] "Adapt_NREM_negLengthLoc_F3_secondQuarter"          "Adapt_N2_negLengthLoc_F3_thirdQuarter"
[11] "Adapt_N3_negLengthLoc_F3_thirdQuarter"          "Adapt_NREM_negLengthLoc_F3_thirdQuarter"
[13] "Adapt_N2_negLengthLoc_F3_fourthQuarter"          "Adapt_N3_negLengthLoc_F3_fourthQuarter"
[15] "Adapt_NREM_negLengthLoc_F3_fourthQuarter"          "Adapt_N2_negLengthLoc_F3_wholeNight"
[17] "Adapt_N3_negLengthLoc_F3_wholeNight"           "Adapt_NREM_negLengthLoc_F3_wholeNight"
[19] "Adapt_N2_negLengthLoc_Fz_firstHour"           "Adapt_N3_negLengthLoc_Fz_firstHour"
...
</code>```

I hope that someone can help me, if there are any further questions then I am of course happy to provide more information!

Thanks in advance!

答:
Illustrating with the mtcars data, one can reorder the columns in a data frame by creating a vector with the the desired order, and using this in the column specification with the [ form of the extract operator.

First, we'll use colnames() to extract the original order of the columns and print them

```<code>theNames <- colnames(mtcars)
theNames

> theNames
 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
</code>```

Next, we'll move all of the integer columns to the left side of the data frame by creating a reorderedNames vector and using it with [.

```<code>reorderedNames <- c("cyl" , "vs" ,  "am" ,  "gear" ,"carb","disp" ,
                     "drat", "wt" ,  "qsec", "mpg")
mtcars[,reorderedNames]
</code>```

...and the first few rows of output:

```<code>> mtcars[,reorderedNames]
                    cyl vs am gear carb  disp drat    wt  qsec  mpg
Mazda RX4             6  0  1    4    4 160.0 3.90 2.620 16.46 21.0
Mazda RX4 Wag         6  0  1    4    4 160.0 3.90 2.875 17.02 21.0
Datsun 710            4  1  1    4    1 108.0 3.85 2.320 18.61 22.8
Hornet 4 Drive        6  1  0    3    1 258.0 3.08 3.215 19.44 21.4
Hornet Sportabout     8  0  0    3    2 360.0 3.15 3.440 17.02 18.7
Valiant               6  1  0    3    1 225.0 2.76 3.460 20.22 18.1
Duster 360            8  0  0    3    4 360.0 3.21 3.570 15.84 14.3
Merc 240D             4  1  0    4    2 146.7 3.69 3.190 20.00 24.4
</code>```

Automating this process for a large data frame

In the OP, the question references a data frame with a large number of columns. In order to extend this process to automate the sorting of columns, there are at least two major approaches.

Process the column names from the data frame in a manner that allows one to sort the column names in the desired order, or

Create a narrow format tidy data set by using pivot_longer() to split the column names into the required grouping variables.

We'll use data from the OP to illustrate approach 1.

```<code>columnName <- c("Adapt_N2_negLengthLoc_C3_firstHour","Adapt_N3_negLengthLoc_C3_firstHour",
"Adapt_NREM_negLengthLoc_C3_firstHour","Book_N2_negLengthLoc_C3_firstHour",
"Book_N3_negLengthLoc_C3_firstHour","Book_NREM_negLengthLoc_C3_firstHour")
splitCols <- strsplit(columnName,"_")

results <- lapply(splitCols,function(x){
     parameter <- x[3]
     condition <- x[1]
     electrode <- x[4]
     nightpart <- x[5]
     sleepstage <- x[2]
     data.frame(parameter,condition,electrode,nightpart,sleepstage)
})

colsData <- do.call(rbind,results)
# add original column names back into data
colsData <- cbind(columnName,colsData)
# convert to factors, specifying the factor order for sorting
conditionOrder <- c("Adapt", "NoFilter", "Filter", "Book")
parameterOrder <- c("negLengthLoc", "posLength", "wholeLength", "negPeak", "nbnegPeaks",
                    "initialMeannegSlope", "finalMeannegSlope", "initialMaxnegslope",
                    "finalMaxnegslope", "posPeak", "nbposPeaks", "initialMeannposSlope",
                    "finalMeanposSlope", "initialMaxposSlope", "PeaktoPeak", "Number", "Density")
electrodeOrder <- c("F3", "Fz", "F4", "C3", "Cz", "C4", "P3", "Pz", "P4", "O1", "O2")
nightpartOrder <- c("firstHour", "firstQuarter", "secondQuarter", "thirdQuarter", "fourthQuarter", "wholeNight")
sleepstageOrder <- c("N2", "N3", "NREM")
colsData$condition <- factor(colsData$condition,levels = conditionOrder,ordered = TRUE)
colsData$parameter <- factor(colsData$parameter,levels = parameterOrder,ordered = TRUE)
colsData$electrode <- factor(colsData$electrode,levels = electrodeOrder,ordered = TRUE)
colsData$nightpart <- factor(colsData$nightpart,levels = nightpartOrder,ordered = TRUE)
colsData$sleepstage <- factor(colsData$sleepstage,levels = sleepstageOrder,ordered = TRUE)

# finally, sort by factors & create a vector for column number
library(dplyr)
colsData <- arrange(colsData,condition,parameter,electrode,nightpart,sleepstage)
colsData$colId <- 1:nrow(colsData)
colsData
</code>```

...and the output:

```<code>> colsData
                            columnName    parameter condition electrode nightpart
1   Adapt_N2_negLengthLoc_C3_firstHour negLengthLoc     Adapt        C3 firstHour
2   Adapt_N3_negLengthLoc_C3_firstHour negLengthLoc     Adapt        C3 firstHour
3 Adapt_NREM_negLengthLoc_C3_firstHour negLengthLoc     Adapt        C3 firstHour
4    Book_N2_negLengthLoc_C3_firstHour negLengthLoc      Book        C3 firstHour
5    Book_N3_negLengthLoc_C3_firstHour negLengthLoc      Book        C3 firstHour
6  Book_NREM_negLengthLoc_C3_firstHour negLengthLoc      Book        C3 firstHour
  sleepstage colId
1         N2     1
2         N3     2
3       NREM     3
4         N2     4
5         N3     5
6       NREM     6
>
</code>```

At this point we can use colsData$columnName to order the original data frame.

Body:
I would like to sort the columns of a large dataframe (around 14000 variables) based on a specific rationale.

The column names have the following structure (Condition_Sleepstage_Parameter_Electrode_Nightpart):

 [1] "Adapt_N2_negLengthLoc_C3_firstHour"          "Adapt_N3_negLengthLoc_C3_firstHour"
  [3] "Adapt_NREM_negLengthLoc_C3_firstHour"        "Book_N2_negLengthLoc_C3_firstHour"
  [5] "Book_N3_negLengthLoc_C3_firstHour"           "Book_NREM_negLengthLoc_C3_firstHour"

R has the columns ordered in a purely alphabetical structure but I would like to have them in a logical order based on the following system:

First, variables should be presented in blocks per parameter. (order: "negLengthLoc", "posLength", "wholeLength", "negPeak", "nbnegPeaks", "initialMeannegSlope", "finalMeannegSlope", "initialMaxnegslope", "finalMaxnegslope", "posPeak", "nbposPeaks", "initialMeannposSlope", "finalMeanposSlope", "initialMaxposSlope", "PeaktoPeak", "Number", "Density")

Within these blocks, the highest order hierarchy should be due to Condition. (order: "Adapt", "NoFilter", "Filter", "Book").

Thereafter, the next hierarchy should be defined by Electrode. (order: "F3", "Fz", "F4", "C3", "Cz", "C4", "P3", "Pz", "P4", "O1", "O2").

Thereafter by Nightpart (order:"firstHour", "firstQuarter", "secondQuarter", "thirdQuarter", "fourthQuarter", "wholeNight") and lastly by Sleepstage ("order: "N2", "N3", "NREM").

The resulting order should look like:

[1] "Adapt_N2_negLengthLoc_F3_firstHour"          "Adapt_N3_negLengthLoc_F3_firstHour"
[3] "Adapt_NREM_negLengthLoc_F3_firstHour"          "Adapt_N2_negLengthLoc_F3_firstQuarter"
[5] "Adapt_N3_negLengthLoc_F3_firstQuarter"          "Adapt_NREM_negLengthLoc_F3_firstQuarter"
[7] "Adapt_N2_negLengthLoc_F3_secondQuarter"          "Adapt_N3_negLengthLoc_F3_secondQuarter"
[9] "Adapt_NREM_negLengthLoc_F3_secondQuarter"          "Adapt_N2_negLengthLoc_F3_thirdQuarter"
[11] "Adapt_N3_negLengthLoc_F3_thirdQuarter"          "Adapt_NREM_negLengthLoc_F3_thirdQuarter"
[13] "Adapt_N2_negLengthLoc_F3_fourthQuarter"          "Adapt_N3_negLengthLoc_F3_fourthQuarter"
[15] "Adapt_NREM_negLengthLoc_F3_fourthQuarter"          "Adapt_N2_negLengthLoc_F3_wholeNight"
[17] "Adapt_N3_negLengthLoc_F3_wholeNight"           "Adapt_NREM_negLengthLoc_F3_wholeNight"
[19] "Adapt_N2_negLengthLoc_Fz_firstHour"           "Adapt_N3_negLengthLoc_Fz_firstHour"
...

I hope that someone can help me, if there are any further questions then I am of course happy to provide more information!

Thanks in advance!

Body:
Illustrating with the mtcars data, one can reorder the columns in a data frame by creating a vector with the the desired order, and using this in the column specification with the [ form of the extract operator.

First, we'll use colnames() to extract the original order of the columns and print them

theNames <- colnames(mtcars)
theNames

> theNames
 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"

Next, we'll move all of the integer columns to the left side of the data frame by creating a reorderedNames vector and using it with [.

reorderedNames <- c("cyl" , "vs" ,  "am" ,  "gear" ,"carb","disp" ,
                     "drat", "wt" ,  "qsec", "mpg")
mtcars[,reorderedNames]

...and the first few rows of output:

> mtcars[,reorderedNames]
                    cyl vs am gear carb  disp drat    wt  qsec  mpg
Mazda RX4             6  0  1    4    4 160.0 3.90 2.620 16.46 21.0
Mazda RX4 Wag         6  0  1    4    4 160.0 3.90 2.875 17.02 21.0
Datsun 710            4  1  1    4    1 108.0 3.85 2.320 18.61 22.8
Hornet 4 Drive        6  1  0    3    1 258.0 3.08 3.215 19.44 21.4
Hornet Sportabout     8  0  0    3    2 360.0 3.15 3.440 17.02 18.7
Valiant               6  1  0    3    1 225.0 2.76 3.460 20.22 18.1
Duster 360            8  0  0    3    4 360.0 3.21 3.570 15.84 14.3
Merc 240D             4  1  0    4    2 146.7 3.69 3.190 20.00 24.4

Automating this process for a large data frame

In the OP, the question references a data frame with a large number of columns. In order to extend this process to automate the sorting of columns, there are at least two major approaches.

Process the column names from the data frame in a manner that allows one to sort the column names in the desired order, or

Create a narrow format tidy data set by using pivot_longer() to split the column names into the required grouping variables.

We'll use data from the OP to illustrate approach 1.

columnName <- c("Adapt_N2_negLengthLoc_C3_firstHour","Adapt_N3_negLengthLoc_C3_firstHour",
"Adapt_NREM_negLengthLoc_C3_firstHour","Book_N2_negLengthLoc_C3_firstHour",
"Book_N3_negLengthLoc_C3_firstHour","Book_NREM_negLengthLoc_C3_firstHour")
splitCols <- strsplit(columnName,"_")

results <- lapply(splitCols,function(x){
     parameter <- x[3]
     condition <- x[1]
     electrode <- x[4]
     nightpart <- x[5]
     sleepstage <- x[2]
     data.frame(parameter,condition,electrode,nightpart,sleepstage)
})

colsData <- do.call(rbind,results)
# add original column names back into data
colsData <- cbind(columnName,colsData)
# convert to factors, specifying the factor order for sorting
conditionOrder <- c("Adapt", "NoFilter", "Filter", "Book")
parameterOrder <- c("negLengthLoc", "posLength", "wholeLength", "negPeak", "nbnegPeaks",
                    "initialMeannegSlope", "finalMeannegSlope", "initialMaxnegslope",
                    "finalMaxnegslope", "posPeak", "nbposPeaks", "initialMeannposSlope",
                    "finalMeanposSlope", "initialMaxposSlope", "PeaktoPeak", "Number", "Density")
electrodeOrder <- c("F3", "Fz", "F4", "C3", "Cz", "C4", "P3", "Pz", "P4", "O1", "O2")
nightpartOrder <- c("firstHour", "firstQuarter", "secondQuarter", "thirdQuarter", "fourthQuarter", "wholeNight")
sleepstageOrder <- c("N2", "N3", "NREM")
colsData$condition <- factor(colsData$condition,levels = conditionOrder,ordered = TRUE)
colsData$parameter <- factor(colsData$parameter,levels = parameterOrder,ordered = TRUE)
colsData$electrode <- factor(colsData$electrode,levels = electrodeOrder,ordered = TRUE)
colsData$nightpart <- factor(colsData$nightpart,levels = nightpartOrder,ordered = TRUE)
colsData$sleepstage <- factor(colsData$sleepstage,levels = sleepstageOrder,ordered = TRUE)

# finally, sort by factors & create a vector for column number
library(dplyr)
colsData <- arrange(colsData,condition,parameter,electrode,nightpart,sleepstage)
colsData$colId <- 1:nrow(colsData)
colsData

...and the output:

> colsData
                            columnName    parameter condition electrode nightpart
1   Adapt_N2_negLengthLoc_C3_firstHour negLengthLoc     Adapt        C3 firstHour
2   Adapt_N3_negLengthLoc_C3_firstHour negLengthLoc     Adapt        C3 firstHour
3 Adapt_NREM_negLengthLoc_C3_firstHour negLengthLoc     Adapt        C3 firstHour
4    Book_N2_negLengthLoc_C3_firstHour negLengthLoc      Book        C3 firstHour
5    Book_N3_negLengthLoc_C3_firstHour negLengthLoc      Book        C3 firstHour
6  Book_NREM_negLengthLoc_C3_firstHour negLengthLoc      Book        C3 firstHour
  sleepstage colId
1         N2     1
2         N3     2
3       NREM     3
4         N2     4
5         N3     5
6       NREM     6
>

At this point we can use colsData$columnName to order the original data frame.


问:
Windows 10: "The ampersand () character is not allowed"
I am learning C language. I installed and configurated everything to start coding

But when I try to use ampersand (&) in scanf my program doesn't compile:

```<code>scanf("%f", &x);
</code>```

I am getting this error:

The ampersand () character is not allowed. The & operator is reserved
  for future use; wrap an ampersand in double quotation marks ("&") to
  pass it as part of a string.

答:
I don't think you have everything installed and configured correctly.
The error looks like a PowerShell error, not a C compilation error.

Get a C compiler like MinGW-w64 GCC from http://winlibs.com/ and make sure to compile your C code (there is an example on that website showing you how to compile from the Command Prompt).

Body:
I am learning C language. I installed and configurated everything to start coding

But when I try to use ampersand (&) in scanf my program doesn't compile:

scanf("%f", &x);

I am getting this error:

The ampersand () character is not allowed. The & operator is reserved
  for future use; wrap an ampersand in double quotation marks ("&") to
  pass it as part of a string.


问:
global variable not defined inside async function
I have an async function that is supposed to add reactions to a list until a certain reaction is pressed then it will add all appropriate roles. to do this I have a global variable "reactions = []" that gets reset when the "ok" reaction is pressed. VS Code is telling me this on the line "for react in reactions:" : "reactions is used before it is defined. Move the definition before." this is confusing because roleEmojis is another global variable but that works fine.
here is my code:

```<code>import os
import discord
import time
from discord.utils import get
from discord.ext import commands

token = "TOKEN"
BOT = commands.Bot("£")
reactions_list = []

@BOT.event
async def on_reaction_add(reaction , user):
    if reaction.emoji in roleEmojis.keys() and user != BOT.user:
        if reaction == get(reaction.message.guild.emojis, name = "OK"):
            for react in reactions_list:
                await user.add_roles(roleEmojis[react.emoji])
            reactions_list = []
        else:
            reactions_list.append(reaction)

BOT.run(token)
</code>```

Side note: I haven't yet figured out how to detect when someone has "un-reacted" to a message, id appreciate any help there

答:
use
global reactions in your local method to make use of global variable

And as per the error you mentioned your error lies in for loop which I cant see in code snipped. In python you need to explicitly mentioned if you're using global variable. (except if it is a list and your using that through function parameter or any other data type which uses address).

Ex-

```<code>a=0
def b():
    a=1
b()
print(a)
</code>```

Will result 0

```<code>a=0
def b():
    global a
    a=1
b()
print(a)
</code>```

will result 1

Body:
I have an async function that is supposed to add reactions to a list until a certain reaction is pressed then it will add all appropriate roles. to do this I have a global variable "reactions = []" that gets reset when the "ok" reaction is pressed. VS Code is telling me this on the line "for react in reactions:" : "reactions is used before it is defined. Move the definition before." this is confusing because roleEmojis is another global variable but that works fine.
here is my code:

import os
import discord
import time
from discord.utils import get
from discord.ext import commands

token = "TOKEN"
BOT = commands.Bot("£")
reactions_list = []

@BOT.event
async def on_reaction_add(reaction , user):
    if reaction.emoji in roleEmojis.keys() and user != BOT.user:
        if reaction == get(reaction.message.guild.emojis, name = "OK"):
            for react in reactions_list:
                await user.add_roles(roleEmojis[react.emoji])
            reactions_list = []
        else:
            reactions_list.append(reaction)

BOT.run(token)

Side note: I haven't yet figured out how to detect when someone has "un-reacted" to a message, id appreciate any help there

Body:
use
global reactions in your local method to make use of global variable

And as per the error you mentioned your error lies in for loop which I cant see in code snipped. In python you need to explicitly mentioned if you're using global variable. (except if it is a list and your using that through function parameter or any other data type which uses address).

Ex-

a=0
def b():
    a=1
b()
print(a)

Will result 0

a=0
def b():
    global a
    a=1
b()
print(a)

will result 1


问:
Is it better to set the default MYSQL JSON value to `{}` or `NULL`
We are starting to use the MySQL json datatype. Is there any recommended best practices when storing default values as NULL or {} for the JSON datatype? What are the PROs and CONs for each?

答:
PhpMyAdmin uses the text null by default, if you add a new JSON column to existing rows.

Note this is different from NULL. NULL means unknown/doesn't exist in the database, null means unknown/doesn't exist after converted to JSON. {} is an empty JSON object.


问:
Semantic Role Labeling using NLTK
I have a list of sentences and I want to analyze every sentence and identify the semantic roles within that sentence. How do I do that?

I came across the PropBankCorpusReader within NLTK module that adds semantic labeling information to the Penn Treebank. Also my research on the internet suggests that this module is used to perform Semantic Role Labeling.

I am however unable to find a small HOWTO that helps me understand how we can leverage the PropBankCorpusReader to perform SRL on arbitary text.

Hence can someone point out examples of using PropbankCorpusReader to perform SRL on arbitary sentences?

答: As of now probably the easiest option is https://demo.allennlp.org/semantic-role-labeling. Due to the underlying transformer architecture, it comes with over 1 GB memory requirement.</p>

Title: Semantic Role Labeling using NLTK


问:
What is the purpose of -p, --project-name option in docker-compose command
What is the purpose of -p or --project-name option in docker-compose command?

What is the use case for it?

I am a newbie and havent yet started docker networking. Is --project-name used there in docker networking?

When I add docker support in Visual Studio 2019, Visual Studio runs some docker compose command which look like below. In each of them, there is a -p option. I am curious about that.

```<code>docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi config
docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi build
docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi up -d --no-build --force-recreate --remove-orphans
</code>```

I have seen the docker docs here and also this, but could not get much from there.

答:
By default, Compose bases the project name on basename of the directory compose
commands are run from. The project name can be overridden either by
passing a -p / --project-name option for each command or setting the
COMPOSE_PROJECT_NAME environment variable.

Use case is basically to maintain different projects with this. For e.g.:- You can use same docker-compose.yml to have 2 different projects.

In the command which you mentioned

```<code>docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi config
docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi build
docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi up -d --no-build --force-recreate --remove-orphans
</code>```

If you see, it's manipulating the same project and that's why -p is given.

Body:
What is the purpose of -p or --project-name option in docker-compose command?

What is the use case for it?

I am a newbie and havent yet started docker networking. Is --project-name used there in docker networking?

When I add docker support in Visual Studio 2019, Visual Studio runs some docker compose command which look like below. In each of them, there is a -p option. I am curious about that.

docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi config
docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi build
docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi up -d --no-build --force-recreate --remove-orphans

I have seen the docker docs here and also this, but could not get much from there.

Body:
By default, Compose bases the project name on basename of the directory compose
commands are run from. The project name can be overridden either by
passing a -p / --project-name option for each command or setting the
COMPOSE_PROJECT_NAME environment variable.

Use case is basically to maintain different projects with this. For e.g.:- You can use same docker-compose.yml to have 2 different projects.

In the command which you mentioned

docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi config
docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi build
docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi up -d --no-build --force-recreate --remove-orphans

If you see, it's manipulating the same project and that's why -p is given.


问:
Save data to firebase realtime database if OTP verification is done
```<code>enter code here

Submit=e=>{

      e.preventDefault();
        let data="";
      this.setUpRecaptcha();
      // window.alert("Appointment Done Successfully at time "+this.state.curTime+" ! Go to the home page");
      var phoneNumber = this.state.contact;
      console.log(phoneNumber)
      var appVerifier = window.recaptchaVerifier;
      firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
          .then(function (confirmationResult) {
            // SMS sent. Prompt user to type the code from the message, then sign the
            // user in with confirmationResult.confirm(code).

            window.confirmationResult = confirmationResult;
            var code = window.prompt("enter OTP")
            confirmationResult.confirm(code).then(function (result) {
              // User signed in successfully.
              var user = result.user;
              alert("OTP is verified!!!");
              this.data="doneit";
              // ...
            }).catch(function (error) {
              // User couldn't sign in (bad verification code?)
              // ...
              alert("OTP verification failed");
            });
          }).catch(function (error) {
            // Error; SMS not sent
            // ...
            alert("cann't send OTP use another Contact number")
          });

//Data storage code
          if(this.data=='doneit'){
            firebase.database().ref("appoinment").push(
              {
                name:this.state.name,
                email:this.state.email,
                contact:this.state.contact,
                age:this.state.age,
                gender:this.state.gender,
                Appointdate:this.state.Appointdate,
                Description:this.state.Description,
                date:this.state.curTime
              }
            );
            alert(" Data saved successfully");
            window.location.reload(false);
          }
          else{
            alert("failed");
          }

    };
</code>```

My code is as shown above. I want execution in such a way that if after submitting form Submit() will be called. Then it will check for OTP verification. If it is successful then only data will be stored at firebase realtime database

List item

答:
Why don't you put the logic to save the data after the confirmation promise:</p>

```<code>Submit=e=>{

      e.preventDefault();
        let data="";
      this.setUpRecaptcha();
      // window.alert("Appointment Done Successfully at time "+this.state.curTime+" ! Go to the home page");
      var phoneNumber = this.state.contact;
      console.log(phoneNumber)
      var appVerifier = window.recaptchaVerifier;
      firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
          .then(function (confirmationResult) {
            // SMS sent. Prompt user to type the code from the message, then sign the
            // user in with confirmationResult.confirm(code).

            window.confirmationResult = confirmationResult;
            var code = window.prompt("enter OTP")
            confirmationResult.confirm(code).then(function (result) {
              // User signed in successfully.
              var user = result.user;
              alert("OTP is verified!!!");
              this.data="doneit";

                 firebase.database().ref("appoinment").push({
                   name:this.state.name,
                   email:this.state.email,
                   contact:this.state.contact,
                   age:this.state.age,
                   gender:this.state.gender,
                   Appointdate:this.state.Appointdate,
                   Description:this.state.Description,
                   date:this.state.curTime
                });
               alert(" Data saved successfully");
               window.location.reload(false);

              // ...
            }).catch(function (error) {
              // User couldn't sign in (bad verification code?)
              // ...
              alert("OTP verification failed");
            });
          }).catch(function (error) {
            // Error; SMS not sent
            // ...
            alert("cann't send OTP use another Contact number")
          });

    };
</code>```

Body:
enter code here

Submit=e=>{

      e.preventDefault();
        let data="";
      this.setUpRecaptcha();
      // window.alert("Appointment Done Successfully at time "+this.state.curTime+" ! Go to the home page");
      var phoneNumber = this.state.contact;
      console.log(phoneNumber)
      var appVerifier = window.recaptchaVerifier;
      firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
          .then(function (confirmationResult) {
            // SMS sent. Prompt user to type the code from the message, then sign the
            // user in with confirmationResult.confirm(code).

            window.confirmationResult = confirmationResult;
            var code = window.prompt("enter OTP")
            confirmationResult.confirm(code).then(function (result) {
              // User signed in successfully.
              var user = result.user;
              alert("OTP is verified!!!");
              this.data="doneit";
              // ...
            }).catch(function (error) {
              // User couldn't sign in (bad verification code?)
              // ...
              alert("OTP verification failed");
            });
          }).catch(function (error) {
            // Error; SMS not sent
            // ...
            alert("cann't send OTP use another Contact number")
          });

//Data storage code
          if(this.data=='doneit'){
            firebase.database().ref("appoinment").push(
              {
                name:this.state.name,
                email:this.state.email,
                contact:this.state.contact,
                age:this.state.age,
                gender:this.state.gender,
                Appointdate:this.state.Appointdate,
                Description:this.state.Description,
                date:this.state.curTime
              }
            );
            alert(" Data saved successfully");
            window.location.reload(false);
          }
          else{
            alert("failed");
          }

    };

My code is as shown above. I want execution in such a way that if after submitting form Submit() will be called. Then it will check for OTP verification. If it is successful then only data will be stored at firebase realtime database

List item

Body:
Why don't you put the logic to save the data after the confirmation promise:

Submit=e=>{

      e.preventDefault();
        let data="";
      this.setUpRecaptcha();
      // window.alert("Appointment Done Successfully at time "+this.state.curTime+" ! Go to the home page");
      var phoneNumber = this.state.contact;
      console.log(phoneNumber)
      var appVerifier = window.recaptchaVerifier;
      firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
          .then(function (confirmationResult) {
            // SMS sent. Prompt user to type the code from the message, then sign the
            // user in with confirmationResult.confirm(code).

            window.confirmationResult = confirmationResult;
            var code = window.prompt("enter OTP")
            confirmationResult.confirm(code).then(function (result) {
              // User signed in successfully.
              var user = result.user;
              alert("OTP is verified!!!");
              this.data="doneit";

                 firebase.database().ref("appoinment").push({
                   name:this.state.name,
                   email:this.state.email,
                   contact:this.state.contact,
                   age:this.state.age,
                   gender:this.state.gender,
                   Appointdate:this.state.Appointdate,
                   Description:this.state.Description,
                   date:this.state.curTime
                });
               alert(" Data saved successfully");
               window.location.reload(false);

              // ...
            }).catch(function (error) {
              // User couldn't sign in (bad verification code?)
              // ...
              alert("OTP verification failed");
            });
          }).catch(function (error) {
            // Error; SMS not sent
            // ...
            alert("cann't send OTP use another Contact number")
          });

    };


问:
Select the value of an element by name
How to access the value of this input field that is checked by its name attribute using Javascript :

```<code><input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">
</code>```

I write this :

```<code>document.querySelector('input[name="rate"]:checked').value;
</code>```

but there is an error:

```<code>TypeError: document.querySelector(...) is null
</code>```

And I do not want to be checked any inputs by default

答:
Not sure if this will help you, but this snippet lets you select the value of the radio element that is checked, if it exists.</p>

```<code>radioElems = document.querySelectorAll("input[name='rate']");
radioElems.forEach((elem) => {
    if (elem.checked) {
        console.log(`Check found with value ${elem.value}`);
    } else {
        console.log("Not checked");
    }
});
</code>```

Title: Select the value of an element by name

Body:
How to access the value of this input field that is checked by its name attribute using Javascript :

<input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">

I write this :

document.querySelector('input[name="rate"]:checked').value;

but there is an error:

TypeError: document.querySelector(...) is null

And I do not want to be checked any inputs by default

Body:
Not sure if this will help you, but this snippet lets you select the value of the radio element that is checked, if it exists.

radioElems = document.querySelectorAll("input[name='rate']");
radioElems.forEach((elem) => {
    if (elem.checked) {
        console.log(`Check found with value ${elem.value}`);
    } else {
        console.log("Not checked");
    }
});


问:
Python - Convert a roman numeral to an integer
I've tried the following Python 3 code that transform from Roman to Integer.

The code is working fine at a glance. But there are certain problem happened when I input X, V or related to X and V value.

For example: when I try V the code is not working but for IV showing correct value.

My code:

```<code>class Solution(object):
   def romanToInt(self, s):
      """
      :type s: str
      :rtype: int
      """
      roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
      i = 0
      num = 0
      while i < len(s):
         if i+1<len(s) and s[i:i+2] in roman:
            num+=roman[s[i:i+2]]
            i+=2
         else:
            #print(i)
            num+=roman[s[i]]
            i+=1
      return num
ob1 = Solution()

message = str(input("Please enter your roman number: "))
if message <= ("MMMCMXCIX"):
   print (ob1.romanToInt(message))
else:
    print ("Try again")
</code>```

I've set the condition which is, if the input roman number is equal or less than MMMCMXCIX, it will print the roman number; else it will print Try again.

The problem is when I input X, V or related to X and V value the output is showing Try again

Please help me to understand where I went wrong.

答:
That is because you are comparing the strings instead first convert the roman to int than check</p>

```<code>class Solution(object):
   def romanToInt(self, s):
      """
      :type s: str
      :rtype: int
      """
      roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
      i = 0
      num = 0
      while i < len(s):
         if i+1<len(s) and s[i:i+2] in roman:
            num+=roman[s[i:i+2]]
            i+=2
         else:
            #print(i)
            num+=roman[s[i]]
            i+=1
      return num
ob1 = Solution()

message = str(input("Please enter your roman number: "))
# converting to integer than comparing the value of "MMMCMXCIX"
if ob1.romanToInt(message) <= 8999:
   print (ob1.romanToInt(message))
else:
    print ("Try again")
</code>```

Body:
I've tried the following Python 3 code that transform from Roman to Integer.

The code is working fine at a glance. But there are certain problem happened when I input X, V or related to X and V value.

For example: when I try V the code is not working but for IV showing correct value.

My code:

class Solution(object):
   def romanToInt(self, s):
      """
      :type s: str
      :rtype: int
      """
      roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
      i = 0
      num = 0
      while i < len(s):
         if i+1<len(s) and s[i:i+2] in roman:
            num+=roman[s[i:i+2]]
            i+=2
         else:
            #print(i)
            num+=roman[s[i]]
            i+=1
      return num
ob1 = Solution()

message = str(input("Please enter your roman number: "))
if message <= ("MMMCMXCIX"):
   print (ob1.romanToInt(message))
else:
    print ("Try again")

I've set the condition which is, if the input roman number is equal or less than MMMCMXCIX, it will print the roman number; else it will print Try again.

The problem is when I input X, V or related to X and V value the output is showing Try again

Please help me to understand where I went wrong.

Body:
That is because you are comparing the strings instead first convert the roman to int than check

class Solution(object):
   def romanToInt(self, s):
      """
      :type s: str
      :rtype: int
      """
      roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
      i = 0
      num = 0
      while i < len(s):
         if i+1<len(s) and s[i:i+2] in roman:
            num+=roman[s[i:i+2]]
            i+=2
         else:
            #print(i)
            num+=roman[s[i]]
            i+=1
      return num
ob1 = Solution()

message = str(input("Please enter your roman number: "))
# converting to integer than comparing the value of "MMMCMXCIX"
if ob1.romanToInt(message) <= 8999:
   print (ob1.romanToInt(message))
else:
    print ("Try again")


问:
bitcode bundle could not be generated because
Basically I have built a compiled released framework and distributed it with cocoaPods. The problem is that then archiving this framework application gets the following error:

ld: bitcode bundle could not be generated because
  '/Users/cagrialtay/Desktop/mucbirsebepler/ios/Flutter/Flutter.framework/Flutter'
  was built without full bitcode. All frameworks and dylibs for bitcode
  must be generated from Xcode Archive or Install build file
  '/Users/cagrialtay/Desktop/mucbirsebepler/ios/Flutter/Flutter.framework/Flutter'
  for architecture armv7 clang: error: linker command failed with exit
  code 1 (use -v to see invocation) Search for Enable Bitcode setting
  and set it to YES for Debug and Release modes.

Things I tried but had no luck

Enable Bitcode' set to 'YES' Adding '-fembed-bitcode' to 'Other C

Flags' Adding 'BITCODE_GENERATION_MODE' with the value 'bitcode' set

skip install to yes

I only need release version, so I did not built an universal framework, just release version... I would genuinely like to solve this issue, because it has been a nightmare for me..

答:
I finally solved this.This error happened because of me . I develop my iOS application with flutter, so if you develop your iOS app in Flutter firstly you must build with flutter not Xcode

```<code>flutter clean
flutter build ios
</code>```

then go

Xcode -> Product -> Destination -> Any iOS Device

Xcode-> Product -> Scheme -> choose scheme -> Runner

Xcode-> Product -> Archive

or

```<code>flutter clean
flutter build ipa
</code>```

then

Xcode-> Product -> Archive

Body:
I finally solved this.This error happened because of me . I develop my iOS application with flutter, so if you develop your iOS app in Flutter firstly you must build with flutter not Xcode

flutter clean
flutter build ios

then go

Xcode -> Product -> Destination -> Any iOS Device

Xcode-> Product -> Scheme -> choose scheme -> Runner

Xcode-> Product -> Archive

or

flutter clean
flutter build ipa

then

Xcode-> Product -> Archive


问:
How to pipe multiple values to a C program, with python -c
So, I know I can pipe a value, with python, to the stdin of a C program:

```<code>python -c 'print "Hello"' | ./program
</code>```

The 'Hello' string will be read by the first scanf of the C program (or similar function).

My problem is, how do I do this when I have multiple scanfs and I want to pass individual values to each one of them?

Thank you!

答:
In the same manner you can do this.
Suppose your C program take a string first and then two integer.

So you separate the input value by \n as you would do in a terminal, like:

```<code>python -c 'print "Hello\n5 10"' | ./program

</code>```

Body:
So, I know I can pipe a value, with python, to the stdin of a C program:

python -c 'print "Hello"' | ./program

The 'Hello' string will be read by the first scanf of the C program (or similar function).

My problem is, how do I do this when I have multiple scanfs and I want to pass individual values to each one of them?

Thank you!

Body:
In the same manner you can do this.
Suppose your C program take a string first and then two integer.

So you separate the input value by \n as you would do in a terminal, like:

python -c 'print "Hello\n5 10"' | ./program


问:
2D array conversion (an integer to a string)
I am writing a game code. The board of this game is 10x10 size. In the beginning, I wrote this board as a two-dimensional integer array. Now I have to replace some places on the board with letters. It will change with letters according to the coordinates entered by the player.</p>

```<code>private static int[][] board = new int[10][10]; //board

StringBuilder sb = new StringBuilder();
    for (int[] array : board) {
        sb.append('\n').append(Arrays.toString(array));
    }
    String new = sb.toString(); //I tried to convert this way

if (new[x][y].equals("r")){
    new[x][y] = "d"; //I'm getting an error in this part.
}
</code>```

答:
There are two major problems in your code:

You have used new as the name of the variable which is not allowed as new is a reserved word, used for instantiating.

The following statement does not produce a 2-D array of strings:

```<code>String s = sb.toString();
</code>```

Therefore, your attempt to access/set s[x][y] will result in compilation error.

Recommendations:

Use a String[][] instead of int[][]. A String[][] will be able to store strings consisting of letter(s) as well as integers represented as a string (which you can always parse to the corresponding integer by using Integer::parseInt if the need be).

Create another array of type, String[][] and copy the elements of your int[][] array to it.

I would go with the former one.

Body:
I am writing a game code. The board of this game is 10x10 size. In the beginning, I wrote this board as a two-dimensional integer array. Now I have to replace some places on the board with letters. It will change with letters according to the coordinates entered by the player.

private static int[][] board = new int[10][10]; //board

StringBuilder sb = new StringBuilder();
    for (int[] array : board) {
        sb.append('\n').append(Arrays.toString(array));
    }
    String new = sb.toString(); //I tried to convert this way

if (new[x][y].equals("r")){
    new[x][y] = "d"; //I'm getting an error in this part.
}

Body:
There are two major problems in your code:

You have used new as the name of the variable which is not allowed as new is a reserved word, used for instantiating.

The following statement does not produce a 2-D array of strings:

String s = sb.toString();

Therefore, your attempt to access/set s[x][y] will result in compilation error.

Recommendations:

Use a String[][] instead of int[][]. A String[][] will be able to store strings consisting of letter(s) as well as integers represented as a string (which you can always parse to the corresponding integer by using Integer::parseInt if the need be).

Create another array of type, String[][] and copy the elements of your int[][] array to it.

I would go with the former one.


问:
picture gallery with small thumbnails, medium size image and full size lightbox view
Is there any javascript, css, ajax product gallery (even paid) that would have image (e.g. 400x300) with 5-6 thumbnails (e.g. 80x60) and lightbox (800x600) when the 400x300 image is clicked?

I need a gallery script like this: http://www.neosport.pl/product-pol-942-Buty-Nike-315343-101.html

答:
I've found an answer on my own.
The simplest solution is to use css gallery from: http://www.sohtanaka.com/web-design/css-multiple-image-viewer-thumbnails/ and then for big picture use any lightbox-like script (I used shadowbox with jQuery adapter from http://www.shadowbox-js.com/index.html)</p>