问:
How do I get the "results" object nested in the array "news" and map over it?
I'm trying to map over an array which is fetched using componentDidMount. However, I keep receiving this same error "Uncaught TypeError: this.state.news.map is not a function".

This is on componentDidMount

```<code>componentDidMount() {
        fetch(
            "https://content.guardianapis.com/search?api-key=test"
        )
            .then(response => response.json())
            .then(data => {
                this.setState({
                    news: data
                })
                console.log(data)
            })
    }
</code>```

This is my function to map over the data

```<code>renderNews() {
        return this.state.news.map((a, i) => (
            <div key={i}>
                {a.response.map((b, i) => (
                    <div key={i}>
                        <div key={i} className="newsEach">
                            <h3>{b.webTitle}</h3>
                            <ul className="newsInfoUl">
                                <li className="newsInfoEach">{b.type}</li>
                                <li className="newsInfoEach">
                                    {b.sectionName}
                                </li>
                                <li className="newsInfoEach">{b.pillarName}</li>
                                <li className="newsInfoEach">{b.webUrl}</li>
                            </ul>
                        </div>
                    </div>
                ))}
            </div>
        ))
    }
</code>```

Then I render out the data over here

```<code>render() {
        return (
            <div className="newsWrapper">
                {/* <h3>{this.renderNews()}</h3> */}
                <h3>Hello</h3>
            </div>
        )
    }
</code>```

Update #1
Here is the data that I got from console.log(data)

```<code>{response: {…}}
response:
currentPage: 1
orderBy: "newest"
pageSize: 10
pages: 211707
results: Array(10)
0: {id: "business/live/2019/may/31/markets-trump-shock-mexi…ffs-trade-war-china-brexit-ftse-100-business-live", type: "liveblog", sectionId: "business", sectionName: "Business", webPublicationDate: "2019-05-31T08:25:12Z", …}
1: {id: "football/2019/may/31/atletico-madrid-stadium-wanda…litano-champions-league-final-liverpool-tottenham", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T08:23:15Z", …}
2: {id: "tv-and-radio/2019/may/31/a-sinister-tale-from-the-minds-behind-dirty-john-podcasts-of-the-week", type: "article", sectionId: "tv-and-radio", sectionName: "Television & radio", webPublicationDate: "2019-05-31T08:12:02Z", …}
3: {id: "politics/2019/may/31/alastair-campbell-labour-expulsion-discrimination-appeal", type: "article", sectionId: "politics", sectionName: "Politics", webPublicationDate: "2019-05-31T08:11:22Z", …}
4: {id: "football/from-the-archive-blog/2019/may/31/womens-football-match-crouch-end-1895", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T08:00:27Z", …}
5: {id: "culture/2019/may/31/what-to-see-this-week-in-the-uk", type: "article", sectionId: "culture", sectionName: "Culture", webPublicationDate: "2019-05-31T08:00:27Z", …}
6: {id: "tv-and-radio/2019/may/31/when-they-see-us-review-netflix-ava-duvernay-central-park-five", type: "article", sectionId: "tv-and-radio", sectionName: "Television & radio", webPublicationDate: "2019-05-31T08:00:27Z", …}
7: {id: "music/2019/may/31/lee-scratch-perry-rainford-review-on-u-sound-records", type: "article", sectionId: "music", sectionName: "Music", webPublicationDate: "2019-05-31T08:00:27Z", …}
8: {id: "books/2019/may/31/mother-ship-francesca-segal-review", type: "article", sectionId: "books", sectionName: "Books", webPublicationDate: "2019-05-31T07:58:27Z", …}
9: {id: "football/2019/may/31/football-transfer-rumours-spurs-to-bid-for-wilfried-zaha", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T07:47:36Z", …}
length: 10
__proto__: Array(0)
startIndex: 1
status: "ok"
total: 2117063
userTier: "developer"
__proto__: Object
__proto__: Object
</code>```

Sorry I forgot to include this portion of my code which is what I initialize this.state.news with. Here it is

```<code>constructor() {
        super()

        this.state = {
            news: []
        }

        this.renderNews = this.renderNews.bind(this)
    }
</code>```

答:
This occours because at render time data is not yet ready.

You can do various things depending on your needs.

1º. Declare a default state like state = { news: [] } to be an empty array.

2º. Render some kind of Loading in render method like if (!this.state.news.length) { return "Loading..." }

I saw you have and array into each news item so you should also take control of it.

state = { news: { data: [] } }

Look, you are setting in setState data into news as a object property and then you tries to iterate over it   with map. You can't do it like this.

Body:
I'm trying to map over an array which is fetched using componentDidMount. However, I keep receiving this same error "Uncaught TypeError: this.state.news.map is not a function".

This is on componentDidMount

componentDidMount() {
        fetch(
            "https://content.guardianapis.com/search?api-key=test"
        )
            .then(response => response.json())
            .then(data => {
                this.setState({
                    news: data
                })
                console.log(data)
            })
    }

This is my function to map over the data

renderNews() {
        return this.state.news.map((a, i) => (

                {a.response.map((b, i) => (

{b.webTitle}

{b.type}

                                    {b.sectionName}

{b.pillarName}

{b.webUrl}

                ))}

        ))
    }

Then I render out the data over here

render() {
        return (

                {/*
{this.renderNews()}
 */}

Hello

        )
    }

Update #1
Here is the data that I got from console.log(data)

{response: {…}}
response:
currentPage: 1
orderBy: "newest"
pageSize: 10
pages: 211707
results: Array(10)
0: {id: "business/live/2019/may/31/markets-trump-shock-mexi…ffs-trade-war-china-brexit-ftse-100-business-live", type: "liveblog", sectionId: "business", sectionName: "Business", webPublicationDate: "2019-05-31T08:25:12Z", …}
1: {id: "football/2019/may/31/atletico-madrid-stadium-wanda…litano-champions-league-final-liverpool-tottenham", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T08:23:15Z", …}
2: {id: "tv-and-radio/2019/may/31/a-sinister-tale-from-the-minds-behind-dirty-john-podcasts-of-the-week", type: "article", sectionId: "tv-and-radio", sectionName: "Television & radio", webPublicationDate: "2019-05-31T08:12:02Z", …}
3: {id: "politics/2019/may/31/alastair-campbell-labour-expulsion-discrimination-appeal", type: "article", sectionId: "politics", sectionName: "Politics", webPublicationDate: "2019-05-31T08:11:22Z", …}
4: {id: "football/from-the-archive-blog/2019/may/31/womens-football-match-crouch-end-1895", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T08:00:27Z", …}
5: {id: "culture/2019/may/31/what-to-see-this-week-in-the-uk", type: "article", sectionId: "culture", sectionName: "Culture", webPublicationDate: "2019-05-31T08:00:27Z", …}
6: {id: "tv-and-radio/2019/may/31/when-they-see-us-review-netflix-ava-duvernay-central-park-five", type: "article", sectionId: "tv-and-radio", sectionName: "Television & radio", webPublicationDate: "2019-05-31T08:00:27Z", …}
7: {id: "music/2019/may/31/lee-scratch-perry-rainford-review-on-u-sound-records", type: "article", sectionId: "music", sectionName: "Music", webPublicationDate: "2019-05-31T08:00:27Z", …}
8: {id: "books/2019/may/31/mother-ship-francesca-segal-review", type: "article", sectionId: "books", sectionName: "Books", webPublicationDate: "2019-05-31T07:58:27Z", …}
9: {id: "football/2019/may/31/football-transfer-rumours-spurs-to-bid-for-wilfried-zaha", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T07:47:36Z", …}
length: 10
__proto__: Array(0)
startIndex: 1
status: "ok"
total: 2117063
userTier: "developer"
__proto__: Object
__proto__: Object

Sorry I forgot to include this portion of my code which is what I initialize this.state.news with. Here it is

constructor() {
        super()

        this.state = {
            news: []
        }

        this.renderNews = this.renderNews.bind(this)
    }


来源: stackexchange

问:
Gstreamer record camera to multiple files in real time
I'm working on an application where I need to capture hours of continuous video, and then later upload specific time windows to a remote machine. Because the video data is large, and this system will be collecting for months, everything has to be compressed.

My first attempt was to use two threads to avoid dropping frames - the first has a very simple pipeline with no compression, while the second performs the compression. Here is the pipeline I would want to run on the first:

```<code>gst-launch-1.0 v4l2src num-buffers=300 ! video/x-raw,framerate=30/1 ! filesink location=myFile
</code>```

This command would be run in a loop to capture a sequence of files. Unfortunately, while this should capture 300/30 = 10s of video, it takes 30s to execute. That means I'm losing a huge amount of video before the next iteration of the loop can start.

I looked into splitmuxsink, but get a message that it doesn't exist, even though I have all the plugins installed.

It seems that gstreamer must be powerful enough for me to access the buffered, raw video and select chunks of it to save as the buffer fills, but there aren't any examples with anything close to this that I can find. How would others recommend going about this goal?

Details:

Jetson Tx1

Ubuntu 14.04

Update

Several folks suggested the gstreamer element splitmuxsink - I think this would work in general, but my TX1 comes with gstreamer 1.2.4, which predates splitmuxsink. I looked into updating gstreamer and didn't find anything helpful / it would break a bunch of the tools that Nvidia includes for hardware optimization.

I built a python application to try dynamically modifying a gstreamer pipeline, pointing the stream to different filesink (see below). The code runs ok and (usually) creates a series of avi files. There are a couple problems:

Even though the event to start a new file triggers every 10s, the videos themselves are only 3s!

Occasionally, a file will be saved with no data, and all subsequent files will be empty

Does anyone have any insight into these problems?

```<code>#! /usr/bin/env python

import os
import sys
import logging

import gi
gi.require_version('Gst', "1.0")
gi.require_version('GstBase', "1.0")
gi.require_version('Gtk', "3.0")
#gi.require_version('GdkX11', '3.0')
gi.require_version('GstVideo', '1.0')

from gi.repository import GObject, Gst, GstBase, Gtk, GstVideo, GdkX11

import numpy as np
import datetime as dt

log = logging.getLogger(__name__)

class Segmenter:
    def __init__(self):
        Gst.init(None)

        self.terminate = False

        # Create gstreamer pipeline
        cmd = "v4l2src ! tee name=tee ! fakesink"
        self.pipeline = Gst.parse_launch(cmd)

        # Store references to gstreamer objects
        self.bus = self.pipeline.get_bus()
        self.recordpipe = None

    def run(self):
        # Initiate main loop
        self.pipeline.set_state(Gst.State.PAUSED)
        self.pipeline.set_state(Gst.State.PLAYING)

        try:
            while not self.terminate:
                print(dt.datetime.now().time())
                # Listen for event messages on the bus
                msg = self.bus.timed_pop_filtered(10 * Gst.SECOND, (Gst.MessageType.EOS | Gst.MessageType.ERROR))

                if msg:
                    if msg.type == Gst.MessageType.ERROR:
                        err, dbg = msg.parse_error()
                        print("ERROR:", msg.src.get_name(), ":", err)
                        if dbg:
                            print("Debug info:", dbg)
                        self.terminate = True

                    elif msg.type == Gst.MessageType.EOS:
                        print("End-Of-Stream reached")
                        self.terminate = True

                else:
                    # No message - must have reached timeout
                    self.begin_new_file()

        finally:
            # Free up resources
            self.pipeline.set_state(Gst.State.NULL)

    def begin_new_file(self):

        # If recording a file currently, terminate it
        if self.recordpipe is not None:

            # Block new data
            filequeue = self.recordpipe.get_by_name("filequeue")
            filequeue.get_static_pad("src").add_probe(Gst.PadProbeType.BLOCK_DOWNSTREAM, self.probe_block)

            # Disconnect the recording pipe
            self.pipeline.get_by_name("tee").unlink(self.recordpipe)

            # Send a termination event to trigger the save
            filequeue.get_static_pad("sink").send_event(Gst.Event.new_eos())

            # Clear the reference to the pipe
            self.recordpipe = None

        # Create a new file target
        filename = dt.datetime.now().strftime("%Y-%m-%d_%H.%M.%S") + ".avi"
        print("Recording {}...".format(filename))

        # Create a new pipeline for the new file
        self.recordpipe = Gst.parse_bin_from_description("queue name=filequeue ! jpegenc ! avimux ! filesink location={} sync=False".format(filename), True)
        self.pipeline.add(self.recordpipe)

        # Connect to the main pipe
        self.pipeline.get_by_name("tee").link(self.recordpipe)

        # Start passing data
        self.recordpipe.set_state(Gst.State.PLAYING)

    def probe_block(self, pad, buf):
        """ Callback for downstream block """
        print('block.')
        return True

if __name__ == '__main__':
    seg = Segmenter()
    seg.run()
</code>```

答:
Here is an example for using gstreamer in python3 with nvidia TX2 along with splitmuxsink for spliting in segments the recorded video.
Also i have used the callback function for renaming the output segments with the timestamp.</p>

```<code>import gi
gi.require_version('Gst', "1.0")
gi.require_version('GstBase', "1.0")
gi.require_version('Gtk', "3.0")
gi.require_version('GstVideo', '1.0')

from gi.repository import GObject, Gst, GstBase, Gtk, GstVideo, GdkX11

GObject.threads_init()
Gst.init(None)

import datetime as dt
import time

class config():
     width = 1280
     height = 720
     fps = 50
     flip = 0
     segments_time = 5000000000 # 5 seconds in nano
     camera_type = "csi"
     usb_cam = "video0"
     iframe_interval = 30 # every 30 frames place a keyframe, this is needed to set frame at 4.75 seconds

config()

global ref_stamp
ref_stamp = 0

# global first segment flag
global first_segment
first_segment = False

def format_location_callback (splitmux, fragment_id):

    global first_segment

    local_frame_t = round(time.time() * 1000)
    timestamp = str(local_frame_t)
    name = str(timestamp) + ".mp4"

    # first segment is affected by the time needed to open the camera source so it will have around 6 seconds in lenght but the actual recorded frames inside are for 4,5 seconds
    # in this case first segemnt will be saved as test and only the rest are actual segments with the good timestamp
    if first_segment == False:
        name = 'test'
    first_segment = True
    return str(name)

src = pipeline.get_by_name ('splitmux')
src.connect("format-location", format_location_callback)

pipeline.set_state(Gst.State.PLAYING)

#playing = round(time.time() * 1000)
#print("PLAYING: ", playing)

bus = pipeline.get_bus()
msg = bus.pop_filtered(Gst.MessageType.EOS | Gst.MessageType.ERROR)

count = 1

while True:
    count = count + 1
    print (count)
    time.sleep(1)
    # if 15 seconds passed stop the recording;
    if count == 15 :
        break

# send the end of stream event and then wait in the bottom loop for event to be send
# throughout the pipeline.
pipeline.send_event(Gst.Event.new_eos())

# wait in the loop until end of stream is reached
while True:
    msg = bus.pop_filtered(Gst.MessageType.EOS | Gst.MessageType.ERROR)
    if msg:
      print("ENTER")
      if msg.type == Gst.MessageType.ERROR:
           err, dbg = msg.parse_error()
           print("ERROR:", msg.src.get_name(), ":", err)
           if dbg:
                print("Debug info:", dbg)
                break

      elif msg.type == Gst.MessageType.EOS:
                print("End-Of-Stream reached")
                break
    time.sleep(0.1)

pipeline.set_state(Gst.State.NULL)

ref_stamp = round(time.time() * 1000)
print("EXIT: ", ref_stamp)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on an application where I need to capture hours of continuous video, and then later upload specific time windows to a remote machine. Because the video data is large, and this system will be collecting for months, everything has to be compressed.

My first attempt was to use two threads to avoid dropping frames - the first has a very simple pipeline with no compression, while the second performs the compression. Here is the pipeline I would want to run on the first:

gst-launch-1.0 v4l2src num-buffers=300 ! video/x-raw,framerate=30/1 ! filesink location=myFile

This command would be run in a loop to capture a sequence of files. Unfortunately, while this should capture 300/30 = 10s of video, it takes 30s to execute. That means I'm losing a huge amount of video before the next iteration of the loop can start.

I looked into splitmuxsink, but get a message that it doesn't exist, even though I have all the plugins installed.

It seems that gstreamer must be powerful enough for me to access the buffered, raw video and select chunks of it to save as the buffer fills, but there aren't any examples with anything close to this that I can find. How would others recommend going about this goal?

Details:

Jetson Tx1

Ubuntu 14.04

Update

Several folks suggested the gstreamer element splitmuxsink - I think this would work in general, but my TX1 comes with gstreamer 1.2.4, which predates splitmuxsink. I looked into updating gstreamer and didn't find anything helpful / it would break a bunch of the tools that Nvidia includes for hardware optimization.

I built a python application to try dynamically modifying a gstreamer pipeline, pointing the stream to different filesink (see below). The code runs ok and (usually) creates a series of avi files. There are a couple problems:

Even though the event to start a new file triggers every 10s, the videos themselves are only 3s!

Occasionally, a file will be saved with no data, and all subsequent files will be empty

Does anyone have any insight into these problems?

#! /usr/bin/env python

import os
import sys
import logging

import gi
gi.require_version('Gst', "1.0")
gi.require_version('GstBase', "1.0")
gi.require_version('Gtk', "3.0")
#gi.require_version('GdkX11', '3.0')
gi.require_version('GstVideo', '1.0')

from gi.repository import GObject, Gst, GstBase, Gtk, GstVideo, GdkX11

import numpy as np
import datetime as dt

log = logging.getLogger(__name__)

class Segmenter:
    def __init__(self):
        Gst.init(None)

        self.terminate = False

        # Create gstreamer pipeline
        cmd = "v4l2src ! tee name=tee ! fakesink"
        self.pipeline = Gst.parse_launch(cmd)

        # Store references to gstreamer objects
        self.bus = self.pipeline.get_bus()
        self.recordpipe = None

    def run(self):
        # Initiate main loop
        self.pipeline.set_state(Gst.State.PAUSED)
        self.pipeline.set_state(Gst.State.PLAYING)

        try:
            while not self.terminate:
                print(dt.datetime.now().time())
                # Listen for event messages on the bus
                msg = self.bus.timed_pop_filtered(10 * Gst.SECOND, (Gst.MessageType.EOS | Gst.MessageType.ERROR))

                if msg:
                    if msg.type == Gst.MessageType.ERROR:
                        err, dbg = msg.parse_error()
                        print("ERROR:", msg.src.get_name(), ":", err)
                        if dbg:
                            print("Debug info:", dbg)
                        self.terminate = True

                    elif msg.type == Gst.MessageType.EOS:
                        print("End-Of-Stream reached")
                        self.terminate = True

                else:
                    # No message - must have reached timeout
                    self.begin_new_file()

        finally:
            # Free up resources
            self.pipeline.set_state(Gst.State.NULL)

    def begin_new_file(self):

        # If recording a file currently, terminate it
        if self.recordpipe is not None:

            # Block new data
            filequeue = self.recordpipe.get_by_name("filequeue")
            filequeue.get_static_pad("src").add_probe(Gst.PadProbeType.BLOCK_DOWNSTREAM, self.probe_block)

            # Disconnect the recording pipe
            self.pipeline.get_by_name("tee").unlink(self.recordpipe)

            # Send a termination event to trigger the save
            filequeue.get_static_pad("sink").send_event(Gst.Event.new_eos())

            # Clear the reference to the pipe
            self.recordpipe = None

        # Create a new file target
        filename = dt.datetime.now().strftime("%Y-%m-%d_%H.%M.%S") + ".avi"
        print("Recording {}...".format(filename))

        # Create a new pipeline for the new file
        self.recordpipe = Gst.parse_bin_from_description("queue name=filequeue ! jpegenc ! avimux ! filesink location={} sync=False".format(filename), True)
        self.pipeline.add(self.recordpipe)

        # Connect to the main pipe
        self.pipeline.get_by_name("tee").link(self.recordpipe)

        # Start passing data
        self.recordpipe.set_state(Gst.State.PLAYING)

    def probe_block(self, pad, buf):
        """ Callback for downstream block """
        print('block.')
        return True

if __name__ == '__main__':
    seg = Segmenter()
    seg.run()

Body:
Here is an example for using gstreamer in python3 with nvidia TX2 along with splitmuxsink for spliting in segments the recorded video.
Also i have used the callback function for renaming the output segments with the timestamp.

import gi
gi.require_version('Gst', "1.0")
gi.require_version('GstBase', "1.0")
gi.require_version('Gtk', "3.0")
gi.require_version('GstVideo', '1.0')

from gi.repository import GObject, Gst, GstBase, Gtk, GstVideo, GdkX11

GObject.threads_init()
Gst.init(None)

import datetime as dt
import time

class config():
     width = 1280
     height = 720
     fps = 50
     flip = 0
     segments_time = 5000000000 # 5 seconds in nano
     camera_type = "csi"
     usb_cam = "video0"
     iframe_interval = 30 # every 30 frames place a keyframe, this is needed to set frame at 4.75 seconds

config()

global ref_stamp
ref_stamp = 0

# global first segment flag
global first_segment
first_segment = False

def format_location_callback (splitmux, fragment_id):

    global first_segment

    local_frame_t = round(time.time() * 1000)
    timestamp = str(local_frame_t)
    name = str(timestamp) + ".mp4"

    # first segment is affected by the time needed to open the camera source so it will have around 6 seconds in lenght but the actual recorded frames inside are for 4,5 seconds
    # in this case first segemnt will be saved as test and only the rest are actual segments with the good timestamp
    if first_segment == False:
        name = 'test'
    first_segment = True
    return str(name)

src = pipeline.get_by_name ('splitmux')
src.connect("format-location", format_location_callback)

pipeline.set_state(Gst.State.PLAYING)

#playing = round(time.time() * 1000)
#print("PLAYING: ", playing)

bus = pipeline.get_bus()
msg = bus.pop_filtered(Gst.MessageType.EOS | Gst.MessageType.ERROR)

count = 1

while True:
    count = count + 1
    print (count)
    time.sleep(1)
    # if 15 seconds passed stop the recording;
    if count == 15 :
        break

# send the end of stream event and then wait in the bottom loop for event to be send
# throughout the pipeline.
pipeline.send_event(Gst.Event.new_eos())

# wait in the loop until end of stream is reached
while True:
    msg = bus.pop_filtered(Gst.MessageType.EOS | Gst.MessageType.ERROR)
    if msg:
      print("ENTER")
      if msg.type == Gst.MessageType.ERROR:
           err, dbg = msg.parse_error()
           print("ERROR:", msg.src.get_name(), ":", err)
           if dbg:
                print("Debug info:", dbg)
                break

      elif msg.type == Gst.MessageType.EOS:
                print("End-Of-Stream reached")
                break
    time.sleep(0.1)

pipeline.set_state(Gst.State.NULL)

ref_stamp = round(time.time() * 1000)
print("EXIT: ", ref_stamp)

ContentLicense: CC BY-SA 4.0


问:
How can I test that my before_save callback does the right thing
I have a callback on my ActiveRecord model as shown below:

```<code>  before_save :sync_to_external_apis

  def sync_to_external_apis
    [user, assoc_user].each {|cuser|
      if cuser.google_refresh
        display_user = other_user(cuser.id)
        api = Google.new(:user => cuser)
        contact = api.sync_user(display_user)
      end
    }
  end
</code>```

I would like to write an rspec test which tests that calling save! on an instance of this model causes sync_user to be called on a new Google instance when google_refresh is true. How could I do this?

答:
```<code>it "should sync to external apis on save!" do
  model = Model.new
  model.expects(:sync_to_external_apis)
  model.save!
end
</code>```

As an aside, requesting unreliable resources like the internet during the request-response cycle is a bad idea. I would suggest creating a background job instead.

Body:
I have a callback on my ActiveRecord model as shown below:

  before_save :sync_to_external_apis

  def sync_to_external_apis
    [user, assoc_user].each {|cuser|
      if cuser.google_refresh
        display_user = other_user(cuser.id)
        api = Google.new(:user => cuser)
        contact = api.sync_user(display_user)
      end
    }
  end

I would like to write an rspec test which tests that calling save! on an instance of this model causes sync_user to be called on a new Google instance when google_refresh is true. How could I do this?

Body:
it "should sync to external apis on save!" do
  model = Model.new
  model.expects(:sync_to_external_apis)
  model.save!
end

As an aside, requesting unreliable resources like the internet during the request-response cycle is a bad idea. I would suggest creating a background job instead.


问:
How to Code Google Script for Delivery Method on Google Ads based on Time of Day
I'm looking for help on coding a google script that will automate a delivery method for Google Ads based on the time of day. For example, I'd like to have an accelerated delivery method during work hours and the standard delivery during 7 PM to 7 AM when traffic is less qualified. Is this possible? Can someone help?

N/A no coding experience thus far

N/A

答:
Unfortunately you can't currently change the delivery method through a script. Since you can't create automated rules to change settings either you might have to create duplicates of all your campaigns, one version on accelerated and one on standard and with ad scheduling to turn them on and off at the relevant times.

Although before doing that I'd say you'd need a pretty strong reason, because it'll make everyday management of the accounts pretty messy - especially if you're not on Search Ads 360.


问:
Get n random elements from ArrayList based on condition, and remove them from original list
Take a list: List<MyObject> objects = new ArrayList<>();, where each MyObject has a field String myString;.

How can I "pop" (retrieve and remove) n random elements from the list where myString == "myString"?

Edit:

I have successfully been able to remove a random element from the list, which I can iterate n times, but this seems fairly inefficient. Also there is no comparative aspect in the code I have.

```<code>List<MyObject> objects = new ArrayList<>();
MyObject object = objects.get(Math.random() * objects.size());
objects.remove(object);
</code>```

答:
```<code> List<MyObject> filtered = objects.stream()
            .filter(o -> o.getMyString().equals("myString"))
            .collect(Collectors.toList());

Collections.shuffle(filtered);
List randomList = filtered.subList(0, n);
objects.removeAll(randomList);
</code>```

Body:
Take a list: List<MyObject> objects = new ArrayList<>();, where each MyObject has a field String myString;.

How can I "pop" (retrieve and remove) n random elements from the list where myString == "myString"?

Edit:

I have successfully been able to remove a random element from the list, which I can iterate n times, but this seems fairly inefficient. Also there is no comparative aspect in the code I have.

List<MyObject> objects = new ArrayList<>();
MyObject object = objects.get(Math.random() * objects.size());
objects.remove(object);


问:
SELECT AVG(invoiceamount) per debtor where date< date row
I have a SQL table with the following columns: Invoice ID, debtor ID, invoice date and invoice amount. where invoice ID is unique.

I'm trying to create an extra column with the average invoice amount. So per row I want the average invoice amount of the debtor, but only of the invoices where the invoice date <= the invoicedate of the column.

I'm not sure where to start, all ideas are welcome

答:
Try this- </p>

```<code>SELECT
A.Invoice_ID,
A.debtor_ID,
A.invoice_date,
A.invoice_amount,
(
    SELECT AVG(B.invoice_amount)
    FROM your_table B
    WHERE B.debtor_ID = A.debtor_ID
    AND B.invoice_date <= A.invoice_date
) AS average_invoice_amount
FROM your_table A
</code>```

Body:
Try this-

SELECT
A.Invoice_ID,
A.debtor_ID,
A.invoice_date,
A.invoice_amount,
(
    SELECT AVG(B.invoice_amount)
    FROM your_table B
    WHERE B.debtor_ID = A.debtor_ID
    AND B.invoice_date <= A.invoice_date
) AS average_invoice_amount
FROM your_table A


问:
Submit button in a hyperlink
I would have never thought that it was valid markup to put a <input type="submit" /> in an anchor  like so:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Submit input in a hyperlink</title>
</head>
<body>
    <form action="/form-submission" method="get">
        <a href="/hyperlink-click"><input type="submit" /></a>
    </form>
</body>
</html>
</code>```

Oddly enough though, if you feed this into the w3c validator, it validates.

What is supposed to happen when a user clicks on the submit button? Would this kind of setup just be unpredictable with different browsers doing whatever they please, or are there explicit rules dictating expected behavior? Would doing something like this ever come in handy?

答:
So here's the answer :)
It may not validate in HTML5, it may validate in HTML < 5, but I was still curious to see what happened.  It turns out it's pretty logical.  The button event fires first and then bubbles up to the link event.  Then the link event fires.  You can play with it here:

http://jsfiddle.net/yEUM2/

It does the same thing in IE8, FF4, Chrome 10

Title: Submit button in a hyperlink

Body:
I would have never thought that it was valid markup to put a <input type="submit" /> in an anchor  like so:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Submit input in a hyperlink</title>

    <form action="/form-submission" method="get">
        <input type="submit" />
    </form>

Oddly enough though, if you feed this into the w3c validator, it validates.

What is supposed to happen when a user clicks on the submit button? Would this kind of setup just be unpredictable with different browsers doing whatever they please, or are there explicit rules dictating expected behavior? Would doing something like this ever come in handy?


问:
How can I uninstall Sublime Text 3 from Windows 10?
How can I uninstall Sublime Text 3 from Windows 10?
How i done it. This is the answer for help another people.

I tried to remove SUBLIME text 3, since some errors appear on each startup.
After clearing and reinstalling, the error reappears.
I searched for answer in google but did not find it.

答:
This is what I did, it helped me.

Open sublime

In top menu choose:
Preferences > Browse Pachages

The new explorer window will open with this path:

C:\Users...you_name...\AppData\Roaming\Sublime Text 3\Packages

Close sublime, but don`t close explorer window

Delete all folders inside this Packages folder

Uninstall sublime as you would do with any other Windows program using Programs and Features

Reinstall sumlime, if you want. Be happy. Now it is virgin clear.


问:
C# if directive
Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

```<code>void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}

...
#if CONDITION
   //mode X with addtional steps
#endif
</code>```

答: The '#IF' directive is used for conditional compilation, which means it looks for tokens defined at compile time and literally compiles or does not compile particular code.  This means the non-compiled code is not part of your program and cannot be used at runtime.  You will need to modify your code to use normal flags rather than conditional compilation if you want to change behavior at runtime.  That said, you may want to consider a deeper design review, as adding new branching functionality based on configuration flags can lead to messy code very quickly.</p>

Title: C# if directive

Body:
Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}

...
#if CONDITION
   //mode X with addtional steps
#endif


问:
@iOSFindBy is displayed as deprecated, what can I use instead (using pagefactory for Hybrid usage of Android and iOS device))
I have no experience with iOS, but I am trying to redesign my Android Project for the iOS Guys to use it as well for iOS.

After search in internet I find out that this can happens by using the page factory and locating elements by @iOSFindBy,
After trying to use @iOSFindby for locating element using the page factory method, the compiler indicate that it is deprecated.

```<code>@iOSFindBy (Accessibility = "button_login")
@AndroidFindBy(id = "net.myApp.int:id/loginBtn")
private MobileElement login_Button2;
</code>```

what Can I use instead of this?

I saw also in Appium java client (https://static.javadoc.io/io.appium/java-client/7.0.0/index.html?deprecated-list.html) :

*io.appium.java_client.pagefactory
Annotation Type iOSFindBy
Deprecated.
UIAutomation is going to get deprecated. Use iOSXCUITFindBy instead It is recommended to use XCUITest

@Retention(value=RUNTIME)  @Target(value={FIELD,TYPE})
  @Repeatable(value=iOSFindBySet.class) public @interface iOSFindBy

Used to mark a field on a Page Object to indicate an alternative mechanism for locating the element or a list of elements. Used in conjunction with PageFactory this allows users to quickly and easily create PageObjects. using iOS UI selectors, accessibility, id, name, class name, tag and xpath*

but I dont know if this is the solution and how to use
If I use it in my Code also get Error:

```<code>@iOSXCUITFindBy Accessibility = "button_login"
@AndroidFindBy(id = "net.myApp.int:id/loginBtn")
private MobileElement login_Button1;
</code>```

Annotation are not allowed here.

Thanks for any Tip in advance

答:
The best way to know how things work is to check related tests in appium-java-client repository on github:

    @iOSXCUITFindBy(accessibility = "IntegerB")
    private MobileElement textField2;

```

<p>So in your case, it should be:</p>

<pre class="lang-java prettyprint-override"><code>    @iOSXCUITFindBy(accessibility = "button_login")
    @AndroidFindBy(id = "net.myApp.int:id/loginBtn")
    private MobileElement login_Button1;
</code>```

Body:
I have no experience with iOS, but I am trying to redesign my Android Project for the iOS Guys to use it as well for iOS.

After search in internet I find out that this can happens by using the page factory and locating elements by @iOSFindBy,
After trying to use @iOSFindby for locating element using the page factory method, the compiler indicate that it is deprecated.

@iOSFindBy (Accessibility = "button_login")
@AndroidFindBy(id = "net.myApp.int:id/loginBtn")
private MobileElement login_Button2;

what Can I use instead of this?

I saw also in Appium java client (https://static.javadoc.io/io.appium/java-client/7.0.0/index.html?deprecated-list.html) :

*io.appium.java_client.pagefactory
Annotation Type iOSFindBy
Deprecated.
UIAutomation is going to get deprecated. Use iOSXCUITFindBy instead It is recommended to use XCUITest

@Retention(value=RUNTIME)  @Target(value={FIELD,TYPE})
  @Repeatable(value=iOSFindBySet.class) public @interface iOSFindBy

Used to mark a field on a Page Object to indicate an alternative mechanism for locating the element or a list of elements. Used in conjunction with PageFactory this allows users to quickly and easily create PageObjects. using iOS UI selectors, accessibility, id, name, class name, tag and xpath*

but I dont know if this is the solution and how to use
If I use it in my Code also get Error:

@iOSXCUITFindBy Accessibility = "button_login"
@AndroidFindBy(id = "net.myApp.int:id/loginBtn")
private MobileElement login_Button1;

Annotation are not allowed here.

Thanks for any Tip in advance

Body:
The best way to know how things work is to check related tests in appium-java-client repository on github:

    @iOSXCUITFindBy(accessibility = "IntegerB")
    private MobileElement textField2;

So in your case, it should be:

    @iOSXCUITFindBy(accessibility = "button_login")
    @AndroidFindBy(id = "net.myApp.int:id/loginBtn")
    private MobileElement login_Button1;


问:
Using cURL GET statement in PHP
I have a cURL GET statement:

```<code>curl -v -X GET "https://admiraltyapi.azure-api.net/uktidalapi/api/V1/Stations/{stationId}" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{body}"
</code>```

that works fine in a terminal window (with my sub key) - I now want to use it in a PHP script to retrieve the associated JSON. Code suggestions for achieving this appreciated...

答:
Not tested but you need something like this with PHP CURL.</p>

```<code>$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://admiraltyapi.azure-api.net/uktidalapi/api/V1/Stations/{stationId}');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_TRANSFERTEXT, true);

$headers = array();
$headers[] = 'Ocp-Apim-Subscription-Key: {subscription key}';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
</code>```

Title: Using cURL GET statement in PHP

Body:
I have a cURL GET statement:

curl -v -X GET "https://admiraltyapi.azure-api.net/uktidalapi/api/V1/Stations/{stationId}" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{body}"

that works fine in a terminal window (with my sub key) - I now want to use it in a PHP script to retrieve the associated JSON. Code suggestions for achieving this appreciated...

Body:
Not tested but you need something like this with PHP CURL.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://admiraltyapi.azure-api.net/uktidalapi/api/V1/Stations/{stationId}');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_TRANSFERTEXT, true);

$headers = array();
$headers[] = 'Ocp-Apim-Subscription-Key: {subscription key}';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);


问:
what functions are called when clicking on the titlebar of a form?
I have a form which includes an Unity process. Sometimes "something" happens that makes impossible to perform some actions on the process.
I discovered that clicking on the titlebar re-enables the possibility to perform the actions that i want on my process.

the "something" is my function:

```<code>private void button1_Click(object sender, EventArgs e)
        {
            myNCServer.SendMessage();
            myNCServer.SendMyObject();

            position = myNCServer.GetPosition();
            compteur++;
            unityHWNDLabel.Text = "position = " + position + " (Updated " + compteur + " times)";

        }
</code>```

so i would like to know what really happens so that i can re-enable my process without clicking on the titlebar

or if you have any other idea on how to handle this... =)

thanks a lot !

答:
What you're trying would be a dirty workaround and there may be better solutions for your problem, resp. the cause for your problem lies somewhere else and has to be handled by an another approach. </p>

<p>But to answer your specific question what happens when the tite bar is clicked: your program then gets a WM_NCACTIVATE message (https://learn.microsoft.com/en-us/windows/desktop/winmsg/wm-ncactivate). This happens on the win32 API layer which is the layer underneath .NET. If you've never been working with win32 API you should first read about it's "message pump" mechanism (https://learn.microsoft.com/de-de/windows/desktop/winmsg/about-messages-and-message-queues). You can send win32 API messages in .NET via PInvoke, there using the synchronous SendMessage() function (https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendmessage) or using the asynchrounous PostMessage() function (https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-postmessagea). This should be a good entry point for your workaround.       </p>

Body:
I have a form which includes an Unity process. Sometimes "something" happens that makes impossible to perform some actions on the process.
I discovered that clicking on the titlebar re-enables the possibility to perform the actions that i want on my process.

the "something" is my function:

private void button1_Click(object sender, EventArgs e)
        {
            myNCServer.SendMessage();
            myNCServer.SendMyObject();

            position = myNCServer.GetPosition();
            compteur++;
            unityHWNDLabel.Text = "position = " + position + " (Updated " + compteur + " times)";

        }

so i would like to know what really happens so that i can re-enable my process without clicking on the titlebar

or if you have any other idea on how to handle this... =)

thanks a lot !

Body:
What you're trying would be a dirty workaround and there may be better solutions for your problem, resp. the cause for your problem lies somewhere else and has to be handled by an another approach.

But to answer your specific question what happens when the tite bar is clicked: your program then gets a WM_NCACTIVATE message (https://learn.microsoft.com/en-us/windows/desktop/winmsg/wm-ncactivate). This happens on the win32 API layer which is the layer underneath .NET. If you've never been working with win32 API you should first read about it's "message pump" mechanism (https://learn.microsoft.com/de-de/windows/desktop/winmsg/about-messages-and-message-queues). You can send win32 API messages in .NET via PInvoke, there using the synchronous SendMessage() function (https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendmessage) or using the asynchrounous PostMessage() function (https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-postmessagea). This should be a good entry point for your workaround.


问:
Scheduling a persistent entity
Let's say I have some DB entity with a CronExpression field:

```<code>@Entity
@Table(name = "job")
public class Job {
    ...
    private CronExpression cronExpression;

}
</code>```

What is the best approach to put it onto quartz schedule? I use Spring3 and Hibernate. Basically I could schedule it in my DAO - anytime Job is created or updated - but I would also need to schedule all existed job at application start-up..

Thanks for your advices!

答:
You need DAO/Repository to get all cronExpression from your storage. I create in memory DAO

```<code>@Repository
public class JobEntityDao {
    public List<JobEntity> findAll() {
        List<JobEntity> list = new ArrayList<JobEntity>();

        JobEntity job1 = new JobEntity("0 0 12 * * ?");
        JobEntity job2 = new JobEntity("0 15 10 ? * *");
        JobEntity job3 = new JobEntity("0 15 10 * * ?");

        list.add(job1);
        list.add(job2);
        list.add(job3);

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

And Component to create quartz scheduler based on your cronExpression. I call it QuartzExecutor

```<code>@Service
public class QuartzExecutor {

    private JobEntityDao jobEntityDao;

    @Autowired
    public QuartzExecutor(JobEntityDao jobEntityDao) throws ParseException, SchedulerException {
        this.jobEntityDao = jobEntityDao;
        init();
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private void init() throws ParseException, SchedulerException {
        List<JobEntity> jobEntities = jobEntityDao.findAll();

        for (JobEntity jobEntity : jobEntities) {
            System.out.println(jobEntity.cronExpression);

            RunMeTask task = new RunMeTask();

            //specify your sceduler task details
            JobDetail job = new JobDetail();
            job.setName("runMeJob");
            job.setJobClass(RunMeJob.class);

            Map dataMap = job.getJobDataMap();
            dataMap.put("runMeTask", task);

            //configure the scheduler time
            CronTrigger trigger = new CronTrigger();
            trigger.setName("runMeJobTesting");
            trigger.setCronExpression(jobEntity.cronExpression);

            //schedule it
            Scheduler scheduler = new StdSchedulerFactory().getScheduler();
            scheduler.start();
            scheduler.scheduleJob(job, trigger);
        }
    }

}
</code>```

you can get RunMeJob and RunMeTask code from http://www.mkyong.com/java/quartz-scheduler-example/.
I Know the class design is not good, but my concern is try to solve your problem.

Is this what you are looking for ?

Title: Scheduling a persistent entity

Body:
Let's say I have some DB entity with a CronExpression field:

@Entity
@Table(name = "job")
public class Job {
    ...
    private CronExpression cronExpression;

}

What is the best approach to put it onto quartz schedule? I use Spring3 and Hibernate. Basically I could schedule it in my DAO - anytime Job is created or updated - but I would also need to schedule all existed job at application start-up..

Thanks for your advices!

Body:
You need DAO/Repository to get all cronExpression from your storage. I create in memory DAO

@Repository
public class JobEntityDao {
    public List<JobEntity> findAll() {
        List<JobEntity> list = new ArrayList<JobEntity>();

        JobEntity job1 = new JobEntity("0 0 12 * * ?");
        JobEntity job2 = new JobEntity("0 15 10 ? * *");
        JobEntity job3 = new JobEntity("0 15 10 * * ?");

        list.add(job1);
        list.add(job2);
        list.add(job3);

        return list;
    }
}

And Component to create quartz scheduler based on your cronExpression. I call it QuartzExecutor

@Service
public class QuartzExecutor {

    private JobEntityDao jobEntityDao;

    @Autowired
    public QuartzExecutor(JobEntityDao jobEntityDao) throws ParseException, SchedulerException {
        this.jobEntityDao = jobEntityDao;
        init();
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private void init() throws ParseException, SchedulerException {
        List<JobEntity> jobEntities = jobEntityDao.findAll();

        for (JobEntity jobEntity : jobEntities) {
            System.out.println(jobEntity.cronExpression);

            RunMeTask task = new RunMeTask();

            //specify your sceduler task details
            JobDetail job = new JobDetail();
            job.setName("runMeJob");
            job.setJobClass(RunMeJob.class);

            Map dataMap = job.getJobDataMap();
            dataMap.put("runMeTask", task);

            //configure the scheduler time
            CronTrigger trigger = new CronTrigger();
            trigger.setName("runMeJobTesting");
            trigger.setCronExpression(jobEntity.cronExpression);

            //schedule it
            Scheduler scheduler = new StdSchedulerFactory().getScheduler();
            scheduler.start();
            scheduler.scheduleJob(job, trigger);
        }
    }

}

you can get RunMeJob and RunMeTask code from http://www.mkyong.com/java/quartz-scheduler-example/.
I Know the class design is not good, but my concern is try to solve your problem.

Is this what you are looking for ?


问:
Error injecting: ch.fortysix.maven.plugin.postaman.MailSenderMojo
While running the postman plug in POM.  We have observed this error in particular system. But at the same time we are successfully executed the same POM file in other systems.

Tried this link but no luck:
Required class is missing: org/codehaus/gmaven/mojo/GroovyMojo when tried to run to generate report and send an email in the Maven Project

[WARNING] Error injecting: ch.fortysix.maven.plugin.postaman.MailSenderMojo
java.lang.TypeNotPresentException: Type ch.fortysix.maven.plugin.postaman.MailSenderMojo not present
    at org.eclipse.sisu.space.URLClassSpace.loadClass(URLClassSpace.java:115)
    at org.eclipse.sisu.space.NamedClass.load(NamedClass.java:46)
    at org.eclipse.sisu.space.AbstractDeferredClass.get(AbstractDeferredClass.java:48)
    at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:86)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:54)
    at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:70)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
    at org.eclipse.sisu.bean.BeanScheduler$Activator.onProvision(BeanScheduler.java:176)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:126)

答:
I have removed .m2 floder in the Users. After that update the maven project. It will take some time to create the new .m2 folder.

This time It won't fail.

Note: Don't delete any specific folders, Just delete the complete .m2 then only you can resolve it.


答:
The problem is that render is called before the data is fetched. I would suggest adding a constructor to your component and initialize the news to an empty array:

```<code>constructor() {
  super();
  this.state = {
    news: []
  };
}
</code>```

And if you want to do it properly, you can add a loading property to your state:

```<code>constructor() {
  super();
  this.state = {
    loading: true,
  };
}

componentDidMount() {
  fetch('https://content.guardianapis.com/search?api-key=test')
    .then(response => response.json())
    .then(data => {
      this.setState({
        news: data,
        loading: false,
      });
      console.log(data);
    });
}

render() {
  const { loading } = this.state;
  return (
    <div>
      {loading ? (
        <h1>Loading...</h1> {/* Or use a loading icon or gif */}
      ) : (
        <div className="newsWrapper">
          <h3>{this.renderNews()}</h3>
        </div>
      )}
    </div>
  );
}
</code>```

This way your UI will be more user-friendly.

Title: How do I get the "results" object nested in the array "news" and map over it?

Body:
I'm trying to map over an array which is fetched using componentDidMount. However, I keep receiving this same error "Uncaught TypeError: this.state.news.map is not a function".

This is on componentDidMount

componentDidMount() {
        fetch(
            "https://content.guardianapis.com/search?api-key=test"
        )
            .then(response => response.json())
            .then(data => {
                this.setState({
                    news: data
                })
                console.log(data)
            })
    }

This is my function to map over the data

renderNews() {
        return this.state.news.map((a, i) => (

                {a.response.map((b, i) => (

{b.webTitle}

{b.type}

                                    {b.sectionName}

{b.pillarName}

{b.webUrl}

                ))}

        ))
    }

Then I render out the data over here

render() {
        return (

                {/*
{this.renderNews()}
 */}

Hello

        )
    }

Update #1
Here is the data that I got from console.log(data)

{response: {…}}
response:
currentPage: 1
orderBy: "newest"
pageSize: 10
pages: 211707
results: Array(10)
0: {id: "business/live/2019/may/31/markets-trump-shock-mexi…ffs-trade-war-china-brexit-ftse-100-business-live", type: "liveblog", sectionId: "business", sectionName: "Business", webPublicationDate: "2019-05-31T08:25:12Z", …}
1: {id: "football/2019/may/31/atletico-madrid-stadium-wanda…litano-champions-league-final-liverpool-tottenham", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T08:23:15Z", …}
2: {id: "tv-and-radio/2019/may/31/a-sinister-tale-from-the-minds-behind-dirty-john-podcasts-of-the-week", type: "article", sectionId: "tv-and-radio", sectionName: "Television & radio", webPublicationDate: "2019-05-31T08:12:02Z", …}
3: {id: "politics/2019/may/31/alastair-campbell-labour-expulsion-discrimination-appeal", type: "article", sectionId: "politics", sectionName: "Politics", webPublicationDate: "2019-05-31T08:11:22Z", …}
4: {id: "football/from-the-archive-blog/2019/may/31/womens-football-match-crouch-end-1895", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T08:00:27Z", …}
5: {id: "culture/2019/may/31/what-to-see-this-week-in-the-uk", type: "article", sectionId: "culture", sectionName: "Culture", webPublicationDate: "2019-05-31T08:00:27Z", …}
6: {id: "tv-and-radio/2019/may/31/when-they-see-us-review-netflix-ava-duvernay-central-park-five", type: "article", sectionId: "tv-and-radio", sectionName: "Television & radio", webPublicationDate: "2019-05-31T08:00:27Z", …}
7: {id: "music/2019/may/31/lee-scratch-perry-rainford-review-on-u-sound-records", type: "article", sectionId: "music", sectionName: "Music", webPublicationDate: "2019-05-31T08:00:27Z", …}
8: {id: "books/2019/may/31/mother-ship-francesca-segal-review", type: "article", sectionId: "books", sectionName: "Books", webPublicationDate: "2019-05-31T07:58:27Z", …}
9: {id: "football/2019/may/31/football-transfer-rumours-spurs-to-bid-for-wilfried-zaha", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T07:47:36Z", …}
length: 10
__proto__: Array(0)
startIndex: 1
status: "ok"
total: 2117063
userTier: "developer"
__proto__: Object
__proto__: Object

Sorry I forgot to include this portion of my code which is what I initialize this.state.news with. Here it is

constructor() {
        super()

        this.state = {
            news: []
        }

        this.renderNews = this.renderNews.bind(this)
    }

Body:
The problem is that render is called before the data is fetched. I would suggest adding a constructor to your component and initialize the news to an empty array:

constructor() {
  super();
  this.state = {
    news: []
  };
}

And if you want to do it properly, you can add a loading property to your state:

constructor() {
  super();
  this.state = {
    loading: true,
  };
}

componentDidMount() {
  fetch('https://content.guardianapis.com/search?api-key=test')
    .then(response => response.json())
    .then(data => {
      this.setState({
        news: data,
        loading: false,
      });
      console.log(data);
    });
}

render() {
  const { loading } = this.state;
  return (
    <div>
      {loading ? (
        <h1>Loading...</h1> {/* Or use a loading icon or gif */}
      ) : (
        <div className="newsWrapper">
          <h3>{this.renderNews()}</h3>
        </div>
      )}
    </div>
  );
}

This way your UI will be more user-friendly.


问:
Use deploy script on Azure release pipeline
I've created a successful build and release that deployed my React app on a Azure Web App environment. The app I created will be deployed on many different customer environments and I don't want to create each app-service myself so I want to automate that proces. I've exported the template and now I have a deploy.psh1 file with a parameters.json and a template.json file. But I'm unsure on what to do now.

I've tried adding a powershell task to my release step and paste in the contents of deploy.sh1 in the inline section but that results in multiple errors:

```<code>2019-05-30T19:16:31.9475172Z ##[section]Starting: PowerShell Script
2019-05-30T19:16:31.9534016Z ==============================================================================
2019-05-30T19:16:31.9534117Z Task         : PowerShell
2019-05-30T19:16:31.9534203Z Description  : Run a PowerShell script on Windows, macOS, or Linux.
2019-05-30T19:16:31.9534274Z Version      : 2.148.0
2019-05-30T19:16:31.9534351Z Author       : Microsoft Corporation
2019-05-30T19:16:31.9534429Z Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613736)
2019-05-30T19:16:31.9534519Z ==============================================================================
2019-05-30T19:16:32.8910231Z Generating script.
2019-05-30T19:16:32.9442109Z ========================== Starting Command Output ===========================
2019-05-30T19:16:32.9667917Z ##[command]"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\agent\_work\_temp\c37bf4b5-41a1-4125-b7c3-04e0c77fe403.ps1'"
2019-05-30T19:16:33.2330921Z At C:\agent\_work\_temp\c37bf4b5-41a1-4125-b7c3-04e0c77fe403.ps1:30 char:10
2019-05-30T19:16:33.2331159Z +  [string]
2019-05-30T19:16:33.2331234Z +          ~
2019-05-30T19:16:33.2331512Z Missing closing ')' in expression.
2019-05-30T19:16:33.2332867Z At C:\agent\_work\_temp\c37bf4b5-41a1-4125-b7c3-04e0c77fe403.ps1:49 char:1
2019-05-30T19:16:33.2333119Z + )
2019-05-30T19:16:33.2333839Z + ~
2019-05-30T19:16:33.2334117Z Unexpected token ')' in expression or statement.
2019-05-30T19:16:33.2335145Z At C:\agent\_work\_temp\c37bf4b5-41a1-4125-b7c3-04e0c77fe403.ps1:29 char:2
2019-05-30T19:16:33.2335362Z +  [Parameter(Mandatory=$True)]
2019-05-30T19:16:33.2336143Z +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2019-05-30T19:16:33.2336345Z Unexpected attribute 'Parameter'.
2019-05-30T19:16:33.2337371Z At C:\agent\_work\_temp\c37bf4b5-41a1-4125-b7c3-04e0c77fe403.ps1:40 char:2
2019-05-30T19:16:33.2337639Z +  [Parameter(Mandatory=$True)]
2019-05-30T19:16:33.2338286Z +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2019-05-30T19:16:33.2338534Z Unexpected attribute 'Parameter'.
2019-05-30T19:16:33.2339929Z     + CategoryInfo          : ParserError: (:) [], ParseException
2019-05-30T19:16:33.2340251Z     + FullyQualifiedErrorId : MissingEndParenthesisInExpression
2019-05-30T19:16:33.2340819Z
2019-05-30T19:16:33.3687310Z ##[error]PowerShell exited with code '1'.
2019-05-30T19:16:33.3968831Z ##[section]Finishing: PowerShell Script
</code>```

So my question is how do I add the creation of the app-service during my release?

答:
There is a Resource Group deployment task which you can use directly to deploy ARM templates: https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/deploy/azure-resource-group-deployment?view=azure-devops

It takes your parameters.json and template.json as input.

Body:
I've created a successful build and release that deployed my React app on a Azure Web App environment. The app I created will be deployed on many different customer environments and I don't want to create each app-service myself so I want to automate that proces. I've exported the template and now I have a deploy.psh1 file with a parameters.json and a template.json file. But I'm unsure on what to do now.

I've tried adding a powershell task to my release step and paste in the contents of deploy.sh1 in the inline section but that results in multiple errors:

2019-05-30T19:16:31.9475172Z ##[section]Starting: PowerShell Script
2019-05-30T19:16:31.9534016Z ==============================================================================
2019-05-30T19:16:31.9534117Z Task         : PowerShell
2019-05-30T19:16:31.9534203Z Description  : Run a PowerShell script on Windows, macOS, or Linux.
2019-05-30T19:16:31.9534274Z Version      : 2.148.0
2019-05-30T19:16:31.9534351Z Author       : Microsoft Corporation
2019-05-30T19:16:31.9534429Z Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613736)
2019-05-30T19:16:31.9534519Z ==============================================================================
2019-05-30T19:16:32.8910231Z Generating script.
2019-05-30T19:16:32.9442109Z ========================== Starting Command Output ===========================
2019-05-30T19:16:32.9667917Z ##[command]"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\agent\_work\_temp\c37bf4b5-41a1-4125-b7c3-04e0c77fe403.ps1'"
2019-05-30T19:16:33.2330921Z At C:\agent\_work\_temp\c37bf4b5-41a1-4125-b7c3-04e0c77fe403.ps1:30 char:10
2019-05-30T19:16:33.2331159Z +  [string]
2019-05-30T19:16:33.2331234Z +          ~
2019-05-30T19:16:33.2331512Z Missing closing ')' in expression.
2019-05-30T19:16:33.2332867Z At C:\agent\_work\_temp\c37bf4b5-41a1-4125-b7c3-04e0c77fe403.ps1:49 char:1
2019-05-30T19:16:33.2333119Z + )
2019-05-30T19:16:33.2333839Z + ~
2019-05-30T19:16:33.2334117Z Unexpected token ')' in expression or statement.
2019-05-30T19:16:33.2335145Z At C:\agent\_work\_temp\c37bf4b5-41a1-4125-b7c3-04e0c77fe403.ps1:29 char:2
2019-05-30T19:16:33.2335362Z +  [Parameter(Mandatory=$True)]
2019-05-30T19:16:33.2336143Z +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2019-05-30T19:16:33.2336345Z Unexpected attribute 'Parameter'.
2019-05-30T19:16:33.2337371Z At C:\agent\_work\_temp\c37bf4b5-41a1-4125-b7c3-04e0c77fe403.ps1:40 char:2
2019-05-30T19:16:33.2337639Z +  [Parameter(Mandatory=$True)]
2019-05-30T19:16:33.2338286Z +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2019-05-30T19:16:33.2338534Z Unexpected attribute 'Parameter'.
2019-05-30T19:16:33.2339929Z     + CategoryInfo          : ParserError: (:) [], ParseException
2019-05-30T19:16:33.2340251Z     + FullyQualifiedErrorId : MissingEndParenthesisInExpression
2019-05-30T19:16:33.2340819Z
2019-05-30T19:16:33.3687310Z ##[error]PowerShell exited with code '1'.
2019-05-30T19:16:33.3968831Z ##[section]Finishing: PowerShell Script

So my question is how do I add the creation of the app-service during my release?


问:
Setting graph attributes in pygraph
I found in the documentation of pygraph how to change the attributes of the nodes and the edges, but I found no help on how to change the attributes of the graphs.

I tried without luck:

```<code>gr = graph()
gr.__setattr__('aspect',2)
</code>```

What do you recommend?

Thanks!

[update]
I also tried:

```<code>gr = graph()
gr.__setattr__('rotate',90)
gr.rotate = 90
gr.color = 'red'
setattr(gr,'bgcolor','red')
</code>```

[update 2]
Example code from the website with the different ideas to change the attributes:

```<code>#!/usr/bin/env python

# Copyright (c) 2007-2008 Pedro Matiello <pmatiello@gmail.com>
# License: MIT (see COPYING file)

# Import graphviz
import sys
sys.path.append('..')
sys.path.append('/usr/lib/graphviz/python/')
sys.path.append('/usr/lib64/graphviz/python/')
import gv

# Import pygraph
from pygraph.classes.graph import graph
from pygraph.classes.digraph import digraph
from pygraph.algorithms.searching import breadth_first_search
from pygraph.readwrite.dot import write

# Graph creation
gr = graph()

gr.__setattr__('rotate',90)
gr.rotate = 90
gr.color = 'red'
setattr(gr,'bgcolor','red')

# Add nodes and edges
gr.add_nodes(["Portugal","Spain","France","Germany","Belgium","Netherlands","Italy"])
gr.add_nodes(["Switzerland","Austria","Denmark","Poland","Czech Republic","Slovakia","Hungary"])
gr.add_nodes(["England","Ireland","Scotland","Wales"])

gr.add_edge(("Portugal", "Spain"))
gr.add_edge(("Spain","France"))
gr.add_edge(("France","Belgium"))
gr.add_edge(("France","Germany"))
gr.add_edge(("France","Italy"))
gr.add_edge(("Belgium","Netherlands"))
gr.add_edge(("Germany","Belgium"))
gr.add_edge(("Germany","Netherlands"))
gr.add_edge(("England","Wales"))
gr.add_edge(("England","Scotland"))
gr.add_edge(("Scotland","Wales"))
gr.add_edge(("Switzerland","Austria"))
gr.add_edge(("Switzerland","Germany"))
gr.add_edge(("Switzerland","France"))
gr.add_edge(("Switzerland","Italy"))
gr.add_edge(("Austria","Germany"))
gr.add_edge(("Austria","Italy"))
gr.add_edge(("Austria","Czech Republic"))
gr.add_edge(("Austria","Slovakia"))
gr.add_edge(("Austria","Hungary"))
gr.add_edge(("Denmark","Germany"))
gr.add_edge(("Poland","Czech Republic"))
gr.add_edge(("Poland","Slovakia"))
gr.add_edge(("Poland","Germany"))
gr.add_edge(("Czech Republic","Slovakia"))
gr.add_edge(("Czech Republic","Germany"))
gr.add_edge(("Slovakia","Hungary"))

# Draw as PNG
dot = write(gr)
gvv = gv.readstring(dot)
gv.layout(gvv,'dot')
gv.render(gvv,'png','europe.png')
</code>```

答:
I don't know about pygraph, but I think the way you set attributes in python was:

```<code>setattr(object, attr, value)
setattr(gr, 'aspect', 2)
</code>```

I mean, you have tried gr.aspect = 2, right?

Title: Setting graph attributes in pygraph

Body:
I found in the documentation of pygraph how to change the attributes of the nodes and the edges, but I found no help on how to change the attributes of the graphs.

I tried without luck:

gr = graph()
gr.__setattr__('aspect',2)

What do you recommend?

Thanks!

[update]
I also tried:

gr = graph()
gr.__setattr__('rotate',90)
gr.rotate = 90
gr.color = 'red'
setattr(gr,'bgcolor','red')

[update 2]
Example code from the website with the different ideas to change the attributes:

#!/usr/bin/env python

# Copyright (c) 2007-2008 Pedro Matiello <pmatiello@gmail.com>
# License: MIT (see COPYING file)

# Import graphviz
import sys
sys.path.append('..')
sys.path.append('/usr/lib/graphviz/python/')
sys.path.append('/usr/lib64/graphviz/python/')
import gv

# Import pygraph
from pygraph.classes.graph import graph
from pygraph.classes.digraph import digraph
from pygraph.algorithms.searching import breadth_first_search
from pygraph.readwrite.dot import write

# Graph creation
gr = graph()

gr.__setattr__('rotate',90)
gr.rotate = 90
gr.color = 'red'
setattr(gr,'bgcolor','red')

# Add nodes and edges
gr.add_nodes(["Portugal","Spain","France","Germany","Belgium","Netherlands","Italy"])
gr.add_nodes(["Switzerland","Austria","Denmark","Poland","Czech Republic","Slovakia","Hungary"])
gr.add_nodes(["England","Ireland","Scotland","Wales"])

gr.add_edge(("Portugal", "Spain"))
gr.add_edge(("Spain","France"))
gr.add_edge(("France","Belgium"))
gr.add_edge(("France","Germany"))
gr.add_edge(("France","Italy"))
gr.add_edge(("Belgium","Netherlands"))
gr.add_edge(("Germany","Belgium"))
gr.add_edge(("Germany","Netherlands"))
gr.add_edge(("England","Wales"))
gr.add_edge(("England","Scotland"))
gr.add_edge(("Scotland","Wales"))
gr.add_edge(("Switzerland","Austria"))
gr.add_edge(("Switzerland","Germany"))
gr.add_edge(("Switzerland","France"))
gr.add_edge(("Switzerland","Italy"))
gr.add_edge(("Austria","Germany"))
gr.add_edge(("Austria","Italy"))
gr.add_edge(("Austria","Czech Republic"))
gr.add_edge(("Austria","Slovakia"))
gr.add_edge(("Austria","Hungary"))
gr.add_edge(("Denmark","Germany"))
gr.add_edge(("Poland","Czech Republic"))
gr.add_edge(("Poland","Slovakia"))
gr.add_edge(("Poland","Germany"))
gr.add_edge(("Czech Republic","Slovakia"))
gr.add_edge(("Czech Republic","Germany"))
gr.add_edge(("Slovakia","Hungary"))

# Draw as PNG
dot = write(gr)
gvv = gv.readstring(dot)
gv.layout(gvv,'dot')
gv.render(gvv,'png','europe.png')

Body:
I don't know about pygraph, but I think the way you set attributes in python was:

setattr(object, attr, value)
setattr(gr, 'aspect', 2)

I mean, you have tried gr.aspect = 2, right?


答:
during the render the news array is not present hence it is null, to solve this</p>

```<code>renderNews() {
        const { news = [] } = this.state; // assign a default value
        return news.map((a, i) => (
            <div key={i}>
                {a.response.map((b, i) => (
                    <div key={i}>
                        <div key={i} className="newsEach">
                            <h3>{b.webTitle}</h3>
                            <ul className="newsInfoUl">
                                <li className="newsInfoEach">{b.type}</li>
                                <li className="newsInfoEach">
                                    {b.sectionName}
                                </li>
                                <li className="newsInfoEach">{b.pillarName}</li>
                                <li className="newsInfoEach">{b.webUrl}</li>
                            </ul>
                        </div>
                    </div>
                ))}
            </div>
        ))
    }
</code>```

Body:
during the render the news array is not present hence it is null, to solve this

renderNews() {
        const { news = [] } = this.state; // assign a default value
        return news.map((a, i) => (
            <div key={i}>
                {a.response.map((b, i) => (
                    <div key={i}>
                        <div key={i} className="newsEach">
                            <h3>{b.webTitle}</h3>
                            <ul className="newsInfoUl">
                                <li className="newsInfoEach">{b.type}</li>
                                <li className="newsInfoEach">
                                    {b.sectionName}
                                </li>
                                <li className="newsInfoEach">{b.pillarName}</li>
                                <li className="newsInfoEach">{b.webUrl}</li>
                            </ul>
                        </div>
                    </div>
                ))}
            </div>
        ))
    }


问:
Error in creating record in zohocrm contacts using php 7.1
I am trying to create a record in zohocrm. i am using  API version2 code.
i recieve this following error which i stated below. I tried stackoverflow  for solutions but can't find relevant solution. I tried this Stackoverflow answer Zoho API V2 Update Record. It doesn't work for me. Help me with some solution. i use php version

7.1

Here's the Code i used:

```<code>public function createRecord($module, $module_fields)
{
    global $HelperObj;
    $WPCapture_includes_helper_Obj = new WPCapture_includes_helper_PRO();
    $activateplugin = $WPCapture_includes_helper_Obj->ActivatedPlugin;
    $moduleslug = $this->ModuleSlug = rtrim(strtolower($module), "s");
    $zohoapi = new SmackZohoApi();
    $module_field['data'] = array($module_fields);
    $module_field['Owner']['id'] = $module_fields['SMOWNERID'];

    $fields_to_skip = ['Digital_Interaction_s', 'Solution'];
    foreach ($module_fields as $fieldname => $fieldvalue) {
        if (!in_array($fieldname, $fields_to_skip)) {
            continue;
        }

        $module_fields[$fieldname] = array();

        if (is_string($fieldvalue)) {
            array_push($module_fields[$fieldname], $fieldvalue);
        } else if (is_array($fieldvalue)) {
            array_push($module_fields[$fieldname], $fieldvalue);
        }
    }

    //$fields = json_encode($module_fields);

    $attachments = $module_fields['attachments'];
    $body_json = array();
    $body_json["data"] = array();
    array_push($body_json["data"], $module_fields);

    $record = $zohoapi->Zoho_CreateRecord($module, $body_json, $attachments);
    if ($record['code'] == 'INVALID_TOKEN' || $record['code'] == 'AUTHENTICATION_FAILURE') {
        $get_access_token = $zohoapi->refresh_token();
        if (isset($get_access_token['error'])) {
            if ($get_access_token['error'] == 'access_denied') {
                $data['result'] = "failure";
                $data['failure'] = 1;
                $data['reason'] = "Access Denied to get the refresh token";
                return $data;
            }
        }

        $exist_config = get_option("wp_wpzohopro_settings");
        $config['access_token'] = $get_access_token['access_token'];
        $config['api_domain'] = $get_access_token['api_domain'];
        $config['key'] = $exist_config['key'];
        $config['secret'] = $exist_config['secret'];
        $config['callback'] = $exist_config['callback'];
        $config['refresh_token'] = $exist_config['refresh_token'];
        update_option("wp_wpzohopro_settings", $config);
        $this->createRecord($module, $module_fields);
    } elseif ($record['data'][0]['code'] == 'SUCCESS') {
        $data['result'] = "success";
        $data['failure'] = 0;
    } else {
        $data['result'] = "failure";
        $data['failure'] = 1;
        $data['reason'] = "failed adding entry";
    }
    return $data;
}
</code>```

API Call Code:

```<code>public function Zoho_CreateRecord($module = "Lead",$data_array,$extraParams) {
    try{
        $apiUrl = "https://www.zohoapis.com/crm/v2/$module";
        $fields = json_encode($data_array);
        $headers = array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($fields),
            sprintf('Authorization: Zoho-oauthtoken %s', $this->access_token),
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        $result = curl_exec($ch);

        curl_close($ch);
        $result_array = json_decode($result,true);
        if($extraParams != "")
        {
            foreach($extraParams as $field => $path){
                $this->insertattachment($result_array,$path,$module);
            }
        }
    }catch(\Exception $exception){
        // TODO - handle the error in log
    }
    return $result_array;
}
</code>```

error i got:

```<code>Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [code] => INVALID_DATA
                    [details] => Array
                        (
                            [expected_data_type] => jsonarray
                            [api_name] => Solution_Interest
                        )

                    [message] => invalid data
                    [status] => error
                )

        )

)
</code>```

答:
By the details which you gave ,

(1)you said you  wish to create "Contacts"  , but the url  you are using to create contact doesn't seems to create "Contacts" either by

**converting leads to account and contact  , or

**directly creating contact

(2)you mentioned module name as "Lead" , try changing it  to "Leads".

(3)variables $data_array & $extraParams , doesn't seems to hold any value , they seems to be null.

(4)Here is a help doc. for you

Create Contact

If that still doesn't solve your problem ,you could ask your queries at zoho crm community , people will definitely solve your queries Ask here

Body:
I am trying to create a record in zohocrm. i am using  API version2 code.
i recieve this following error which i stated below. I tried stackoverflow  for solutions but can't find relevant solution. I tried this Stackoverflow answer Zoho API V2 Update Record. It doesn't work for me. Help me with some solution. i use php version

7.1

Here's the Code i used:

public function createRecord($module, $module_fields)
{
    global $HelperObj;
    $WPCapture_includes_helper_Obj = new WPCapture_includes_helper_PRO();
    $activateplugin = $WPCapture_includes_helper_Obj->ActivatedPlugin;
    $moduleslug = $this->ModuleSlug = rtrim(strtolower($module), "s");
    $zohoapi = new SmackZohoApi();
    $module_field['data'] = array($module_fields);
    $module_field['Owner']['id'] = $module_fields['SMOWNERID'];

    $fields_to_skip = ['Digital_Interaction_s', 'Solution'];
    foreach ($module_fields as $fieldname => $fieldvalue) {
        if (!in_array($fieldname, $fields_to_skip)) {
            continue;
        }

        $module_fields[$fieldname] = array();

        if (is_string($fieldvalue)) {
            array_push($module_fields[$fieldname], $fieldvalue);
        } else if (is_array($fieldvalue)) {
            array_push($module_fields[$fieldname], $fieldvalue);
        }
    }

    //$fields = json_encode($module_fields);

    $attachments = $module_fields['attachments'];
    $body_json = array();
    $body_json["data"] = array();
    array_push($body_json["data"], $module_fields);

    $record = $zohoapi->Zoho_CreateRecord($module, $body_json, $attachments);
    if ($record['code'] == 'INVALID_TOKEN' || $record['code'] == 'AUTHENTICATION_FAILURE') {
        $get_access_token = $zohoapi->refresh_token();
        if (isset($get_access_token['error'])) {
            if ($get_access_token['error'] == 'access_denied') {
                $data['result'] = "failure";
                $data['failure'] = 1;
                $data['reason'] = "Access Denied to get the refresh token";
                return $data;
            }
        }

        $exist_config = get_option("wp_wpzohopro_settings");
        $config['access_token'] = $get_access_token['access_token'];
        $config['api_domain'] = $get_access_token['api_domain'];
        $config['key'] = $exist_config['key'];
        $config['secret'] = $exist_config['secret'];
        $config['callback'] = $exist_config['callback'];
        $config['refresh_token'] = $exist_config['refresh_token'];
        update_option("wp_wpzohopro_settings", $config);
        $this->createRecord($module, $module_fields);
    } elseif ($record['data'][0]['code'] == 'SUCCESS') {
        $data['result'] = "success";
        $data['failure'] = 0;
    } else {
        $data['result'] = "failure";
        $data['failure'] = 1;
        $data['reason'] = "failed adding entry";
    }
    return $data;
}

API Call Code:

public function Zoho_CreateRecord($module = "Lead",$data_array,$extraParams) {
    try{
        $apiUrl = "https://www.zohoapis.com/crm/v2/$module";
        $fields = json_encode($data_array);
        $headers = array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($fields),
            sprintf('Authorization: Zoho-oauthtoken %s', $this->access_token),
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        $result = curl_exec($ch);

        curl_close($ch);
        $result_array = json_decode($result,true);
        if($extraParams != "")
        {
            foreach($extraParams as $field => $path){
                $this->insertattachment($result_array,$path,$module);
            }
        }
    }catch(\Exception $exception){
        // TODO - handle the error in log
    }
    return $result_array;
}

error i got:

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [code] => INVALID_DATA
                    [details] => Array
                        (
                            [expected_data_type] => jsonarray
                            [api_name] => Solution_Interest
                        )

                    [message] => invalid data
                    [status] => error
                )

        )

)


问:
c2i_ASN1_INTEGER function in Openssl 1.1.0
I recently updated openssl from 1.0.2n to 1.1.0g in linux system.

Earlier I was using

ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp, long len)  function. As this function is removed in openssl 1.1.0, now i replaced this with

ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp, long length) .

Now when i run my application then i get warning as

Warning:0:-- SSL Error queue report --
Warning:0: - asn1 encoding routines|d2i_ASN1_UINTEGER|expecting an integer:218718323

What is the solution for this problem?

答:
ASN.1 encoding of an INTEGER (as BER or DER) consists of 1 or more "identifier" octets (usually 1), followed by 1 or more "length" octets, followed by "content" octets (the length of which is determined by the previous "length" octets).

The function c2i_ASN1_INTEGER assumes you have already parsed the "identifier" and "length" octets and coverts the "content" bytes into an integer. This was removed from OpenSSL 1.1.0 because this is considered a very low level parsing operation that applications should not be calling directly.

The function d2i_ASN1_UINTEGER is not a direct drop in replacement for c2i_ASN1_INTEGER. It parses the whole integer (including the "identifier" and "length" octets). If you pass it just the content octets then it will interpret the first byte as an "identifier" octet. This will likely have the wrong value for an integer and so this is probably why you are seeing the "expecting an integer" error.

You will need to rewrite your code to pass the whole integer to d2i_ASN1_UINTEGER.


问:
xlrd import issue with Python 2.7
I have an assignment to read excel data in Python. I have Python 2.7 installed. I tried installing xlrd0.8.0 with the following commands in Windows.

```<code>C:\Python27\xlrd-0.8.0>python setup.py build
running build
running build_py
creating build
creating build\lib
creating build\lib\xlrd
copying xlrd\biffh.py -> build\lib\xlrd
....

C:\Python27\xlrd-0.8.0>python setup.py install
running install
running build
running build_py
running build_scripts
running install_lib
running install_scripts
running install_egg_info
Writing C:\Python27\Lib\site-packages\xlrd-0.8.0-py2.7.egg-info
</code>```

I don't get any error message while installing. I also see xlrd-0.8.0 folder in site-packages in /lib folder...

But when I try to import it, Python is not able to recognize it...

```<code>>>> import xlrd
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import xlrd
ImportError: No module named xlrd
</code>```

Can you suggest how to find the issue?

答:
python -m pip install xlrd

For my case I have both python2 and python3 installed, pip install xlrd default install xlrd into the Python3 library (/usr/local/lib/python3.6/site-packages/xlrd/. By specifying python2 for pip install solved my problem.

Title: xlrd import issue with Python 2.7

Body:
I have an assignment to read excel data in Python. I have Python 2.7 installed. I tried installing xlrd0.8.0 with the following commands in Windows.

C:\Python27\xlrd-0.8.0>python setup.py build
running build
running build_py
creating build
creating build\lib
creating build\lib\xlrd
copying xlrd\biffh.py -> build\lib\xlrd
....

C:\Python27\xlrd-0.8.0>python setup.py install
running install
running build
running build_py
running build_scripts
running install_lib
running install_scripts
running install_egg_info
Writing C:\Python27\Lib\site-packages\xlrd-0.8.0-py2.7.egg-info

I don't get any error message while installing. I also see xlrd-0.8.0 folder in site-packages in /lib folder...

But when I try to import it, Python is not able to recognize it...

>>> import xlrd
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import xlrd
ImportError: No module named xlrd

Can you suggest how to find the issue?


问:
VS17 Resharper Complaining about React.Component
I have turned on Resharper Ultimate on a .Net Core Web Application that is using TypeScript to code React Components.

So I have a simple component class;

export class Index extends React.Component<{},{}>{

Resharper is warning me that

Generic type '_$_$RsRpExt"FromFile;....\node_modules\@types\react\index.d.ts, module=JavaScriptReferencedFilesModule:Referenced external files".React.Component' requires 1 type argument(s), but got 2

My npm packages for react are;

Dependencies:

```<code>"react": "^15.6.1",
"react-dom": "^15.6.1",
</code>```

Dev Dependencies

```<code>"@types/react": "^15.0.39",
"@types/react-dom": "^15.5.1",
</code>```

Looking at the typed files, I can see that the React Component takes in 2 arguments as it should:

```<code>interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
    class Component<P, S> {
        constructor(props?: P, context?: any);
</code>```

I am using webpack to compile the TS/TSX files and it is all working and the project works, however it is going to be annoying if Resharper is not playing well with the TypeScript code.

Anyone know a way to resolve this?

答:
In VisualStudio 2019 / Resharper 2019.1 you can now enable JSX syntax in JS files. You can do this by following these steps:

Extensions - Resharper - Options - JavaScript - Inspections - Enable JSX syntax in JS files: Always

I also changed my JavaScript language Level to ECMAScript 2016 but I think that is not necessary.

Body:
I have turned on Resharper Ultimate on a .Net Core Web Application that is using TypeScript to code React Components.

So I have a simple component class;

export class Index extends React.Component<{},{}>{

Resharper is warning me that

Generic type '_$_$RsRpExt"FromFile;....\node_modules\@types\react\index.d.ts, module=JavaScriptReferencedFilesModule:Referenced external files".React.Component' requires 1 type argument(s), but got 2

My npm packages for react are;

Dependencies:

"react": "^15.6.1",
"react-dom": "^15.6.1",

Dev Dependencies

"@types/react": "^15.0.39",
"@types/react-dom": "^15.5.1",

Looking at the typed files, I can see that the React Component takes in 2 arguments as it should:

interface Component
 extends ComponentLifecycle
 { }
    class Component
 {
        constructor(props?: P, context?: any);

I am using webpack to compile the TS/TSX files and it is all working and the project works, however it is going to be annoying if Resharper is not playing well with the TypeScript code.

Anyone know a way to resolve this?


问:
Real World Haskell book - asymptotic complexity of Logger monad example
I just reached Chapter 14 of Real World Haskell and was wondering about this yesterday.

In the Logger monad example, the bind function is implemented as follows:

```<code>-- (>>=) :: Logger a -> (a -> Logger b) -> Logger b
    m >>= k = let (a, w) = execLogger m
                  n      = k a
                  (b, x) = execLogger n
              in Logger (b, w ++ x)
</code>```

where the 2nd element in the injector function contains our log messages, which are continuously being appended using ++. (Read online around here for more context.)

My question is.. wouldn't that make the runtime complexity using this Logger quadratic to the number of messages?

If I'm wrong, please help provide the correct analysis and big oh notation.

If I'm right, I'm hoping people who have more experience/insights with Haskell and the book can tell me some reasons of choosing that implementation, and why it is ok.
In the previous chapter of the book there's a section that says this way of appending of list is bad, and teaches us the difference list technique. Why is this not being used here?

BTW I love the book, it's going to be a book I'll read cover to cover since a long long time.

答:
That's the standard (naive) encoding of the Writer monad, specialized to list output. It works well enough for the majority of uses, using the monoid instance for lists:

```<code>instance Monoid [a] where
        mempty  = []
        mappend = (++)
</code>```

Alternatives with better complexity involve loggic to dlists, or even more efficiently, a text or builder monoid.

Body:
I just reached Chapter 14 of Real World Haskell and was wondering about this yesterday.

In the Logger monad example, the bind function is implemented as follows:

-- (>>=) :: Logger a -> (a -> Logger b) -> Logger b
    m >>= k = let (a, w) = execLogger m
                  n      = k a
                  (b, x) = execLogger n
              in Logger (b, w ++ x)

where the 2nd element in the injector function contains our log messages, which are continuously being appended using ++. (Read online around here for more context.)

My question is.. wouldn't that make the runtime complexity using this Logger quadratic to the number of messages?

If I'm wrong, please help provide the correct analysis and big oh notation.

If I'm right, I'm hoping people who have more experience/insights with Haskell and the book can tell me some reasons of choosing that implementation, and why it is ok.
In the previous chapter of the book there's a section that says this way of appending of list is bad, and teaches us the difference list technique. Why is this not being used here?

BTW I love the book, it's going to be a book I'll read cover to cover since a long long time.

Body:
That's the standard (naive) encoding of the Writer monad, specialized to list output. It works well enough for the majority of uses, using the monoid instance for lists:

instance Monoid [a] where
        mempty  = []
        mappend = (++)

Alternatives with better complexity involve loggic to dlists, or even more efficiently, a text or builder monoid.