问:
Compare value objects using a custom comparator
I want to compare value objects in a way that null properties are ignored.

More specifically, I only want to include those properties of a value object in the comparison which are not-null on the right side.
E.g.

```<code>class Person {
  String name;
  String surname;
}

Person personLeft = new Person();
personLeft.name = "John";
personLeft.surname = "Doe";

Person personRight = new Person();
personRight.name="John"

// this should NOT yield any changes
javers.compare(personLeft, personRight);

// that comparison however, will show that surname has changed
javers.compare(personRight, personLeft);
</code>```

I though I could tackle this problem by writing a custom comparator and registering it for Person.
Unfortunately this comparator is never called.
Stumbling upon that post, I fear that this is not possible using a custom comparator for the Person class.

Instead I would have to register custom comparators for all containing value types of the Person class, i.e. String.

Is that the intended use of javers or are there any alternatives to that approach?

答:
What is important here is that CustomValueComparator can be used only for Value types. So you have 2 options:

Map Person as Value and then you implement diff algorithm for
Person. It works but is awkward because Person is more like an
Entity.

Register a CustomValueComparator for Strings (all Strings), and then you can use Person as Entity. That's the option that I would choose.

See how it works (groovy):

class Entity {
    @Id int id
    Person person
}

class Person {
    String name
}

def "should use CustomValueComparator for Person when Person is mapped as Value"(){
  given:
    def javers = JaversBuilder.javers().registerValue(Person,
            { l, r -> if (r.name == null) return true
                      else return r.name.equals(l.name)
            }).build()

    def personLeft = new Person(name: "john")
    def personRight = new Person()

    def eLeft = new Entity(id:1, person: personLeft)
    def eRight = new Entity(id:1, person: personRight)

  expect:
    javers.compare(eLeft, eRight).changes.size() == 0
    javers.compare(eRight, eLeft).changes.size() == 1

    javers.getTypeMapping(Person) instanceof ValueType
}

def "should used CustomValueComparator for Strings"(){
  given:
    def javers = JaversBuilder.javers().registerValue(String,
          { l, r -> if (r == null) return true
          else return r.equals(l)
          }).build()

    def personLeft = new Person(name: "john")
    def personRight = new Person()

  expect:
    javers.compare(personLeft, personRight).changes.size() == 0
    javers.compare(personRight, personLeft).changes.size() == 1

    javers.getTypeMapping(Person) instanceof ValueObjectType
}
```

Body:
I want to compare value objects in a way that null properties are ignored.

More specifically, I only want to include those properties of a value object in the comparison which are not-null on the right side.
E.g.

class Person {
  String name;
  String surname;
}

Person personLeft = new Person();
personLeft.name = "John";
personLeft.surname = "Doe";

Person personRight = new Person();
personRight.name="John"

// this should NOT yield any changes
javers.compare(personLeft, personRight);

// that comparison however, will show that surname has changed
javers.compare(personRight, personLeft);

I though I could tackle this problem by writing a custom comparator and registering it for Person.
Unfortunately this comparator is never called.
Stumbling upon that post, I fear that this is not possible using a custom comparator for the Person class.

Instead I would have to register custom comparators for all containing value types of the Person class, i.e. String.

Is that the intended use of javers or are there any alternatives to that approach?


来源: stackexchange

问:
How to use try-catch to catch the segmentation error of an external code?
I am calling an external exec. file (not written by me) using the system() command inside the MATLAB code. For some reasons the external file s/t gives the Segmentation fault error, and if I run the code again, it gets fixed.

Therefore, as we do in other languages, I am using try catch to catch the error, w/o stopping the whole process. Here is what I have written:

```<code>flag = false;
while(~flag)
    try
        system('….');
        flag = true;
    catch MExc
        flag = false;
    end
end
</code>```

However, it does not catch the error. How to fix it?

答:
I doubt that you can catch an exception thrown by an external application when called within Matlab (actually it's not a doubt, I'm certain, but the sentence is much more elegant). Anyway, from my knowledge, an application that shuts down without errors should return an ExitCode equal to 0.

Fortunately, the system function returns that value as its first output argument (official documentation), so try the following code instead:

```<code>status = -1;

while (status ~= 0)
    [status,cmdout] = system('...');
end

% do something with cmdout
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am calling an external exec. file (not written by me) using the system() command inside the MATLAB code. For some reasons the external file s/t gives the Segmentation fault error, and if I run the code again, it gets fixed.

Therefore, as we do in other languages, I am using try catch to catch the error, w/o stopping the whole process. Here is what I have written:

flag = false;
while(~flag)
    try
        system('….');
        flag = true;
    catch MExc
        flag = false;
    end
end

However, it does not catch the error. How to fix it?

Body:
I doubt that you can catch an exception thrown by an external application when called within Matlab (actually it's not a doubt, I'm certain, but the sentence is much more elegant). Anyway, from my knowledge, an application that shuts down without errors should return an ExitCode equal to 0.

Fortunately, the system function returns that value as its first output argument (official documentation), so try the following code instead:

status = -1;

while (status ~= 0)
    [status,cmdout] = system('...');
end

% do something with cmdout


问:
CTE Execution Order
In the following CTE statement:

```<code>CREATE TABLE test_table (Field1 INTEGER, Field2 INTEGER);
CREATE TABLE test_table2 (Field1 INTEGER, Field2 INTEGER);

WITH table_stage1(fld1, fld2) AS
    (SELECT Field1, Field2 from test_table1)
, table_stage2 AS
    (SELECT fld1, fld2 FROM table_stage1 GROUP BY fld1, fld2)
, table_stage3 AS
    (SELECT fld1 FROM table_stage1 GROUP BY fld1)
INSERT INTO test_table2(Field1, Field2)
    SELECT t1.fld1, t2.fld2
        FROM table_stage2 t1
        JOIN table_stage3 t2
    ON t1.fld1 = t2.fld1;
</code>```

Can I assume the following order of query execution:

SELECT inside WITH statemt

Concurrent execution of SELECT inside table_stage2, and table_stage3 segments

INSERT INTO waits till execution of table_stage2, table_stage3 is finished

This question is not related to a particular (presented) statement.

I would like to know if by selecting from a named segment there is a guarantee the current statement will be executed after the particular named segment.
Meybe what is significat is having a number of select statements folowed by a write CTE that joins results from previous segments

The PostgeSQL documentations we can read:

The sub-statements in WITH are executed concurrently with each other
  and with the main query. Therefore, when using data-modifying
  statements in WITH, the order in which the specified updates actually
  happen is unpredictable.

I am working on PostgreSQL 9.6

答:
The part of the documentation that you cite refers to the execution of more than one data-modifying statement (using data-modifying statements ... the order is unpredictable). But if in one of the statement is used the name of a previous statement, this means that the current statement refer to all the tuples returned by the previous one.

So, in your example the statements relative to table_stage2 and table_stage3 can be executed in parallel, but using all the tuples returned by table_stage1, while the final insert will be executed by using all the tuples returned by the previous two statements (and so by using all the tuples produced by the previous three statements).

Note that: “B uses all the tuples returned by A” is not necessarily equivalent to: “B is executed after A”: the optimizer can in fact transform B so that it is not necessary to execute A. It is just a semantics definition, and is not related to an actual implementation.

Title: CTE Execution Order

Body:
In the following CTE statement:

CREATE TABLE test_table (Field1 INTEGER, Field2 INTEGER);
CREATE TABLE test_table2 (Field1 INTEGER, Field2 INTEGER);

WITH table_stage1(fld1, fld2) AS
    (SELECT Field1, Field2 from test_table1)
, table_stage2 AS
    (SELECT fld1, fld2 FROM table_stage1 GROUP BY fld1, fld2)
, table_stage3 AS
    (SELECT fld1 FROM table_stage1 GROUP BY fld1)
INSERT INTO test_table2(Field1, Field2)
    SELECT t1.fld1, t2.fld2
        FROM table_stage2 t1
        JOIN table_stage3 t2
    ON t1.fld1 = t2.fld1;

Can I assume the following order of query execution:

SELECT inside WITH statemt

Concurrent execution of SELECT inside table_stage2, and table_stage3 segments

INSERT INTO waits till execution of table_stage2, table_stage3 is finished

This question is not related to a particular (presented) statement.

I would like to know if by selecting from a named segment there is a guarantee the current statement will be executed after the particular named segment.
Meybe what is significat is having a number of select statements folowed by a write CTE that joins results from previous segments

The PostgeSQL documentations we can read:

The sub-statements in WITH are executed concurrently with each other
  and with the main query. Therefore, when using data-modifying
  statements in WITH, the order in which the specified updates actually
  happen is unpredictable.

I am working on PostgreSQL 9.6


问:
Detecting Interword Space in OCR using Python and OpenCV
I am new to Python and OpenCV . I am currently working on OCR using Python and OpenCV without using Tesseract.Till now I have been successful in detecting the text (character and digit) but I am encountering a problem to detect space between words.
Eg-
If the image says "Hello John", then it detects hello john but cannot detect space between them, so my output is "HelloJohn" without any space between them.My code for extracting contour goes like this(I have imported all the required modules, this one is the main module extracting contour)  :

```<code> imgGray = cv2.cvtColor(imgTrainingNumbers, cv2.COLOR_BGR2GRAY)
 imgBlurred = cv2.GaussianBlur(imgGray, (5,5), 0)

 imgThresh = cv2.adaptiveThreshold(imgBlurred,
                                  255,
                                  cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                  cv2.THRESH_BINARY_INV,
                                  11,
                                  2)

 cv2.imshow("imgThresh", imgThresh)

 imgThreshCopy = imgThresh.copy()

 imgContours, npaContours, npaHierarchy = cv2.findContours(imgThreshCopy,
                                             cv2.RETR_EXTERNAL,
                                             cv2.CHAIN_APPROX_SIMPLE)
</code>```

After this I classify the extracted contours which are digits and character.
Please help me detecting space between them.
Thank You in advance,your reply would be really helpful.

答:
Since you did not give any example images, I just generated a simple image to test with:

```<code>h, w = 100, 600
img = np.zeros((h, w), dtype=np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'OCR with OpenCV', (30, h-30), font, 2, 255, 2, cv2.LINE_AA)
</code>```

As I mentioned in the comments, if you simply dilate the image, then the white areas will expand. If you do this with a large enough kernel so that nearby letters merge, but small enough that separate words do not, then you'll be able to extract contours of each word and use that to mask one word at a time for OCR purposes.

```<code>kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15))
dilated = cv2.dilate(img, kernel)
</code>```

To get the mask of each word individually, just find the contours of these larger blobs. You can sort the contours too; vertically, horizontally, or both so that you get the words in proper order. Here since I just have a single line I'll sort just in the x direction:

```<code>contours = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[1]
contours = sorted(contours, key=lambda c: min(min(c[:, :, 0])))

for i in range(len(contours)):

    mask = np.zeros((h, w), dtype=np.uint8)

    # i is the contour to draw, -1 means fill the contours
    mask = cv2.drawContours(mask, contours, i, 255, -1)
    masked_img = cv2.bitwise_and(img, img, mask=mask)

    cv2.imshow('Masked single word', masked_img)
    cv2.waitKey()

    # do your OCR here on the masked image
</code>```

Body:
I am new to Python and OpenCV . I am currently working on OCR using Python and OpenCV without using Tesseract.Till now I have been successful in detecting the text (character and digit) but I am encountering a problem to detect space between words.
Eg-
If the image says "Hello John", then it detects hello john but cannot detect space between them, so my output is "HelloJohn" without any space between them.My code for extracting contour goes like this(I have imported all the required modules, this one is the main module extracting contour)  :

 imgGray = cv2.cvtColor(imgTrainingNumbers, cv2.COLOR_BGR2GRAY)
 imgBlurred = cv2.GaussianBlur(imgGray, (5,5), 0)

 imgThresh = cv2.adaptiveThreshold(imgBlurred,
                                  255,
                                  cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                  cv2.THRESH_BINARY_INV,
                                  11,
                                  2)

 cv2.imshow("imgThresh", imgThresh)

 imgThreshCopy = imgThresh.copy()

 imgContours, npaContours, npaHierarchy = cv2.findContours(imgThreshCopy,
                                             cv2.RETR_EXTERNAL,
                                             cv2.CHAIN_APPROX_SIMPLE)

After this I classify the extracted contours which are digits and character.
Please help me detecting space between them.
Thank You in advance,your reply would be really helpful.

Body:
Since you did not give any example images, I just generated a simple image to test with:

h, w = 100, 600
img = np.zeros((h, w), dtype=np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'OCR with OpenCV', (30, h-30), font, 2, 255, 2, cv2.LINE_AA)

As I mentioned in the comments, if you simply dilate the image, then the white areas will expand. If you do this with a large enough kernel so that nearby letters merge, but small enough that separate words do not, then you'll be able to extract contours of each word and use that to mask one word at a time for OCR purposes.

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15))
dilated = cv2.dilate(img, kernel)

To get the mask of each word individually, just find the contours of these larger blobs. You can sort the contours too; vertically, horizontally, or both so that you get the words in proper order. Here since I just have a single line I'll sort just in the x direction:

contours = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[1]
contours = sorted(contours, key=lambda c: min(min(c[:, :, 0])))

for i in range(len(contours)):

    mask = np.zeros((h, w), dtype=np.uint8)

    # i is the contour to draw, -1 means fill the contours
    mask = cv2.drawContours(mask, contours, i, 255, -1)
    masked_img = cv2.bitwise_and(img, img, mask=mask)

    cv2.imshow('Masked single word', masked_img)
    cv2.waitKey()

    # do your OCR here on the masked image


问:
onServerClick function not working on Dynamic Creation
I have several anchor buttons with onServerClick methods being dynamically created, but when I click on the buttons on the webpage, they will not call the function. Below is an example of a tag:

```<code><a href="#" runat="server" id="button0" class="btn btn-default btn-sm" onserverclick="reportMessage" creator="Tom" content="This is a test."><i class="fa fa-flag"></i> Report</a>
</code>```

And here is some of the method that is being called:

```<code>private void reportMessage(object sender, EventArgs e)
    {
        var btn = (HtmlAnchor)sender;
        string content = btn.Attributes["content"].ToString();
        string commentCreator = btn.Attributes["creator"].ToString()}
</code>```

Any help is appreciated.

答:
Since button0 is HTML anchor control ID, you can add a handler to ServerClick event in Page_Load event to handle each anchor link like this:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    HtmlAnchor btn = button0 as HtmlAnchor;
    btn.ServerClick += new EventHandler(reportMessage);
}
</code>```

Additionally you can add onclick event contains return true to ensure server click event is firing.

```<code><a href="#" runat="server" id="button0" onserverclick="reportMessage" onclick="return true;" ...>Link Text</a>
</code>```

NB: Since reportMessage is an event handler method bound to HtmlAnchor, I recommend using protected level instead of private.

Similar issue:

Adding onserverclick event to a HtmlAnchor dynamically

Body:
I have several anchor buttons with onServerClick methods being dynamically created, but when I click on the buttons on the webpage, they will not call the function. Below is an example of a tag:

 Report

And here is some of the method that is being called:

private void reportMessage(object sender, EventArgs e)
    {
        var btn = (HtmlAnchor)sender;
        string content = btn.Attributes["content"].ToString();
        string commentCreator = btn.Attributes["creator"].ToString()}

Any help is appreciated.

Body:
Since button0 is HTML anchor control ID, you can add a handler to ServerClick event in Page_Load event to handle each anchor link like this:

protected void Page_Load(object sender, EventArgs e)
{
    HtmlAnchor btn = button0 as HtmlAnchor;
    btn.ServerClick += new EventHandler(reportMessage);
}

Additionally you can add onclick event contains return true to ensure server click event is firing.

<a href="#" runat="server" id="button0" onserverclick="reportMessage" onclick="return true;" ...>Link Text</a>

NB: Since reportMessage is an event handler method bound to HtmlAnchor, I recommend using protected level instead of private.

Similar issue:

Adding onserverclick event to a HtmlAnchor dynamically


问:
Rendering text in WPF so that it perfectly fits in a given rectangle
I need to display words on a WPF Canvas in such a way that they perfectly fit in pre-defined boxes.

One box typically contains a single line of text, from one letter to a few words.

The text inside a box must be as large as possible, i.e: touching all borders of the box (except maybe where it would cause too much text distortion due to abnormal box witdh/height ratio).

I could not find a good way to calculate the appropriate font height, scaling and offset, based on the text content.

A first solution where the original text width/height ratio can't be changed would already be very nice !

I'd like to use TextBlock elements, but anything else that works should be ok.

答: You could check out Charles Petzold's article  "Render Text on a Path with WPF". Unfortunately I can't refresh my knowledges about subject at present moment due to something goes wrong with MSDN site, but he described how to scale text within path. </p>

ContentLicense: CC BY-SA 2.5


问:
how to include jqplot in wordpress?
i am developing plugin where i am using jqplot for bar charts , i have done in the same way how they told in documentaion,but in wordpress its not working, but it is working in normal php, below is my code

<link rel="stylesheet" type="text/css" href="<?php echo WP_PLUGIN_URL; ?>/css/jquery.jqplot.css" />
```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="chart1" style="height:400px;width:300px; "></div></code>```

答:
You should read up on how to properly enqueue scripts to ensure dependencies are met.  In your case, here is how I would enqueue the first script, jquery should already be loaded by WordPress unless you have removed it.  Also, move all your scripts under your child theme directory like I have done below.  Either that or create a proper plugin and nest them underneath that not in the root plugins directory like you have done.</p>

```<code>function wpb_adding_scripts() {
     wp_register_script('jqplot', get_template_directory_uri() . '/js/jquery.jqplot.js', array('jquery'),'1.1', true);
     wp_enqueue_script('jqplot');
}

add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
</code>```

Title: how to include jqplot in wordpress?

Body:
You should read up on how to properly enqueue scripts to ensure dependencies are met.  In your case, here is how I would enqueue the first script, jquery should already be loaded by WordPress unless you have removed it.  Also, move all your scripts under your child theme directory like I have done below.  Either that or create a proper plugin and nest them underneath that not in the root plugins directory like you have done.

function wpb_adding_scripts() {
     wp_register_script('jqplot', get_template_directory_uri() . '/js/jquery.jqplot.js', array('jquery'),'1.1', true);
     wp_enqueue_script('jqplot');
}

add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );


问:
Elasticsearch query on apostrophes
I am querying on elasticsearch the query is apples. In our index data, the text is presented like apple's. If I search like apples I got no results. If I searched for apple's we got results. But in my concern, if I search with apples also I need same results for apple's query. Is there any way to handle these type of cases.

答: Feels like you need a fuzzy search, if I got your point right. Please give a look on this article: https://www.elastic.co/blog/found-fuzzy-search and let know, if that isn't what you're looking for.

Title: Elasticsearch query on apostrophes


问:
Blade: Undefined Variable Inside Foreach Loop

I have a controller which gets an array of a User's diaries from my database and passes them to my view:

<?php

public function readDiaries($hash)
{
    $user = User::where('hash', $hash)->first();
    $diaries = Diary::where('user_id', $user->id)->get();

    return view('app.diary.readDiaries', ['diaries' => $diaries]);
}
```

<p>In my view, I am looping through the diaries using a <code>@foreach</code> loop.</p>

<pre class="lang-php prettyprint-override"><code><div id="diaries" class="card-columns">
    @if (count($diaries) > 0)
        @foreach ($diaries as $dairy)
            {{ var_dump($diary) }}
        @endforeach
    @endif
</div>
</code>```

But I am getting the following undefined variable error...

Undefined variable: diary (View: C:\xampp\htdocs\personal_projects\Active\diary_app\resources\views\app\diary\readDiaries.blade.php)

Why is my $diary variable undefined inside the @foreach loop?

答:
You have a typo

change @foreach ($diaries as $dairy) to @foreach ($diaries as $diary)

and it should work!

ContentLicense: CC BY-SA 4.0

Body:
I have a controller which gets an array of a User's diaries from my database and passes them to my view:

<?php

public function readDiaries($hash)
{
    $user = User::where('hash', $hash)->first();
    $diaries = Diary::where('user_id', $user->id)->get();

    return view('app.diary.readDiaries', ['diaries' => $diaries]);
}

In my view, I am looping through the diaries using a @foreach loop.

    @if (count($diaries) > 0)
        @foreach ($diaries as $dairy)
            {{ var_dump($diary) }}
        @endforeach
    @endif

But I am getting the following undefined variable error...

Undefined variable: diary (View: C:\xampp\htdocs\personal_projects\Active\diary_app\resources\views\app\diary\readDiaries.blade.php)

Why is my $diary variable undefined inside the @foreach loop?


问:
Use JSoup to get all textual links
I'm using JSoup to grab content from web pages.

I want to get all the links on a page that have some contained text (it doesn't matter what the text is) just needs to be non-empty/image etc.

Example of links I want:

```<code><a href="somepage.html">Link to Some Page</a>
</code>```

Since it contains the text "Link to Some Page"

Links I don't want:

```<code><a href="somepage.html"><img src="someimage.jpg"/></a>
<a href="somepage.html"></a>
</code>```

My code looks like this. How can I modify it to only get the first type of link?

```<code>Document document = // I get my document object
Elements linksOnPage = document.select("a[href]")
for (Element page : linksOnPage) {
    String link = page.attr("abs:href");
    // I do stuff with the link
}
</code>```

答:
I am using this and it's working fine:</p>

```<code>Document document = // I get my document object
Elements linksOnPage = document.select("a:matches(([^\\s]+))");
for (Element page : linksOnPage) {
    String link = page.attr("abs:href");
    // I do stuff with the link
}
</code>```

Title: Use JSoup to get all textual links

Body:
I'm using JSoup to grab content from web pages.

I want to get all the links on a page that have some contained text (it doesn't matter what the text is) just needs to be non-empty/image etc.

Example of links I want:

Link to Some Page

Since it contains the text "Link to Some Page"

Links I don't want:

My code looks like this. How can I modify it to only get the first type of link?

Document document = // I get my document object
Elements linksOnPage = document.select("a[href]")
for (Element page : linksOnPage) {
    String link = page.attr("abs:href");
    // I do stuff with the link
}

Body:
I am using this and it's working fine:

Document document = // I get my document object
Elements linksOnPage = document.select("a:matches(([^\\s]+))");
for (Element page : linksOnPage) {
    String link = page.attr("abs:href");
    // I do stuff with the link
}


问:
Unable to load resources from thread context class loader?
I am trying to get the complete file path of a resource in a java project that was given to me. The code fails to find the file by using the filename only. I need help to make it work.

This is the project structure:

This is the code:

```<code>package com.testing.software.apps;

public class FileTest {

    public static void main(String[]args) {
        String fileName = "orders-2017.txt";
        String filePath = getFilePath(fileName);
        System.out.println("File path is: " + filePath);
    }

    public static String getFilePath(String fileName) {
        String fullFilepath = Thread.currentThread().
                getContextClassLoader().
                getResource(fileName).
                getPath();
        return fullFilepath;
    }

}
</code>```

This code throws a null pointer exception in the "getPath();" line. I figured out that the exception occurs because this line "getResource(fileName)" returns a null URL object. Upon inspecting the getResource code, I see that finally "url = findResource(name);" returns null.

```<code>public URL getResource(String name) {
    URL url;
    if (parent != null) {
        url = parent.getResource(name);
    } else {
        url = getBootstrapResource(name);
    }
    if (url == null) {
        url = findResource(name);
    }
    return url;
}
</code>```

Looking at the definition of java.net.URL findResource, I see that it always returns null, thereby giving me a null all the time.

```<code>protected URL findResource(String name) {
    return null;
}
</code>```

Can someone please explain why this code always ends up giving null and how I can make it find the file by only using the filename?

答:
ClassLoader is an abstract class. The method findResource returns null in default implementation. In runtime there should be used and implementation of this class that overrides this method.

```<code>/**
     * Finds the resource with the given name. Class loader implementations
     * should override this method to specify where to find resources.
     *
     * @param  name
     *         The resource name
     *
     * @return  A <tt>URL</tt> object for reading the resource, or
     *          <tt>null</tt> if the resource could not be found
     *
     * @since  1.2
     */
    protected URL findResource(String name) {
        return null;
    }
</code>```

You get errror because you are using wrong path. You should add directories since the method does not goes recursively through resource directory. Try with fileName = "text-files/orders/orders-2017.txt";

If you are using default maven path configuration and if you want to use this resource in main function you should move them to src/main/resources.

If you want to keep them in src/test/java then they will be only available from classes that are in src/test/java directory.

Body:
I am trying to get the complete file path of a resource in a java project that was given to me. The code fails to find the file by using the filename only. I need help to make it work.

This is the project structure:

This is the code:

package com.testing.software.apps;

public class FileTest {

    public static void main(String[]args) {
        String fileName = "orders-2017.txt";
        String filePath = getFilePath(fileName);
        System.out.println("File path is: " + filePath);
    }

    public static String getFilePath(String fileName) {
        String fullFilepath = Thread.currentThread().
                getContextClassLoader().
                getResource(fileName).
                getPath();
        return fullFilepath;
    }

}

This code throws a null pointer exception in the "getPath();" line. I figured out that the exception occurs because this line "getResource(fileName)" returns a null URL object. Upon inspecting the getResource code, I see that finally "url = findResource(name);" returns null.

public URL getResource(String name) {
    URL url;
    if (parent != null) {
        url = parent.getResource(name);
    } else {
        url = getBootstrapResource(name);
    }
    if (url == null) {
        url = findResource(name);
    }
    return url;
}

Looking at the definition of java.net.URL findResource, I see that it always returns null, thereby giving me a null all the time.

protected URL findResource(String name) {
    return null;
}

Can someone please explain why this code always ends up giving null and how I can make it find the file by only using the filename?

Body:
ClassLoader is an abstract class. The method findResource returns null in default implementation. In runtime there should be used and implementation of this class that overrides this method.

/**
     * Finds the resource with the given name. Class loader implementations
     * should override this method to specify where to find resources.
     *
     * @param  name
     *         The resource name
     *
     * @return  A <tt>URL</tt> object for reading the resource, or
     *          <tt>null</tt> if the resource could not be found
     *
     * @since  1.2
     */
    protected URL findResource(String name) {
        return null;
    }

You get errror because you are using wrong path. You should add directories since the method does not goes recursively through resource directory. Try with fileName = "text-files/orders/orders-2017.txt";

If you are using default maven path configuration and if you want to use this resource in main function you should move them to src/main/resources.

If you want to keep them in src/test/java then they will be only available from classes that are in src/test/java directory.


问:
spacing between UITableViewCells swift3
I am creating a IOS app in swift and want to add spacing between cells like this

I would like to give space of each table view cell same like my attach image.
How I can do that? and Right now all cells are coming without any space.
swift3

答:
you can try this in your class of tableView cell:</p>

```<code>class cell: UITableViewCell{
override var frame: CGRect {
    get {
        return super.frame
    }
    set (newFrame) {
        var frame =  newFrame
        frame.origin.y += 4
        frame.size.height -= 2 * 5
        super.frame = frame
    }
  }
}
</code>```

Title: spacing between UITableViewCells swift3

Body:
you can try this in your class of tableView cell:

class cell: UITableViewCell{
override var frame: CGRect {
    get {
        return super.frame
    }
    set (newFrame) {
        var frame =  newFrame
        frame.origin.y += 4
        frame.size.height -= 2 * 5
        super.frame = frame
    }
  }
}


问:
SpringApplicationConfiguration not found: Erroneous spring-boot-starter-test content?
Getting a compilation error in Maven:

```<code>[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /C:/prototypes/demo-sse-spring-boot-master/src/test/java/com/cedric/demo/sse/SseDemoApplicationTests.java:[6,37] package org.springframework.boot.test does not exist
[ERROR] /C:/TITAN/demo-sse-spring-boot-master/src/test/java/com/cedric/demo/sse/SseDemoApplicationTests.java:[10,2] cannot find symbol
  symbol: class SpringApplicationConfiguration
[INFO] 2 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
</code>```

Maven repo seems to have the jar present:

howerever that jar doesn't have any compiled classes inside it. only META-INF dir:

Is that by design?  Where do I get the jar containing SpringApplicationConfiguration class to make Maven happy?

Here's the relevant parts of my pom.xml:

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
        <relativePath/>
        <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>jquery</artifactId>
            <version>2.1.3</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</code>```

答:
As the error is due to the upgrade of Spring Boot from 1.4 to 1.5, its important to note (from below) that several new classes that are introduced in 1.4 deprecated some of the existing classes leading way to finally getting removed in 1.5. The details of such can be found at: Spring boot release notes

Quoted from website (edited):

Additionally, Spring Boot 1.4 (and above) attempts to rationalize and simplify the various ways that a Spring Boot test can be run. You should migrate the following to use the new @SpringBootTest annotation:

From @SpringApplicationConfiguration(classes=MyConfig.class) to @SpringBootTest(classes=MyConfig.class)

From @ContextConfiguration(classes=MyConfig.class,  loader=SpringApplicationContextLoader.class) to
  @SpringBootTest(classes=MyConfig.class)

From @IntegrationTest to
  @SpringBootTest(webEnvironment=WebEnvironment.NONE)

From @IntegrationTest with @WebAppConfiguration to
  @SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT) (or RANDOM_PORT)

From @WebIntegrationTest to
  @SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT) (or RANDOM_PORT)

Tip Whilst migrating tests you may also want to replace any
  @RunWith(SpringJUnit4ClassRunner.class) declarations with Spring 4.3’s
  more readable @RunWith(SpringRunner.class).

Body:
Getting a compilation error in Maven:

[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /C:/prototypes/demo-sse-spring-boot-master/src/test/java/com/cedric/demo/sse/SseDemoApplicationTests.java:[6,37] package org.springframework.boot.test does not exist
[ERROR] /C:/TITAN/demo-sse-spring-boot-master/src/test/java/com/cedric/demo/sse/SseDemoApplicationTests.java:[10,2] cannot find symbol
  symbol: class SpringApplicationConfiguration
[INFO] 2 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

Maven repo seems to have the jar present:

howerever that jar doesn't have any compiled classes inside it. only META-INF dir:

Is that by design?  Where do I get the jar containing SpringApplicationConfiguration class to make Maven happy?

Here's the relevant parts of my pom.xml:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
        <relativePath/>

    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>jquery</artifactId>
            <version>2.1.3</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


问:
reload/reload.js route is not working
reload/reload.js route is not working

I'm using express-generator app code template to create my node applications

I also followed github issues information for this package
https://github.com/alallier/reload/issues/56#issuecomment-288393265

In this comment he said to create a custom route to listen for this file

```<code>app.get('/reloader', (req, res) => {
  res.type('text/javascript')
  res.sendFile(require.resolve('reload/lib/reload-client'))
});
</code>```

But, when i tried this reload is not working and in console an error exception occurring:

Uncaught DOMException: Failed to construct 'WebSocket': The URL's
  scheme must be either 'ws' or 'wss'. 'http' is not allowed.
      at new WrappedWebSocket (:164:21)

Here is my code (bin/www)

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

/**
 * Module dependencies.
 */

var app = require('../app');
var reload = require('reload');
var debug = require('debug')('node1:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

reload(app); // here i'm using reload module

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}
</code>```

答:
I resolved this issue by using reload(app) in ./app.js instead of ./bin/www

It is working fine in app.js file (even if i change the location of this statement) but, in ./bin/www file it is not working.

Code (./app.js):

```<code>var express = require('express');
var path = require('path');
var reload = require('reload');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressHandlebars = require('express-handlebars');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

reload(app); // Init Reload module
</code>```

Title: reload/reload.js route is not working

Body:
reload/reload.js route is not working

I'm using express-generator app code template to create my node applications

I also followed github issues information for this package
https://github.com/alallier/reload/issues/56#issuecomment-288393265

In this comment he said to create a custom route to listen for this file

app.get('/reloader', (req, res) => {
  res.type('text/javascript')
  res.sendFile(require.resolve('reload/lib/reload-client'))
});

But, when i tried this reload is not working and in console an error exception occurring:

Uncaught DOMException: Failed to construct 'WebSocket': The URL's
  scheme must be either 'ws' or 'wss'. 'http' is not allowed.
      at new WrappedWebSocket (:164:21)

Here is my code (bin/www)

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var reload = require('reload');
var debug = require('debug')('node1:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

reload(app); // here i'm using reload module

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

Body:
I resolved this issue by using reload(app) in ./app.js instead of ./bin/www

It is working fine in app.js file (even if i change the location of this statement) but, in ./bin/www file it is not working.

Code (./app.js):

var express = require('express');
var path = require('path');
var reload = require('reload');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressHandlebars = require('express-handlebars');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

reload(app); // Init Reload module


问:
gnu make: How to concat two strings
Given the line:

```<code>program_OBJS := ${program_SRCS:.cpp=.o}
</code>```

I would like to append .o to each filename instead of replacing .cpp with .o.

How do I do that?

答:
How about this:

```<code>STRING1:="foo"
STRING2:="bar"

STRING1:=$(STRING1)$(STRING2)
</code>```

Obviuosly, you could save the result to a new variable.

Title: gnu make: How to concat two strings

Body:
Given the line:

program_OBJS := ${program_SRCS:.cpp=.o}

I would like to append .o to each filename instead of replacing .cpp with .o.

How do I do that?

Body:
How about this:

STRING1:="foo"
STRING2:="bar"

STRING1:=$(STRING1)$(STRING2)

Obviuosly, you could save the result to a new variable.


问:
Linking G729 library (Library exists and symbols too)
Iam currently struggeling with linking just a simple library.

I compiled and installed successfully the G729 implementation from here Belledonne G729 like this:

```<code>cmake . -DCMAKE_INSTALL_PREFIX=/usr
make
make install
</code>```

When i check the if the symbols exist they exsist:

```<code>nm /usr/lib64/libbcg729.so | less
....
0000000000001fb8 T _init
000000000000de40 T initBcg729CNGChannel
00000000000046dd T initBcg729DecoderChannel
000000000000f5c6 T initBcg729DTXChannel
0000000000005353 T initBcg729EncoderChannel
0000000000010107 T initBcg729VADChannel
....
</code>```

But when i try to compile this simple main.cpp:

```<code>#include <bcg729/decoder.h>             // for bcg729DecoderChannelContextStruct

int main()
{
    bcg729DecoderChannelContextStruct* decoderChannelContext = initBcg729DecoderChannel();

    return 0;
}
</code>```

I get this as result:

```<code>c++ -v main.o -o main -lbcg729

Using built-in specs.
COLLECT_GCC=c++
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-linker-hash-style=gnu --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-initfini-array --disable-libgcj --with-isl=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/isl-install --with-cloog=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/cloog-install --enable-gnu-indirect-function --with-tune=generic --with-arch_32=x86-64 --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC)
COMPILER_PATH=/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/:/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/:/usr/libexec/gcc/x86_64-redhat-linux/:/usr/lib/gcc/x86_64-redhat-linux/4.8.5/:/usr/lib/gcc/x86_64-redhat-linux/
LIBRARY_PATH=/usr/lib/gcc/x86_64-redhat-linux/4.8.5/:/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/:/lib/../lib64/:/usr/lib/../lib64/:/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../:/lib/:/usr/lib/
COLLECT_GCC_OPTIONS='-v' '-o' 'main' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
 /usr/libexec/gcc/x86_64-redhat-linux/4.8.5/collect2 --build-id --no-add-needed --eh-frame-hdr --hash-style=gnu -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o main /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crti.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtbegin.o -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5 -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../.. main.o -lbcg729 -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtend.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crtn.o
main.o: In function `main':
/opt/cppplayground/main.cpp:39: undefined reference to `initBcg729DecoderChannel()'
collect2: error: ld returned 1 exit status
</code>```

I dont get where the issue is here, since if the library wouldnt be found, the linker would complain it does not exist. But in this case the library exists and the function i want to use does also exists.

Woulbe be nice if anyone could help ;)

Thanks in advance!

答:
Found it ....
Since it's a C-Library i forgot to add the 'extern "C" {}' around the includes.</p>

Body:
Iam currently struggeling with linking just a simple library.

I compiled and installed successfully the G729 implementation from here Belledonne G729 like this:

cmake . -DCMAKE_INSTALL_PREFIX=/usr
make
make install

When i check the if the symbols exist they exsist:

nm /usr/lib64/libbcg729.so | less
....
0000000000001fb8 T _init
000000000000de40 T initBcg729CNGChannel
00000000000046dd T initBcg729DecoderChannel
000000000000f5c6 T initBcg729DTXChannel
0000000000005353 T initBcg729EncoderChannel
0000000000010107 T initBcg729VADChannel
....

But when i try to compile this simple main.cpp:

#include <bcg729/decoder.h>             // for bcg729DecoderChannelContextStruct

int main()
{
    bcg729DecoderChannelContextStruct* decoderChannelContext = initBcg729DecoderChannel();

    return 0;
}

I get this as result:

c++ -v main.o -o main -lbcg729

Using built-in specs.
COLLECT_GCC=c++
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-linker-hash-style=gnu --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-initfini-array --disable-libgcj --with-isl=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/isl-install --with-cloog=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/cloog-install --enable-gnu-indirect-function --with-tune=generic --with-arch_32=x86-64 --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC)
COMPILER_PATH=/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/:/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/:/usr/libexec/gcc/x86_64-redhat-linux/:/usr/lib/gcc/x86_64-redhat-linux/4.8.5/:/usr/lib/gcc/x86_64-redhat-linux/
LIBRARY_PATH=/usr/lib/gcc/x86_64-redhat-linux/4.8.5/:/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/:/lib/../lib64/:/usr/lib/../lib64/:/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../:/lib/:/usr/lib/
COLLECT_GCC_OPTIONS='-v' '-o' 'main' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
 /usr/libexec/gcc/x86_64-redhat-linux/4.8.5/collect2 --build-id --no-add-needed --eh-frame-hdr --hash-style=gnu -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o main /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crti.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtbegin.o -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5 -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../.. main.o -lbcg729 -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtend.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crtn.o
main.o: In function `main':
/opt/cppplayground/main.cpp:39: undefined reference to `initBcg729DecoderChannel()'
collect2: error: ld returned 1 exit status

I dont get where the issue is here, since if the library wouldnt be found, the linker would complain it does not exist. But in this case the library exists and the function i want to use does also exists.

Woulbe be nice if anyone could help ;)

Thanks in advance!


问:
Bash-shell awk if-else with ternary operator grammar issue
```<code>cat file
AirIfLoadProfile trafficModelPrb ulDlRatioPerQci
EUtranCellTDD servOrPrioTriggeredErabAction 1
</code>```

When I execute the command:

```<code> awk '($NF!~/^[0-9]+$/)?{printf("%s,%s,%s",$1,$2.$3)}:{printf("%s,%s,%s",$1,$2,$3)}' file
</code>```

It comes to the error below:

```<code>awk: cmd. line:1: ($NF!~/^[0-9]+$/)?{printf("%s,%s,%s",$1,$2.$3)}:{printf("%s,%s,%s",$1,$2,$3)}
awk: cmd. line:1:                   ^ syntax error
awk: cmd. line:1: ($NF!~/^[0-9]+$/)?{printf("%s,%s,%s",$1,$2.$3)}:{printf("%s,%s,%s",$1,$2,$3)}
awk: cmd. line:1:                                                ^ syntax error
</code>```

Please help me find the format issue.

答:
The right way:

```<code>awk '{ printf("%s %s%s%s\n",$1,$2,($NF~/^[0-9]+$/? " ":"."),$3) }' file
</code>```

the 3rd format specifier %s accepts the result of the condition ($NF~/^[0-9]+$/? " ":".")

The output:

```<code>AirIfLoadProfile trafficModelPrb.ulDlRatioPerQci
EUtranCellTDD servOrPrioTriggeredErabAction 1
</code>```

Body:
cat file
AirIfLoadProfile trafficModelPrb ulDlRatioPerQci
EUtranCellTDD servOrPrioTriggeredErabAction 1

When I execute the command:

 awk '($NF!~/^[0-9]+$/)?{printf("%s,%s,%s",$1,$2.$3)}:{printf("%s,%s,%s",$1,$2,$3)}' file

It comes to the error below:

awk: cmd. line:1: ($NF!~/^[0-9]+$/)?{printf("%s,%s,%s",$1,$2.$3)}:{printf("%s,%s,%s",$1,$2,$3)}
awk: cmd. line:1:                   ^ syntax error
awk: cmd. line:1: ($NF!~/^[0-9]+$/)?{printf("%s,%s,%s",$1,$2.$3)}:{printf("%s,%s,%s",$1,$2,$3)}
awk: cmd. line:1:                                                ^ syntax error

Please help me find the format issue.

Body:
The right way:

awk '{ printf("%s %s%s%s\n",$1,$2,($NF~/^[0-9]+$/? " ":"."),$3) }' file

the 3rd format specifier %s accepts the result of the condition ($NF~/^[0-9]+$/? " ":".")

The output:

AirIfLoadProfile trafficModelPrb.ulDlRatioPerQci
EUtranCellTDD servOrPrioTriggeredErabAction 1


问:
Status of "Synchronization Domain" technology
Why do I find discussion of synchronization domains to be almost absent anywhere (books, articles, etc).  Is it because it is considered an outmoded technique that is maintained merely for backward compatability?  Or are its applications so rarified that no one bothers with them?

I had heard of the SynchronizationAttribute before, which is integral to synch domains, but no one seems to discuss that attribute much either.

答: Being placed in System.Runtime.Remoting it looks more like an implementation detail or a legacy COM technique. When you look at the namespace documentation this impression is reinforced because it talks about COM activation contexts. Most applications execute in a single process and never bother with remote execution of COM objects, so I guess for most people it's just not relevant.</p>


问:
How to handle Spinner position in recyclerview
i have 2 Views in listView andif (position == 0) repidly called again and again how to prevent it?

1:- i want when spinner change the value then  notifyDataSetChanged(); for update the list

```<code> @Override
public void onBindViewHolder(MyViewHolder holder, int position) {

    int viewType = getItemViewType(position);
    switch (viewType) {
        case LAYOUT_ZERO_INDEX:
                holder.materialDesignSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        String item = parent.getItemAtPosition(position).toString();
                        Toast.makeText(parent.getContext(), "" + position, Toast.LENGTH_LONG).show();

                        if (position == 0) {
                             dataarry.clear();
                            dataarry.add(0, 1000);
                            dataarry.add(1, 5000);
                            dataarry.add(2, 6000);
                            dataarry.add(3, 8000);
                            dataarry.add(4, 3500);
                            dataarry.add(5, 4000);
                            dataarry.add(6, 5500);
                            notifyDataSetChanged();
                            setData(6, 8000, holder);
                            holder.mChart.invalidate();
                        }
                     if (position == 1) {
                            dataarry.clear();
                            dataarry.add(0, 5500);
                            dataarry.add(1, 4500);
                            dataarry.add(2, 5200);
                            dataarry.add(3, 7000);
                            dataarry.add(4, 7000);
                            dataarry.add(5, 6000);
                            dataarry.add(6, 7800);
        //                        mChart.getData().notifyDataChanged();
    //                        mChart.notifyDataSetChanged();
          //                        mChart.clear();
                            notifyDataSetChanged();
                            setData(6, 8000, holder);
                            holder.mChart.invalidate();
                            // setData(6, 8000);
                        }

                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
                ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
       (context, android.R.layout.simple_dropdown_item_1line, weeklist);
                holder.materialDesignSpinner.setAdapter(arrayAdapter);
                holder.mChart.setDrawBarShadow(false);
                setData(6, 8000, holder);

            if (position == 1) {
                holder.year.setText("ahmad");
                holder.year.setText("Mon,Oct 2");
                holder.earning.setText("Rs 1200");
                holder.trips.setText("10 سفر");
            }
            break;

    }

}
</code>```

答:
```<code> @Override
public void onBindViewHolder(MyViewHolder holder, int position) {
int positonOld=0;
int viewType = getItemViewType(position);
switch (viewType) {
    case LAYOUT_ZERO_INDEX:
            holder.materialDesignSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                    if(position==positonOld){
                    {
                        return;
                    }
                    positonOld=positon;

                    String item = parent.getItemAtPosition(position).toString();
                    Toast.makeText(parent.getContext(), "" + position, Toast.LENGTH_LONG).show();

                    if (position == 0) {
                        dataarry.clear();
                        dataarry.add(0, 1000);
                        dataarry.add(1, 5000);
                        dataarry.add(2, 6000);
                        dataarry.add(3, 8000);
                        dataarry.add(4, 3500);
                        dataarry.add(5, 4000);
                        dataarry.add(6, 5500);
                        notifyDataSetChanged();
                        setData(6, 8000, holder);
                        holder.mChart.invalidate();
                    }
                    if (positionn == 1) {
                        dataarry.clear();
                        dataarry.add(0, 5500);
                        dataarry.add(1, 4500);
                        dataarry.add(2, 5200);
                        dataarry.add(3, 7000);
                        dataarry.add(4, 7000);
                        dataarry.add(5, 6000);
                        dataarry.add(6, 7800);
    //                        mChart.getData().notifyDataChanged();
//                        mChart.notifyDataSetChanged();
      //                        mChart.clear();
                        notifyDataSetChanged();
                        setData(6, 8000, holder);
                        holder.mChart.invalidate();
                        // setData(6, 8000);
                    }

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
   (context, android.R.layout.simple_dropdown_item_1line, weeklist);
            holder.materialDesignSpinner.setAdapter(arrayAdapter);
            holder.mChart.setDrawBarShadow(false);
            setData(6, 8000, holder);

        if (position == 1) {
            holder.year.setText("ahmad");
            holder.year.setText("Mon,Oct 2");
            holder.earning.setText("Rs 1200");
            holder.trips.setText("10 سفر");
        }
        break;
}
</code>```

<p>}</p>

Body:
i have 2 Views in listView andif (position == 0) repidly called again and again how to prevent it?

1:- i want when spinner change the value then  notifyDataSetChanged(); for update the list

 @Override
public void onBindViewHolder(MyViewHolder holder, int position) {

    int viewType = getItemViewType(position);
    switch (viewType) {
        case LAYOUT_ZERO_INDEX:
                holder.materialDesignSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        String item = parent.getItemAtPosition(position).toString();
                        Toast.makeText(parent.getContext(), "" + position, Toast.LENGTH_LONG).show();

                        if (position == 0) {
                             dataarry.clear();
                            dataarry.add(0, 1000);
                            dataarry.add(1, 5000);
                            dataarry.add(2, 6000);
                            dataarry.add(3, 8000);
                            dataarry.add(4, 3500);
                            dataarry.add(5, 4000);
                            dataarry.add(6, 5500);
                            notifyDataSetChanged();
                            setData(6, 8000, holder);
                            holder.mChart.invalidate();
                        }
                     if (position == 1) {
                            dataarry.clear();
                            dataarry.add(0, 5500);
                            dataarry.add(1, 4500);
                            dataarry.add(2, 5200);
                            dataarry.add(3, 7000);
                            dataarry.add(4, 7000);
                            dataarry.add(5, 6000);
                            dataarry.add(6, 7800);
        //                        mChart.getData().notifyDataChanged();
    //                        mChart.notifyDataSetChanged();
          //                        mChart.clear();
                            notifyDataSetChanged();
                            setData(6, 8000, holder);
                            holder.mChart.invalidate();
                            // setData(6, 8000);
                        }

                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
                ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
       (context, android.R.layout.simple_dropdown_item_1line, weeklist);
                holder.materialDesignSpinner.setAdapter(arrayAdapter);
                holder.mChart.setDrawBarShadow(false);
                setData(6, 8000, holder);

            if (position == 1) {
                holder.year.setText("ahmad");
                holder.year.setText("Mon,Oct 2");
                holder.earning.setText("Rs 1200");
                holder.trips.setText("10 سفر");
            }
            break;

    }

}

Body:
 @Override
public void onBindViewHolder(MyViewHolder holder, int position) {
int positonOld=0;
int viewType = getItemViewType(position);
switch (viewType) {
    case LAYOUT_ZERO_INDEX:
            holder.materialDesignSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                    if(position==positonOld){
                    {
                        return;
                    }
                    positonOld=positon;

                    String item = parent.getItemAtPosition(position).toString();
                    Toast.makeText(parent.getContext(), "" + position, Toast.LENGTH_LONG).show();

                    if (position == 0) {
                        dataarry.clear();
                        dataarry.add(0, 1000);
                        dataarry.add(1, 5000);
                        dataarry.add(2, 6000);
                        dataarry.add(3, 8000);
                        dataarry.add(4, 3500);
                        dataarry.add(5, 4000);
                        dataarry.add(6, 5500);
                        notifyDataSetChanged();
                        setData(6, 8000, holder);
                        holder.mChart.invalidate();
                    }
                    if (positionn == 1) {
                        dataarry.clear();
                        dataarry.add(0, 5500);
                        dataarry.add(1, 4500);
                        dataarry.add(2, 5200);
                        dataarry.add(3, 7000);
                        dataarry.add(4, 7000);
                        dataarry.add(5, 6000);
                        dataarry.add(6, 7800);
    //                        mChart.getData().notifyDataChanged();
//                        mChart.notifyDataSetChanged();
      //                        mChart.clear();
                        notifyDataSetChanged();
                        setData(6, 8000, holder);
                        holder.mChart.invalidate();
                        // setData(6, 8000);
                    }

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
   (context, android.R.layout.simple_dropdown_item_1line, weeklist);
            holder.materialDesignSpinner.setAdapter(arrayAdapter);
            holder.mChart.setDrawBarShadow(false);
            setData(6, 8000, holder);

        if (position == 1) {
            holder.year.setText("ahmad");
            holder.year.setText("Mon,Oct 2");
            holder.earning.setText("Rs 1200");
            holder.trips.setText("10 سفر");
        }
        break;
}

}


问:
Android Material Design - How to change background color of Toolbar after CollapsingToolbarLayout is collapsed
After the user scrolls down the screen, the image in the CollapsingToolbarLayout disappears and is left with a toolbar with the back button, content title, and settings menu. I want to know how to change the background color of that toolbar only when its in a 'collapsed' state.

The action I am referring to is similar to this where the toolbar background color changes to green:

Below the CollapsingToolbarLayout I have a NestedScrollView with CardViews

答:
```<code>    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
            R.drawable.header);

    Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
        @SuppressWarnings("ResourceType")

        @Override
        public void onGenerated(Palette palette) {
            Palette.Swatch vibrant =
                    palette.getVibrantSwatch();

            if (vibrant != null) {

                collapsingToolbar.setBackgroundColor(getResources().getColor(R.color.cpb_blue));
                collapsingToolbar.setStatusBarScrimColor(getResources().getColor(R.color.cpb_blue));
                collapsingToolbar.setContentScrimColor(getResources().getColor(R.color.cpb_blue));

            }
        }

    });
</code>```


问:
Post method with axios and spring
I am new in vue.js.I am looking for how to save the data of a form with axios in a database.I work with spring and thymeleaf template engine.

Here are my code :

Html page :

```<code><!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Handling Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <div id="app">
    <h1>TEST FORM</h1>
     <form action="#" method="post">
        <p>Type description: <input type="text" v-model="description" /></p>
        <p><button v-on:click="addType()"> Send </button><input type="reset" value="Reset" /></p>
    </form>
    </div>

 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="http://cdn.jsdelivr.net/vue/1.0.10/vue.min.js"></script>
    <script>
     Vue.prototype.$http = axios;
      new Vue({
            el: '#app',
            data:{
                 description: ' '
            },
           methods:{
             addType(){
               var vm = this;
               this.$http.post('/insert', {
                    body:vm.description
               }).then(response => {})
            }
         }
      });
    </script>

</body>
</html>
</code>```

I declared the description field NOT NULL in my table and when I execute this code I have this exception in the console:

```<code>org.sqlite.SQLiteException: [SQLITE_CONSTRAINT_NOTNULL]  A NOT NULL constraint failed (NOT     NULL constraint failed: type.description)
</code>```

I suppose it’s the value entered in the form field that is not retrieved. How can I solve this problem?

Here is my insert method using spring:

```<code>@RequestMapping(value = "/insert",method = RequestMethod.POST)
    public @ResponseBody void createType(@ModelAttribute Type type) {
         if(Objects.equals(type.getDescription(), "")) {
             throw new NullPointerException("The description should not be empty.");
         }
         typeService.createType(type);
    }

   @RequestMapping(value = "/insert",method = RequestMethod.GET)
    public String createTypeForm(Model model) {
        model.addAttribute("insertType", new Type());
        return "insertType";
    }
</code>```

Thank you in advance for your help.

答:
Your post method's body should be under a data property and you should access the description of your Vue instance as this.description:

```<code>this.$http.post('/insert', {
  data: this.description
}).then(response => {})
</code>```

Hope this helps!

Title: Post method with axios and spring

Body:
I am new in vue.js.I am looking for how to save the data of a form with axios in a database.I work with spring and thymeleaf template engine.

Here are my code :

Html page :

<!DOCTYPE HTML>

    <title>Getting Started: Handling Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

TEST FORM

     <form action="#" method="post">

Type description: <input type="text" v-model="description" />

<button v-on:click="addType()"> Send </button><input type="reset" value="Reset" />

    </form>

I declared the description field NOT NULL in my table and when I execute this code I have this exception in the console:

org.sqlite.SQLiteException: [SQLITE_CONSTRAINT_NOTNULL]  A NOT NULL constraint failed (NOT     NULL constraint failed: type.description)

I suppose it’s the value entered in the form field that is not retrieved. How can I solve this problem?

Here is my insert method using spring:

@RequestMapping(value = "/insert",method = RequestMethod.POST)
    public @ResponseBody void createType(@ModelAttribute Type type) {
         if(Objects.equals(type.getDescription(), "")) {
             throw new NullPointerException("The description should not be empty.");
         }
         typeService.createType(type);
    }

   @RequestMapping(value = "/insert",method = RequestMethod.GET)
    public String createTypeForm(Model model) {
        model.addAttribute("insertType", new Type());
        return "insertType";
    }

Thank you in advance for your help.

Body:
Your post method's body should be under a data property and you should access the description of your Vue instance as this.description:

this.$http.post('/insert', {
  data: this.description
}).then(response => {})

Hope this helps!


问:
configure your forms app unable to select iOS on target platform
Hi all new to this but just downloaded and installed xamarin studio to my mac but iOS on the target platforms: section on the configure your forms app page is greyed out and cant be selected

any idea how to solve this please

答:
I had the same issue Visual Studio 7.2.2, the iOS box was disabled. There were couple of issues I had

I had the Xcode app named as XCode9.app in the application folder so VS was unable to find the location, so I fixed that one.

I then searched for installed components About VisualStudio--> ShowDetails and found that Xamarin.iOS10 was installed which seem to have incompatibility with XCode9 so I ran the VS installer once again and found that Xamarin.iOS11 was out and after installing the update and restarting, everything worked.


问:
Preventing completion handler to be executed synchronously
I'm writing some networking code in Swift that prevents initiating a download that is already in progress. I do this by keeping tracking of the identity of the network request along with the associated completion handlers in an (synchronized) array A. When a network call finishes it calls the completion handlers that are associated with that resource and it subsequently removes those handlers from the array A.

I want to make sure there is no way for threads to access the array in certain cases. For example, consider the following scenario:

A request to download resource X is started.

Verify whether the request has already been made.

Add the completion handler to the array A.

If request has not been made, start the download.

What if resource X was already downloading, and the completion handler for this download interrupts the thread between steps 2 and 3? It has been verified that the request has been made so the download will not be started, but the new completion handler will be added to array A which will now never be called.

How would I block this from happening? Can I lock the array for writing while I do steps 2 and 3?

答:
Based on Josh's answer I created a generic Request & Requester below. It had a few more specific needs than I described in the question above. I want the Request instance to manage only requests with a certain ID (which I made into a String for now, but I guess this could also made more generic). Different ID's require a different Request instance. I created the Requester class for this purpose.

The requester class manages an array of Requests. For example, one could choose T = UIImage, and ID = image URL. This would give us an image downloader. Or one could choose T = User, and ID = user id. This would get a user object only once, even when requested several times.

I also wanted to be able to cancel requests from individual callers. It tags the completion handler with a unique ID that is passed back to the caller. It can use this to cancel the request. If all callers cancel, the request is removed from the Requester.

(The code below has not been tested so I cannot guarantee it to be bug free. Use at your own risk.)

```<code>import Foundation

typealias RequestWork<T> = (Request<T>) -> ()
typealias RequestCompletionHandler<T> = (Result<T>) -> ()
typealias RequestCompletedCallback<T> = (Request<T>) -> ()

struct UniqueID {
    private static var ID: Int = 0
    static func getID() -> Int {
        ID = ID + 1
        return ID
    }
}

enum RequestError: Error {
    case canceled
}

enum Result<T> {
    case success(T)
    case failure(Error)
}

protocol CancelableOperation: class {
    func cancel()
}

final class Request<T> {
    private lazy var completionHandlers = [(invokerID: Int,
                                            completion: RequestCompletionHandler<T>)]()
    private let mutex = NSLock()
    // To inform requester the request has finished
    private let completedCallback: RequestCompletedCallback<T>!
    private var isIdle = true
    // After work is executed, operation should be set so the request can be
    // canceled if possible
    var operation: CancelableOperation?
    let ID: String!

    init(ID: String,
         completedCallback: @escaping RequestCompletedCallback<T>) {
        self.ID = ID
        self.completedCallback = completedCallback
    }

    // Cancel the request for a single invoker and it invokes the competion
    // handler with a cancel error. If the only remaining invoker cancels, the
    // request will attempt to cancel
    // the associated operation.
    func cancel(invokerID: Int) {
        self.mutex.lock()
        defer { self.mutex.unlock() }
        if let index = self.completionHandlers.index(where: { $0.invokerID == invokerID }) {
            self.completionHandlers[index].completion(Result.failure(RequestError.canceled))
            self.completionHandlers.remove(at: index)
            if self.completionHandlers.isEmpty {
                self.isIdle = true
                operation?.cancel()
                self.completedCallback(self)
            }
        }
    }

    // Request work to be done. It will only be done if it hasn't been done yet.
    // The work block should set the operation on this request if possible. The
    // work block should call requestFinished(result:) if the work has finished.
    func request(work: @escaping RequestWork<T>,
                 completion: @escaping RequestCompletionHandler<T>) -> Int {
        self.mutex.lock()
        defer { self.mutex.unlock() }
        let ID = UniqueID.getID()
        self.completionHandlers.append((invokerID: ID, completion: completion))
        guard self.isIdle else { return ID }
        work(self)
        self.isIdle = false
        return ID
    }

    // This method should be called from the work block when the work has
    // completed. It will pass the result to all completion handlers and call
    // the Requester class to inform that this request has finished.
    func requestFinished(result: Result<T>) {
        self.mutex.lock()
        defer { self.mutex.unlock() }
        completionHandlers.forEach { $0.completion(result) }
        completionHandlers = []
        self.completedCallback(self)
        self.isIdle = true
    }
}

final class Requester<T>  {
    private lazy var requests = [Request<T>]()
    private let mutex = NSLock()

    init() { }

    // reuqestFinished(request:) should be called after a single Request has
    // finished its work. It removes the requests from the array of requests.
    func requestFinished(request: Request<T>) {
        self.mutex.lock()
        defer { self.mutex.unlock() }
        if let index = requests.index(where: { $0.ID == request.ID }) {
            requests.remove(at: index)
        }
    }

    // request(ID:, work:) will create a request or add a completion handler to
    // an existing request if a request with the supplied ID already exists.
    // When a request is created, it passes a closure that removes the request.
    // It returns the invoker ID to the invoker for cancelation purposes.
    func request(ID: String,
                 work: @escaping RequestWork<T>,
                 completion: @escaping RequestCompletionHandler<T>) ->
        (Int, Request<T>) {
        self.mutex.lock()
        defer { self.mutex.unlock() }
        if let existingRequest = requests.first(where: { $0.ID == ID }) {
            let invokerID = existingRequest.request(work: work, completion: completion)
            return (invokerID, existingRequest)
        } else {
            let request = Request<T>(ID: ID) { [weak self] (request) in
                self?.requestFinished(request: request)
            }
            let invokerID = request.request(work: work, completion: completion)
            return (invokerID, request)
        }
    }
}
</code>```

Body:
Based on Josh's answer I created a generic Request & Requester below. It had a few more specific needs than I described in the question above. I want the Request instance to manage only requests with a certain ID (which I made into a String for now, but I guess this could also made more generic). Different ID's require a different Request instance. I created the Requester class for this purpose.

The requester class manages an array of Requests. For example, one could choose T = UIImage, and ID = image URL. This would give us an image downloader. Or one could choose T = User, and ID = user id. This would get a user object only once, even when requested several times.

I also wanted to be able to cancel requests from individual callers. It tags the completion handler with a unique ID that is passed back to the caller. It can use this to cancel the request. If all callers cancel, the request is removed from the Requester.

(The code below has not been tested so I cannot guarantee it to be bug free. Use at your own risk.)

import Foundation

typealias RequestWork<T> = (Request<T>) -> ()
typealias RequestCompletionHandler<T> = (Result<T>) -> ()
typealias RequestCompletedCallback<T> = (Request<T>) -> ()

struct UniqueID {
    private static var ID: Int = 0
    static func getID() -> Int {
        ID = ID + 1
        return ID
    }
}

enum RequestError: Error {
    case canceled
}

enum Result<T> {
    case success(T)
    case failure(Error)
}

protocol CancelableOperation: class {
    func cancel()
}

final class Request<T> {
    private lazy var completionHandlers = [(invokerID: Int,
                                            completion: RequestCompletionHandler<T>)]()
    private let mutex = NSLock()
    // To inform requester the request has finished
    private let completedCallback: RequestCompletedCallback<T>!
    private var isIdle = true
    // After work is executed, operation should be set so the request can be
    // canceled if possible
    var operation: CancelableOperation?
    let ID: String!

    init(ID: String,
         completedCallback: @escaping RequestCompletedCallback<T>) {
        self.ID = ID
        self.completedCallback = completedCallback
    }

    // Cancel the request for a single invoker and it invokes the competion
    // handler with a cancel error. If the only remaining invoker cancels, the
    // request will attempt to cancel
    // the associated operation.
    func cancel(invokerID: Int) {
        self.mutex.lock()
        defer { self.mutex.unlock() }
        if let index = self.completionHandlers.index(where: { $0.invokerID == invokerID }) {
            self.completionHandlers[index].completion(Result.failure(RequestError.canceled))
            self.completionHandlers.remove(at: index)
            if self.completionHandlers.isEmpty {
                self.isIdle = true
                operation?.cancel()
                self.completedCallback(self)
            }
        }
    }

    // Request work to be done. It will only be done if it hasn't been done yet.
    // The work block should set the operation on this request if possible. The
    // work block should call requestFinished(result:) if the work has finished.
    func request(work: @escaping RequestWork<T>,
                 completion: @escaping RequestCompletionHandler<T>) -> Int {
        self.mutex.lock()
        defer { self.mutex.unlock() }
        let ID = UniqueID.getID()
        self.completionHandlers.append((invokerID: ID, completion: completion))
        guard self.isIdle else { return ID }
        work(self)
        self.isIdle = false
        return ID
    }

    // This method should be called from the work block when the work has
    // completed. It will pass the result to all completion handlers and call
    // the Requester class to inform that this request has finished.
    func requestFinished(result: Result<T>) {
        self.mutex.lock()
        defer { self.mutex.unlock() }
        completionHandlers.forEach { $0.completion(result) }
        completionHandlers = []
        self.completedCallback(self)
        self.isIdle = true
    }
}

final class Requester<T>  {
    private lazy var requests = [Request<T>]()
    private let mutex = NSLock()

    init() { }

    // reuqestFinished(request:) should be called after a single Request has
    // finished its work. It removes the requests from the array of requests.
    func requestFinished(request: Request<T>) {
        self.mutex.lock()
        defer { self.mutex.unlock() }
        if let index = requests.index(where: { $0.ID == request.ID }) {
            requests.remove(at: index)
        }
    }

    // request(ID:, work:) will create a request or add a completion handler to
    // an existing request if a request with the supplied ID already exists.
    // When a request is created, it passes a closure that removes the request.
    // It returns the invoker ID to the invoker for cancelation purposes.
    func request(ID: String,
                 work: @escaping RequestWork<T>,
                 completion: @escaping RequestCompletionHandler<T>) ->
        (Int, Request<T>) {
        self.mutex.lock()
        defer { self.mutex.unlock() }
        if let existingRequest = requests.first(where: { $0.ID == ID }) {
            let invokerID = existingRequest.request(work: work, completion: completion)
            return (invokerID, existingRequest)
        } else {
            let request = Request<T>(ID: ID) { [weak self] (request) in
                self?.requestFinished(request: request)
            }
            let invokerID = request.request(work: work, completion: completion)
            return (invokerID, request)
        }
    }
}


问:
Duplicate symbols for architecture x86_64 under Xcode
I now have the same question with above title but have not found the right answer yet. I got the error:

```<code>    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Intermediates/TestMoboSDK-Client.build/Debug-iphonesimulator/TestMoboSDK-Client.build/Objects-normal/x86_64/MoboSDK.o
    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Products/Debug-iphonesimulator/libMoboSDK.a(MoboSDK.o)
duplicate symbol _OBJC_METACLASS_$_MoboSDK in:
    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Intermediates/TestMoboSDK-Client.build/Debug-iphonesimulator/TestMoboSDK-Client.build/Objects-normal/x86_64/MoboSDK.o
    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Products/Debug-iphonesimulator/libMoboSDK.a(MoboSDK.o)
ld: 75 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Any help is appreciated.

Finally I find out the reason of this error cause I added -ObjC to the Other Linker Flags. After remove this value then I can build my project successfully, but I don't know why. Can anyone explain this?

答:
Similar to Juice007, I had declared and initialized a C type variable in two different .m files (that weren't imported!)

```<code>BOOL myVar = NO;
</code>```

however, this method of declaring and initializing a variable, even in .m, even in @implementation grants it global scope. Your options are:

Declare it as static, to limit the scope to class:

```<code>static BOOL myVar = NO;
</code>```

Remove the initialization (which will make the two classes share the global var):

```<code>BOOL myVar;
-(void) init{
    myVar = NO;
}
</code>```

Declare it as a property:

```<code>@property BOOL myVar;
</code>```

Declare it as a proper iVar in the @interface

```<code>@interface myClass(){
    BOOL myVar;
}
@end
</code>```

Body:
I now have the same question with above title but have not found the right answer yet. I got the error:

    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Intermediates/TestMoboSDK-Client.build/Debug-iphonesimulator/TestMoboSDK-Client.build/Objects-normal/x86_64/MoboSDK.o
    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Products/Debug-iphonesimulator/libMoboSDK.a(MoboSDK.o)
duplicate symbol _OBJC_METACLASS_$_MoboSDK in:
    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Intermediates/TestMoboSDK-Client.build/Debug-iphonesimulator/TestMoboSDK-Client.build/Objects-normal/x86_64/MoboSDK.o
    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Products/Debug-iphonesimulator/libMoboSDK.a(MoboSDK.o)
ld: 75 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any help is appreciated.

Finally I find out the reason of this error cause I added -ObjC to the Other Linker Flags. After remove this value then I can build my project successfully, but I don't know why. Can anyone explain this?

Body:
Similar to Juice007, I had declared and initialized a C type variable in two different .m files (that weren't imported!)

BOOL myVar = NO;

however, this method of declaring and initializing a variable, even in .m, even in @implementation grants it global scope. Your options are:

Declare it as static, to limit the scope to class:

static BOOL myVar = NO;

Remove the initialization (which will make the two classes share the global var):

BOOL myVar;
-(void) init{
    myVar = NO;
}

Declare it as a property:

@property BOOL myVar;

Declare it as a proper iVar in the @interface

@interface myClass(){
    BOOL myVar;
}
@end


问:
How to get the Caller Info from VoIP in real-time in a .NET Application?
I am working on a project which includes a lot of VoIP functions. I don't have access to the source code of the previous system that was being used so I can't dissect it to find out what I need to know.  I will describe how the previous system used to work and then ask my question.

First, the old system that we have been using depends on Physical Phones which receive calls over the internet. There is a Desktop App installed on our computer which somehow takes the phone call received by the phone and shows that phone number on the Desktop App. Which uses that number to look up data about the caller. But the problem is that this Desktop App is over a decade old and has not been updated since. So we want to build a new Web Based Application with .NET that will do the same. My question is:

1- How do I fetch the Caller Information From the Physical Phone and use it how I want? The phone being used is SNOM 760 but its possible that other brands or models be used in the future.

2- Let's say that a specific page is always opened on the browser. How do I transfer the caller number to the server and then show a pop up with the information about the caller in that page that's always opened in the browser in a RELIABLE way? What about when that specific page is not opened? Remember that the phone that is receiving this call is not directly in communication with the server. But that is also not a restriction. I read somewhere while researching that I could have my server take the call first and then transfer it to that physical phone. The only restriction is that we use VoIP phones/numbers.

Like I said, I have very vague information on the subject. Any help is appreciated. I've studied that I could use Twillio or other such third party services to achieve this task but I just wanted to know if I can do it myself instead of relying on someone else and hoping they don't shut down their services in the next few years.

答:
Those are a lot of questions jammed into 1 there, I'll try to answer some.

As you already tagged it, TAPI is an option but not very easy to get into. TAPI normally get it's information centrally from the PBX, but in your particular case the SNOM system has the phones themselves connect to a central server to gather the information and distribute it there. You may be able to hook into a proprietary protocol.

Gathering calls on a central server to then distribute them to phones is usually done with an IVR (Interactive voice response). Channeling outside calls through it is easy but the problem with getting your call information from this point is usually you miss the internal calls.

Your website pop-up is not my area of expertise, maybe someone else could comment on the feasibility of that, but personally I would go with a task-tray style app if reliability is your highest priority.


问:
Blade: Undefined Variable Inside Foreach Loop

I have a controller which gets an array of a User's diaries from my database and passes them to my view:

<?php

public function readDiaries($hash)
{
    $user = User::where('hash', $hash)->first();
    $diaries = Diary::where('user_id', $user->id)->get();

    return view('app.diary.readDiaries', ['diaries' => $diaries]);
}
```

<p>In my view, I am looping through the diaries using a <code>@foreach</code> loop.</p>

<pre class="lang-php prettyprint-override"><code><div id="diaries" class="card-columns">
    @if (count($diaries) > 0)
        @foreach ($diaries as $dairy)
            {{ var_dump($diary) }}
        @endforeach
    @endif
</div>
</code>```

But I am getting the following undefined variable error...

Undefined variable: diary (View: C:\xampp\htdocs\personal_projects\Active\diary_app\resources\views\app\diary\readDiaries.blade.php)

Why is my $diary variable undefined inside the @foreach loop?

答:
There is some typo in var_dump use {{ var_dump($dairy) }}
Try to use compact method for pass data to view as shown below</p>

```<code> //return view('app.diary.readDiaries', compact('diaries'));
public function readDiaries($hash)
{
    $user = User::where('hash', $hash)
        ->first();
    $diaries = Diary::where('user_id', $user->id)
        ->get();
    return view('app.diary.readDiaries', compact('diaries'));
}
</code>```

Body:
I have a controller which gets an array of a User's diaries from my database and passes them to my view:

<?php

public function readDiaries($hash)
{
    $user = User::where('hash', $hash)->first();
    $diaries = Diary::where('user_id', $user->id)->get();

    return view('app.diary.readDiaries', ['diaries' => $diaries]);
}

In my view, I am looping through the diaries using a @foreach loop.

    @if (count($diaries) > 0)
        @foreach ($diaries as $dairy)
            {{ var_dump($diary) }}
        @endforeach
    @endif

But I am getting the following undefined variable error...

Undefined variable: diary (View: C:\xampp\htdocs\personal_projects\Active\diary_app\resources\views\app\diary\readDiaries.blade.php)

Why is my $diary variable undefined inside the @foreach loop?

Body:
There is some typo in var_dump use {{ var_dump($dairy) }}
Try to use compact method for pass data to view as shown below

 //return view('app.diary.readDiaries', compact('diaries'));
public function readDiaries($hash)
{
    $user = User::where('hash', $hash)
        ->first();
    $diaries = Diary::where('user_id', $user->id)
        ->get();
    return view('app.diary.readDiaries', compact('diaries'));
}