问:
Swift: downloading data from url causes semaphore_wait_trap freeze
In my application, button tapping downloads data from an Internet site. The site is a list of links containing binary data. Sometimes, the first link may not contain the proper data. In this case, the application takes the next link in the array and gets data from there. The links are correct.

The problem I have is that frequently (not always though) the application freezes for seconds when I tap on the button. After 5-30 seconds, it unfreezes and downloading implements normally. I understand, something is blocking the main thread. When stopping the process in xCode, I get this (semaphore_wait_trap noted):

This is how I do it:

```<code>// Button Action
@IBAction func downloadWindNoaa(_ sender: UIButton)
    {
            // Starts activity indicator
            startActivityIndicator()

            // Starts downloading and processing data

            // Either use this
            DispatchQueue.global(qos: .default).async
                {
                    DispatchQueue.main.async
                        {
                            self.downloadWindsAloftData()
                        }
                }

            // Or this - no difference.
            //downloadWindsAloftData()
        }
    }

func downloadWindsAloftData()
    {
        // Creates a list of website addresses to request data: CHECKED.
        self.listOfLinks = makeGribWebAddress()

        // Extract and save the data
        saveGribFile()
    }

// This downloads the data and saves it in a required format. I suspect, this is the culprit

    func saveGribFile()
    {
        // Check if the links have been created
        if (!self.listOfLinks.isEmpty)
        {
            /// Instance of OperationQueue
            queue = OperationQueue()

            // Convert array of Strings to array of URL links
            let urls = self.listOfLinks.map { URL(string: $0)! }

            guard self.urlIndex != urls.count else
            {
                NSLog("report failure")
                return
            }

            // Current link
            let url = urls[self.urlIndex]

            // Increment the url index
            self.urlIndex += 1

            // Add operation to the queue
            queue.addOperation { () -> Void in

                // Variables for Request, Queue, and Error
                let request = URLRequest(url: url)
                let session = URLSession.shared

                // Array of bytes that will hold the data
                var dataReceived = [UInt8]()

                // Read data
                let task = session.dataTask(with: request) {(data, response, error) -> Void in

                    if error != nil
                    {
                        print("Request transport error")
                    }
                    else
                    {
                        let response = response as! HTTPURLResponse
                        let data = data!

                        if response.statusCode == 200
                        {
                            //Converting data to String
                            dataReceived = [UInt8](data)
                        }
                        else
                        {
                            print("Request server-side error")
                        }
                    }

                    // Main thread
                    OperationQueue.main.addOperation(
                        {
                            // If downloaded data is less than 2 KB in size, repeat the operation
                            if dataReceived.count <= 2000
                            {
                                self.saveGribFile()
                            }

                            else
                            {
                                self.setWindsAloftDataFromGrib(gribData: dataReceived)

                                // Reset the URL Index back to 0
                                self.urlIndex = 0
                            }
                        }
                    )
                }
                task.resume()
            }
        }
    }

// Processing data further
func setWindsAloftDataFromGrib(gribData: [UInt8])
    {
        // Stops spinning activity indicator
        stopActivityIndicator()

        // Other code to process data...
    }

// Makes Web Address

let GRIB_URL = "http://xxxxxxxxxx"

func makeGribWebAddress() -> [String]
    {
        var finalResult = [String]()

        // Main address site
        let address1 = "http://xxxxxxxx"

        // Address part with type of data
        let address2 = "file=gfs.t";
        let address4 = "z.pgrb2.1p00.anl&lev_250_mb=on&lev_450_mb=on&lev_700_mb=on&var_TMP=on&var_UGRD=on&var_VGRD=on"

        let leftlon = "0"
        let rightlon = "359"
        let toplat = "90"
        let bottomlat = "-90"

        // Address part with coordinates
        let address5 = "&leftlon="+leftlon+"&rightlon="+rightlon+"&toplat="+toplat+"&bottomlat="+bottomlat

        // Vector that includes all Grib files available for download
        let listOfFiles = readWebToString()

        if (!listOfFiles.isEmpty)
        {
            for i in 0..<listOfFiles.count
            {
                // Part of the link that includes the file
                let address6 = "&dir=%2F"+listOfFiles[i]

                // Extract time: last 2 characters
                let address3 = listOfFiles[i].substring(from:listOfFiles[i].index(listOfFiles[i].endIndex, offsetBy: -2))

                // Make the link
                let addressFull = (address1 + address2 + address3 + address4 + address5 + address6).trimmingCharacters(in: .whitespacesAndNewlines)

                finalResult.append(addressFull)
            }
        }

        return finalResult;
    }

func readWebToString() -> [String]
    {
        // Final array to return
        var finalResult = [String]()

        guard let dataURL = NSURL(string: self.GRIB_URL)
            else
        {
            print("IGAGribReader error: No URL identified")
            return []
        }

        do
        {
            // Get contents of the page
            let contents = try String(contentsOf: dataURL as URL)

            // Regular expression
            let expression : String = ">gfs\\.\\d+<"
            let range = NSRange(location: 0, length: contents.characters.count)

            do
            {
                // Match the URL content with regex expression
                let regex = try NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.caseInsensitive)
                let contentsNS = contents as NSString
                let matches = regex.matches(in: contents, options: [], range: range)

                for match in matches
                {
                    for i in 0..<match.numberOfRanges
                    {
                        let resultingNS = contentsNS.substring(with: (match.rangeAt(i))) as String
                        finalResult.append(resultingNS)
                    }
                }

                // Remove "<" and ">" from the strings
                if (!finalResult.isEmpty)
                {
                    for i in 0..<finalResult.count
                    {
                        finalResult[i].remove(at: finalResult[i].startIndex)
                        finalResult[i].remove(at: finalResult[i].index(before: finalResult[i].endIndex))
                    }
                }
            }
            catch
            {
                print("IGAGribReader error: No regex match")
            }

        }
        catch
        {
            print("IGAGribReader error: URL content is not read")
        }

        return finalResult;
    }
</code>```

I have been trying to fix it for the past several weeks but in vain. Any help would be much appreciated!

答:
Your stack trace is telling you that it's stopping at String(contentsOf:), called by readWebToString, called by makeGribWebAddress.

The problem is that String(contentsOf:) performs a synchronous network request. If that request takes any time, it will block that thread. And if you call this from the main thread, your app may freeze.

Theoretically, you could just dispatch that process to a background queue, but that merely hides the deeper problem, that you are doing a network request with an API that is synchronous, non-cancellable, and offers no meaningful error reporting.

You really should doing asynchronous requests with URLSession, like you have elsewhere. Avoid using String(contentsOf:) with remote URL.

Body:
In my application, button tapping downloads data from an Internet site. The site is a list of links containing binary data. Sometimes, the first link may not contain the proper data. In this case, the application takes the next link in the array and gets data from there. The links are correct.

The problem I have is that frequently (not always though) the application freezes for seconds when I tap on the button. After 5-30 seconds, it unfreezes and downloading implements normally. I understand, something is blocking the main thread. When stopping the process in xCode, I get this (semaphore_wait_trap noted):

This is how I do it:

// Button Action
@IBAction func downloadWindNoaa(_ sender: UIButton)
    {
            // Starts activity indicator
            startActivityIndicator()

            // Starts downloading and processing data

            // Either use this
            DispatchQueue.global(qos: .default).async
                {
                    DispatchQueue.main.async
                        {
                            self.downloadWindsAloftData()
                        }
                }

            // Or this - no difference.
            //downloadWindsAloftData()
        }
    }

func downloadWindsAloftData()
    {
        // Creates a list of website addresses to request data: CHECKED.
        self.listOfLinks = makeGribWebAddress()

        // Extract and save the data
        saveGribFile()
    }

// This downloads the data and saves it in a required format. I suspect, this is the culprit

    func saveGribFile()
    {
        // Check if the links have been created
        if (!self.listOfLinks.isEmpty)
        {
            /// Instance of OperationQueue
            queue = OperationQueue()

            // Convert array of Strings to array of URL links
            let urls = self.listOfLinks.map { URL(string: $0)! }

            guard self.urlIndex != urls.count else
            {
                NSLog("report failure")
                return
            }

            // Current link
            let url = urls[self.urlIndex]

            // Increment the url index
            self.urlIndex += 1

            // Add operation to the queue
            queue.addOperation { () -> Void in

                // Variables for Request, Queue, and Error
                let request = URLRequest(url: url)
                let session = URLSession.shared

                // Array of bytes that will hold the data
                var dataReceived = [UInt8]()

                // Read data
                let task = session.dataTask(with: request) {(data, response, error) -> Void in

                    if error != nil
                    {
                        print("Request transport error")
                    }
                    else
                    {
                        let response = response as! HTTPURLResponse
                        let data = data!

                        if response.statusCode == 200
                        {
                            //Converting data to String
                            dataReceived = [UInt8](data)
                        }
                        else
                        {
                            print("Request server-side error")
                        }
                    }

                    // Main thread
                    OperationQueue.main.addOperation(
                        {
                            // If downloaded data is less than 2 KB in size, repeat the operation
                            if dataReceived.count <= 2000
                            {
                                self.saveGribFile()
                            }

                            else
                            {
                                self.setWindsAloftDataFromGrib(gribData: dataReceived)

                                // Reset the URL Index back to 0
                                self.urlIndex = 0
                            }
                        }
                    )
                }
                task.resume()
            }
        }
    }

// Processing data further
func setWindsAloftDataFromGrib(gribData: [UInt8])
    {
        // Stops spinning activity indicator
        stopActivityIndicator()

        // Other code to process data...
    }

// Makes Web Address

let GRIB_URL = "http://xxxxxxxxxx"

func makeGribWebAddress() -> [String]
    {
        var finalResult = [String]()

        // Main address site
        let address1 = "http://xxxxxxxx"

        // Address part with type of data
        let address2 = "file=gfs.t";
        let address4 = "z.pgrb2.1p00.anl&lev_250_mb=on&lev_450_mb=on&lev_700_mb=on&var_TMP=on&var_UGRD=on&var_VGRD=on"

        let leftlon = "0"
        let rightlon = "359"
        let toplat = "90"
        let bottomlat = "-90"

        // Address part with coordinates
        let address5 = "&leftlon="+leftlon+"&rightlon="+rightlon+"&toplat="+toplat+"&bottomlat="+bottomlat

        // Vector that includes all Grib files available for download
        let listOfFiles = readWebToString()

        if (!listOfFiles.isEmpty)
        {
            for i in 0..<listOfFiles.count
            {
                // Part of the link that includes the file
                let address6 = "&dir=%2F"+listOfFiles[i]

                // Extract time: last 2 characters
                let address3 = listOfFiles[i].substring(from:listOfFiles[i].index(listOfFiles[i].endIndex, offsetBy: -2))

                // Make the link
                let addressFull = (address1 + address2 + address3 + address4 + address5 + address6).trimmingCharacters(in: .whitespacesAndNewlines)

                finalResult.append(addressFull)
            }
        }

        return finalResult;
    }

func readWebToString() -> [String]
    {
        // Final array to return
        var finalResult = [String]()

        guard let dataURL = NSURL(string: self.GRIB_URL)
            else
        {
            print("IGAGribReader error: No URL identified")
            return []
        }

        do
        {
            // Get contents of the page
            let contents = try String(contentsOf: dataURL as URL)

            // Regular expression
            let expression : String = ">gfs\\.\\d+<"
            let range = NSRange(location: 0, length: contents.characters.count)

            do
            {
                // Match the URL content with regex expression
                let regex = try NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.caseInsensitive)
                let contentsNS = contents as NSString
                let matches = regex.matches(in: contents, options: [], range: range)

                for match in matches
                {
                    for i in 0..<match.numberOfRanges
                    {
                        let resultingNS = contentsNS.substring(with: (match.rangeAt(i))) as String
                        finalResult.append(resultingNS)
                    }
                }

                // Remove "<" and ">" from the strings
                if (!finalResult.isEmpty)
                {
                    for i in 0..<finalResult.count
                    {
                        finalResult[i].remove(at: finalResult[i].startIndex)
                        finalResult[i].remove(at: finalResult[i].index(before: finalResult[i].endIndex))
                    }
                }
            }
            catch
            {
                print("IGAGribReader error: No regex match")
            }

        }
        catch
        {
            print("IGAGribReader error: URL content is not read")
        }

        return finalResult;
    }

I have been trying to fix it for the past several weeks but in vain. Any help would be much appreciated!


来源: stackexchange

问:
Child headers for ExpandableListView using CursorTreeAdapter
How do I create a header for every expanded ChildView without affecting my underlying data and onClick / onLongClick events on the ChildView. Below is the skeleton implementation of my ExpandableListView adapter:

private class EAdapter extends CursorTreeAdapter {

```<code>public EAdapter(Cursor cursor, Context context) {
   super(cursor, context);
  }

  @Override
  protected void bindChildView(View view, Context context, Cursor cursor,
    boolean isLastChild) {

 }

  @Override
  protected void bindGroupView(View view, Context context, Cursor cursor,
    boolean isExpanded) {

 }

  ChildHolder childHolder;

  @Override
  protected View newChildView(Context context, Cursor cursor,
    boolean isLastChild, ViewGroup parent) {

  view.setTag(childHolder);
   registerForContextMenu(view);
   return view;
  }

  GroupHolder groupHolder;

  @Override
  protected View newGroupView(Context context, final Cursor cursor,
    boolean isExpanded, ViewGroup parent) {

view.setTag(groupHolder);
   return view;
  }

  @Override
  protected Cursor getChildrenCursor(Cursor groupCursor) {

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

Any help/pointers will be most helpful.

答: You can create a layout XML that you load for the new View in the newChildView function.</p>

ContentLicense: CC BY-SA 3.0

Body:
How do I create a header for every expanded ChildView without affecting my underlying data and onClick / onLongClick events on the ChildView. Below is the skeleton implementation of my ExpandableListView adapter:

private class EAdapter extends CursorTreeAdapter {

public EAdapter(Cursor cursor, Context context) {
   super(cursor, context);
  }

  @Override
  protected void bindChildView(View view, Context context, Cursor cursor,
    boolean isLastChild) {

 }

  @Override
  protected void bindGroupView(View view, Context context, Cursor cursor,
    boolean isExpanded) {

 }

  ChildHolder childHolder;

  @Override
  protected View newChildView(Context context, Cursor cursor,
    boolean isLastChild, ViewGroup parent) {

  view.setTag(childHolder);
   registerForContextMenu(view);
   return view;
  }

  GroupHolder groupHolder;

  @Override
  protected View newGroupView(Context context, final Cursor cursor,
    boolean isExpanded, ViewGroup parent) {

view.setTag(groupHolder);
   return view;
  }

  @Override
  protected Cursor getChildrenCursor(Cursor groupCursor) {

 return cursor;
  }
}

Any help/pointers will be most helpful.

ContentLicense: CC BY-SA 2.5


问:
C# WPF MVVM TabItem HeaderTemplate won't work?
I am currently working on an application with a TabControl, and every tab has a ViewModel which inherits from ITabViewModel, which has two properties: HeaderText and HeaderImage. I would like these to be set from each ViewModel. Thus, I attempted to use a HeaderTemplate style, but this did not work. Could anyone tell me how I could get this to work?

```<code><TabControl>
    <TabControl.Resources>
        <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}">
            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding HeaderImage}" Height="20" Margin="5, 0"/>
                            <TextBlock Text="{Binding HeaderText}"/>
                        </StackPanel>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </TabControl.Resources>

    <TabItem DataContext="{Binding ViewModelStart}">

    </TabItem>

    <TabItem DataContext="{Binding ViewModelStartupManager}">

    </TabItem>
</TabControl>
</code>```

答:
Just define the DataTemplate under the ItemTemplate section

```<code> <TabControl>
    <TabControl.ItemTemplate>
        <DataTemplate>
             <StackPanel Orientation="Horizontal">
</code>```

And so on with your bindings

ItemTemplate is the template used to format each item in the ItemsSource to create the headers

Body:
I am currently working on an application with a TabControl, and every tab has a ViewModel which inherits from ITabViewModel, which has two properties: HeaderText and HeaderImage. I would like these to be set from each ViewModel. Thus, I attempted to use a HeaderTemplate style, but this did not work. Could anyone tell me how I could get this to work?

<TabControl>
    <TabControl.Resources>

    </TabControl.Resources>

    <TabItem DataContext="{Binding ViewModelStart}">

    </TabItem>

    <TabItem DataContext="{Binding ViewModelStartupManager}">

    </TabItem>
</TabControl>

Body:
Just define the DataTemplate under the ItemTemplate section

 <TabControl>
    <TabControl.ItemTemplate>
        <DataTemplate>
             <StackPanel Orientation="Horizontal">

And so on with your bindings

ItemTemplate is the template used to format each item in the ItemsSource to create the headers


问:
Reliably determine what shell (cmd, bash, or etc) was used to run node.js script
As the title states, I'd like determine what shell (cmd, bash, or etc)  was used to run the node.js script (from within the script).

While detecting the OS with the os module can give some clues, it is not enough is some instances, such as as if I were executing from bash on win32 through a terminal like GitBash or Cygwin.

Is there a property somewhere on the process object that has this information?

*Edit: While process.env.SHELL is an option, it is not always populated and maybe undefined when using some terminals

答:
You can use the process.env.SHELL property to get that as seen in the official documentation,

The process.env property returns an object containing the user environment. An example of this object looks like:

```<code>{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
}
</code>```

Body:
You can use the process.env.SHELL property to get that as seen in the official documentation,

The process.env property returns an object containing the user environment. An example of this object looks like:

{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
}


问:
How to create thread-safe random number generator in C using rand_r()?
I was asked to not use rand() because they were not "thread safe" and to also use a different seed value each time. I found examples on GitHub using a seed value like this:

unsigned int seed = time(NULL);

That only has a precision by seconds. Since the program runs in under 1 second, I end up getting the same random number every instance.

How would I fix this algorithm so that it only uses rand_r() or any other "thread safe" methods to generate 10 random numbers?

```<code>int main()
{
    for(int i = 0; i < 10; i++){
        int random;
        unsigned int seed = time(NULL);
            random = 1 + (rand_r(&seed)% 10);
        printf("%d\n",random);
    }
 return 0;
}
</code>```

答:
The rand_r function takes a pointer to a state variable.  This is set to a seed value before rand_r is called for the first time.  Then each time you call rand_r, you pass in address of this value.

To be thread safe, each thread needs to have its own state variable.  You don't however want to use the same initial value for each thread's state variable, otherwise every thread will generate the same sequence of pseudo-random values.

You need to seed the state variable with data that differs for each thread, such as the thread id, plus other information such as the time and/or pid.

For example:

```<code>// 2 threads, 1 state variable each
unsigned int state[2];

void *mythread(void *p_mystate)
{
    unsigned int *mystate = p_mystate;
    // XOR multiple values together to get a semi-unique seed
    *mystate = time(NULL) ^ getpid() ^ pthread_self();

    ...
    int rand1 = rand_r(mystate);
    ...
    int rand2 = rand_r(mystate);
    ...
    return NULL;
}

int main()
{
    pthread_t t1, t2;

    // give each thread the address of its state variable
    pthread_create(&t1, NULL, mythread, &state[0]);
    pthread_create(&t2, NULL, mythread, &state[1]);
    ...
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    return 0;
}
</code>```

Body:
I was asked to not use rand() because they were not "thread safe" and to also use a different seed value each time. I found examples on GitHub using a seed value like this:

unsigned int seed = time(NULL);

That only has a precision by seconds. Since the program runs in under 1 second, I end up getting the same random number every instance.

How would I fix this algorithm so that it only uses rand_r() or any other "thread safe" methods to generate 10 random numbers?

int main()
{
    for(int i = 0; i < 10; i++){
        int random;
        unsigned int seed = time(NULL);
            random = 1 + (rand_r(&seed)% 10);
        printf("%d\n",random);
    }
 return 0;
}

Body:
The rand_r function takes a pointer to a state variable.  This is set to a seed value before rand_r is called for the first time.  Then each time you call rand_r, you pass in address of this value.

To be thread safe, each thread needs to have its own state variable.  You don't however want to use the same initial value for each thread's state variable, otherwise every thread will generate the same sequence of pseudo-random values.

You need to seed the state variable with data that differs for each thread, such as the thread id, plus other information such as the time and/or pid.

For example:

// 2 threads, 1 state variable each
unsigned int state[2];

void *mythread(void *p_mystate)
{
    unsigned int *mystate = p_mystate;
    // XOR multiple values together to get a semi-unique seed
    *mystate = time(NULL) ^ getpid() ^ pthread_self();

    ...
    int rand1 = rand_r(mystate);
    ...
    int rand2 = rand_r(mystate);
    ...
    return NULL;
}

int main()
{
    pthread_t t1, t2;

    // give each thread the address of its state variable
    pthread_create(&t1, NULL, mythread, &state[0]);
    pthread_create(&t2, NULL, mythread, &state[1]);
    ...
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    return 0;
}


问:
Using variable declared in one method to open webpage in another method
I am working on a CLI Project and trying to open up a web page by using url variable declared in another method.

```<code>def self.open_deal_page(input)
  index = input.to_i - 1
  @deals = PopularDeals::NewDeals.new_deals
  @deals.each do |info|
  d = info[index]
  @product_url = "#{d.url}"
  end
  @product_url.to_s
  puts "They got me!"
end

def self.deal_page(product_url)
  #self.open_deal_page(input)
  deal = {}
  html = Nokogiri::HTML(open(@product_url))
  doc = Nokogiri::HTML(html)
  deal[:name] = doc.css(".dealTitle h1").text.strip
  deal[:discription] = doc.css(".textDescription").text.strip
  deal[:purchase] = doc.css("div a.button").attribute("href")
  deal
  #binding.pry
end
</code>```

but I am receiving this error.

```<code>  `open': no implicit conversion of nil into String (TypeError)
</code>```

any possible solution? Thank you so much in advance.

答:
Try returning your @product_url within your open_deal_page method, because now you're returning puts "They got me!", and also note that your product_url is being created inside your each block, so, it won't be accessible then, try creating it before as an empty string and then you can return it.

```<code>def open_deal_page(input)
  ...
  # Create the variable
  product_url = ''
  # Assign it the value
  deals.each do |info|
    product_url = "#{info[index].url}"
  end
  # And return it
  product_url
end
</code>```

In your deal_page method tell to Nokogiri to open the product_url that you're passing as argument.

```<code>def deal_page(product_url)
  ...
  html = Nokogiri::HTML(open(product_url))
  ...
end
</code>```

Body:
I am working on a CLI Project and trying to open up a web page by using url variable declared in another method.

def self.open_deal_page(input)
  index = input.to_i - 1
  @deals = PopularDeals::NewDeals.new_deals
  @deals.each do |info|
  d = info[index]
  @product_url = "#{d.url}"
  end
  @product_url.to_s
  puts "They got me!"
end

def self.deal_page(product_url)
  #self.open_deal_page(input)
  deal = {}
  html = Nokogiri::HTML(open(@product_url))
  doc = Nokogiri::HTML(html)
  deal[:name] = doc.css(".dealTitle h1").text.strip
  deal[:discription] = doc.css(".textDescription").text.strip
  deal[:purchase] = doc.css("div a.button").attribute("href")
  deal
  #binding.pry
end

but I am receiving this error.

  `open': no implicit conversion of nil into String (TypeError)

any possible solution? Thank you so much in advance.

Body:
Try returning your @product_url within your open_deal_page method, because now you're returning puts "They got me!", and also note that your product_url is being created inside your each block, so, it won't be accessible then, try creating it before as an empty string and then you can return it.

def open_deal_page(input)
  ...
  # Create the variable
  product_url = ''
  # Assign it the value
  deals.each do |info|
    product_url = "#{info[index].url}"
  end
  # And return it
  product_url
end

In your deal_page method tell to Nokogiri to open the product_url that you're passing as argument.

def deal_page(product_url)
  ...
  html = Nokogiri::HTML(open(product_url))
  ...
end


问:
TimePicker reset bug. Any workaround?
I found some problem for TimePicker widget. After user change time in widget setHour and setMinute methods not works.

```<code>public class MainActivity extends AppCompatActivity {

    private Button mButton;
    private TimePicker mTimePicker;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mButton = (Button) findViewById(R.id.reset);
        mTimePicker = (TimePicker) findViewById(R.id.timePicker);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar cal = Calendar.getInstance();
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                int minute = cal.get(Calendar.MINUTE);

                mTimePicker.setHour(hour);
                mTimePicker.setMinute(minute);

                Log.v(TAG, "onClick: " + hour + "=>" + mTimePicker.getHour());
                Log.v(TAG, "onClick: " + minute + "=>" + mTimePicker.getMinute());
            }
        });
    }
}
</code>```

Step for reproduce:

Run app (my time: 13:21)

Change time on the Widget (21:21)

Tap on the Reset button

Result:time not reset to 13:21

Log:

03-30 13:18:05.765 30923-30923/ru.neverdark.timepickerproblem
  V/MainActivity: onClick: 13=>21 03-30 13:18:05.765
  30923-30923/ru.neverdark.timepickerproblem V/MainActivity: onClick:
  18=>18

Any workaround for this problem?

Same bug I found in Issue Tracker: https://code.google.com/p/android/issues/detail?id=208180 but in SDK25 not fixed...

Demo project on the github: https://github.com/yankovskiy/TimePickerProblem

答:
Well, I have to admit, this is not my proudest code.

But as a workaround you can have this:

```<code>mButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Calendar cal = Calendar.getInstance();
        int currentHour = cal.get(Calendar.HOUR_OF_DAY);
        int currentMinute = cal.get(Calendar.MINUTE);

        fixValues();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mTimePicker.setHour(currentHour);
            mTimePicker.setMinute(currentMinute);
        } else {
            mTimePicker.setCurrentHour(currentHour);
            mTimePicker.setCurrentMinute(currentMinute);
        }
    }
});

private void fixValues() {
    // bug is not reproducible in APIs 24 and above
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) return;
    try {
        int hour, minute;
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
            hour = mTimePicker.getHour();
            minute = mTimePicker.getMinute();
        } else {
            hour = mTimePicker.getCurrentHour();
            minute = mTimePicker.getCurrentMinute();
        }

        Field mDelegateField = mTimePicker.getClass().getDeclaredField("mDelegate");
        mDelegateField.setAccessible(true);
        Class<?> clazz;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            clazz = Class.forName("android.widget.TimePickerClockDelegate");
        } else {
            clazz = Class.forName("android.widget.TimePickerSpinnerDelegate");
        }
        Field mInitialHourOfDayField = clazz.getDeclaredField("mInitialHourOfDay");
        Field mInitialMinuteField = clazz.getDeclaredField("mInitialMinute");
        mInitialHourOfDayField.setAccessible(true);
        mInitialMinuteField.setAccessible(true);
        mInitialHourOfDayField.setInt(mDelegateField.get(mTimePicker), hour);
        mInitialMinuteField.setInt(mDelegateField.get(mTimePicker), minute);
    } catch (NoSuchFieldException | IllegalAccessException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}
</code>```

Tested on APIs 21, 22 and 23.

Bug is not reproducible in APIs 24, 25.

Title: TimePicker reset bug. Any workaround?

Body:
I found some problem for TimePicker widget. After user change time in widget setHour and setMinute methods not works.

public class MainActivity extends AppCompatActivity {

    private Button mButton;
    private TimePicker mTimePicker;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mButton = (Button) findViewById(R.id.reset);
        mTimePicker = (TimePicker) findViewById(R.id.timePicker);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar cal = Calendar.getInstance();
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                int minute = cal.get(Calendar.MINUTE);

                mTimePicker.setHour(hour);
                mTimePicker.setMinute(minute);

                Log.v(TAG, "onClick: " + hour + "=>" + mTimePicker.getHour());
                Log.v(TAG, "onClick: " + minute + "=>" + mTimePicker.getMinute());
            }
        });
    }
}

Step for reproduce:

Run app (my time: 13:21)

Change time on the Widget (21:21)

Tap on the Reset button

Result:time not reset to 13:21

Log:

03-30 13:18:05.765 30923-30923/ru.neverdark.timepickerproblem
  V/MainActivity: onClick: 13=>21 03-30 13:18:05.765
  30923-30923/ru.neverdark.timepickerproblem V/MainActivity: onClick:
  18=>18

Any workaround for this problem?

Same bug I found in Issue Tracker: https://code.google.com/p/android/issues/detail?id=208180 but in SDK25 not fixed...

Demo project on the github: https://github.com/yankovskiy/TimePickerProblem

Body:
Well, I have to admit, this is not my proudest code.

But as a workaround you can have this:

mButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Calendar cal = Calendar.getInstance();
        int currentHour = cal.get(Calendar.HOUR_OF_DAY);
        int currentMinute = cal.get(Calendar.MINUTE);

        fixValues();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mTimePicker.setHour(currentHour);
            mTimePicker.setMinute(currentMinute);
        } else {
            mTimePicker.setCurrentHour(currentHour);
            mTimePicker.setCurrentMinute(currentMinute);
        }
    }
});

private void fixValues() {
    // bug is not reproducible in APIs 24 and above
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) return;
    try {
        int hour, minute;
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
            hour = mTimePicker.getHour();
            minute = mTimePicker.getMinute();
        } else {
            hour = mTimePicker.getCurrentHour();
            minute = mTimePicker.getCurrentMinute();
        }

        Field mDelegateField = mTimePicker.getClass().getDeclaredField("mDelegate");
        mDelegateField.setAccessible(true);
        Class<?> clazz;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            clazz = Class.forName("android.widget.TimePickerClockDelegate");
        } else {
            clazz = Class.forName("android.widget.TimePickerSpinnerDelegate");
        }
        Field mInitialHourOfDayField = clazz.getDeclaredField("mInitialHourOfDay");
        Field mInitialMinuteField = clazz.getDeclaredField("mInitialMinute");
        mInitialHourOfDayField.setAccessible(true);
        mInitialMinuteField.setAccessible(true);
        mInitialHourOfDayField.setInt(mDelegateField.get(mTimePicker), hour);
        mInitialMinuteField.setInt(mDelegateField.get(mTimePicker), minute);
    } catch (NoSuchFieldException | IllegalAccessException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}

Tested on APIs 21, 22 and 23.

Bug is not reproducible in APIs 24, 25.


问:
Dynamic String array dosent work
I'm trying to create a dynamic array of 1000 character long strings using calloc:

```<code>int i;
char** strarr =(char**)calloc(argc,sizeof(char)*1000);
if(strarr == NULL)
    return 0;
strarr[0][0] ='a';
printf("%c\n",strarr[0][0]);
</code>```

Every time i try to run this code i get segmentation fault on the printf line, i don't get why does this happen (you can assume that argc is bigger than 0)
Thanks

P.s. im sorry that the code is in text format but im using a mobile so i dont have the code feature

答:
Try this:</p>

```<code>const int num_of_strings = 255; //argc ?
const int num_of_chars = 1000;

int i;
char** strarr =(char**)malloc(sizeof(char*)*num_of_strings);

if(strarr == NULL)
    return 0;
for (i = 0; i < num_of_strings; i++) strarr[i] = (char*)malloc(sizeof(char)*num_of_chars);
</code>```

Title: Dynamic String array dosent work

Body:
I'm trying to create a dynamic array of 1000 character long strings using calloc:

int i;
char** strarr =(char**)calloc(argc,sizeof(char)*1000);
if(strarr == NULL)
    return 0;
strarr[0][0] ='a';
printf("%c\n",strarr[0][0]);

Every time i try to run this code i get segmentation fault on the printf line, i don't get why does this happen (you can assume that argc is bigger than 0)
Thanks

P.s. im sorry that the code is in text format but im using a mobile so i dont have the code feature

Body:
Try this:

const int num_of_strings = 255; //argc ?
const int num_of_chars = 1000;

int i;
char** strarr =(char**)malloc(sizeof(char*)*num_of_strings);

if(strarr == NULL)
    return 0;
for (i = 0; i < num_of_strings; i++) strarr[i] = (char*)malloc(sizeof(char)*num_of_chars);


问:
Combination Sum in Go
```<code>/*
Given an array: [1,2] and a target: 4
Find the solution set that adds up to the target
in this case:
[1,1,1,1]
[1,1,2]
[2,2]
*/
import "sort"
func combinationSum(candidates []int, target int) [][]int {
    sort.Ints(candidates)
    return combine(0, target, []int{}, candidates)
}
func combine(sum int, target int, curComb []int, candidates []int) [][]int {
    var tmp [][]int
    var result [][]int
    if sum == target {
        fmt.Println(curComb)
        return [][]int{curComb}
    } else if sum < target {
        for i,v := range candidates {
            tmp = combine(sum+v, target, append(curComb, v), candidates[i:])
            result = append(result,tmp...)
        }
    }
    return result
}
</code>```

This is a problem in Leetcode and I use recursion to solve it.

In line 18, I print every case when the sum is equal to the target.
The output is :

```<code>[1,1,1,1]
[1,1,2]
[2,2]
</code>```

And that is the answer that I want!
But why is the final answer (two-dimensional):

```<code>[[1,1,1,2],[1,1,2],[2,2]]
</code>```

Expected answer is : [[1,1,1,1],[1,1,2],[2,2]]

Please help me find the mistake in the code. Thanks for your time.

答:
This happens because of the way slices work. A slice object is a reference to an underlying array, along with the length of the slice, a pointer to the start of the slice in the array, and the slice's capacity. The capacity of a slice is the number of elements from the beginning of the slice to the end of the array. When you append to a slice, if there is available capacity for the new element, it is added to the existing array. However, if there isn't sufficient capacity, append allocates a new array and copies the elements. The new array is allocated with extra capacity so that an allocation isn't required for every append.

In your for loop, when curComb is [1, 1, 1], its capacity is 4. On successive iterations of the loop, you append 1 and then 2, neither of which causes a reallocation because there's enough room in the array for the new element. When curComb is [1, 1, 1, 1], it is put on the results list, but in the next iteration of the for loop, the append changes the last element to 2 (remember that it's the same underlying array), so that's what you see when you print the results at the end.

The solution to this is to return a copy of curComb when the sum equals the target:

```<code>if sum == target {
    fmt.Println(curComb)
    tmpCurComb := make([]int, len(curComb))
    copy(tmpCurComb, curComb)
    return [][]int{tmpCurComb}
</code>```

This article gives a good explanation of how slices work.

Title: Combination Sum in Go

Body:
/*
Given an array: [1,2] and a target: 4
Find the solution set that adds up to the target
in this case:
[1,1,1,1]
[1,1,2]
[2,2]
*/
import "sort"
func combinationSum(candidates []int, target int) [][]int {
    sort.Ints(candidates)
    return combine(0, target, []int{}, candidates)
}
func combine(sum int, target int, curComb []int, candidates []int) [][]int {
    var tmp [][]int
    var result [][]int
    if sum == target {
        fmt.Println(curComb)
        return [][]int{curComb}
    } else if sum < target {
        for i,v := range candidates {
            tmp = combine(sum+v, target, append(curComb, v), candidates[i:])
            result = append(result,tmp...)
        }
    }
    return result
}

This is a problem in Leetcode and I use recursion to solve it.

In line 18, I print every case when the sum is equal to the target.
The output is :

[1,1,1,1]
[1,1,2]
[2,2]

And that is the answer that I want!
But why is the final answer (two-dimensional):

[[1,1,1,2],[1,1,2],[2,2]]

Expected answer is : [[1,1,1,1],[1,1,2],[2,2]]

Please help me find the mistake in the code. Thanks for your time.

Body:
This happens because of the way slices work. A slice object is a reference to an underlying array, along with the length of the slice, a pointer to the start of the slice in the array, and the slice's capacity. The capacity of a slice is the number of elements from the beginning of the slice to the end of the array. When you append to a slice, if there is available capacity for the new element, it is added to the existing array. However, if there isn't sufficient capacity, append allocates a new array and copies the elements. The new array is allocated with extra capacity so that an allocation isn't required for every append.

In your for loop, when curComb is [1, 1, 1], its capacity is 4. On successive iterations of the loop, you append 1 and then 2, neither of which causes a reallocation because there's enough room in the array for the new element. When curComb is [1, 1, 1, 1], it is put on the results list, but in the next iteration of the for loop, the append changes the last element to 2 (remember that it's the same underlying array), so that's what you see when you print the results at the end.

The solution to this is to return a copy of curComb when the sum equals the target:

if sum == target {
    fmt.Println(curComb)
    tmpCurComb := make([]int, len(curComb))
    copy(tmpCurComb, curComb)
    return [][]int{tmpCurComb}

This article gives a good explanation of how slices work.


问:
How do I break out of nested loops in Java?
I've got a nested loop construct like this:

```<code>for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do something and break...
             break; // Breaks out of the inner loop
         }
    }
}
</code>```

Now how can I break out of both loops? I've looked at similar questions, but none concerns Java specifically. I couldn't apply these solutions because most used gotos.

I don't want to put the inner loop in a different method.

I don't want to return the loops. When breaking I'm finished with the execution of the loop block.

答:
If it's a new implementation, you can try rewriting the logic as if-else_if-else statements.

```<code>while(keep_going) {

    if(keep_going && condition_one_holds) {
        // Code
    }
    if(keep_going && condition_two_holds) {
        // Code
    }
    if(keep_going && condition_three_holds) {
        // Code
    }
    if(keep_going && something_goes_really_bad) {
        keep_going=false;
    }
    if(keep_going && condition_four_holds) {
        // Code
    }
    if(keep_going && condition_five_holds) {
        // Code
    }
}
</code>```

Otherwise you can try setting a flag when that special condition has occured and check for that flag in each of your loop-conditions.

```<code>something_bad_has_happened = false;
while(something is true && !something_bad_has_happened){
    // Code, things happen
    while(something else && !something_bad_has_happened){
        // Lots of code, things happens
        if(something happened){
            -> Then control should be returned ->
            something_bad_has_happened=true;
            continue;
        }
    }
    if(something_bad_has_happened) { // The things below will not be executed
        continue;
    }

    // Other things may happen here as well, but they will not be executed
    //  once control is returned from the inner cycle.
}
</code>```

HERE! So, while a simple break will not work, it can be made to work using continue.

If you are simply porting the logic from one programming language to Java and just want to get the thing working you can try using labels.

ContentLicense: CC BY-SA 4.0

Body:
I've got a nested loop construct like this:

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do something and break...
             break; // Breaks out of the inner loop
         }
    }
}

Now how can I break out of both loops? I've looked at similar questions, but none concerns Java specifically. I couldn't apply these solutions because most used gotos.

I don't want to put the inner loop in a different method.

I don't want to return the loops. When breaking I'm finished with the execution of the loop block.

Body:
If it's a new implementation, you can try rewriting the logic as if-else_if-else statements.

while(keep_going) {

    if(keep_going && condition_one_holds) {
        // Code
    }
    if(keep_going && condition_two_holds) {
        // Code
    }
    if(keep_going && condition_three_holds) {
        // Code
    }
    if(keep_going && something_goes_really_bad) {
        keep_going=false;
    }
    if(keep_going && condition_four_holds) {
        // Code
    }
    if(keep_going && condition_five_holds) {
        // Code
    }
}

Otherwise you can try setting a flag when that special condition has occured and check for that flag in each of your loop-conditions.

something_bad_has_happened = false;
while(something is true && !something_bad_has_happened){
    // Code, things happen
    while(something else && !something_bad_has_happened){
        // Lots of code, things happens
        if(something happened){
            -> Then control should be returned ->
            something_bad_has_happened=true;
            continue;
        }
    }
    if(something_bad_has_happened) { // The things below will not be executed
        continue;
    }

    // Other things may happen here as well, but they will not be executed
    //  once control is returned from the inner cycle.
}

HERE! So, while a simple break will not work, it can be made to work using continue.

If you are simply porting the logic from one programming language to Java and just want to get the thing working you can try using labels.


问:
How to enlarge custom slide in slick.js
I want to know how to enlarge specific slide in slick gallery. I want to enlarge slide with class toEnlarge. I tried with scalling, adding padding, margin, etc., but no effect. Any idea?

HTML:

```<code><div class="slick-holder">
   <a href="link.html">
       <div class="single"></div>
   </a>
   <a href="link.html" class="toEnlarge">
       <div class="single"></div>
   </a>
   ...
   <a href="link.html">
       <div class="single"></div>
   </a>
</div>
</code>```

JS:

```<code>$('.slick-holder').slick({
    slidesToShow: 5,
    slidesToScroll: 1,
    infinite: true,
});
</code>```

I'm trying to do something like this:

答:
have you tried something like?</p>

```<code>.toEnlarge{
  display: block;
  transform: scale(1.3);
  transform-origin: 50% 50%;
}
</code>```

Title: How to enlarge custom slide in slick.js

Body:
I want to know how to enlarge specific slide in slick gallery. I want to enlarge slide with class toEnlarge. I tried with scalling, adding padding, margin, etc., but no effect. Any idea?

HTML:

   ...

JS:

$('.slick-holder').slick({
    slidesToShow: 5,
    slidesToScroll: 1,
    infinite: true,
});

I'm trying to do something like this:

Body:
have you tried something like?

.toEnlarge{
  display: block;
  transform: scale(1.3);
  transform-origin: 50% 50%;
}


问:
Android studio internal file path, file not saved
Small problem, I am trying to save my PDF file in phone (LG G5 - no SD card), but file is never saved, is there a problem with file path? Using PdfBox-Android library. See picture from debugger - Debugger picture. The aim is to save pdf file to internal downloads folder. I tried 10x solutions, nothing is working. Please help.</p>

答:
I think you are trying to run the code on M version. Please check for Write External Storage permission and other read and write permissions in manifest file. For Android M and above versions use the concept of runtime permissions.

Let, me know if it was helpful.


问:
bigquery queryresults rows pagintation configuration options?
https://googlecloudplatform.github.io/google-cloud-php/#/docs/v0.21.1/bigquery/table?method=rows

Bigquery table has method "rows". rows() method can take parameter "options", which can be used for pagination

Such as

```<code>$options = [
            'maxResults' => 3,
            'startIndex' => 0
        ];
</code>```

$rows = $table->rows($options);

Now what I want is using pagination in bigquery queryresults rows() method

https://googlecloudplatform.github.io/google-cloud-php/#/docs/v0.21.1/bigquery/queryresults?method=rows

Here is the documentation for queryresults rows method. rows() also takes options as parameter. (But it does not give which field should be in the options).

```<code>$queryResults = $this->bigQuery->runQuery($query, ['useLegacySql' => false]);
$options = [
            'maxResults' => 3,
            'startIndex' => 0
        ];

$rows = $queryResults->rows($options);
</code>```

But the options only ask for the top 3 records does not work. It still give me full set of queryresults rows.

Thanks!

答:
https://googlecloudplatform.github.io/google-cloud-php/#/docs/google-cloud/v0.25.0/bigquery/bigqueryclient?method=runQuery

The maxResults option actually needs to be set on the runQuery call:

```<code>$queryResults = $this->bigQuery->runQuery($query, [
    'useLegacySql' => false,
    'maxResults' => 3
]);
</code>```

Let me know if that does the trick for you.

Body:
https://googlecloudplatform.github.io/google-cloud-php/#/docs/v0.21.1/bigquery/table?method=rows

Bigquery table has method "rows". rows() method can take parameter "options", which can be used for pagination

Such as

$options = [
            'maxResults' => 3,
            'startIndex' => 0
        ];

$rows = $table->rows($options);

Now what I want is using pagination in bigquery queryresults rows() method

https://googlecloudplatform.github.io/google-cloud-php/#/docs/v0.21.1/bigquery/queryresults?method=rows

Here is the documentation for queryresults rows method. rows() also takes options as parameter. (But it does not give which field should be in the options).

$queryResults = $this->bigQuery->runQuery($query, ['useLegacySql' => false]);
$options = [
            'maxResults' => 3,
            'startIndex' => 0
        ];

$rows = $queryResults->rows($options);

But the options only ask for the top 3 records does not work. It still give me full set of queryresults rows.

Thanks!

Body:
https://googlecloudplatform.github.io/google-cloud-php/#/docs/google-cloud/v0.25.0/bigquery/bigqueryclient?method=runQuery

The maxResults option actually needs to be set on the runQuery call:

$queryResults = $this->bigQuery->runQuery($query, [
    'useLegacySql' => false,
    'maxResults' => 3
]);

Let me know if that does the trick for you.


问:
How to make your desktop Java app looks like Open Office or Eclipse etc.?
How to make your desktop Java app looks like Open Office or Eclipse  etc ?
Installation process looks like any Windpws app. installation. There is no Java logo on the to on a app window. You run it by .exe file. How it is done? Is this jar->exe conversion?
Is there any free tool to do that?</p>

答:
Note that, for the graphic part, Eclipse uses a library called SWT, which is a set of widgets that feel and behave in a different way that Java Swing or AWT.

Anyway, if you go the normal Java (Swing) way, the Java logo on the top of an app window is setIconImage() method in JFrame components.

Riduidel already told you about .exe wrappers and installers you can use. For the installer, I also suggest you to consider Java Web Start instead of a normal Windows installer.


问:
Add C++ redistribuitable in my .msi and install on silent
I am working with a setup project of Visual Studio 2015. I want to distribute the 2015 C++ library, vc_redist.x86.exe. But I don't want user to be aware of this pre-requisite, so the idea is that while he is running the .msi, the C++ library will be auto-installed.
I have been reading about the merge modules, but this cannot fix my problem because the setup.exe should be run. Please, could anybody tell me how to deal with this?
Many thanks!</p>

答:
You'll need to change (or create your own custom one) the standard bootstrapper that has documentation starting here:

https://msdn.microsoft.com/en-us/library/ms165429.aspx

The bootstrapper packages contain the detection and install logic for the redistributables. For example, the \Bootstrapper\Packages folder has VC redist folders, each with a product.xml and a package.xml about installing them as prerequisites. They have standard command lines such as:

Command PackageFile="vcredist_x64.exe" Arguments=' /q:a

and you can substitute that command with something like those listed here:

http://asawicki.info/news_1597_installing_visual_c_redistributable_package_from_command_line.html

that show the quiet options (as do standard Microsoft docs somewhere).


问:
Java - SQLite connection (No suitable driver found for JDBC:sqlite:main.db)
I have problem with SQLite connection on my Java project. Error looks like this :

No suitable driver found for JDBC:sqlite:main.db

That's my code:

```<code>public static void main(String[] args)  {

    Connection c = null;
    try {
      //  Class.forName("org.sqlite.JDBC");
        String url = "JDBC:sqlite:main.db";
        c = DriverManager.getConnection(url);
        System.out.println("Connection to sql");
    } catch ( SQLException e ) {
        System.err.println( e.getMessage() );
    } finally {
        try{
            if( c!= null ) {
                c.close();
            }
        }catch( SQLException ex )
        {
            System.out.println(ex.getMessage());
        }
    }
}
</code>```

Can You help me please?

答:
"No suitable driver" means that the connection URL is incorrect for the JDBC driver JAR that was loaded.

Case matters: it should be jdbc:sqlite:main.db.  Please read the tutorial.

Body:
I have problem with SQLite connection on my Java project. Error looks like this :

No suitable driver found for JDBC:sqlite:main.db

That's my code:

public static void main(String[] args)  {

    Connection c = null;
    try {
      //  Class.forName("org.sqlite.JDBC");
        String url = "JDBC:sqlite:main.db";
        c = DriverManager.getConnection(url);
        System.out.println("Connection to sql");
    } catch ( SQLException e ) {
        System.err.println( e.getMessage() );
    } finally {
        try{
            if( c!= null ) {
                c.close();
            }
        }catch( SQLException ex )
        {
            System.out.println(ex.getMessage());
        }
    }
}

Can You help me please?


问:
RHEL Environment Variable Path To Mongo Shell
I have installed mongodb in one of our environments & this has been done using MongoDb Operations Manager. Though i have my PATH variable set correctly i'm unable to connect mongo shell with my user account but able to connect as a sudo. could someone help me if i'm missing anything here.

Details:

```<code>[user01@west.company.com@rhel01 /]$ echo $PATH
> /var/lib/mongodb-mms-automation/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/nfs/home/user01/.local/bin:/nfs/home/user01/bin
[user01@west.company.com@rhel01 /]$ mongo
> -bash: mongo: command not found

[user01@west.company.com@rhel01 /]$ sudo -i
[sudo] password for user01@west.company.com:
[root@rhel01 ~]# echo $PATH
> /var/lib/mongodb-mms-automation/bin:/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
[root@rhel01 ~]# mongo
> MongoDB shell
> version: 3.2.10 connecting to: test
> MongoDB Enterprise MYMONGOREPLSET01:PRIMARY>
</code>```

Which Mongo Output:

```<code>[user01@west.company.com@rhel01 /]$ which mongo
/usr/bin/which: no mongo in (/var/lib/mongodb-mms-automation/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/nfs/home/user01/.local/bin:/nfs/home/user01/bin)

[root@rhel01 ~]# which mongo
/var/lib/mongodb-mms-automation/bin/mongo
</code>```

Observation:

i just noticed the bin location is set like this ...

```<code>[root@rhel01 mongodb-mms-automation]# pwd
/var/lib/mongodb-mms-automation
[root@rhel01 mongodb-mms-automation]# ls -la
total 32
drwxr-xr-x   3 mongod mongod  4096 Mar 30 13:58 .
drwxr-xr-x. 57 root   root    4096 Apr  1 03:23 ..
lrwxrwxrwx   1 mongod mongod    67 Nov  4 13:45 bin -> /var/lib/mongodb-mms-automation/mongodb-linux-x86_64-3.2.10-ent/bin
-rw-------   1 mongod mongod  1024 Mar 27 15:07 keyfile
-rw-------   1 mongod mongod 10686 Mar 30 13:58 mms-cluster-config-backup.json
drwxr-x---   4 mongod mongod  4096 Nov  4 13:45 mongodb-linux-x86_64-3.2.10-ent
</code>```

答: add this to path /var/lib/mongodb-mms-automation/mongodb-linux-x86_64-3.2.10-ent/bin</p>

Body:
I have installed mongodb in one of our environments & this has been done using MongoDb Operations Manager. Though i have my PATH variable set correctly i'm unable to connect mongo shell with my user account but able to connect as a sudo. could someone help me if i'm missing anything here.

Details:

[user01@west.company.com@rhel01 /]$ echo $PATH
> /var/lib/mongodb-mms-automation/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/nfs/home/user01/.local/bin:/nfs/home/user01/bin
[user01@west.company.com@rhel01 /]$ mongo
> -bash: mongo: command not found

[user01@west.company.com@rhel01 /]$ sudo -i
[sudo] password for user01@west.company.com:
[root@rhel01 ~]# echo $PATH
> /var/lib/mongodb-mms-automation/bin:/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
[root@rhel01 ~]# mongo
> MongoDB shell
> version: 3.2.10 connecting to: test
> MongoDB Enterprise MYMONGOREPLSET01:PRIMARY>

Which Mongo Output:

[user01@west.company.com@rhel01 /]$ which mongo
/usr/bin/which: no mongo in (/var/lib/mongodb-mms-automation/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/nfs/home/user01/.local/bin:/nfs/home/user01/bin)

[root@rhel01 ~]# which mongo
/var/lib/mongodb-mms-automation/bin/mongo

Observation:

i just noticed the bin location is set like this ...

[root@rhel01 mongodb-mms-automation]# pwd
/var/lib/mongodb-mms-automation
[root@rhel01 mongodb-mms-automation]# ls -la
total 32
drwxr-xr-x   3 mongod mongod  4096 Mar 30 13:58 .
drwxr-xr-x. 57 root   root    4096 Apr  1 03:23 ..
lrwxrwxrwx   1 mongod mongod    67 Nov  4 13:45 bin -> /var/lib/mongodb-mms-automation/mongodb-linux-x86_64-3.2.10-ent/bin
-rw-------   1 mongod mongod  1024 Mar 27 15:07 keyfile
-rw-------   1 mongod mongod 10686 Mar 30 13:58 mms-cluster-config-backup.json
drwxr-x---   4 mongod mongod  4096 Nov  4 13:45 mongodb-linux-x86_64-3.2.10-ent


问:
Unable to read URL string from json and apply it to Object in Android
I'm building an application and have a User object:

```<code>public class User {
    private Integer id = null;
    private String username = null;
    private String password = null;
    private String first_name = null;
    private String last_name = null;
    private String email = null;
    private String phone = null;
    private String avatar = null;
    private String role = null;
    private Boolean confirmed = null;
    private Boolean active = null;
    private String created_at = null;
    private String updated_at = null;
    private String sex = null;
    private Object company = null;
}
</code>```

This object(class) contains setters and getters.
When authorization response has come - i'm proccessing it with next callback:

```<code>public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                ApiResponse apiResponse = response.body();

                Log.i("log_i", apiResponse.getData().toString());

                JsonReader jsonResponse = new JsonReader(new StringReader(apiResponse.getData().toString()));
                jsonResponse.setLenient(true);

                try {
                    User user = new Gson().fromJson(jsonResponse, User.class);
                    Log.i("log_i", user.toString());
                    Toast.makeText(context, apiResponse.getMessage(), Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    Log.i("log_i", e.getMessage());
                    Toast.makeText(context, "Failed to authorize in case of application exception.", Toast.LENGTH_SHORT).show();
                }
            }
</code>```

After it step to firt line after try{} - it's crashes and next error is apperas in Log:

```<code>I/log_i: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 147 path $.avatar
</code>```

Logged JSON:

```<code>{
    id=4,
    username=admin,
    first_name=Test,
    last_name=User,
    email=test@email.com,
    phone=012.345.678,
    confirmed=true,
    active=true,
    avatar=https://path/to/avatar.png,
    role=admin,
    created_at=2017-02-24T14: 22: 50+00: 00,
    updated_at=null,
    company_id=2.0,
    sex=m,
    company={
        id=2.0,
        title=companyTitle,
        active=true,
        created_at=2017-02-24T14: 22: 50+00: 00,
        updated_at=null,
        deleted_at=2017-02-24T14: 22: 50+00: 00
    }
}
</code>```

Any help will be appreciated. Cause i'm trying to solve this issue

UPD 1

On next line i'm getting error:

```<code>User user = new Gson().fromJson(jsonResponse, User.class);
</code>```

答:
Problem has been solved. My actions was next:
Instad of declaring:

```<code>User user = new Gson().fromJson(jsonResponse, User.class);
</code>```

I should declare:

```<code>user = (User) apiUserResponse.getData();
// or
User user = (User) apiUserResponse.getData();
</code>```

In other cases, Your JSON will be readed as malformed and exception will be thrown.

Body:
I'm building an application and have a User object:

public class User {
    private Integer id = null;
    private String username = null;
    private String password = null;
    private String first_name = null;
    private String last_name = null;
    private String email = null;
    private String phone = null;
    private String avatar = null;
    private String role = null;
    private Boolean confirmed = null;
    private Boolean active = null;
    private String created_at = null;
    private String updated_at = null;
    private String sex = null;
    private Object company = null;
}

This object(class) contains setters and getters.
When authorization response has come - i'm proccessing it with next callback:

public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                ApiResponse apiResponse = response.body();

                Log.i("log_i", apiResponse.getData().toString());

                JsonReader jsonResponse = new JsonReader(new StringReader(apiResponse.getData().toString()));
                jsonResponse.setLenient(true);

                try {
                    User user = new Gson().fromJson(jsonResponse, User.class);
                    Log.i("log_i", user.toString());
                    Toast.makeText(context, apiResponse.getMessage(), Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    Log.i("log_i", e.getMessage());
                    Toast.makeText(context, "Failed to authorize in case of application exception.", Toast.LENGTH_SHORT).show();
                }
            }

After it step to firt line after try{} - it's crashes and next error is apperas in Log:

I/log_i: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 147 path $.avatar

Logged JSON:

{
    id=4,
    username=admin,
    first_name=Test,
    last_name=User,
    email=test@email.com,
    phone=012.345.678,
    confirmed=true,
    active=true,
    avatar=https://path/to/avatar.png,
    role=admin,
    created_at=2017-02-24T14: 22: 50+00: 00,
    updated_at=null,
    company_id=2.0,
    sex=m,
    company={
        id=2.0,
        title=companyTitle,
        active=true,
        created_at=2017-02-24T14: 22: 50+00: 00,
        updated_at=null,
        deleted_at=2017-02-24T14: 22: 50+00: 00
    }
}

Any help will be appreciated. Cause i'm trying to solve this issue

UPD 1

On next line i'm getting error:

User user = new Gson().fromJson(jsonResponse, User.class);

Body:
Problem has been solved. My actions was next:
Instad of declaring:

User user = new Gson().fromJson(jsonResponse, User.class);

I should declare:

user = (User) apiUserResponse.getData();
// or
User user = (User) apiUserResponse.getData();

In other cases, Your JSON will be readed as malformed and exception will be thrown.


问:
Unit Testing ReactNative with Jest
I am searching for how can I implement unit testing feature in my app but there are limited resources are available , Is there any documentation available which provide step to step guide on adding Unit testing feature in ReactNative app.

Coz most of the document are outdated as one says we need to mock react-native and there import react/addons which was is not available now.

Now there is no add ons file in React....

答:
Although this is a while back, the docs aren't complete awesome on unit testing with React Native, but here's how I handle a test on a method for a component, which is probably most of what I use.

Here's a typical example in Jest:

```<code>it('handles onInputTextChanged', () => {
  const wrapper = shallow(<TuraltChat isAnimated={false} />);
  wrapper.instance().onInputTextChanged("The message has changed");
  expect(wrapper.state("text")).toBe("The message has changed");
});
</code>```

The instance() method exposes the underlying component, and you can then call methods on it in the usual way.

Even though it's annoying in all the DOM dependencies, I'm also using enzyme, which helps a lot for component-level tests, because I don't need to worry about all the nested components.

```<code>import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';

...

it('renders initially', () => {
  const wrapper = shallow(<Composer />);
  const json = toJson(wrapper);
  expect(json).toMatchSnapshot();
});
</code>```

Title: Unit Testing ReactNative with Jest

Body:
Although this is a while back, the docs aren't complete awesome on unit testing with React Native, but here's how I handle a test on a method for a component, which is probably most of what I use.

Here's a typical example in Jest:

it('handles onInputTextChanged', () => {
  const wrapper = shallow(<TuraltChat isAnimated={false} />);
  wrapper.instance().onInputTextChanged("The message has changed");
  expect(wrapper.state("text")).toBe("The message has changed");
});

The instance() method exposes the underlying component, and you can then call methods on it in the usual way.

Even though it's annoying in all the DOM dependencies, I'm also using enzyme, which helps a lot for component-level tests, because I don't need to worry about all the nested components.

import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';

...

it('renders initially', () => {
  const wrapper = shallow(<Composer />);
  const json = toJson(wrapper);
  expect(json).toMatchSnapshot();
});


问:
Using REDCap API in android keeps getting 403
I have a REDCap project complete setup on Redcap console .

API token generated .

Record saving working from REDCap .

Also from browser tool.

But when I call it from Android App it returns 403 forbidden .

is there anything like set permission for a user.

Also same is working perfectly from ios app .

```<code> HashMap<String, String> params = new HashMap<String, String>();

        params.put("token","MY TOKEN");
        params.put("content","record");

OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(JSON, String.valueOf(params));
        Request request = new Request.Builder()
                .url("MY_URL")
                .post(body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(com.squareup.okhttp.Request request, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(com.squareup.okhttp.Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                } else {
                    // do something wih the result
                    Log.d("check ok http response ", response.toString());
                }
            }

    });
</code>```

From Browser tool if I put same URL with selecting POST and set only two params token and content , it return 200 OK .

But from Android it returns 403 . Please help , I have tried several methods in android code .

答:
You're doing this:

```<code>RequestBody body = RequestBody.create(JSON, String.valueOf(params));
</code>```

that's not a valid form body. Do this:

```<code>FormBody.Builder formBuilder = new FormBody.Builder()
    .add("token","MY TOKEN").add("content","record");
</code>```

and then

```<code>Request request = new Request.Builder()
            .url("MY_URL")
            .post(formBuilder.build())
            .addHeader("Content-Type", "application/x-www-form-urlencoded")
            .build();
</code>```

Body:
I have a REDCap project complete setup on Redcap console .

API token generated .

Record saving working from REDCap .

Also from browser tool.

But when I call it from Android App it returns 403 forbidden .

is there anything like set permission for a user.

Also same is working perfectly from ios app .

 HashMap<String, String> params = new HashMap<String, String>();

        params.put("token","MY TOKEN");
        params.put("content","record");

OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(JSON, String.valueOf(params));
        Request request = new Request.Builder()
                .url("MY_URL")
                .post(body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(com.squareup.okhttp.Request request, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(com.squareup.okhttp.Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                } else {
                    // do something wih the result
                    Log.d("check ok http response ", response.toString());
                }
            }

    });

From Browser tool if I put same URL with selecting POST and set only two params token and content , it return 200 OK .

But from Android it returns 403 . Please help , I have tried several methods in android code .

Body:
You're doing this:

RequestBody body = RequestBody.create(JSON, String.valueOf(params));

that's not a valid form body. Do this:

FormBody.Builder formBuilder = new FormBody.Builder()
    .add("token","MY TOKEN").add("content","record");

and then

Request request = new Request.Builder()
            .url("MY_URL")
            .post(formBuilder.build())
            .addHeader("Content-Type", "application/x-www-form-urlencoded")
            .build();


问:
I want to delete multiple images from source folder through PHP but the code for deleting the multiple images from the folder is not working
```<code>    <?php include("header.php"); ?>
    <?php
    if (@$_POST['delete']=="Delete"){
        $count=count($_POST['delbx']);
        for($i=0;$i<$count;$i++){
            $delete = "DELETE FROM admin WHERE a_id='".$_POST['delbx'][$i]."'";
            $resulty = mysqli_query($conn, $delete) or die(mysql_error());
            $select_delete = "SELECT `a_image` FROM admin WHERE a_id='".$_POST['delbx'][$i]."'";
            $resultrowdy = $conn->query($select_delete);
            $rowdy = $resultrowdy->fetch_assoc();
            $path="admin/".$rowdy['a_image'];
            echo $path;
            unlink($path);
            echo '<script>window.location="view_user.php"</script>';
        }
    } ?>

    <div class="table-responsive">
        <table class="table">
            <caption>All Users</caption>
            <?php
            $sql = "SELECT a_id, a_name, a_phone, a_password, a_role, a_mail, a_image FROM admin";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {?>
                <thead>
                    <tr>
                        <th><form action="view_user.php" method="post"><input name="delete" type="submit" id="delete" value="Delete"></th><th>S. No.</th> <th>Name</th> <th>Phone No.</th> <th>Mail Id</th> <th>Role</th> <th>Password</th> <th>Image</th>
                    </tr>
                </thead>
                <?php
                while($row = $result->fetch_assoc()) { ?>
                    <tbody>
                        <tr>
                             <th scope="row">
                                 <?php echo $row["a_id"]; ?>
                             </th>
                             <td align="center" bgcolor="#FFFFFF">
                                 <input name="delbx[]" type="checkbox" id="delbx[]" value="<?php echo $row["a_id"]; ?>" />
                             </td>
                             <td>
                                 <?php echo $row["a_name"]; ?>
                             </td>
                             <td>
                                 <?php echo $row["a_phone"]; ?>
                             </td>
                             <td>
                                 <?php  echo $row["a_mail"]; ?>
                             </td>
                             <td>
                                 <?php echo $row["a_role"]; ?>
                             </td>
                             <td>
                                 <?php echo $row["a_password"]; ?>
                             </td>
                             <td>
                                 <img src="admin/<?php echo $row["a_image"]; ?>" width="60" height="40">
                             </td>
                             <th>
                                 <a href="admin_update.php?editid=<?php echo $row["a_id"];?>" style="color:#FFF;">Edit</a>
                             </th>
                         </tr>
                     </tbody>
            <?php
                }
            } else {
                echo "0 results";
            }?>
            </table>
        </form>
    </div>
    <?php include("footer.php"); ?>
</code>```

The code I mention is not deleting the multiple images from the source folder but deleting the multiple data from database whereas I am trying to delete images from the source folder along with data please help thanks in advance

答:
One of the problem is you are deleting the row and trying to select image column from the deleted row.. dont use user supplied variables directly in your query

your code should be

```<code>    for($i=0;$i<$count;$i++){
      $select_delete = "SELECT `a_image` FROM admin WHERE a_id='".$_POST['delbx'][$i]."'";
      $resultrowdy = $conn->query($select_delete);
      $rowdy = $resultrowdy->fetch_assoc();

      $delete = "DELETE FROM admin WHERE a_id='".$_POST['delbx'][$i]."'";
      if(mysqli_query($conn, $delete)){
        $path="admin/".$rowdy['a_image'];
        unlink($path);
        echo '<script>window.location="view_user.php"</script>';
      }
    }
</code>```

Body:
    <?php include("header.php"); ?>
    <?php
    if (@$_POST['delete']=="Delete"){
        $count=count($_POST['delbx']);
        for($i=0;$i<$count;$i++){
            $delete = "DELETE FROM admin WHERE a_id='".$_POST['delbx'][$i]."'";
            $resulty = mysqli_query($conn, $delete) or die(mysql_error());
            $select_delete = "SELECT `a_image` FROM admin WHERE a_id='".$_POST['delbx'][$i]."'";
            $resultrowdy = $conn->query($select_delete);
            $rowdy = $resultrowdy->fetch_assoc();
            $path="admin/".$rowdy['a_image'];
            echo $path;
            unlink($path);
            echo '';
        }
    } ?>

All Users

            <?php
            $sql = "SELECT a_id, a_name, a_phone, a_password, a_role, a_mail, a_image FROM admin";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {?>

                        <form action="view_user.php" method="post"><input name="delete" type="submit" id="delete" value="Delete">	S. No.	 Name	 Phone No.	 Mail Id	 Role	 Password	 Image

                <?php
                while($row = $result->fetch_assoc()) { ?>

                                 <?php echo $row["a_id"]; ?>

                                 <input name="delbx[]" type="checkbox" id="delbx[]" value="<?php echo $row["a_id"]; ?>" />

                                 <?php echo $row["a_name"]; ?>

                                 <?php echo $row["a_phone"]; ?>

                                 <?php  echo $row["a_mail"]; ?>

                                 <?php echo $row["a_role"]; ?>

                                 <?php echo $row["a_password"]; ?>

                                 <img src="admin/<?php echo $row["a_image"]; ?>" width="60" height="40">

                                 <a href="admin_update.php?editid=<?php echo $row["a_id"];?>" style="color:#FFF;">Edit

            <?php
                }
            } else {
                echo "0 results";
            }?>

        </form>

    <?php include("footer.php"); ?>

The code I mention is not deleting the multiple images from the source folder but deleting the multiple data from database whereas I am trying to delete images from the source folder along with data please help thanks in advance

Body:
One of the problem is you are deleting the row and trying to select image column from the deleted row.. dont use user supplied variables directly in your query

your code should be

    for($i=0;$i<$count;$i++){
      $select_delete = "SELECT `a_image` FROM admin WHERE a_id='".$_POST['delbx'][$i]."'";
      $resultrowdy = $conn->query($select_delete);
      $rowdy = $resultrowdy->fetch_assoc();

      $delete = "DELETE FROM admin WHERE a_id='".$_POST['delbx'][$i]."'";
      if(mysqli_query($conn, $delete)){
        $path="admin/".$rowdy['a_image'];
        unlink($path);
        echo '<script>window.location="view_user.php"</script>';
      }
    }


问:
My interceptors are not fetching values from action page to FTL in Struts 2
I am not able to find the issue that why my FTL couldn't fetch values from action page.

This is my FTL code:

<#assign temp = 12311>

hello world  : ${FirstAction?if_exists.random} #{temp}

```
<p><strong>This is my <code>struts.xml</code>:</strong></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <constant name="struts.enable.DynamicMethodInvocation"
        value="true" />
    <constant name="struts.devMode" value="true" />
  <package name="default" extends="struts-default">

    <action name="getTutorial" class="MyActions.FirstAction" >
      <result name="success">/success.jsp</result>
      <result name="failure">/error.jsp</result>
    </action>

    <action name="submit" class="MyActions.FirstAction" method="submit"></action>

    <action name="callme" class="MyActions.FirstAction" method="myMethod">
      <result name="success">/FreeMarkerPages/testingAction.jsp</result>
      <result name="failure"  type="freemarker">/FreeMarkerPages/FirstFTL.ftl</result>
    </action>

  </package>
</struts>
</code>```

This is my action class:

package MyActions;

import java.util.Random;

import com.opensymphony.xwork2.ActionSupport;

import service.ColorPicker;

    public class FirstAction extends ActionSupport{
        private int random;
        public String execute() {
            return "failure";
        }
        public String myMethod(){
            setRandom(9999);
            System.out.println("My method "+random);
            return "failure";
        }

        public String submit(){
            System.out.println(random);
            return null;
        }

        public int getRandom() {
            return random;
        }
        public void setRandom(int random) {
            this.random = random;
        }
```
<p><strong>This is my FTL error :</strong></p>
<pre class="lang-xml prettyprint-override"><code>FreeMarker template error (HTML_DEBUG mode; use RETHROW in production!)
</code>```

The following has evaluated to null or missing:
==> FirstAction?if_exists.random  [in template "FreeMarkerPages/FirstFTL.ftl" at line 5, column 22]

答:
You have used deprecated api. See Handling missing values.

Note:

These operators exist since FreeMarker 2.3.7 (replacing the default,
  exists and if_exists built-ins).

If you want to lean how properties are resolved in Struts 2 you can read this answer.

Body:
I am not able to find the issue that why my FTL couldn't fetch values from action page.

This is my FTL code:

<#assign temp = 12311>

hello world  : ${FirstAction?if_exists.random} #{temp}

This is my struts.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <constant name="struts.enable.DynamicMethodInvocation"
        value="true" />
    <constant name="struts.devMode" value="true" />
  <package name="default" extends="struts-default">

    <action name="getTutorial" class="MyActions.FirstAction" >
      <result name="success">/success.jsp</result>
      <result name="failure">/error.jsp</result>
    </action>

    <action name="submit" class="MyActions.FirstAction" method="submit"></action>

    <action name="callme" class="MyActions.FirstAction" method="myMethod">
      <result name="success">/FreeMarkerPages/testingAction.jsp</result>
      <result name="failure"  type="freemarker">/FreeMarkerPages/FirstFTL.ftl</result>
    </action>

  </package>
</struts>

This is my action class:

package MyActions;

import java.util.Random;

import com.opensymphony.xwork2.ActionSupport;

import service.ColorPicker;

    public class FirstAction extends ActionSupport{
        private int random;
        public String execute() {
            return "failure";
        }
        public String myMethod(){
            setRandom(9999);
            System.out.println("My method "+random);
            return "failure";
        }

        public String submit(){
            System.out.println(random);
            return null;
        }

        public int getRandom() {
            return random;
        }
        public void setRandom(int random) {
            this.random = random;
        }

This is my FTL error :

FreeMarker template error (HTML_DEBUG mode; use RETHROW in production!)

The following has evaluated to null or missing:
==> FirstAction?if_exists.random  [in template "FreeMarkerPages/FirstFTL.ftl" at line 5, column 22]


问:
how to reuse a zenity dialog?
Is possible to reuse a zenity dialog? A list for example.
Assign it to a variable it gets the value of the selected item. So when use the variable I just get the selected item' s value.</p>

答:
Maybe this is what you are asking for? Your request is bit unclear. See this test with yad (advanced fork of zenity). Same test will work with zenity as well:</p>

```<code>$ resp=$(yad --list --column "fruit" --column "color" "apple" "red" "banana" "yellow")
#Yad list appears and i select "banana"
$ echo "$resp"
#Output of variable $resp
banana|yellow|
</code>```

Title: how to reuse a zenity dialog?

Body:
Maybe this is what you are asking for? Your request is bit unclear. See this test with yad (advanced fork of zenity). Same test will work with zenity as well:

$ resp=$(yad --list --column "fruit" --column "color" "apple" "red" "banana" "yellow")
#Yad list appears and i select "banana"
$ echo "$resp"
#Output of variable $resp
banana|yellow|