问:
Javascript: Sort object array by number properties which include undefined
I can define an array of numbers and sort them like this

var array = ['2', undefined, '1'];
array.sort((a, b) => a - b);
console.log(array);```
</div>
</div>
</p>

<p>The output is <code>1, 2, null</code>.</p>

<p>I have an array of objects that can include a number property, which I can define like this. Not all objects have the number property. Now I want to sort this array of objects by the number property. So I tried this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [
  { number: 2 },
  {},
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);</code>```

The output is not what I want. I get 2, undefined, 1.

If all objects in the array have the number property defined, the same sort function produces 1, 2, which is the result I would expect.

var array = [
  { number: 2 },
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);```

So my question is, what is the best way to sort an array of objects by a property, where the property is not always defined. The intended result is that the objects are ordered by the property (number), with objects that do not define that property at the end of the array.

My only solution so far is to iterate the set, and if the property is not defined, set the property to 0 or null. I can then pass the object array to the sort function and it works as I want. Is there a better way than this?

Jfiddle: https://jsfiddle.net/t2r6z13e/1/

答:
The explanation is in the comments:

let array = [
  {},
  { number: 2 },
  {},
  { number: 1 }
];

array.sort((a, b) => {
  // two undefined values should be treated as equal ( 0 )
  if( typeof a.number === 'undefined' && typeof b.number === 'undefined' )
    return 0;
  // if a is undefined and b isn't a should have a lower index in the array
  else if( typeof a.number === 'undefined' )
    return 1;
    // if b is undefined and a isn't a should have a higher index in the array
  else if( typeof b.number === 'undefined' )
    return -1;
    // if both numbers are defined compare as normal
  else
    return a.number - b.number;
});

console.log( array );```

Body:
I can define an array of numbers and sort them like this

var array = ['2', undefined, '1'];
array.sort((a, b) => a - b);
console.log(array);

The output is 1, 2, null.

I have an array of objects that can include a number property, which I can define like this. Not all objects have the number property. Now I want to sort this array of objects by the number property. So I tried this:

var array = [
  { number: 2 },
  {},
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);

The output is not what I want. I get 2, undefined, 1.

If all objects in the array have the number property defined, the same sort function produces 1, 2, which is the result I would expect.

var array = [
  { number: 2 },
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);

So my question is, what is the best way to sort an array of objects by a property, where the property is not always defined. The intended result is that the objects are ordered by the property (number), with objects that do not define that property at the end of the array.

My only solution so far is to iterate the set, and if the property is not defined, set the property to 0 or null. I can then pass the object array to the sort function and it works as I want. Is there a better way than this?

Jfiddle: https://jsfiddle.net/t2r6z13e/1/


来源: stackexchange

问:
UIView Function Bug
I am trying to create a UIView function which when called will return a view with 2 buttons, a TextView in some stackViews. I am having trouble and at the moment all it is returning is an empty rectangle(it's not showing any of the info inside). What am I doing wrong?

```<code>func returnView(text1: String, text2: String) -> UIView {

let customView = UIView()
let firstButton = UIButton()
let secondButton = UIButton()
let textView = UITextView()

customView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 90)
customView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

firstButton.setTitle(text1, for: .normal)
firstButton.setTitleColor(UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0), for: .normal)
firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)

secondButton.setTitle("apple", for: .normal)
secondButton.setTitleColor(UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0), for: .normal)
secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)

textView.text = text2

let stack1 = UIStackView()
stack1.axis = .horizontal
stack1.alignment = .fill
stack1.distribution = .fillEqually

stack1.addArrangedSubview(firstButton)
stack1.addArrangedSubview(secondButton)

let stack2 = UIStackView()
stack2.axis = .horizontal
stack2.alignment = .fill
stack2.distribution = .fillEqually

stack2.addArrangedSubview(textView)

let fullStack = UIStackView()
fullStack.axis = .vertical
fullStack.alignment = .fill
fullStack.distribution = .fillEqually
fullStack.addArrangedSubview(stack1)
fullStack.addArrangedSubview(stack2)

customView.addSubview(fullStack)

stack1.translatesAutoresizingMaskIntoConstraints = false
stack2.translatesAutoresizingMaskIntoConstraints = false
fullStack.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([fullStack.topAnchor.constraint(equalTo: customView.topAnchor), fullStack.leftAnchor.constraint(equalTo: customView.leftAnchor), fullStack.rightAnchor.constraint(equalTo: customView.rightAnchor), fullStack.heightAnchor.constraint(equalTo: customView.heightAnchor), (fullStack.centerXAnchor.constraint(equalTo: customView.centerXAnchor))])

return customView
}
</code>```

EDIT I am calling it from this function:

```<code>func renderAttachment() {

    let view = returnView(text1: "test1", text2: "test2")

    // Render Image
    let renderer = UIGraphicsImageRenderer(size: view.frame.size)
    let image = renderer.image {
        view.layer.render(in: $0.cgContext)
    }

    // Create Attachment
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRect(origin: .zero, size: image.size)

    // Current Attributed String
    let atStr = NSMutableAttributedString(attributedString: textview.attributedText)

    // Insert Attachment
    let attachmentAtStr = NSAttributedString(attachment: attachment)
    if let selectedRange = textview.selectedTextRange {
        let cursorIndex = textview.offset(from: textview.beginningOfDocument, to: selectedRange.start)
        atStr.insert(attachmentAtStr, at: cursorIndex)
        atStr.addAttributes(self.textview.typingAttributes, range: NSRange(location: cursorIndex, length: 1))
    } else {
        atStr.append(attachmentAtStr)
    }
    textview.attributedText = atStr
    print(atStr)
}
</code>```

This is how it shows in my textView(just an empty box!)

答:
I tried to add a view using your function and it worked perfectly fine. Please see below screenshot.

add below line of code after the self.returnView(text1: "Test1", text2: "Test2") function call.

```<code>view.layoutIfNeeded()
</code>```

Hope this helps.

ContentLicense: CC BY-SA 4.0

Title: UIView Function Bug

Body:
I am trying to create a UIView function which when called will return a view with 2 buttons, a TextView in some stackViews. I am having trouble and at the moment all it is returning is an empty rectangle(it's not showing any of the info inside). What am I doing wrong?

func returnView(text1: String, text2: String) -> UIView {

let customView = UIView()
let firstButton = UIButton()
let secondButton = UIButton()
let textView = UITextView()

customView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 90)
customView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

firstButton.setTitle(text1, for: .normal)
firstButton.setTitleColor(UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0), for: .normal)
firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)

secondButton.setTitle("apple", for: .normal)
secondButton.setTitleColor(UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0), for: .normal)
secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)

textView.text = text2

let stack1 = UIStackView()
stack1.axis = .horizontal
stack1.alignment = .fill
stack1.distribution = .fillEqually

stack1.addArrangedSubview(firstButton)
stack1.addArrangedSubview(secondButton)

let stack2 = UIStackView()
stack2.axis = .horizontal
stack2.alignment = .fill
stack2.distribution = .fillEqually

stack2.addArrangedSubview(textView)

let fullStack = UIStackView()
fullStack.axis = .vertical
fullStack.alignment = .fill
fullStack.distribution = .fillEqually
fullStack.addArrangedSubview(stack1)
fullStack.addArrangedSubview(stack2)

customView.addSubview(fullStack)

stack1.translatesAutoresizingMaskIntoConstraints = false
stack2.translatesAutoresizingMaskIntoConstraints = false
fullStack.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([fullStack.topAnchor.constraint(equalTo: customView.topAnchor), fullStack.leftAnchor.constraint(equalTo: customView.leftAnchor), fullStack.rightAnchor.constraint(equalTo: customView.rightAnchor), fullStack.heightAnchor.constraint(equalTo: customView.heightAnchor), (fullStack.centerXAnchor.constraint(equalTo: customView.centerXAnchor))])

return customView
}

EDIT I am calling it from this function:

func renderAttachment() {

    let view = returnView(text1: "test1", text2: "test2")

    // Render Image
    let renderer = UIGraphicsImageRenderer(size: view.frame.size)
    let image = renderer.image {
        view.layer.render(in: $0.cgContext)
    }

    // Create Attachment
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRect(origin: .zero, size: image.size)

    // Current Attributed String
    let atStr = NSMutableAttributedString(attributedString: textview.attributedText)

    // Insert Attachment
    let attachmentAtStr = NSAttributedString(attachment: attachment)
    if let selectedRange = textview.selectedTextRange {
        let cursorIndex = textview.offset(from: textview.beginningOfDocument, to: selectedRange.start)
        atStr.insert(attachmentAtStr, at: cursorIndex)
        atStr.addAttributes(self.textview.typingAttributes, range: NSRange(location: cursorIndex, length: 1))
    } else {
        atStr.append(attachmentAtStr)
    }
    textview.attributedText = atStr
    print(atStr)
}

This is how it shows in my textView(just an empty box!)

Body:
I tried to add a view using your function and it worked perfectly fine. Please see below screenshot.

add below line of code after the self.returnView(text1: "Test1", text2: "Test2") function call.

view.layoutIfNeeded()

Hope this helps.


问:
How to fix: Doctrine not returning properly
I want to make dynamic delete posts function but the result is error because value is null.

Controller

```<code>/**
  * @Route("/posts/delete/{id}", name="delete_post", methods={"DELETE"})
  */
  public function deletePost($id, LoggerInterface $logger)
  {

    $post=$this->getDoctrine()->getRepository(Article::class)->find($id);

    if(!$post)
    {
        $this->addFlash(
            'notice',
            'Something went wrong'
        );
        $logger->info($id);
    }
    else
    {

        $entityManager=$this->getDoctrine()->getManager();
        $entityManager->remove($post);
        $entityManager->flush();
        $entityManager->clear();
    }

    $response=new Response();
    return($response);
  }
</code>```

JS

```<code>const articles = document.getElementById("articles");

if (articles) {
 articles.addEventListener("click", e => {
  if (e.target.className === "btn btn-danger delete-article") {
  if (confirm("Are you sure?")) {
    const id = e.target.getAttribute("data-id");

    fetch("/posts/delete/${id}", {
      method: "DELETE"
    }).then(res => window.location.reload());
  }
 }
 });
}
</code>```

Twig

```<code><table border="1" id="articles">
        <tr>
            <th class="pt">Post title</th>
            <th class="pe">Edit</th>
            <th class="pd">Delete</th>
        </tr>
        {% for article in articles %}
            <tr>
                <td class="title">{{ article.title }}</td>
                <td class="edit">
                    <a href="{{ path('posts_editor', {'id':article.id}) }}" class="btn btn-primary edit-article">
                        <img src="{{ asset('images/edit.png') }}" class="image">
                    </a>
                </td>
                <td class="delete">
                    <a href="#" class="btn btn-danger delete-article" data-id="{{article.id}}">
                        <img src="{{ asset('images/delete.png') }}" class="image">
                    </a>
                </td>
            </tr>
        {% endfor %}
    </table>
</code>```

I was doing it with video tutorial and I don't know what is wrong on video this code was working but when I wrote it I just got an error below

Error

EntityManager#remove() expects parameter 1 to be an entity object, NULL given.

Hope anyone can help me, I am really getting frustrated because of it is not working.

答:
Fixed

Just had to change this

```<code>fetch("/posts/delete/${id}", {
  method: "DELETE"
}).then(res => window.location.reload());
</code>```

In this

```<code>fetch("/posts/delete/" + id, {
      method: "POST"
    }).then(res => window.location.reload());
</code>```

Now it's deleting posts properly

Body:
I want to make dynamic delete posts function but the result is error because value is null.

Controller

/**
  * @Route("/posts/delete/{id}", name="delete_post", methods={"DELETE"})
  */
  public function deletePost($id, LoggerInterface $logger)
  {

    $post=$this->getDoctrine()->getRepository(Article::class)->find($id);

    if(!$post)
    {
        $this->addFlash(
            'notice',
            'Something went wrong'
        );
        $logger->info($id);
    }
    else
    {

        $entityManager=$this->getDoctrine()->getManager();
        $entityManager->remove($post);
        $entityManager->flush();
        $entityManager->clear();
    }

    $response=new Response();
    return($response);
  }

JS

const articles = document.getElementById("articles");

if (articles) {
 articles.addEventListener("click", e => {
  if (e.target.className === "btn btn-danger delete-article") {
  if (confirm("Are you sure?")) {
    const id = e.target.getAttribute("data-id");

    fetch("/posts/delete/${id}", {
      method: "DELETE"
    }).then(res => window.location.reload());
  }
 }
 });
}

Twig

            Post title
            Edit
            Delete

        {% for article in articles %}

                {{ article.title }}

        {% endfor %}

I was doing it with video tutorial and I don't know what is wrong on video this code was working but when I wrote it I just got an error below

Error

EntityManager#remove() expects parameter 1 to be an entity object, NULL given.

Hope anyone can help me, I am really getting frustrated because of it is not working.

Body:
Fixed

Just had to change this

fetch("/posts/delete/${id}", {
  method: "DELETE"
}).then(res => window.location.reload());

In this

fetch("/posts/delete/" + id, {
      method: "POST"
    }).then(res => window.location.reload());

Now it's deleting posts properly


问:
OutOfMemoryException occurred when uploading file using Symfony
I have followed the instructions in the Symfony documentation for how to upload a file exactly as per https://symfony.com/doc/current/controller/upload_file.html.

However when I post the file using Postman I get an OutOfMemoryException. Does anyone know what causes this and how to fix it?

The error received is as follows:
(1/1) OutOfMemoryException
Error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 109056000 bytes)

答:
In your php.ini change configuration

```<code>upload_max_filesize = 2M
</code>```

also, check

```<code>post_max_size = 8M
</code>```

change this configuration ...
restart server and check

Body:
In your php.ini change configuration

upload_max_filesize = 2M

also, check

post_max_size = 8M

change this configuration ...
restart server and check


问:
Reusing variables in Rust
I have the following code:

```<code>let display_value = entry.path().display();
files_and_dirs.push(DiskEntry {
    path: display_value.to_string(),
    is_dir: is_dir(display_value.to_string()),
    name: display_value.to_string()
});
</code>```

If I write it thus:

```<code>let display_value = entry.path().display();
let dir_name = display_value.to_string();
files_and_dirs.push(DiskEntry {
    path: dir_name,
    is_dir: is_dir(dir_name),
    name: dir_name
});
</code>```

I get the following error:

move occurs because dir_name has type std::string::String, which
  does not implement the Copy trait

I understand in Rust values are moved around when assigning. I want to declare one variable and use it multiple times in the second block of code. How do I do this?

答:
I want to declare one variable and use it multiple times in the second block of code. How do I do this?

You don't, because "in Rust values are moved around when assigning". The compiler doesn't automatically copy most kinds of values, because it's not clear when that's possible, and it would introduce an overhead that the programmer might want to avoid.

If you want to use the value of a Clone variable multiple times - just clone it.

If you want to avoid repeating yourself, you can give the computation a name by using a closure.

let display_value = entry.path().display();
let dir_name = || display_value.to_string();
files_and_dirs.push(DiskEntry {
    path: dir_name(),
    is_dir: is_dir(dir_name()),
    name: dir_name()
});
```

This does not let you use the value multiple times - it produces a new value with each call.

Title: Reusing variables in Rust

Body:
I have the following code:

let display_value = entry.path().display();
files_and_dirs.push(DiskEntry {
    path: display_value.to_string(),
    is_dir: is_dir(display_value.to_string()),
    name: display_value.to_string()
});

If I write it thus:

let display_value = entry.path().display();
let dir_name = display_value.to_string();
files_and_dirs.push(DiskEntry {
    path: dir_name,
    is_dir: is_dir(dir_name),
    name: dir_name
});

I get the following error:

move occurs because dir_name has type std::string::String, which
  does not implement the Copy trait

I understand in Rust values are moved around when assigning. I want to declare one variable and use it multiple times in the second block of code. How do I do this?

Body:
I want to declare one variable and use it multiple times in the second block of code. How do I do this?

You don't, because "in Rust values are moved around when assigning". The compiler doesn't automatically copy most kinds of values, because it's not clear when that's possible, and it would introduce an overhead that the programmer might want to avoid.

If you want to use the value of a Clone variable multiple times - just clone it.

If you want to avoid repeating yourself, you can give the computation a name by using a closure.

let display_value = entry.path().display();
let dir_name = || display_value.to_string();
files_and_dirs.push(DiskEntry {
    path: dir_name(),
    is_dir: is_dir(dir_name()),
    name: dir_name()
});

This does not let you use the value multiple times - it produces a new value with each call.


问:
How to use different images as form submit button which passes different values to the php page?
I made a html and a php page. I put 3 images in html page showing different genre of movies- horror, fantasy, romance. I want the images to work as form submit button and should get redirected to the php page and the php page should get the genre of the image.

What I already tried- I tried lot of different things but nothing worked.
And I wonder how php page will take different inputs from different images using $_POST method.

Expected output-
Suppose if user clicked on image of genre 'horror', then in php page value of $genre should be Horror.

答: The images should have an href tag that redirects to your PHP page. Note that this method will mean that you should get the value through $_REQUEST variables and not POST or GET. For example lets say href='myphp.php?genre=horror'. and in the PHP file $genre = $_REQUEST['genre'];</p>


问:
How do I map 'Ctrl+C' to the button on RaspberryPi?
I've written a script that periodically scrapes twitter data using while True.

For the except element, I initiate a one-time scrape of a large chunk of data.

The only way I can trigger this is by using Ctrl+C. What I want to do is map the 'Ctrl+C' function to the button on my RaspberryPi Pibrella.

I've looked around here, there, and everywhere, but had no joy. The only module I can find does not work on Raspberry Pi (Linux).

```<code>def status_update():
    while True:
        try:
            scrape_some_stuff()
            time.sleep(1x60)
        except:
            scrape_lots_of_stuff()
            time.sleep(1x60)
</code>```

答:
pibrella has a package (pip install pibrella) so you can easily monitor the button status, with which you can use to raise your exception

```<code>import pibrella

# add this line into your codes
pibrella.button.pressed(raise Exception)
</code>```

Their github repo has some examples.

Body:
I've written a script that periodically scrapes twitter data using while True.

For the except element, I initiate a one-time scrape of a large chunk of data.

The only way I can trigger this is by using Ctrl+C. What I want to do is map the 'Ctrl+C' function to the button on my RaspberryPi Pibrella.

I've looked around here, there, and everywhere, but had no joy. The only module I can find does not work on Raspberry Pi (Linux).

def status_update():
    while True:
        try:
            scrape_some_stuff()
            time.sleep(1x60)
        except:
            scrape_lots_of_stuff()
            time.sleep(1x60)

Body:
pibrella has a package (pip install pibrella) so you can easily monitor the button status, with which you can use to raise your exception

import pibrella

# add this line into your codes
pibrella.button.pressed(raise Exception)

Their github repo has some examples.


问:
PHP array_search
Is there any function which will accomplish the equivalent of array_search with a $needle that is an array? Like, this would be an ideal solution:

```<code>$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

// Returns key 1 in haystack
$search = array_search( $needle, $haystack );
</code>```

If no function, any other functions that accept needles which may be arrays that I can use to create a custom function?

答:
```<code>$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

// Returns key 1 in haystack

function array_needle_array_search($needle, $haystack)
{
        $results = array();
        foreach($needle as $n)
        {
                $p = array_search($n, $haystack);
                if($p)
                    $results[] = $p;
        }
        return ($results)?$results:false;
}

print_r(array_needle_array_search($needle, $haystack));
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP array_search

Body:
Is there any function which will accomplish the equivalent of array_search with a $needle that is an array? Like, this would be an ideal solution:

$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

// Returns key 1 in haystack
$search = array_search( $needle, $haystack );

If no function, any other functions that accept needles which may be arrays that I can use to create a custom function?


问:
why django username parameters passed to urls is connecting directly and how prevent it
I'm trying to access to a user profil if urls parameters is profile/username
it work but i have a security problem because user is directly connected.

How i can define in django user profil access depending if user is authenticated or not

profil.html

```<code>{% if  user.is_authenticated %}
            <p>{{ user.username}}</p>
            <a href="">edit your profile</a>

            {% else %}
            <p>{{ user.username}}</p>
            <p>basic profile of user</p>
 {% endif%}
</code>```

views.py

```<code>def profil(request,username):
    user=get_object_or_404(User, username=username)
    context = {
        'user':user
    }
    return render(request, 'service/profil.html',context)
</code>```

答:
You can use the login required decorator. Just add it to your view:</p>

```<code>from django.contrib.auth.decorators import login_required

@login_required
def profil(request, username):
...
</code>```

Body:
I'm trying to access to a user profil if urls parameters is profile/username
it work but i have a security problem because user is directly connected.

How i can define in django user profil access depending if user is authenticated or not

profil.html

{% if  user.is_authenticated %}

{{ user.username}}

            edit your profile

            {% else %}

{{ user.username}}

basic profile of user

 {% endif%}

views.py

def profil(request,username):
    user=get_object_or_404(User, username=username)
    context = {
        'user':user
    }
    return render(request, 'service/profil.html',context)

Body:
You can use the login required decorator. Just add it to your view:

from django.contrib.auth.decorators import login_required

@login_required
def profil(request, username):
...


问:
why Mainwindow is closed during pressing the OK button of the messagebox
i have a mainwindow and a button.i am parsing one xml and the rwesult is displayed in messagebox...when i pressed ok button of messagebox it show the next loop of xml...and at the end mainwindow is also closed.i dont want to close the mainwindow....how to achieve it?????</p>

答:
It seems that the mainwindow is a dialog. Try to change the type of the form (FormBorderStyle property).
Maybe, you should change property AcceptButton. </p>


答:
You could try something similar to the following:

```<code><input class='genre' type='image' src='/images/genres/horror.jpg' data-genre='horror' />
<input class='genre' type='image' src='/images/genres/sci-fi.jpg' data-genre='sci-fi' />
<input class='genre' type='image' src='/images/genres/chickflick.jpg' data-genre='chickflick' />

<script>
    Array.prototype.slice.call( document.querySelectorAll('input.genre') ).forEach( function(input){
        input.addEventListener('click', function(e){
            e.preventDefault();
            location.href='info.php?genre='+this.dataset.genre
        });
    })
</script>
</code>```

Assign each input a dataset attribute which you query later in the click handler. That dataset value is then used to construct the url...

Alternatively a slightly different approach would be to POST the data by setting the value of a hidden field to the dataset attribute value- like:

```<code><form name='genres' method='post'>
    <input class='genre' type='image' src='/images/genres/horror.jpg' data-genre='horror' />
    <input class='genre' type='image' src='/images/genres/sci-fi.jpg' data-genre='sci-fi' />
    <input class='genre' type='image' src='/images/genres/chickflick.jpg' data-genre='chickflick' />
    <input class='genre' type='image' src='/images/genres/thriller.jpg' data-genre='thriller' />
    <input class='genre' type='image' src='/images/genres/adventure.jpg' data-genre='adventure' />
    <input class='genre' type='image' src='/images/genres/period-drama.jpg' data-genre='period-drama' />
    <input type='hidden' name='genre' />
</form>
<script>
    let form=document.forms.genres;
    let genre=form.genre;

    Array.prototype.slice.call( document.querySelectorAll('input.genre') ).forEach( function(input){
        input.addEventListener('click', function(e){
            e.preventDefault();
            /* set hidden input value */
            genre.value=this.dataset.genre;
            /* append the genre to the qction/querystring */
            form.action='?genre='+this.dataset.genre;
            /* go */
            form.submit();
        });
    })
</script>
</code>```

Title: How to use different images as form submit button which passes different values to the php page?

Body:
I made a html and a php page. I put 3 images in html page showing different genre of movies- horror, fantasy, romance. I want the images to work as form submit button and should get redirected to the php page and the php page should get the genre of the image.

What I already tried- I tried lot of different things but nothing worked.
And I wonder how php page will take different inputs from different images using $_POST method.

Expected output-
Suppose if user clicked on image of genre 'horror', then in php page value of $genre should be Horror.

Body:
You could try something similar to the following:

<input class='genre' type='image' src='/images/genres/horror.jpg' data-genre='horror' />
<input class='genre' type='image' src='/images/genres/sci-fi.jpg' data-genre='sci-fi' />
<input class='genre' type='image' src='/images/genres/chickflick.jpg' data-genre='chickflick' />

<script>
    Array.prototype.slice.call( document.querySelectorAll('input.genre') ).forEach( function(input){
        input.addEventListener('click', function(e){
            e.preventDefault();
            location.href='info.php?genre='+this.dataset.genre
        });
    })
</script>

Assign each input a dataset attribute which you query later in the click handler. That dataset value is then used to construct the url...

Alternatively a slightly different approach would be to POST the data by setting the value of a hidden field to the dataset attribute value- like:

<form name='genres' method='post'>
    <input class='genre' type='image' src='/images/genres/horror.jpg' data-genre='horror' />
    <input class='genre' type='image' src='/images/genres/sci-fi.jpg' data-genre='sci-fi' />
    <input class='genre' type='image' src='/images/genres/chickflick.jpg' data-genre='chickflick' />
    <input class='genre' type='image' src='/images/genres/thriller.jpg' data-genre='thriller' />
    <input class='genre' type='image' src='/images/genres/adventure.jpg' data-genre='adventure' />
    <input class='genre' type='image' src='/images/genres/period-drama.jpg' data-genre='period-drama' />
    <input type='hidden' name='genre' />
</form>
<script>
    let form=document.forms.genres;
    let genre=form.genre;

    Array.prototype.slice.call( document.querySelectorAll('input.genre') ).forEach( function(input){
        input.addEventListener('click', function(e){
            e.preventDefault();
            /* set hidden input value */
            genre.value=this.dataset.genre;
            /* append the genre to the qction/querystring */
            form.action='?genre='+this.dataset.genre;
            /* go */
            form.submit();
        });
    })
</script>


问:
java.util.Date to XMLGregorianCalendar
Isn't there a convenient way of getting from a java.util.Date to a XMLGregorianCalendar?</p>

答:
I should like to take a step back and a modern look at this 10 years old question. The classes mentioned, Date and XMLGregorianCalendar, are old now. I challenge the use of them and offer alternatives.

Date was always poorly designed and is more than 20 years old. This is simple: don’t use it.

XMLGregorianCalendar is old too and has an old-fashioned design. As I understand it, it was used for producing dates and times in XML format for XML documents. Like 2009-05-07T19:05:45.678+02:00 or 2009-05-07T17:05:45.678Z. These formats agree well enough with ISO 8601 that the classes of java.time, the modern Java date and time API, can produce them, which we prefer.

No conversion necessary

For many (most?) purposes the modern replacement for a Date will be an Instant. An Instant is a point in time (just as a Date is).

```<code>    Instant yourInstant = // ...
    System.out.println(yourInstant);
</code>```

An example output from this snippet:

2009-05-07T17:05:45.678Z

It’s the same as the latter of my example XMLGregorianCalendar strings above. As most of you know, it comes from Instant.toString being implicitly called by System.out.println. With java.time, in many cases we don’t need the conversions that in the old days we made between Date, Calendar, XMLGregorianCalendar and other classes (in some cases we do need conversions, though, I am showing you a couple in the next section).

Controlling the offset

Neither a Date nor in Instant has got a time zone nor a UTC offset. The previously accepted and still highest voted answer by Ben Noland uses the JVMs current default time zone for selecting the offset of the XMLGregorianCalendar. To include an offset in a modern object we use an OffsetDateTime. For example:

```<code>    ZoneId zone = ZoneId.of("America/Asuncion");
    OffsetDateTime dateTime = yourInstant.atZone(zone).toOffsetDateTime();
    System.out.println(dateTime);
</code>```

2009-05-07T13:05:45.678-04:00

Again this conforms with XML format. If you want to use the current JVM time zone setting again, set zone to ZoneId.systemDefault().

What if I absolutely need an XMLGregorianCalendar?

There are more ways to convert Instant to XMLGregorianCalendar. I will present a couple, each with its pros and cons. First, just as an XMLGregorianCalendar produces a string like 2009-05-07T17:05:45.678Z, it can also be built from such a string:

```<code>    String dateTimeString = yourInstant.toString();
    XMLGregorianCalendar date2
            = DatatypeFactory.newInstance().newXMLGregorianCalendar(dateTimeString);
    System.out.println(date2);
</code>```

2009-05-07T17:05:45.678Z

Pro: it’s short and I don’t think it gives any surprises. Con: To me it feels like a waste formatting the instant into a string and parsing it back.

```<code>    ZonedDateTime dateTime = yourInstant.atZone(zone);
    GregorianCalendar c = GregorianCalendar.from(dateTime);
    XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    System.out.println(date2);
</code>```

2009-05-07T13:05:45.678-04:00

Pro: It’s the official conversion. Controlling the offset comes naturally. Con: It goes through more steps and is therefore longer.

What if we got a Date?

If you got an old-fashioned Date object from a legacy API that you cannot afford to change just now, convert it to Instant:

```<code>    Instant i = yourDate.toInstant();
    System.out.println(i);
</code>```

Output is the same as before:

2009-05-07T17:05:45.678Z

If you want to control the offset, convert further to an OffsetDateTime in the same way as above.

If you’ve got an old-fashioned Date and absolutely need an old-fashioned XMLGregorianCalendar, just use the answer by Ben Noland.

Links

Oracle tutorial: Date Time explaining how to use java.time.

XSD Date and Time Data Types on W3Schools.

Wikipedia article: ISO 8601

ContentLicense: CC BY-SA 2.5

Title: java.util.Date to XMLGregorianCalendar

Body:
I should like to take a step back and a modern look at this 10 years old question. The classes mentioned, Date and XMLGregorianCalendar, are old now. I challenge the use of them and offer alternatives.

Date was always poorly designed and is more than 20 years old. This is simple: don’t use it.

XMLGregorianCalendar is old too and has an old-fashioned design. As I understand it, it was used for producing dates and times in XML format for XML documents. Like 2009-05-07T19:05:45.678+02:00 or 2009-05-07T17:05:45.678Z. These formats agree well enough with ISO 8601 that the classes of java.time, the modern Java date and time API, can produce them, which we prefer.

No conversion necessary

For many (most?) purposes the modern replacement for a Date will be an Instant. An Instant is a point in time (just as a Date is).

    Instant yourInstant = // ...
    System.out.println(yourInstant);

An example output from this snippet:

2009-05-07T17:05:45.678Z

It’s the same as the latter of my example XMLGregorianCalendar strings above. As most of you know, it comes from Instant.toString being implicitly called by System.out.println. With java.time, in many cases we don’t need the conversions that in the old days we made between Date, Calendar, XMLGregorianCalendar and other classes (in some cases we do need conversions, though, I am showing you a couple in the next section).

Controlling the offset

Neither a Date nor in Instant has got a time zone nor a UTC offset. The previously accepted and still highest voted answer by Ben Noland uses the JVMs current default time zone for selecting the offset of the XMLGregorianCalendar. To include an offset in a modern object we use an OffsetDateTime. For example:

    ZoneId zone = ZoneId.of("America/Asuncion");
    OffsetDateTime dateTime = yourInstant.atZone(zone).toOffsetDateTime();
    System.out.println(dateTime);

2009-05-07T13:05:45.678-04:00

Again this conforms with XML format. If you want to use the current JVM time zone setting again, set zone to ZoneId.systemDefault().

What if I absolutely need an XMLGregorianCalendar?

There are more ways to convert Instant to XMLGregorianCalendar. I will present a couple, each with its pros and cons. First, just as an XMLGregorianCalendar produces a string like 2009-05-07T17:05:45.678Z, it can also be built from such a string:

    String dateTimeString = yourInstant.toString();
    XMLGregorianCalendar date2
            = DatatypeFactory.newInstance().newXMLGregorianCalendar(dateTimeString);
    System.out.println(date2);

2009-05-07T17:05:45.678Z

Pro: it’s short and I don’t think it gives any surprises. Con: To me it feels like a waste formatting the instant into a string and parsing it back.

    ZonedDateTime dateTime = yourInstant.atZone(zone);
    GregorianCalendar c = GregorianCalendar.from(dateTime);
    XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    System.out.println(date2);

2009-05-07T13:05:45.678-04:00

Pro: It’s the official conversion. Controlling the offset comes naturally. Con: It goes through more steps and is therefore longer.

What if we got a Date?

If you got an old-fashioned Date object from a legacy API that you cannot afford to change just now, convert it to Instant:

    Instant i = yourDate.toInstant();
    System.out.println(i);

Output is the same as before:

2009-05-07T17:05:45.678Z

If you want to control the offset, convert further to an OffsetDateTime in the same way as above.

If you’ve got an old-fashioned Date and absolutely need an old-fashioned XMLGregorianCalendar, just use the answer by Ben Noland.

Links

Oracle tutorial: Date Time explaining how to use java.time.

XSD Date and Time Data Types on W3Schools.

Wikipedia article: ISO 8601


问:
Dictionary size reduces upon increasing one element
I ran this:

```<code>import sys

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1}
print sys.getsizeof(diii)
# output: 1048

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1,'key8':2}
print sys.getsizeof(diii)
# output: 664
</code>```

Before asking here, I restarted my python shell and tried it online too and got the same result.

I thought a dictionary with one more element will either give same bytes as output or more, than the one containing one less element.

Any idea what am I doing wrong?

答: You're not doing anything wrong. The size of a dictionary doesn't exactly correspond to the number of elements, as dictionaries are overallocated and dynamically resized once a certain percentage of their memory space is used. I'm not sure what makes the dict smaller in 2.7 (it doesn't in 3) in your example, but you don't have to worry about it. Why are you using 2.7 and why do you want to know the exact memory usage of the dict (which btw doesn't include the memory used by the variables contained in the dictionary, as the dictionary itself is filled with pointers.</p>

Body:
I ran this:

import sys

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1}
print sys.getsizeof(diii)
# output: 1048

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1,'key8':2}
print sys.getsizeof(diii)
# output: 664

Before asking here, I restarted my python shell and tried it online too and got the same result.

I thought a dictionary with one more element will either give same bytes as output or more, than the one containing one less element.

Any idea what am I doing wrong?


问:
SAPUI5 Problem with rootUri in Mock Sever
Thanks a lot to all of you, my friends for your help and advices.
Guys, I think I solved the problem, almost. Just need your help with this moment:
My Table get data from mock server, but doesn't show it to user. Instead of the rows it shows an empty table where the rows count is equal to the data in my mockserver file.
I mean: At the moment, in "ZMA_BPSet" there'se 8 rows. Because of this you can see 8 rows in table.
Can anybody help me?

答:
rootUri is used to determine the path of the OData service that should by intercepted by the mock server. It should always correspond to the service uri of your OData service specified in manifest.json.

So, if you have this in your manifest

```<code>"dataSources": {
    "mainService": {
        "uri": "/sap/opu/odata/your-service/",
        "type": "OData",
        "settings": {
            "localUri": "localService/metadata.xml"
        }
    }
},
</code>```

your mock server constructor should look like this:

```<code>var oMockServer = new MockServer({
    rootUri: "/sap/opu/odata/your-service/"
});
</code>```

Note that the rootUri must always have a trailing slash. If your service url in manifest.json does not have one, make sure that rootUri does.

You don't have to change anything in your manifest.json. All test setups are done in mockServer.html and its referenced files.

Body:
rootUri is used to determine the path of the OData service that should by intercepted by the mock server. It should always correspond to the service uri of your OData service specified in manifest.json.

So, if you have this in your manifest

"dataSources": {
    "mainService": {
        "uri": "/sap/opu/odata/your-service/",
        "type": "OData",
        "settings": {
            "localUri": "localService/metadata.xml"
        }
    }
},

your mock server constructor should look like this:

var oMockServer = new MockServer({
    rootUri: "/sap/opu/odata/your-service/"
});

Note that the rootUri must always have a trailing slash. If your service url in manifest.json does not have one, make sure that rootUri does.

You don't have to change anything in your manifest.json. All test setups are done in mockServer.html and its referenced files.


问:
ISQL 7.3 Perform screens with 132-columns
If I change SuSE's terminfo to 132-column (co#132) and in my Perform .per code specify
SCREEN SIZE 24 BY 132, would I be able to fit more field tags past the 80-column mark and it display them properly?.. I want to cram more stuff into one screen without having to split it up into separate screens. Has anyone done this before?  </p>

答: Assuming you have set INFORMIXTERM=terminfo so Perform uses Terminfo, then yes, what you suggest should work.  It is a long while since I last did this, but it worked back in the early '90s on real green (or orange) screens - like Wyse 60 terminals.


问:
Delegate data from one UIViewController to another one
I am completely new to Swift programming and tried to delegate a single String from one ViewController to another by clicking a send button. The problem is , that it does not work ...

I guess it would be easy for you to solve this and considering that it would be very helpful wether you explain me what I did wrong. :)

Thank you a lot

```<code>import UIKit

protocol protoTYdelegate {
    func didSendMessage(message: String)
}

class New: UIViewController {

    @IBOutlet weak var SendButton: UIButton!

    var tydelegate: protoTYdelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func SendButtonAction(_ sender: Any) {

        let nachricht = "It works fine."
        tydelegate?.didSendMessage(message: nachricht)

    }

}

</code>```

```<code>import UIKit

class ThankYouPage: UIViewController {

    @IBOutlet weak var numbersView: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let controller = New()
        controller.tydelegate = self

    }

}

extension ThankYouPage: protoTYdelegate{
    func didSendMessage(message: String) {
        numbersView.text = message
    }
</code>```

答:
@Eyup Göymen's answer is right.

I have another way, assuming that you are not using segue and you are pushing to next controller by manual-code.

So your ThankYouPage code should be like :

```<code>import UIKit

class ThankYouPage: UIViewController {

    @IBOutlet weak var numbersView: UILabel!

    override func viewDidLoad() {
         super.viewDidLoad()
    }

    @IBAction func someButtonAction(_ sender: Any) { // By clicking on some, you are opening that `New` controller
         let detailView = self.storyboard?.instantiateViewController(withIdentifier: "New") as! New
         detailView.tydelegate = self
         self.navigationController?.pushViewController(detailView, animated: true)
    }
}

extension ThankYouPage: protoTYdelegate {

     func didSendMessage(message: String) {
         numbersView.text = message
    }
}
</code>```

Body:
I am completely new to Swift programming and tried to delegate a single String from one ViewController to another by clicking a send button. The problem is , that it does not work ...

I guess it would be easy for you to solve this and considering that it would be very helpful wether you explain me what I did wrong. :)

Thank you a lot

import UIKit

protocol protoTYdelegate {
    func didSendMessage(message: String)
}

class New: UIViewController {

    @IBOutlet weak var SendButton: UIButton!

    var tydelegate: protoTYdelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func SendButtonAction(_ sender: Any) {

        let nachricht = "It works fine."
        tydelegate?.didSendMessage(message: nachricht)

    }

}

import UIKit

class ThankYouPage: UIViewController {

    @IBOutlet weak var numbersView: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let controller = New()
        controller.tydelegate = self

    }

}

extension ThankYouPage: protoTYdelegate{
    func didSendMessage(message: String) {
        numbersView.text = message
    }

Body:
@Eyup Göymen's answer is right.

I have another way, assuming that you are not using segue and you are pushing to next controller by manual-code.

So your ThankYouPage code should be like :

import UIKit

class ThankYouPage: UIViewController {

    @IBOutlet weak var numbersView: UILabel!

    override func viewDidLoad() {
         super.viewDidLoad()
    }

    @IBAction func someButtonAction(_ sender: Any) { // By clicking on some, you are opening that `New` controller
         let detailView = self.storyboard?.instantiateViewController(withIdentifier: "New") as! New
         detailView.tydelegate = self
         self.navigationController?.pushViewController(detailView, animated: true)
    }
}

extension ThankYouPage: protoTYdelegate {

     func didSendMessage(message: String) {
         numbersView.text = message
    }
}


问:
How do I change the background of a site with a button?
I'm trying to coding a site where I need to change the background with a button, but I can't...

I created a button that changes the color of the background while clicking a button but after I added an image as a background, it doesn't want to change the color background (obviously)...

 // creating a variable for the bg of my site

 // using this variable

            <button onclick="changeColor(); backgroundHiding();" class="lightbutton">Turn On/Off the lights </button>

 // creating the button that interact with the two js functions

```

<p>I expected that it works but... huh... no
It works sometimes, like 1 time every 100 times, I don't know why...
If someone could help me, I would really appreciate it!</p>

```https://stackblitz.com/edit/typescript-ppvsvl?embed=1&file=index.html
```

答:
First of all, you don't need additional event listener:

```<code>root.addEventListener("onclick", e => {...})
</code>```

The second, as I get it, you are trying to read the CSS variable and compare it in if statement. This won't work:

```<code>if (--main-bg) =  "#2d2d2d"
</code>```

I've fixed it here:

https://stackblitz.com/edit/js-crl57k?file=index.html

Does it look like what you wanted to do?

Body:
I'm trying to coding a site where I need to change the background with a button, but I can't...

I created a button that changes the color of the background while clicking a button but after I added an image as a background, it doesn't want to change the color background (obviously)...

 // creating a variable for the bg of my site

 // using this variable

            <button onclick="changeColor(); backgroundHiding();" class="lightbutton">Turn On/Off the lights </button>

 // creating the button that interact with the two js functions

I expected that it works but... huh... no
It works sometimes, like 1 time every 100 times, I don't know why...
If someone could help me, I would really appreciate it!

https://stackblitz.com/edit/typescript-ppvsvl?embed=1&file=index.html

Body:
First of all, you don't need additional event listener:

root.addEventListener("onclick", e => {...})

The second, as I get it, you are trying to read the CSS variable and compare it in if statement. This won't work:

if (--main-bg) =  "#2d2d2d"

I've fixed it here:

https://stackblitz.com/edit/js-crl57k?file=index.html

Does it look like what you wanted to do?


问:
GitHub Authentication - How to limit to the organization users?
I have a GitHub app setup for authentication for my webapp per https://developer.github.com/v3/guides/basics-of-authentication/.  How can I setup my GitHub app so that only members of the organization can authenticate?

Thanks

答: So there's no way to do this directly.  You need to query if the user is a member of an authorized org.  Seems odd to be but thats the way this is handled in every implementation i've seen</p>


问:
Problem doing multiplication tables with while function
I am a new programmer and this is my first question here so excuse me if its pretty easy.
M doing a multiplication table but each time it stops after the 1 and it doesnt increment the number

I am trying to do it with 2 while loops

```<code>nb = 1
i = 0
while nb<10 :
    while i<=10 :
        print(nb * i)
        i+=1
    nb+=1
</code>```

with that code I only have the 1 multiplication table then the program stops

答:
Reset variable inside loop. Variable i reaches its max value after the first iteration of inner loop, which we need to set back to 0 for the next iteration to work:

```<code>nb = 1
while nb < 10 :
    i = 0
    while i <= 10 :
        print(nb * i)
        i += 1
    nb += 1
</code>```

You can do the same using for, which in my opinion is more readable and you don't need to worry about incrementing/resetting variables:

```<code>for x in range(1, 10):
    for y in range(11):
        print(x * y)
</code>```

Body:
I am a new programmer and this is my first question here so excuse me if its pretty easy.
M doing a multiplication table but each time it stops after the 1 and it doesnt increment the number

I am trying to do it with 2 while loops

nb = 1
i = 0
while nb<10 :
    while i<=10 :
        print(nb * i)
        i+=1
    nb+=1

with that code I only have the 1 multiplication table then the program stops

Body:
Reset variable inside loop. Variable i reaches its max value after the first iteration of inner loop, which we need to set back to 0 for the next iteration to work:

nb = 1
while nb < 10 :
    i = 0
    while i <= 10 :
        print(nb * i)
        i += 1
    nb += 1

You can do the same using for, which in my opinion is more readable and you don't need to worry about incrementing/resetting variables:

for x in range(1, 10):
    for y in range(11):
        print(x * y)


问:
Blackberry check internet connection on device
How do I check if the Internet connection is ON or OFF on a device?</p>

答:
I think there is no direct way.
You just request for a server,if there is there is no internet not avilable at that time an exception is thrown, you catch it display an alert to the user.
Some thing like below:</p>

```<code>try {
// request http
}
catch(IOException e) {
            UiApplication.getUiApplication().invokeLater(new Runnable() {

                public void run() {
                    Dialog.alert("No Internet Connectivity");
                    //System.exit(0);
                }
            });
            System.out.println(e);
        }
</code>```

Body:
I think there is no direct way.
You just request for a server,if there is there is no internet not avilable at that time an exception is thrown, you catch it display an alert to the user.
Some thing like below:

try {
// request http
}
catch(IOException e) {
            UiApplication.getUiApplication().invokeLater(new Runnable() {

                public void run() {
                    Dialog.alert("No Internet Connectivity");
                    //System.exit(0);
                }
            });
            System.out.println(e);
        }


问:
Flutter fresh installation flutter run stuck
I am new to flutter i have fresh installtion.

All as in docs.

As after fresh installation i was fine worked but when i want to work on another day flutter run i stuck.... I do not know why. I only make boilerplate app. I xcode when i build app is opening in simulator but stating as flutter run not working. I even try to wait 20 min with this flutter run but still stuck

flutter doctor -v

```<code>[✓] Flutter (Channel master, v1.6.4-pre.14, on Mac OS X 10.14.5 18F132, locale
    pl-PL)
    • Flutter version 1.6.4-pre.14 at /Users/db/Desktop/Mobile/flutter
    • Framework revision 81c38b22cb (32 hours ago), 2019-05-24 22:51:02 -0400
    • Engine revision 8dc3a4cde2
    • Dart version 2.3.2 (build 2.3.2-dev.0.0 e3edfd36b2)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/db/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling
      support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      1.8.0_152-release-1343-b01)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 10.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.2.1, Build version 10E1001
    • CocoaPods version 1.7.0

[✓] iOS tools - develop for iOS devices
    • ios-deploy 1.9.4

[✓] Android Studio (version 3.4)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 35.3.1
    • Dart plugin version 183.6270
    • Java version OpenJDK Runtime Environment (build
      1.8.0_152-release-1343-b01)

[✓] Connected device (1 available)
    • iPhone 8 • F35EFD3E-C637-427A-8405-30EDF202939A • ios •
      com.apple.CoreSimulator.SimRuntime.iOS-12-2 (simulator)

• No issues found!
</code>```

flutter run -v stuck at this stage.

```<code>+file:///Users/db/Desktop/Mobile/flutter/packages/flutter/lib/widgets.d
art
[        ] -> +file:///Users/db/Desktop/Flutter/iamsmart/lib/main.dart
[        ] -> 35191e22-84d6-4fab-abef-178ae9e4c665 build/app.dill 0
[ +319 ms] Building bundle
[        ] Writing asset files to build/flutter_assets
[  +55 ms] Wrote build/flutter_assets
[  +12 ms] Using legacy Xcode build system.
[  +27 ms] executing: [/Users/db/Desktop/Flutter/iamsmart/ios/]
/usr/bin/xcodebuild -list
</code>```

答:
Run this command

```<code>flutter clean
</code>```

And then again

```<code>flutter run
</code>```

Body:
I am new to flutter i have fresh installtion.

All as in docs.

As after fresh installation i was fine worked but when i want to work on another day flutter run i stuck.... I do not know why. I only make boilerplate app. I xcode when i build app is opening in simulator but stating as flutter run not working. I even try to wait 20 min with this flutter run but still stuck

flutter doctor -v

[✓] Flutter (Channel master, v1.6.4-pre.14, on Mac OS X 10.14.5 18F132, locale
    pl-PL)
    • Flutter version 1.6.4-pre.14 at /Users/db/Desktop/Mobile/flutter
    • Framework revision 81c38b22cb (32 hours ago), 2019-05-24 22:51:02 -0400
    • Engine revision 8dc3a4cde2
    • Dart version 2.3.2 (build 2.3.2-dev.0.0 e3edfd36b2)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/db/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling
      support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      1.8.0_152-release-1343-b01)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 10.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.2.1, Build version 10E1001
    • CocoaPods version 1.7.0

[✓] iOS tools - develop for iOS devices
    • ios-deploy 1.9.4

[✓] Android Studio (version 3.4)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 35.3.1
    • Dart plugin version 183.6270
    • Java version OpenJDK Runtime Environment (build
      1.8.0_152-release-1343-b01)

[✓] Connected device (1 available)
    • iPhone 8 • F35EFD3E-C637-427A-8405-30EDF202939A • ios •
      com.apple.CoreSimulator.SimRuntime.iOS-12-2 (simulator)

• No issues found!

flutter run -v stuck at this stage.

+file:///Users/db/Desktop/Mobile/flutter/packages/flutter/lib/widgets.d
art
[        ] -> +file:///Users/db/Desktop/Flutter/iamsmart/lib/main.dart
[        ] -> 35191e22-84d6-4fab-abef-178ae9e4c665 build/app.dill 0
[ +319 ms] Building bundle
[        ] Writing asset files to build/flutter_assets
[  +55 ms] Wrote build/flutter_assets
[  +12 ms] Using legacy Xcode build system.
[  +27 ms] executing: [/Users/db/Desktop/Flutter/iamsmart/ios/]
/usr/bin/xcodebuild -list

Body:
Run this command

flutter clean

And then again

flutter run


问:
How do I explain this in English?
```<code>select S.acnum
from interest S
where upper(S.descrip) like '%LOGIC%'
    and exists (select fieldnum
                    from interest
                    where acnum = S.acnum
                        and upper(descrip) not like '%LOGIC%');
</code>```

I need to describe the outer query in English. How do I do that?

答:
I would prefer to write this as:

```<code>select i.acnum
from interest i
group by i.acnum
having sum(case when upper(i.descrip) like '%LOGIC%' then 1 else 0 end) > 0 and
       sum(case when upper(i.descrip) not like '%LOGIC%' then 1 else 0 end) > 0;
</code>```

This version does not produce duplicate values.  It is saying to get all acnum that have at least one record where descrip contains LOGIC and another that does not contain LOGIC.

Title: How do I explain this in English?

Body:
select S.acnum
from interest S
where upper(S.descrip) like '%LOGIC%'
    and exists (select fieldnum
                    from interest
                    where acnum = S.acnum
                        and upper(descrip) not like '%LOGIC%');

I need to describe the outer query in English. How do I do that?

Body:
I would prefer to write this as:

select i.acnum
from interest i
group by i.acnum
having sum(case when upper(i.descrip) like '%LOGIC%' then 1 else 0 end) > 0 and
       sum(case when upper(i.descrip) not like '%LOGIC%' then 1 else 0 end) > 0;

This version does not produce duplicate values.  It is saying to get all acnum that have at least one record where descrip contains LOGIC and another that does not contain LOGIC.


问:
Lambda loses captured value
I cannot understand why the captured value is lost. I understand that it is connected with an out of scope or copying of an object of LambdaWrapper. But what exactly happens? If LambdaWrapper(100) leaves the scope in Add and reference to __value loses, then why there is no same to LambdaWrapper(300).

```<code>#include <iostream>
#include <vector>
#include <functional>
using namespace std;

class LambdaWrapper {
public:
    LambdaWrapper(double new_value): __value (new_value) {
        cout << "constructed with " << __value << endl;
        __func = [this](){ cout << __value << endl;};
    }
    void call() const { __func(); }
private:
    double __value;
    function<void(void)> __func;
};

class LambdaContainer {
public:
    void Add(double value) {
        LambdaWrapper w(value); //out of scope
        parts.push_back(w);
    }

    void Add(LambdaWrapper w) // passed as value
    {
        parts.push_back(w);
    }

    void call() const {
        for (const auto& part : parts)
                part.call();
    }
private:
    vector<LambdaWrapper> parts;
};

int main() {
    LambdaContainer c;
    c.Add(100);

    LambdaWrapper w(200);
    c.Add(w);

    c.Add( LambdaWrapper(300) ); //LambdaWrapper(300) will out of scope too

    cout << "==============" << endl;
    c.call();

    return 0;
}
</code>```

The output:

```<code>constructed with 100
constructed with 200
constructed with 300
==============
6.95168e-308 <<< WHY?
200
300
</code>```

答:
Why one need to do this, if lambda is already a wrapper like that? To preserve capture? You're doing opposite of that.

Your closure, created within Add(double) method, captures value of this , which points at object for which that method was called. And that object "dies" when method goes out of scope. Value of that pointer stays incorrect, it's a dangling pointer to a local or temporal object. Same would happen with other objects too because of this design.

```<code>LambdaWrapper(const LambdaWrapper &obj) {
        __value = obj.__value;
        __func = [this](){cout << __value << endl;};
    }
</code>```

This constructor works, because it creates new lambda with new this value for instance which would persist. Lambda is nothing more but syntax sugar for an instance of class with pointer field (presumably __this) which stores value of this and contains void operator() () {cout << __this->__value << endl;};

Any call to Add(double) would result in dangling pointer and UB, call with temporal object results in UB too, because that object would not be bound with const reference (which works only in local anyway), so it's a dangling pointer too. The method accepts wrapper by value, which results in another step of copy.

That design is suboptimal because every time a new object is created. You would not need a copy constructor if you'll capture just the value.

PS. As an illustration to nature of lambda closures, GCC even had a bug\flaw in past, where members of lambda are accessible from outside, because they weren't private members.

Title: Lambda loses captured value

Body:
I cannot understand why the captured value is lost. I understand that it is connected with an out of scope or copying of an object of LambdaWrapper. But what exactly happens? If LambdaWrapper(100) leaves the scope in Add and reference to __value loses, then why there is no same to LambdaWrapper(300).

#include <iostream>
#include <vector>
#include <functional>
using namespace std;

class LambdaWrapper {
public:
    LambdaWrapper(double new_value): __value (new_value) {
        cout << "constructed with " << __value << endl;
        __func = [this](){ cout << __value << endl;};
    }
    void call() const { __func(); }
private:
    double __value;
    function<void(void)> __func;
};

class LambdaContainer {
public:
    void Add(double value) {
        LambdaWrapper w(value); //out of scope
        parts.push_back(w);
    }

    void Add(LambdaWrapper w) // passed as value
    {
        parts.push_back(w);
    }

    void call() const {
        for (const auto& part : parts)
                part.call();
    }
private:
    vector<LambdaWrapper> parts;
};

int main() {
    LambdaContainer c;
    c.Add(100);

    LambdaWrapper w(200);
    c.Add(w);

    c.Add( LambdaWrapper(300) ); //LambdaWrapper(300) will out of scope too

    cout << "==============" << endl;
    c.call();

    return 0;
}

The output:

constructed with 100
constructed with 200
constructed with 300
==============
6.95168e-308 <<< WHY?
200
300

Body:
Why one need to do this, if lambda is already a wrapper like that? To preserve capture? You're doing opposite of that.

Your closure, created within Add(double) method, captures value of this , which points at object for which that method was called. And that object "dies" when method goes out of scope. Value of that pointer stays incorrect, it's a dangling pointer to a local or temporal object. Same would happen with other objects too because of this design.

LambdaWrapper(const LambdaWrapper &obj) {
        __value = obj.__value;
        __func = [this](){cout << __value << endl;};
    }

This constructor works, because it creates new lambda with new this value for instance which would persist. Lambda is nothing more but syntax sugar for an instance of class with pointer field (presumably __this) which stores value of this and contains void operator() () {cout << __this->__value << endl;};

Any call to Add(double) would result in dangling pointer and UB, call with temporal object results in UB too, because that object would not be bound with const reference (which works only in local anyway), so it's a dangling pointer too. The method accepts wrapper by value, which results in another step of copy.

That design is suboptimal because every time a new object is created. You would not need a copy constructor if you'll capture just the value.

PS. As an illustration to nature of lambda closures, GCC even had a bug\flaw in past, where members of lambda are accessible from outside, because they weren't private members.


问:
Calling a function that was passed through its props
I am currently new to react-bootstrap and have a question i can not solve.

I want to set my parents state by passing it as a prop to its child. Whe ncalling the function it seems to be executed, but the state is not set.. I have no clue why that is.

```<code>class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state={
            component : ""
        }

        this.returnDashboard = this.returnDashboard.bind(this);
    }

    returnDashboard=()=>{
        console.log("i am executed")
        this.setState({component : <Dashboard />})
    }

    render(){
        return (
            <Child returnDashboard={this.returnDashboard}/>
        );
    }
};

class Child extends React.Component{
    constructor(props){
        super(props);
    }

    render(){
         return(
                <button onClick={()={this.props.returnSettings()}}>foo</button>
            );
    }
}
</code>```

when pressing the button the console logs "i am executed" and this: ƒ () { [native code] }. Can someone help me with that?

答:
You have a typo

```<code>onClick={()={this.props.returnSettings()}}
</code>```

Should be

```<code>onClick={() => this.props.returnSettings()}
</code>```

Or even simpler

```<code>onClick={this.props.returnSettings}
</code>```

Body:
I am currently new to react-bootstrap and have a question i can not solve.

I want to set my parents state by passing it as a prop to its child. Whe ncalling the function it seems to be executed, but the state is not set.. I have no clue why that is.

class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state={
            component : ""
        }

        this.returnDashboard = this.returnDashboard.bind(this);
    }

    returnDashboard=()=>{
        console.log("i am executed")
        this.setState({component : <Dashboard />})
    }

    render(){
        return (
            <Child returnDashboard={this.returnDashboard}/>
        );
    }
};

class Child extends React.Component{
    constructor(props){
        super(props);
    }

    render(){
         return(
                <button onClick={()={this.props.returnSettings()}}>foo</button>
            );
    }
}

when pressing the button the console logs "i am executed" and this: ƒ () { [native code] }. Can someone help me with that?

Body:
You have a typo

onClick={()={this.props.returnSettings()}}

Should be

onClick={() => this.props.returnSettings()}

Or even simpler

onClick={this.props.returnSettings}


问:
Iphone Custom Navigation Bar - White Box Error
My problem is simple. I used the method of subclassing navigation bar, and then using drawRect to attempt to draw my own custom navigation bar image. However, it doesn't draw my image... only a blank white space.

The structure of my project is a tab bar with a navigation controller under each one of it's tabs. Each navigation controller has a navigation bar and I have set those bars to my custom class (customNavBar) in IB.

In my customNavBar.h file I have:

```<code>@interface customNavBar : UINavigationBar {
}

@end
</code>```

In my customNavBar.m file I have:

```<code>#import "customNavBar.h"

@implementation customNavBar

-(void) dealloc{
    [super dealloc];
}

- (void)drawRect:(CGRect)rect
{
    UIImage *image = [UIImage imageNamed:@"navigation_bg.png"];
    [image drawInRect:CGRectMake(55, 0, self.frame.size.width, self.frame.size.height)];
}

@end
</code>```

Any ideas why my image might not be showing and instead just getting a white background? My image is in the project under the resources folder.

Thank you everyone. :)

答:
When I implemented your code in a test project, I did in fact see the image. I however did

```<code>[image drawInRect:self.frame];
</code>```

The image ended up covering the bottom half of the nav bar and the top half was white (like you are seeing). Perhaps your image is being drawn too low? Try playing with the rect values or just set it to self.frame like I did and see what happens. If you still don't see image, make sure your nav bar class is actual set to your custom class in interface builder and that code is being called to draw your nav bar (maybe put print statement be sure).

Body:
My problem is simple. I used the method of subclassing navigation bar, and then using drawRect to attempt to draw my own custom navigation bar image. However, it doesn't draw my image... only a blank white space.

The structure of my project is a tab bar with a navigation controller under each one of it's tabs. Each navigation controller has a navigation bar and I have set those bars to my custom class (customNavBar) in IB.

In my customNavBar.h file I have:

@interface customNavBar : UINavigationBar {
}

@end

In my customNavBar.m file I have:

#import "customNavBar.h"

@implementation customNavBar

-(void) dealloc{
    [super dealloc];
}

- (void)drawRect:(CGRect)rect
{
    UIImage *image = [UIImage imageNamed:@"navigation_bg.png"];
    [image drawInRect:CGRectMake(55, 0, self.frame.size.width, self.frame.size.height)];
}

@end

Any ideas why my image might not be showing and instead just getting a white background? My image is in the project under the resources folder.

Thank you everyone. :)

Body:
When I implemented your code in a test project, I did in fact see the image. I however did

[image drawInRect:self.frame];

The image ended up covering the bottom half of the nav bar and the top half was white (like you are seeing). Perhaps your image is being drawn too low? Try playing with the rect values or just set it to self.frame like I did and see what happens. If you still don't see image, make sure your nav bar class is actual set to your custom class in interface builder and that code is being called to draw your nav bar (maybe put print statement be sure).


问:
Javascript: Sort object array by number properties which include undefined
I can define an array of numbers and sort them like this

var array = ['2', undefined, '1'];
array.sort((a, b) => a - b);
console.log(array);```
</div>
</div>
</p>

<p>The output is <code>1, 2, null</code>.</p>

<p>I have an array of objects that can include a number property, which I can define like this. Not all objects have the number property. Now I want to sort this array of objects by the number property. So I tried this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [
  { number: 2 },
  {},
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);</code>```

The output is not what I want. I get 2, undefined, 1.

If all objects in the array have the number property defined, the same sort function produces 1, 2, which is the result I would expect.

var array = [
  { number: 2 },
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);```

So my question is, what is the best way to sort an array of objects by a property, where the property is not always defined. The intended result is that the objects are ordered by the property (number), with objects that do not define that property at the end of the array.

My only solution so far is to iterate the set, and if the property is not defined, set the property to 0 or null. I can then pass the object array to the sort function and it works as I want. Is there a better way than this?

Jfiddle: https://jsfiddle.net/t2r6z13e/1/

答:
If compareFunction is supplied, all non-undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFunction).

In your code, in case of array with number sort function does not call for item with undefined value; while in case of array with object, object is defined but obj.number is not defined, so sort function get call for blank({}) object also and required to add undefined check for number in sort function.

Body:
I can define an array of numbers and sort them like this

var array = ['2', undefined, '1'];
array.sort((a, b) => a - b);
console.log(array);

The output is 1, 2, null.

I have an array of objects that can include a number property, which I can define like this. Not all objects have the number property. Now I want to sort this array of objects by the number property. So I tried this:

var array = [
  { number: 2 },
  {},
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);

The output is not what I want. I get 2, undefined, 1.

If all objects in the array have the number property defined, the same sort function produces 1, 2, which is the result I would expect.

var array = [
  { number: 2 },
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);

So my question is, what is the best way to sort an array of objects by a property, where the property is not always defined. The intended result is that the objects are ordered by the property (number), with objects that do not define that property at the end of the array.

My only solution so far is to iterate the set, and if the property is not defined, set the property to 0 or null. I can then pass the object array to the sort function and it works as I want. Is there a better way than this?

Jfiddle: https://jsfiddle.net/t2r6z13e/1/


问:
Modelio class diagram compartments
I need help about Modelio UML Tool Class diagram components. Normal a class diagram in other modelling tools have 3 compartments. The top compartment contains the name of the class. The middle compartment contains the attributes of the class. The bottom compartment contains the operations the class can execute. But modelio has 4th compartments I need to know that why it is. I have a software project contains UML diagrams and I need to explain this stuff.

I checked their tutorials but couldnt have any answer.

答:
Normal a class diagram in other modelling tools have 3 compartments

no, from UML formal/2017-12-05 §11.4.4 Notation

A Class has four mandatory compartments: attributes, operations, receptions (see 9.2.4) and internal structure (see
  11.2.4). A Class may also have optional compartments as described for Classifiers in general (see 9.2.4)

Title: Modelio class diagram compartments


问:
How do you programmatically redact PDF FIles?
Adobe Acrobat has the ability to redact PDF files (that is, actually remove the information, rather than simply drawing a black box on top of it). I would like to use this feature programmatically. To redact using the GUI you select the Mark for Redaction Tool, draw it over the text to be redacted, then Apply Redactions.

Is there any way to do this programmatically, either through AppleScript or some other way?

I know the (X,y) location of the text to be redacted.

Thanks!

答:
You can use GroupDocs.Redaction for .NET to programmatically redact text in the PDF documents. You can perform the exact phrase, case-sensitive and regular expression redaction of the text. This is how you can perform the exact phrase redaction.

```<code>using (Document doc = Redactor.Load("D:\\candy.pdf"))
{
     doc.RedactWith(new ExactPhraseRedaction("candy", new ReplacementOptions("[redacted]")));
     // Save the document to "*_Redacted.*" file.
     doc.Save(new SaveOptions() { AddSuffix = true, RasterizeToPDF = false });
}
</code>```

Disclosure: I work as Developer Evangelist at GroupDocs.

Body:
You can use GroupDocs.Redaction for .NET to programmatically redact text in the PDF documents. You can perform the exact phrase, case-sensitive and regular expression redaction of the text. This is how you can perform the exact phrase redaction.

using (Document doc = Redactor.Load("D:\\candy.pdf"))
{
     doc.RedactWith(new ExactPhraseRedaction("candy", new ReplacementOptions("[redacted]")));
     // Save the document to "*_Redacted.*" file.
     doc.Save(new SaveOptions() { AddSuffix = true, RasterizeToPDF = false });
}

Disclosure: I work as Developer Evangelist at GroupDocs.


问:
Jenkins not able to fetch code from remote git
My jenkins build is suddenly not working now.The error is as follows:-

```<code>Fetching changes from the remote Git repository
 > git config remote.origin.url <url> # timeout=10
ERROR: Error fetching remote repo 'origin'
hudson.plugins.git.GitException: Failed to fetch from <url>
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:735)
    at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:983)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1016)
    at hudson.scm.SCM.checkout(SCM.java:484)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:1270)
    at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:622)
    at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:528)
    at hudson.model.Run.execute(Run.java:1759)
    at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:529)
    at hudson.model.ResourceController.execute(ResourceController.java:89)
    at hudson.model.Executor.run(Executor.java:240)
Caused by: hudson.plugins.git.GitException: Command "git config remote.origin.url <url> returned status code 4:
stdout:
stderr: error: failed to write new configuration file .git/config.lock
</code>```

I am not able to figure out the root cause.
I have checked the permission and ownership for jenkins home folder which is /var/lib/jenkins:-
drwxrwxrwx 17 jenkins       jenkins        4096 Jun 25 04:30 jenkins

Permission and ownership of .git folder inside workspace folder of jenkins is:-
drwxrwxrwx 8 jenkins jenkins   4096 Jun 30 21:51 .git

Please guide me fix the problem.

答: we deleted the branches from gitlab, but the slaves weren't updated so we saw this error. We deleted the workspace and it looks ok</p>

Body:
My jenkins build is suddenly not working now.The error is as follows:-

Fetching changes from the remote Git repository
 > git config remote.origin.url <url> # timeout=10
ERROR: Error fetching remote repo 'origin'
hudson.plugins.git.GitException: Failed to fetch from <url>
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:735)
    at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:983)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1016)
    at hudson.scm.SCM.checkout(SCM.java:484)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:1270)
    at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:622)
    at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:528)
    at hudson.model.Run.execute(Run.java:1759)
    at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:529)
    at hudson.model.ResourceController.execute(ResourceController.java:89)
    at hudson.model.Executor.run(Executor.java:240)
Caused by: hudson.plugins.git.GitException: Command "git config remote.origin.url <url> returned status code 4:
stdout:
stderr: error: failed to write new configuration file .git/config.lock

I am not able to figure out the root cause.
I have checked the permission and ownership for jenkins home folder which is /var/lib/jenkins:-
drwxrwxrwx 17 jenkins       jenkins        4096 Jun 25 04:30 jenkins

Permission and ownership of .git folder inside workspace folder of jenkins is:-
drwxrwxrwx 8 jenkins jenkins   4096 Jun 30 21:51 .git

Please guide me fix the problem.


问:
Propagate transaction to Forkjoin submit
I'm create a ForkJoinPool with a number of thread to execute a stream parallel, that is  executed from a query in jpa, but I'm have trouble with the Transactional propagate to the method submit of ForkJoinPool.

```<code>@Transactional(readOnly = true)
public void streamTest() {
    ForkJoinPool customThreadPool = new ForkJoinPool(20);
    try {
    customThreadPool.submit(() ->
         priceRepository.streamAll()
         .parallel()
         .map(p -> this.transform(p))
         .forEach(System.out::println)
         ).get();
    } catch (InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

I'm getting the error: "You're trying to execute a streaming query method without a surrounding transaction that keeps the connection open so that the Stream can actually be consumed. Make sure the code consuming the stream uses @Transactional or any other way of declaring a (read-only) transaction."

If I take off the ForkJoinPool to execute the stream, it's works fine.
How can I propagate the transaction(readOnly) to the execution of the method submit from ForkJoinPool, is there a way?

答:
I discovered how to set transactional inside the task of ForkJoinPool.
I only have to use the TransactionSynchronizationManager as I did below.

```<code>@Transactional(readOnly = true)
public void streamTest() {
ForkJoinPool customThreadPool = new ForkJoinPool(20);
try {
customThreadPool.submit(() -> {
    TransactionSynchronizationManager.setActualTransactionActive(true);
    TransactionSynchronizationManager.setCurrentTransactionReadOnly(true);
    TransactionSynchronizationManager.initSynchronization();
     priceRepository.streamAll()
     .parallel()
     .map(p -> this.transform(p))
     .forEach(System.out::println);
     }).get();
} catch (InterruptedException | ExecutionException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
</code>```

}

Body:
I'm create a ForkJoinPool with a number of thread to execute a stream parallel, that is  executed from a query in jpa, but I'm have trouble with the Transactional propagate to the method submit of ForkJoinPool.

@Transactional(readOnly = true)
public void streamTest() {
    ForkJoinPool customThreadPool = new ForkJoinPool(20);
    try {
    customThreadPool.submit(() ->
         priceRepository.streamAll()
         .parallel()
         .map(p -> this.transform(p))
         .forEach(System.out::println)
         ).get();
    } catch (InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I'm getting the error: "You're trying to execute a streaming query method without a surrounding transaction that keeps the connection open so that the Stream can actually be consumed. Make sure the code consuming the stream uses @Transactional or any other way of declaring a (read-only) transaction."

If I take off the ForkJoinPool to execute the stream, it's works fine.
How can I propagate the transaction(readOnly) to the execution of the method submit from ForkJoinPool, is there a way?

Body:
I discovered how to set transactional inside the task of ForkJoinPool.
I only have to use the TransactionSynchronizationManager as I did below.

@Transactional(readOnly = true)
public void streamTest() {
ForkJoinPool customThreadPool = new ForkJoinPool(20);
try {
customThreadPool.submit(() -> {
    TransactionSynchronizationManager.setActualTransactionActive(true);
    TransactionSynchronizationManager.setCurrentTransactionReadOnly(true);
    TransactionSynchronizationManager.initSynchronization();
     priceRepository.streamAll()
     .parallel()
     .map(p -> this.transform(p))
     .forEach(System.out::println);
     }).get();
} catch (InterruptedException | ExecutionException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

}


问:
How to change color of tableview background
I am trying to figure how to change the color of the background of a plain uitableview after the using has scrolled past the top or bottom of the table. Not sure what its called but if you look at the mail app, if you scroll down, whilst already at the top of the table, the background is a dark gray color with a slight gradient. Anyone know how i go about implementing this?</p>

答:
```<code>tableview.backgroundColor = [UIColor clearColor]; // you can write any color in place of clear color
</code>```


问:
How can I solve this datatype problem with only one function,best with pattern matching
I'm doing my Haskell Datentyp homework, and have try to solve this problem for a whole day.

The question is like this .

Use this Datentyp and only one function tokenize, other functions in the library are not permitted.

```<code>data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]
</code>```

The brace is the sign of Placeholder

The result should like this:
when we give input"Hallo {name}, {xyz}."

should give [Text "Hallo ", Placeholder "name", Text ", ", Placeholder "xyz", Text "."] out

I have tried for a whole day, only Text output or Placehold is OK, but I have several problems:

How to handle curly brackets {}

How to use pattern match to match "{longtext...}"

Because of Datentype [token],  tokenize (x: xs) = x :[ Text (xs:[])] do not works , so how to deal with it

how to combine the comma and all of them together, with only type [token] result function,I have tried ++ and : , but they all report error.

According to 4, there is a common question besides this homework: when using Datentype, and type of result doesn't fits type of input,  how to use recursion.

This is the last edition of my answer, it is still far away

```<code>data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]
tokenize [] = []
tokenize ('{':x:xs) = [ Placeholder (x:xs)]
tokenize (x: xs) = [ Text (x:xs)]
otherwise = error "TODO: Implementierung vervollstaendigen"

</code>```

The result should like this:
when we give input"Hallo {name}, {xyz}."

should give [Text "Hallo ", Placeholder "name", Text ", ", Placeholder "xyz", Text "."] out

Suppose all the input without internal bracket and are correctly denoted by curly brackets{}

答:
In the real-world, you'd probably want to use a library like Parsec. But for a homework, something like the following is probably enough:

data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]
tokenize xs = parseText "" xs

parseText :: String -> String -> [Token]
parseText text ('{':xs) = Text text : parsePlaceholder "" xs
parseText text (x:xs)   = parseText (text ++ [x]) xs
parseText text ""       = [Text text]

parsePlaceholder :: String -> String -> [Token]
parsePlaceholder name ('}':xs) = Placeholder name : parseText "" xs
parsePlaceholder name (x:xs)   = parsePlaceholder (name ++ [x]) xs
parsePlaceholder name ""       = [Text name]

main :: IO ()
main = print (tokenize "Hallo {name}, {xyz}.")
```

<p>Instead of studying the code closely right away, you may want to try to copy only the type signatures of <code>parseText</code> and <code>parsePlaceholder</code> to see whether you can implement them yourself.</p>

<p>A few points of critique:</p>

<ul>
<li><p>Appending to the end of a linked list (as I do with <code>text ++ [x]</code> and <code>name ++ [x]</code>) is not very efficient. A possible approach would be to prepend (with <code>(:)</code>) and then in the end do once a <code>reverse</code>.</p></li>
<li><p><code>tokenize "{foo}"</code> returns <code>[Text "",Placeholder "foo",Text ""]</code>, which is not so nice, you may want to incorporate the following helper function:</p>

<pre class="lang-hs prettyprint-override"><code>createText ""   = []
createText text = [Text text]
</code>```

Body:
I'm doing my Haskell Datentyp homework, and have try to solve this problem for a whole day.

The question is like this .

Use this Datentyp and only one function tokenize, other functions in the library are not permitted.

data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]

The brace is the sign of Placeholder

The result should like this:
when we give input"Hallo {name}, {xyz}."

should give [Text "Hallo ", Placeholder "name", Text ", ", Placeholder "xyz", Text "."] out

I have tried for a whole day, only Text output or Placehold is OK, but I have several problems:

How to handle curly brackets {}

How to use pattern match to match "{longtext...}"

Because of Datentype [token],  tokenize (x: xs) = x :[ Text (xs:[])] do not works , so how to deal with it

how to combine the comma and all of them together, with only type [token] result function,I have tried ++ and : , but they all report error.

According to 4, there is a common question besides this homework: when using Datentype, and type of result doesn't fits type of input,  how to use recursion.

This is the last edition of my answer, it is still far away

data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]
tokenize [] = []
tokenize ('{':x:xs) = [ Placeholder (x:xs)]
tokenize (x: xs) = [ Text (x:xs)]
otherwise = error "TODO: Implementierung vervollstaendigen"

The result should like this:
when we give input"Hallo {name}, {xyz}."

should give [Text "Hallo ", Placeholder "name", Text ", ", Placeholder "xyz", Text "."] out

Suppose all the input without internal bracket and are correctly denoted by curly brackets{}

Body:
In the real-world, you'd probably want to use a library like Parsec. But for a homework, something like the following is probably enough:

data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]
tokenize xs = parseText "" xs

parseText :: String -> String -> [Token]
parseText text ('{':xs) = Text text : parsePlaceholder "" xs
parseText text (x:xs)   = parseText (text ++ [x]) xs
parseText text ""       = [Text text]

parsePlaceholder :: String -> String -> [Token]
parsePlaceholder name ('}':xs) = Placeholder name : parseText "" xs
parsePlaceholder name (x:xs)   = parsePlaceholder (name ++ [x]) xs
parsePlaceholder name ""       = [Text name]

main :: IO ()
main = print (tokenize "Hallo {name}, {xyz}.")

Instead of studying the code closely right away, you may want to try to copy only the type signatures of parseText and parsePlaceholder to see whether you can implement them yourself.

A few points of critique:

Appending to the end of a linked list (as I do with text ++ [x] and name ++ [x]) is not very efficient. A possible approach would be to prepend (with (:)) and then in the end do once a reverse.

tokenize "{foo}" returns [Text "",Placeholder "foo",Text ""], which is not so nice, you may want to incorporate the following helper function:

createText ""   = []
createText text = [Text text]


问:
What's the right HTTP Status code for a blocked, abusive user?
I am building an app in which users might be blocked for using offensive language. When a user is blocked, his or her app can not access some API calls.

What should be the right HTTP status code when a blocked user tried access these API parts? Error 403 seems like a good choice, but I wonder if there's anything more specific.

答:
Just for completeness ....

The answer to the question is that there is no other code that is (clearly) more appropriate than 403.  As Wikipedia says:

"HTTP 403 is returned when the client is not permitted access to the resource despite providing authentication - either because authentication failed, or for some reason besides authentication, such as insufficient permissions of the authenticated account. This other reason needs to be acted upon before re-requesting access to the resource."

That is a good fit to the scenario you describe.

The other thing is that since you have blocked the users, you probably don't care what they think about the "correctness" of the status code.  Nobody else will care one way or the other.

Ultimately it is your choice.


问:
SpringBootJpa in clause with subMatching
How to apply like with in clause in spring boot jpa.Below is the class. </p>

```<code>@Table(name="media")
public class Media {

 @NotBlank
 private String url;

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 Long id;

 @ElementCollection
 private Set<String> tagList = new HashSet<String>();

 public Media(String urlString) {
      this.url = urlString ;
 }
}
</code>```

<p>For example if there is a row with tagList ["mentos", "hurre"] and i want to search for "men" or ["men","hu"] this row should come ?
I have defined below method but it return a row only if string completely match. </p>

```<code>Set<Media> findByTagListIn(List<String> tagList);
</code>```

答:
You need to query by specification like below:  </p>

```<code>//MediaRepository
import org.springframework.data.jpa.domain.Specification;
...
List<Media> findAll(Specification<Media> spec);
</code>```

<p>and create that specification in service class.  </p>

```<code>//MediaService
List<Media> findMediaByTags(List<String> tags){

Specification<Media> specification = (Specification<Media>) (root, query, criteriaBuilder) -> {
  Predicate predicate = criteriaBuilder.conjunction();
  for (String tag : tags) {
    predicate = criteriaBuilder.and(predicate,
        criteriaBuilder.isMember(tag, root.get("tags")));
  }
  return predicate;
};
return mediaRepository.findAll(specification);
}
</code>```

Body:
How to apply like with in clause in spring boot jpa.Below is the class.

@Table(name="media")
public class Media {

 @NotBlank
 private String url;

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 Long id;

 @ElementCollection
 private Set<String> tagList = new HashSet<String>();

 public Media(String urlString) {
      this.url = urlString ;
 }
}

For example if there is a row with tagList ["mentos", "hurre"] and i want to search for "men" or ["men","hu"] this row should come ?
I have defined below method but it return a row only if string completely match.

Set<Media> findByTagListIn(List<String> tagList);

Body:
You need to query by specification like below:

//MediaRepository
import org.springframework.data.jpa.domain.Specification;
...
List<Media> findAll(Specification<Media> spec);

and create that specification in service class.

//MediaService
List<Media> findMediaByTags(List<String> tags){

Specification<Media> specification = (Specification<Media>) (root, query, criteriaBuilder) -> {
  Predicate predicate = criteriaBuilder.conjunction();
  for (String tag : tags) {
    predicate = criteriaBuilder.and(predicate,
        criteriaBuilder.isMember(tag, root.get("tags")));
  }
  return predicate;
};
return mediaRepository.findAll(specification);
}