问:
Fixed menu doesn't work properly, disturb the fluency of the page
I've developed a Wordpress menu, this menu should change when you scroll down and should become a different menu. Everything works fine in the menu but I'm not getting why every time that the menu change from "relative" to fixed I lose a piece of page and this is very annoying.

This is the website with the menu:
http://matrix-test.com/scoilbhride/

as you can see when you scroll down and the menu changes I'm automatically brought at the mid of the slide. It is not very functional in this way and not fluent.

Here my html:

```<code><div class="nav-wrap">
    <nav>
        <div class="logo-container">
            <?php happylearning_header_logo() ?>
        </div>
        <div id="menu-toggle-main">
            <span>MENU</span>
        </div>
  <?php
        wp_nav_menu( array(

            'theme_location' => 'menu-1',
            'container' => 'nav',
            'container_class' => 'nav-bar-conatainer',
            'menu_class' => 'menu-class'

            ) );
  ?>
    </nav>
</div>
</code>```

There is a Wordpress function instead of the nav container, the ul and li.

so something like this:

```<code><nav class="nav-bar-conatainer">
   <ul class="menu-class">
       <li><a>example</a></li>
       <li><a>example</a></li>
       <li><a>example</a></li>
   </ul>
</nav>
</code>```

Here my css:

```<code>.nav-wrap {
    position: relative;
    background-color: #577188;
    padding: 40px 20px;
}

.main-navbar-fixed {
    position: fixed;
    padding: 0;
    margin: 0;
    z-index: 1000;
    width: 100%;
    top: 0;
}

.site-logo {
    display: inline;
    position: absolute;
    z-index: 1000;
    top: 0;
    left: 20;
}

.site-logo > a.site-logo__link > img.site-link__img {
    max-width: 190px;
}

.logo-navbar-fixed {
    max-width: 125px !important;
}

nav.nav-bar-conatainer {
    text-align: right;
}

ul.menu-class {
    margin: 0;
    margin-left: 190px;
    padding: 0;
}

ul.menu-class > li {
    list-style: none;
    display: inline-block;
    padding: 12px;
    margin: 0;
}

ul.menu-class > li.current-menu-item {
    border-bottom: 3px solid #fff;
}

ul.menu-class > li > a {
    color: #fff;
    text-transform: uppercase;
    font-size: 15px;
    font-weight: bold;
}

ul.menu-class > li > a:hover {
    color: #c7d13e;
}

#menu-menu_website > li > ul.sub-menu  {
    display: none;
    position: absolute;
    padding: 20px;
    padding-top: 20px;
    margin: 0;
    background-color: #7e9cb9;
}

#menu-menu_website > li:last-child > ul.sub-menu {
    right: 0px;
}

#menu-menu_website > li:hover > ul {
    display: block;
    z-index: 9999;
}

#menu-menu_website > li > ul > li {
    list-style: none;
    text-align: left;
}

#menu-menu_website > li > ul > li > a {
    color: #fff;
    font-size: 14px;
    font-weight: bold;
  white-space: nowrap;
}

#menu-menu_website > li > ul > li > a:hover {
    color: #c7d13e;
}

#menu-toggle-main {
    display: none;
    text-align: center;
    padding-top: 15px;
    padding-bottom: 15px;
    background-color: #000;
    margin-top: 15px;
    margin-bottom: 15px;
}

#menu-toggle-main > span {
    color: #fff;
    font-weight: bold;

}

.active-main-menu {
    display: block !important;
}

.margin-from-header {
    margin-top: 120px;
}

.bkg-img-subpages {
    min-height: 250px;
    background-size: cover;
    background-repeat: none;
    background-position: center center;
}
</code>```

Here my jQuery:

```<code>jQuery(document).ready(function() {

  jQuery(window).scroll(function () {
      //if you hard code, then use console
      //.log to determine when you want the
      //nav bar to stick.
      console.log(jQuery(window).scrollTop())
    if (jQuery(window).scrollTop() > 180) {
      jQuery('.nav-wrap').addClass('main-navbar-fixed');
    }
    if (jQuery(window).scrollTop() < 181) {
      jQuery('.nav-wrap').removeClass('main-navbar-fixed');
    }
  });
});

jQuery(document).ready(function() {

  jQuery(window).scroll(function () {
      //if you hard code, then use console
      //.log to determine when you want the
      //nav bar to stick.
      console.log(jQuery(window).scrollTop())
    if (jQuery(window).scrollTop() > 180) {
      jQuery('.site-link__img').addClass('logo-navbar-fixed');
    }
    if (jQuery(window).scrollTop() < 181) {
      jQuery('.site-link__img').removeClass('logo-navbar-fixed');
    }
  });
});
</code>```

答:
As I suggested

```<code>.site-content-wrap {padding-top: 194px}
header{
    position: absolute;
    top: 0;
    z-index: 5;
    width: 100%;
}
</code>```

Your main header takes up space where the fixed one does not. So when the main header disappears, so does the space it took up.

Body:
I've developed a Wordpress menu, this menu should change when you scroll down and should become a different menu. Everything works fine in the menu but I'm not getting why every time that the menu change from "relative" to fixed I lose a piece of page and this is very annoying.

This is the website with the menu:
http://matrix-test.com/scoilbhride/

as you can see when you scroll down and the menu changes I'm automatically brought at the mid of the slide. It is not very functional in this way and not fluent.

Here my html:

            <?php happylearning_header_logo() ?>

            MENU

  <?php
        wp_nav_menu( array(

            'theme_location' => 'menu-1',
            'container' => 'nav',
            'container_class' => 'nav-bar-conatainer',
            'menu_class' => 'menu-class'

            ) );
  ?>

There is a Wordpress function instead of the nav container, the ul and li.

so something like this:

example

example

example

Here my css:

.nav-wrap {
    position: relative;
    background-color: #577188;
    padding: 40px 20px;
}

.main-navbar-fixed {
    position: fixed;
    padding: 0;
    margin: 0;
    z-index: 1000;
    width: 100%;
    top: 0;
}

.site-logo {
    display: inline;
    position: absolute;
    z-index: 1000;
    top: 0;
    left: 20;
}

.site-logo > a.site-logo__link > img.site-link__img {
    max-width: 190px;
}

.logo-navbar-fixed {
    max-width: 125px !important;
}

nav.nav-bar-conatainer {
    text-align: right;
}

ul.menu-class {
    margin: 0;
    margin-left: 190px;
    padding: 0;
}

ul.menu-class > li {
    list-style: none;
    display: inline-block;
    padding: 12px;
    margin: 0;
}

ul.menu-class > li.current-menu-item {
    border-bottom: 3px solid #fff;
}

ul.menu-class > li > a {
    color: #fff;
    text-transform: uppercase;
    font-size: 15px;
    font-weight: bold;
}

ul.menu-class > li > a:hover {
    color: #c7d13e;
}

#menu-menu_website > li > ul.sub-menu  {
    display: none;
    position: absolute;
    padding: 20px;
    padding-top: 20px;
    margin: 0;
    background-color: #7e9cb9;
}

#menu-menu_website > li:last-child > ul.sub-menu {
    right: 0px;
}

#menu-menu_website > li:hover > ul {
    display: block;
    z-index: 9999;
}

#menu-menu_website > li > ul > li {
    list-style: none;
    text-align: left;
}

#menu-menu_website > li > ul > li > a {
    color: #fff;
    font-size: 14px;
    font-weight: bold;
  white-space: nowrap;
}

#menu-menu_website > li > ul > li > a:hover {
    color: #c7d13e;
}

#menu-toggle-main {
    display: none;
    text-align: center;
    padding-top: 15px;
    padding-bottom: 15px;
    background-color: #000;
    margin-top: 15px;
    margin-bottom: 15px;
}

#menu-toggle-main > span {
    color: #fff;
    font-weight: bold;

}

.active-main-menu {
    display: block !important;
}

.margin-from-header {
    margin-top: 120px;
}

.bkg-img-subpages {
    min-height: 250px;
    background-size: cover;
    background-repeat: none;
    background-position: center center;
}

Here my jQuery:

jQuery(document).ready(function() {

  jQuery(window).scroll(function () {
      //if you hard code, then use console
      //.log to determine when you want the
      //nav bar to stick.
      console.log(jQuery(window).scrollTop())
    if (jQuery(window).scrollTop() > 180) {
      jQuery('.nav-wrap').addClass('main-navbar-fixed');
    }
    if (jQuery(window).scrollTop() < 181) {
      jQuery('.nav-wrap').removeClass('main-navbar-fixed');
    }
  });
});

jQuery(document).ready(function() {

  jQuery(window).scroll(function () {
      //if you hard code, then use console
      //.log to determine when you want the
      //nav bar to stick.
      console.log(jQuery(window).scrollTop())
    if (jQuery(window).scrollTop() > 180) {
      jQuery('.site-link__img').addClass('logo-navbar-fixed');
    }
    if (jQuery(window).scrollTop() < 181) {
      jQuery('.site-link__img').removeClass('logo-navbar-fixed');
    }
  });
});

Body:
As I suggested

.site-content-wrap {padding-top: 194px}
header{
    position: absolute;
    top: 0;
    z-index: 5;
    width: 100%;
}

Your main header takes up space where the fixed one does not. So when the main header disappears, so does the space it took up.


来源: stackexchange

问:
Static data memory limit in C++ application
Someone has written function in our C++ application and is already in the production and I don't know why it's not crashing the application yet. Below is the code.

```<code>char *str_Modify()
{
    char buffer[70000] = { 0 };
    char targetString[70000] = { 0 };

    memset(targetString, '\0', sizeof(targetString));

    ...
    ...
    ...
    return targetString;
}
</code>```

As you can see, the function is returning the address of a local variable and the allocated memory will be released once the function returns.
My question

Wanted to know what is the static data memory limit?

What can be the quick fix for this code? Is it a good practice to make the variable targetString static?

答:
It is well defined behaviour in C and C++ because return an address of a static variable exist in memory after function call is over.

For example:

```<code>#include <stdio.h>

int *f()
{
    static int a[10]={0};
    return a;
}
int main()
{
    f();
    return 0;
}
</code>```

It is working fine on GCC compiler. [Live Demo]

But, if you remove static keyword then compiler generates warning:

```<code>prog.c: In function 'f':
prog.c:6:12: warning: function returns address of local variable [-Wreturn-local-addr]
     return a;
            ^
</code>```

Also, see this question comments wrote by Ludin.

I believe you are confusing this with int* fun (void) { static int i
  = 10; return &i; } versus int* fun (void) { int i = 10; return &i; }, which is another story. The former is well-defined, the latter is
  undefined behavior.

Also, tutorialspoint say's :

Second point to remember is that C does not advocate to return the
  address of a local variable to outside of the function, so you would
  have to define the local variable as static variable.

ContentLicense: CC BY-SA 3.0

Body:
Someone has written function in our C++ application and is already in the production and I don't know why it's not crashing the application yet. Below is the code.

char *str_Modify()
{
    char buffer[70000] = { 0 };
    char targetString[70000] = { 0 };

    memset(targetString, '\0', sizeof(targetString));

    ...
    ...
    ...
    return targetString;
}

As you can see, the function is returning the address of a local variable and the allocated memory will be released once the function returns.
My question

Wanted to know what is the static data memory limit?

What can be the quick fix for this code? Is it a good practice to make the variable targetString static?

Body:
It is well defined behaviour in C and C++ because return an address of a static variable exist in memory after function call is over.

For example:

#include <stdio.h>

int *f()
{
    static int a[10]={0};
    return a;
}
int main()
{
    f();
    return 0;
}

It is working fine on GCC compiler. [Live Demo]

But, if you remove static keyword then compiler generates warning:

prog.c: In function 'f':
prog.c:6:12: warning: function returns address of local variable [-Wreturn-local-addr]
     return a;
            ^

Also, see this question comments wrote by Ludin.

I believe you are confusing this with int* fun (void) { static int i
  = 10; return &i; } versus int* fun (void) { int i = 10; return &i; }, which is another story. The former is well-defined, the latter is
  undefined behavior.

Also, tutorialspoint say's :

Second point to remember is that C does not advocate to return the
  address of a local variable to outside of the function, so you would
  have to define the local variable as static variable.


问:
UnexpectedValueException Could not parse version constraint when trying to instal laravelcollective
I am new to laravel and I am trying to install laravelcollective. I am just following to documentation here and I am using this from my project directory:

composer require "laravelcollective/html":"^5.4.0"

Unfortunately, immediately after I press ented I get the following error :

[UnexpectedValueException]
    Could not parse version constraint :5.4.0: Invalid version string ":5.4.0"

I just don't know how to troubleshoot this. I didn't find much on google and this combined with my lack of experience with laravel leaves me stuck.

Can someone help?

答:
You should never run composer update without any arguments if you do not want to update all your dependencies.

In your case, the issue probably is that the ^ character is already interpreted by your shell before the argument is passed to Composer. This could possibly be solved by using single quotes instead of double quotes:

```<code>composer require 'laravelcollective/html:^5.4.0'
</code>```

When you used the 5.4.* constraint as suggested in one of the comments above, you added a space after the colon which leads to Composer interpreting the version constraint as a package name. The right command would have been this:

```<code>composer require "laravelcollective/html":"5.4.*"
</code>```

Body:
You should never run composer update without any arguments if you do not want to update all your dependencies.

In your case, the issue probably is that the ^ character is already interpreted by your shell before the argument is passed to Composer. This could possibly be solved by using single quotes instead of double quotes:

composer require 'laravelcollective/html:^5.4.0'

When you used the 5.4.* constraint as suggested in one of the comments above, you added a space after the colon which leads to Composer interpreting the version constraint as a package name. The right command would have been this:

composer require "laravelcollective/html":"5.4.*"


问:
@Autowired Repository null
ExampleRepository injected by @Autowired annotation into test class works well, but injected into service class is null. Why does it happen and how can I fix it?

Repository class

```<code>public interface ExampleRepository extends JpaRepository<Example, Long> {

    // ...
}
</code>```

Service class

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

    @Autowired
    private ExampleRepository exampleRepository;

    private File file;

    public Feed(String file) {
        this.file = new File(file);
    }

    // ...
}
</code>```

Test class

```<code>@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Rollback(false)
public abstract class ExampleTests {

    @Autowired
    private ExampleRepository exampleRepository;

    @BeforeEach
    public void setUp() {
        restoreInitialData();
    }

    protected void restoreInitialData() {
        this.exampleRepository.deleteAll();
    }

    @Test
    public void test() {
        Feed feed = new Feed("example.json");
        Optional<Example> example = feed.ingest();
        assertTrue(example.isPresent());
    }

    // ...
}
</code>```

答: Add the @Repository annotation to the interface ExampleRepository

Title: @Autowired Repository null

Body:
ExampleRepository injected by @Autowired annotation into test class works well, but injected into service class is null. Why does it happen and how can I fix it?

Repository class

public interface ExampleRepository extends JpaRepository<Example, Long> {

    // ...
}

Service class

@Service
public class Feed {

    @Autowired
    private ExampleRepository exampleRepository;

    private File file;

    public Feed(String file) {
        this.file = new File(file);
    }

    // ...
}

Test class

@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Rollback(false)
public abstract class ExampleTests {

    @Autowired
    private ExampleRepository exampleRepository;

    @BeforeEach
    public void setUp() {
        restoreInitialData();
    }

    protected void restoreInitialData() {
        this.exampleRepository.deleteAll();
    }

    @Test
    public void test() {
        Feed feed = new Feed("example.json");
        Optional<Example> example = feed.ingest();
        assertTrue(example.isPresent());
    }

    // ...
}


问:
Confusion using object oriented design .. need help
Let say we have an Order class and OrderManagerService class.

Order class: [some state and methods that act on the state]

Item[]

status

OrderManagerService class: [have no state. only following static methods]

createOrder

getOrder

Question: Let say we are using a relational DB in the back. Our goal is to update Order status. Well, the status need to get updated in the DB. My concern is where to put the updateStatus method.

Should I call OrderManagerService.getOrder then, call Order.updateStatus?

or create a new method as OrderManagerService.updateOrderStatus?

well, 1st option seems following encapsulation. But, personally I dont like it as we may end up calling DAO layer from entity objects [perhaps, that might be ok]. Wondering what would be a right design choice and why? any help is greatly appreciated.

答:
Option 2 - create a new method as OrderManagerService.updateOrderStatus?

Why?

Your service layer should encapsulate the logical business unit of work and in your case the UOW is

get the order from DB

update the status of the object

persist the changes

and you would demarcate the updateOrderStatus(...) with a transaction. and the service is still stateless.

ContentLicense: CC BY-SA 2.5


问:
Correct terminology for Dead Man Switch
I've implemented a Dead Man Switch this way:

A script can be fired by an event. When the script starts it looks for a specific object on an S3 bucket. If that object can't be found for any reason (be it network issues to access the bucket, lack of permissions, the object was removed or any other reason) then the script will abort before doing any other actions.

I suppose this is a classic Dead Man Switch.

The idea is to let us remove this object in case we need to stop the script in an emergency.

My question is about terminology - I also supply a script to our team to create or remove that S3 object. I want it to be clear which actions means what (remove object - stop script from doing anything, create object - let the script continue with its work). I used "removed" and "reinstate" and was told this is too ambiguous. I now contemplate about "pushed" and "enabled" but this too sounds too vague. I'm also thinking about "pulled" (object removed) vs. "rearmed" (object created).

It's important that the terminology will be clear since if this script is used then this is expected to happen during emergency, so we want to minimize confusion as much as possible.

I suppose the problem is the inherent "double negative".

So far I didn't find any common name used to describe these actions. Wikipedia and other places describe what the switch is, but not actions of enabling or disabling it.

Any ideas?

答:
I would say that the system would be:

Enabled if the object is present

Disabled if the object is absent

Placing the object would enable the script.

Removing (deleting) the object would disable the script.

You could even call the file enable-xxx-script to make it more obvious.

Title: Correct terminology for Dead Man Switch


问:
How can I pass encoded values by `Link` using react-router?
Sorry to disturb, guys. I'm so new to react and react-router and I've been struggling for few days already.

Actually I am trying to pass some values before jumping to a new page (using Link attribute target="_blank") and in the new page, I want to use these values to communicate with the server and when the data from the server comes, the new page will load its content.

the route path is something like this

```<code><Route path="/root/the_page" component={the_component} />
</code>```

and the link will be like this:

```<code><Link to="/root/the_page" target="_blank" />
</code>```

What I have checked is this discussion about using a function to pass the value, but I really cannot re-produce it. As for the query-params, I cannot retrieve the query in this.props.location even I set the link as follows:

```<code><Link to={{pathname:"/root/the_page", query: {the_key: the_value}}} target="_blank" />
</code>```

Any advice will be helpful.

Thank you in advance!

答:
Check this codepen (click on users submenu item). The new window is opened with params.

```<code><Link to={{pathname: "/users", query: { someParam: 'someValue' }}} target="_blank">Users</Link>
</code>```

https://codepen.io/Kotuhan/pen/JOJzNY

Then, you can get your params from window.location.search string.

Body:
Sorry to disturb, guys. I'm so new to react and react-router and I've been struggling for few days already.

Actually I am trying to pass some values before jumping to a new page (using Link attribute target="_blank") and in the new page, I want to use these values to communicate with the server and when the data from the server comes, the new page will load its content.

the route path is something like this

<Route path="/root/the_page" component={the_component} />

and the link will be like this:

<Link to="/root/the_page" target="_blank" />

What I have checked is this discussion about using a function to pass the value, but I really cannot re-produce it. As for the query-params, I cannot retrieve the query in this.props.location even I set the link as follows:

<Link to={{pathname:"/root/the_page", query: {the_key: the_value}}} target="_blank" />

Any advice will be helpful.

Thank you in advance!

Body:
Check this codepen (click on users submenu item). The new window is opened with params.

<Link to={{pathname: "/users", query: { someParam: 'someValue' }}} target="_blank">Users</Link>

https://codepen.io/Kotuhan/pen/JOJzNY

Then, you can get your params from window.location.search string.


问:
Displaying appropriate error message when data from JSON doesn't get fetched in HTML
I've a sample JSON:

```<code>[
    {
        "componentid": 4,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "theme",
        "shortdesc": "to set theme for different applications"
    },
    {
        "componentid": 7,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "preferences",
        "shortdesc": "preferences screen for apps"
    }
]
</code>```

I've a JavaScript code that goes through above JSON and fetches the data

function prepareTopComponentList(data) {

```<code>    try {

        var preparedHtml = "";

        for (var count = 0; count < data.length; count++) {
            preparedHtml += "<div class=\"col-lg-4\" style=\"margin-top: 20px\">\n" +
                "                <div class=\"card wow fadeIn\" data-wow-delay=\"0.2s\">\n" +
                "                    <img class=\"img-fluid\" src=\"";
            preparedHtml += data[count].displayImageUrl;
            preparedHtml += "\" alt=\"N/A\">\n" +
                "                    <div class=\"card-body\">\n" +
                "                        <h4 class=\"card-title\">";
            preparedHtml += data[count].title;
            preparedHtml += "</h4>\n" +
                "                        <p class=\"card-text\">";
            preparedHtml += data[count].shortdesc;
            preparedHtml += "</p>\n" +
                "                        <a  onclick='Redirect(this)' href='#' class=\"btn btn-info\" id=\"";
            preparedHtml += "component_desc_=" + data[count].componentid;
            preparedHtml += "\">Learn more</a>\n" +
                "                    </div>\n" +
                "\n" +
                "                </div>\n" +
                "            </div>";

        }

        $("#div_top_component").append(preparedHtml);

    } catch (err) {

    }

}
function Redirect(element) {
    try {
        window.location = "http://localhost:9090/Reusable%20Components/pages/homepage.php?" + element.id;
    } catch (err) {

    }

}
</code>```

I also have a HTML code for displaying error:

```<code><!--Error/Warning Modal-->
<div class="modal fade" id="modal_show_error" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title" id="modal_error_title"></h4>
            </div>
            <div class="modal-body">
                <p id="modal_error_description"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">Okay</button>
            </div>
        </div>

    </div>
</div>
</code>```

I'm fetching componentid from JSON. But if it is NULL, then I want a bootstrap error pop up saying that componentid is NULL. Catch block of above JavaScript code is empty, I'm not getting what code I should put there to get bootstrap error pop up.

答:
If you want no string to be appened at all if one of the items is invalid, you can use the following (I did it in es6, but you get the id)

If you want only the valid items to be appened, you can just replace the throw statement by return memo;

```<code>try {
    const preparedHtml = data.reduce((memo, item) => {
        if(typeof(item.componentid) === typeof(null))
            throw new Error(`All items must have a componentid`);
        const htmlChunk = `<div class="col-lg-4" style="margin-top: 20px">\n
            <div class="col-lg-4" style="margin-top: 20px">\n
                <div class="card wow fadeIn" data-wow-delay="0.2s">\n
                    <img class="img-fluid" src="${item.displayImageUrl} alt="N/A">\n
                    <div class="card-body">\n
                        <h4 class="card-title">${item.title}</h4>\n
                        <p class="card-text">${item.shortdesc}</p>\n
                        <a  onclick='Redirect(this)'
                            href='#' class=\"btn btn-info\" id=\""
                            component_desc_="${item.componentid}">Learn more</a>\n
                    </div>\n\n
                </div>\n
            </div>`;
        return memo.concat(htmlChunk);
        }, '');
        $('#div_top_component').append(preparedHtml);
    } catch (err) {
        //bootstrap modal code
    }
</code>```

Body:
I've a sample JSON:

[
    {
        "componentid": 4,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "theme",
        "shortdesc": "to set theme for different applications"
    },
    {
        "componentid": 7,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "preferences",
        "shortdesc": "preferences screen for apps"
    }
]

I've a JavaScript code that goes through above JSON and fetches the data

function prepareTopComponentList(data) {

    try {

        var preparedHtml = "";

        for (var count = 0; count < data.length; count++) {
            preparedHtml += "
\n" +
                "
\n" +
                "                    \n" +
                "
\n" +
                "
";
            preparedHtml += data[count].title;
            preparedHtml += "
\n" +
                "
";
            preparedHtml += data[count].shortdesc;
            preparedHtml += "
\n" +
                "                        Learn more\n" +
                "
\n" +
                "\n" +
                "
\n" +
                "
";

        }

        $("#div_top_component").append(preparedHtml);

    } catch (err) {

    }

}
function Redirect(element) {
    try {
        window.location = "http://localhost:9090/Reusable%20Components/pages/homepage.php?" + element.id;
    } catch (err) {

    }

}

I also have a HTML code for displaying error:

                <button type="button" class="close" data-dismiss="modal">×</button>

                <button type="button" class="btn btn-primary" data-dismiss="modal">Okay</button>

I'm fetching componentid from JSON. But if it is NULL, then I want a bootstrap error pop up saying that componentid is NULL. Catch block of above JavaScript code is empty, I'm not getting what code I should put there to get bootstrap error pop up.

Body:
If you want no string to be appened at all if one of the items is invalid, you can use the following (I did it in es6, but you get the id)

If you want only the valid items to be appened, you can just replace the throw statement by return memo;

try {
    const preparedHtml = data.reduce((memo, item) => {
        if(typeof(item.componentid) === typeof(null))
            throw new Error(`All items must have a componentid`);
        const htmlChunk = `<div class="col-lg-4" style="margin-top: 20px">\n
            <div class="col-lg-4" style="margin-top: 20px">\n
                <div class="card wow fadeIn" data-wow-delay="0.2s">\n
                    <img class="img-fluid" src="${item.displayImageUrl} alt="N/A">\n
                    <div class="card-body">\n
                        <h4 class="card-title">${item.title}</h4>\n
                        <p class="card-text">${item.shortdesc}</p>\n
                        <a  onclick='Redirect(this)'
                            href='#' class=\"btn btn-info\" id=\""
                            component_desc_="${item.componentid}">Learn more</a>\n
                    </div>\n\n
                </div>\n
            </div>`;
        return memo.concat(htmlChunk);
        }, '');
        $('#div_top_component').append(preparedHtml);
    } catch (err) {
        //bootstrap modal code
    }


问:
Mercurial 1.7.3 certificate error Windows
I'm trying to clone my repo in Mercurial 1.7.3 on Windows and get the following error:

C:\Dev>hg clone https://dev.mydomain.com/repo
abort: dev.mydomain.com certificate error: certificate is for *.webfaction.com

Do I have to pay for a real SSL certificate to get this to work at all or is there some way I can force it to do the clone?  (I understand that this is not a good idea in general for security reasons.  I would just like to get the code checked out.)

Thanks,
Brian

答:
You should look at this: CACertificates.

Mercurial just recently started verifying certificates.  You can create exceptions for self-signed certs.


问:
how to get specific part from string in sql
I want to retrieve file names from urls in sql.
for example:

Input:

url:

https://www.google.co.in/root/subdir/file.extension?p1=v1&p2=v2
https://www.abxdhcak.com/sitemap-companies.xml

then Output should be:

file.extension

sitemap-companies.xml

答:
To match your expected output you can use REGEXP_REPLACE

```<code>REGEXP_REPLACE(txt, '^.*/|\?.*$') as rg
</code>```

This does 2 things:

```<code>'^.*/'
</code>```

This removes all characters up to and including the last forward-slash in the string.

```<code>'\?.*$'
</code>```

This removes all characters after and including a question mark.

This may not work for all cases, but it works for the examples provided.

Body:
To match your expected output you can use REGEXP_REPLACE

REGEXP_REPLACE(txt, '^.*/|\?.*$') as rg

This does 2 things:

'^.*/'

This removes all characters up to and including the last forward-slash in the string.

'\?.*$'

This removes all characters after and including a question mark.

This may not work for all cases, but it works for the examples provided.


问:
:app:mergeDebugResources FAILED Error: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.AaptException
Jenkins returns me the following error when I run the gradlew assembleDebug.
In Android Studio 3.0 I don't have this problem.
Does anyone know the reason?

```<code>AAPT err(Facade for 2147483181): \\?\C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-1\files-1.1\appcompat-v7-25.3.1.aar\e9979393938d5eeff956c6f4b76be0a3\res\drawable-xxhdpi-v4\abc_switch_track_mtrl_alpha.9.png ERROR: Unable to open PNG file
:app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.AaptException:

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:mergeDebugResources'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
    at
</code>```

What I tryied

gradle.properties

```<code>android.enableAapt2=false
android.enableBuildCache=true#and false
android.buildCacheDir=c:/temp/
</code>```

答:
Do you apply these operations separately?

Check the path to your project. If the path is too long, then move up your project to an upper directory.

If Path contains non-ASCII characters, correct it.

Clear the build cache. See this page for details.

On Windows:

gradlew cleanBuildCache

On Mac or Linux:

./gradlew cleanBuildCache

Go to gradle.properties file, and disable build cache.

// To re-enable
  the build cache, either delete the following

// line or set the
  property to 'true'.

android.enableBuildCache=false the other way is to
  modify build cache dir by adding first line can be skipped because
  true is the default value by 2.3

android.enableBuildCache=true

android.buildCacheDir =c:\temp\

Invalidate Caches / Restart then Clean and Rebuild project

Body:
Jenkins returns me the following error when I run the gradlew assembleDebug.
In Android Studio 3.0 I don't have this problem.
Does anyone know the reason?

AAPT err(Facade for 2147483181): \\?\C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-1\files-1.1\appcompat-v7-25.3.1.aar\e9979393938d5eeff956c6f4b76be0a3\res\drawable-xxhdpi-v4\abc_switch_track_mtrl_alpha.9.png ERROR: Unable to open PNG file
:app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.AaptException:

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:mergeDebugResources'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
    at

What I tryied

gradle.properties

android.enableAapt2=false
android.enableBuildCache=true#and false
android.buildCacheDir=c:/temp/


问:
How to get back result as returned object type when executing script as PowerShell.exe -File
If I have a script (script.ps1) like below:

```<code>$dir = Get-Item "C:\Windows"
$dir
</code>```

and if I call it like:

```<code>$myDir = "script.ps1"
</code>```

I get back the $dir object in $myDir and if I use:

```<code>$myDir.Name
</code>```

I get:

```<code>Windows
</code>```

I have a scenario where I need to call scripts using

```<code>$myDir = Powershell.exe -File "script.ps1"
</code>```

With this, I end up getting the output in the form of a string array object and not in the form of the script-returned object as the command is apparently executed in a different session. Due to this, I can't call any property. E.g: $myDir.Name returns nothing

My question is, how do I get the returned object type back as the result in the above case. i.e, even when I execute

```<code>$myDir = Powershell.exe -File "script.ps1"
</code>```

$myDir.Name should return Windows. Is it even possible?

Thanks for any help.

答:
You could try like this :

script.ps1 (returns value of $dir):

```<code>$dir = Get-Item "C:\Windows"
return $dir
</code>```

script2.ps1 (returns name of $dir) :

```<code>$myDir = .\script.ps1
$myDir.Name
</code>```

$myDir.Name returns : Windows

Body:
If I have a script (script.ps1) like below:

$dir = Get-Item "C:\Windows"
$dir

and if I call it like:

$myDir = "script.ps1"

I get back the $dir object in $myDir and if I use:

$myDir.Name

I get:

Windows

I have a scenario where I need to call scripts using

$myDir = Powershell.exe -File "script.ps1"

With this, I end up getting the output in the form of a string array object and not in the form of the script-returned object as the command is apparently executed in a different session. Due to this, I can't call any property. E.g: $myDir.Name returns nothing

My question is, how do I get the returned object type back as the result in the above case. i.e, even when I execute

$myDir = Powershell.exe -File "script.ps1"

$myDir.Name should return Windows. Is it even possible?

Thanks for any help.

Body:
You could try like this :

script.ps1 (returns value of $dir):

$dir = Get-Item "C:\Windows"
return $dir

script2.ps1 (returns name of $dir) :

$myDir = .\script.ps1
$myDir.Name

$myDir.Name returns : Windows


问:
Compare values of two hashes with mixed types
I want to compare the hash if the key-value pairs are same in the second hash. I don't want to use smartmatch as it gives warnings.

What is the best way to compare two hashes with integers,strings and maybe also arrays in it?

```<code>use warnings;
use diagnostics;

my $hash1={"key_str"=>"a string", "key_int"=>4};
my $hash2={"key_str"=>"b string", "key_int"=>2};

foreach my $key ( keys(%$hash1) ) {
    if ($hash1->{$key} != $hash2->{$key}) {
        print($key);
    }
}
</code>```

the output as expected is:

```<code>Argument "b string" isn't numeric in numeric ne (!=) at hash_compare.pl line 8 (#1)
    (W numeric) The indicated string was fed as an argument to an operator
    that expected a numeric value instead.  If you're fortunate the message
    will identify which operator was so unfortunate.

Argument "a string" isn't numeric in numeric ne (!=) at hash_compare.pl line 8 (#1)
</code>```

答:
First, Perl does not have types. It does not distinguish between strings and numbers (on the outside).

Furthermore, it does not make a difference between numbers and strings on this level. The numerical context and string context matters if you check what's greater or less than. Consider this:

```<code>my $foo = 200;
my $bar = 99;
print $foo > $bar ? $foo : $bar;
</code>```

Obviously it will print 200, because 200 is numerically larger than 99.

```<code>my $foo = 200;
my $bar = 99;
print $foo gt $bar ? $foo : $bar;
</code>```

But this will print 99, because 9 is alphanumerically (as in string) greater than 2. It compared the numbers of the code points for the characters.

But if all you want to do is check for inequality, the ne operator is fine. Even when you are not sure whether there are things other than numbers in your input.

```<code>foreach my $key ( keys(%$hash1) ) {
    if ($hash1->{$key} ne $hash2->{$key}) {
        print($key);
    }
}
</code>```

eq (and ne) are smart enough to see if a number was initially a string or a number without quotes, because the internal representation of those differs.

Warning, technical details ahead.

Scalar values are saved in _SV_s. These in terms can contain different things. There's a special internal type for simple integers called IV, and also one called PV for strings. Perl internally converts between those two as needed when you use numbers inside of strings, or vise versa.

You can get some debugging information about the internal representation of data with Dump from Devel::Peek.

```<code>use Devel::Peek;

Dump("01");
Dump(01);
</code>```

This will output:

```<code>SV = PV(0x19560d0) at 0x19327d0
  REFCNT = 1
  FLAGS = (POK,READONLY,IsCOW,pPOK)
  PV = 0x1c94fd0 "01"\0
  CUR = 2
  LEN = 10
  COW_REFCNT = 0
SV = IV(0x19739b0) at 0x19739c0
  REFCNT = 1
  FLAGS = (IOK,READONLY,pIOK)
  IV = 1
</code>```

As you can see, the first one is a string, and the second one is a number.
But if we do this

```<code>print "01" eq 01;
</code>```

there is no output, because the 01 is an integer and will be converted to "1" for comparison. Since the 0 of "01" is not equal to 1, nothing gets printed.

If the values of your data structures are more complex, you need to walk the structure. Each type of element needs to have its own handling. There could be array references, hash references, scalar references, scalars, glob references, dualvars and so on. There might be objects that you want to treat specially.

I suggest taking a look at how Test::Deep implements this. If you decide to use it in production code (and not a unit test), you can use Test::Deep::NoTest.

Body:
I want to compare the hash if the key-value pairs are same in the second hash. I don't want to use smartmatch as it gives warnings.

What is the best way to compare two hashes with integers,strings and maybe also arrays in it?

use warnings;
use diagnostics;

my $hash1={"key_str"=>"a string", "key_int"=>4};
my $hash2={"key_str"=>"b string", "key_int"=>2};

foreach my $key ( keys(%$hash1) ) {
    if ($hash1->{$key} != $hash2->{$key}) {
        print($key);
    }
}

the output as expected is:

Argument "b string" isn't numeric in numeric ne (!=) at hash_compare.pl line 8 (#1)
    (W numeric) The indicated string was fed as an argument to an operator
    that expected a numeric value instead.  If you're fortunate the message
    will identify which operator was so unfortunate.

Argument "a string" isn't numeric in numeric ne (!=) at hash_compare.pl line 8 (#1)

Body:
First, Perl does not have types. It does not distinguish between strings and numbers (on the outside).

Furthermore, it does not make a difference between numbers and strings on this level. The numerical context and string context matters if you check what's greater or less than. Consider this:

my $foo = 200;
my $bar = 99;
print $foo > $bar ? $foo : $bar;

Obviously it will print 200, because 200 is numerically larger than 99.

my $foo = 200;
my $bar = 99;
print $foo gt $bar ? $foo : $bar;

But this will print 99, because 9 is alphanumerically (as in string) greater than 2. It compared the numbers of the code points for the characters.

But if all you want to do is check for inequality, the ne operator is fine. Even when you are not sure whether there are things other than numbers in your input.

foreach my $key ( keys(%$hash1) ) {
    if ($hash1->{$key} ne $hash2->{$key}) {
        print($key);
    }
}

eq (and ne) are smart enough to see if a number was initially a string or a number without quotes, because the internal representation of those differs.

Warning, technical details ahead.

Scalar values are saved in _SV_s. These in terms can contain different things. There's a special internal type for simple integers called IV, and also one called PV for strings. Perl internally converts between those two as needed when you use numbers inside of strings, or vise versa.

You can get some debugging information about the internal representation of data with Dump from Devel::Peek.

use Devel::Peek;

Dump("01");
Dump(01);

This will output:

SV = PV(0x19560d0) at 0x19327d0
  REFCNT = 1
  FLAGS = (POK,READONLY,IsCOW,pPOK)
  PV = 0x1c94fd0 "01"\0
  CUR = 2
  LEN = 10
  COW_REFCNT = 0
SV = IV(0x19739b0) at 0x19739c0
  REFCNT = 1
  FLAGS = (IOK,READONLY,pIOK)
  IV = 1

As you can see, the first one is a string, and the second one is a number.
But if we do this

print "01" eq 01;

there is no output, because the 01 is an integer and will be converted to "1" for comparison. Since the 0 of "01" is not equal to 1, nothing gets printed.

If the values of your data structures are more complex, you need to walk the structure. Each type of element needs to have its own handling. There could be array references, hash references, scalar references, scalars, glob references, dualvars and so on. There might be objects that you want to treat specially.

I suggest taking a look at how Test::Deep implements this. If you decide to use it in production code (and not a unit test), you can use Test::Deep::NoTest.


问:
DRY Then and Always in jQuery Promise
I have the following example JS code:

```<code>function loadData(url, data) {
    return $.get(url, data ? data : {});
}

function example1() {

    showSpinner();

    $.when(loadData('/example1', { hello: 'world' }))
        .then(function (resp) {
            // do something with the data
        })
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}

function example2() {

    showSpinner();

    $.when(loadData('/example2', { hello: 'world' }))
        .then(function (resp) {
            // do something with the data
        })
        .then(function () {
            // do something else
        })
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}
</code>```

Both example1() and example2() use the same promise logic and will do something different with the returned data and then always hide the spinner and handle the failures the same (if any). The issue is that I may want to do different things after the data is loaded in each example and have multiple then's follow.

However I am having to repeat the always and fail code. How can I make them more DRY so they are only written once but used in both scenarios (and other examples if need be). So I can't just move the when into a method and pass a callback as there maybe more than one and in different then`s. So this wouldn't work:

```<code>function customPromise(load, callback) {

    showSpinner();

    $.when(load)
    .then(function (resp) {
        callback(resp);
    })
    .always(function(){
        hideSpinner();
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        handleError(jqXHR);
    });

}

function example3() {
    customPromise(loadData('/example2', { hello: 'world' }));
}
</code>```

答:
I could think of something like this. Not sure if loadData should be held responsible for showing the spinner.

$(function() {
  example1();
  example2();
});

function loadData(url, data) {
  showSpinner();

  return $.get(url, data ? data : {})
    .always(function() {
      hideSpinner();
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
      handleError(jqXHR);
    });
}

function example1() {
  $.when(loadData('https://jsonplaceholder.typicode.com/users', {
      hello: 'world'
    }))
    .then(function(resp) {
      console.log(resp.length + ' lengthed data received');
    });
}

function example2() {
  $.when(loadData('https://jsonplaceholder.typicode.com/posts', {
      hello: 'world'
    }))
    .then(function(resp) {
      return resp;
    })
    .then(function(data) {
      console.log(data.length + ' lengthed data received');
    });
}

function showSpinner() {
  console.log('Showing spinner...');
}

function hideSpinner() {
  console.log('Hiding spinner...');
}

function handleError(xhr) {
  console.error(xhr);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: DRY Then and Always in jQuery Promise

Body:
I have the following example JS code:

function loadData(url, data) {
    return $.get(url, data ? data : {});
}

function example1() {

    showSpinner();

    $.when(loadData('/example1', { hello: 'world' }))
        .then(function (resp) {
            // do something with the data
        })
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}

function example2() {

    showSpinner();

    $.when(loadData('/example2', { hello: 'world' }))
        .then(function (resp) {
            // do something with the data
        })
        .then(function () {
            // do something else
        })
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}

Both example1() and example2() use the same promise logic and will do something different with the returned data and then always hide the spinner and handle the failures the same (if any). The issue is that I may want to do different things after the data is loaded in each example and have multiple then's follow.

However I am having to repeat the always and fail code. How can I make them more DRY so they are only written once but used in both scenarios (and other examples if need be). So I can't just move the when into a method and pass a callback as there maybe more than one and in different then`s. So this wouldn't work:

function customPromise(load, callback) {

    showSpinner();

    $.when(load)
    .then(function (resp) {
        callback(resp);
    })
    .always(function(){
        hideSpinner();
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        handleError(jqXHR);
    });

}

function example3() {
    customPromise(loadData('/example2', { hello: 'world' }));
}

Body:
I could think of something like this. Not sure if loadData should be held responsible for showing the spinner.

$(function() {
  example1();
  example2();
});

function loadData(url, data) {
  showSpinner();

  return $.get(url, data ? data : {})
    .always(function() {
      hideSpinner();
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
      handleError(jqXHR);
    });
}

function example1() {
  $.when(loadData('https://jsonplaceholder.typicode.com/users', {
      hello: 'world'
    }))
    .then(function(resp) {
      console.log(resp.length + ' lengthed data received');
    });
}

function example2() {
  $.when(loadData('https://jsonplaceholder.typicode.com/posts', {
      hello: 'world'
    }))
    .then(function(resp) {
      return resp;
    })
    .then(function(data) {
      console.log(data.length + ' lengthed data received');
    });
}

function showSpinner() {
  console.log('Showing spinner...');
}

function hideSpinner() {
  console.log('Hiding spinner...');
}

function handleError(xhr) {
  console.error(xhr);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Can you specify the HTTP method to use with Sinatra's redirect?
I have something like this:

```<code>post "/login" do

end

get "/login" do

end

post "/register" do
  ...
  redirect "/login" # I would like to redirect to get "/login" instead of post "login"
end
</code>```

Can I tell sinatra that I want to use get, and not have it implicitly select "post" ?

答:
Most browsers will reset to GET with a 302 (default) redirect. If you're up against a browser that is actually doing the correct thing and NOT changing the request method, you can force it to change with a 303.

```<code>redirect '/login', 303
</code>```

Source:
http://www.gittr.com/index.php/archive/details-of-sinatras-redirect-helper/

Body:
I have something like this:

post "/login" do

end

get "/login" do

end

post "/register" do
  ...
  redirect "/login" # I would like to redirect to get "/login" instead of post "login"
end

Can I tell sinatra that I want to use get, and not have it implicitly select "post" ?

Body:
Most browsers will reset to GET with a 302 (default) redirect. If you're up against a browser that is actually doing the correct thing and NOT changing the request method, you can force it to change with a 303.

redirect '/login', 303

Source:
http://www.gittr.com/index.php/archive/details-of-sinatras-redirect-helper/


问:
Data Frame Mapping in spark scala?
I have a data set like below

```<code>INo,Sc,Desc,Quan,IDate,UPice,CID,Country
1,2,"H,H",6,12-1-2010 8:26,2.55,c1,United Kingdom
2,3,"WE,RN",6,12-1-2010 8:26,3.39,c2,United Kingdom
3,3,CREAM ,8,12-1-2010 8:26,2.75,c3,United Kingdom
4,4,KLE,6,12-1-2010 8:26,3.39,c4,United Kingdom
5,5,"DI,AMR,ROR, ",2,1-7-2011 13:55,11.02,c5,United Kingdom
6,6,SU"asasa,1,12-9-2010 16:26,11.02,c6,United Kingdom
</code>```

I have created Data frame by executing below code:

```<code>case class Rating(CID: String, SC: String, rating: Double)
def parseRating(str: String): Rating = {
val fields = str.split(",")
Rating(fields(6), fields(1), 1.0D)
}
val ratings = spark.read.textFile("C:/Users/test/Desktop/test123.txt").map(parseRating).toDF().dropDuplicates("CID", "SC")
ratings.collect().map(t => println(t))
ratings.show()
</code>```

I am getting output like below

```<code>+---------------+---+------+
|            CID| SC|rating|
+---------------+---+------+
|12-9-2010 16:26|  6|   1.0|
|             c3|  3|   1.0|
|            CID| Sc|   1.0|
|             c4|  4|   1.0|
|           3.39|  3|   1.0|
|              2|  5|   1.0|
|           2.55|  2|   1.0|
+---------------+---+------+
</code>```

Here I came to because of field=str.split(",").input data is
6,6,"SET,CO,SU",1,12-9-2010 16:26,11.02,c6,United Kingdom

But my expected output is

```<code>+---------------+---+------+
|            CID| SC|rating|
+---------------+---+------+
|             c6|  6|   1.0|
|             c3|  3|   1.0|
|             c2|  3|   1.0|
|             c4|  4|   1.0|
|             c5|  5|   1.0|
|             c1|  2|   1.0|
+---------------+---+------+
</code>```

Please help me on this.

答:
You cannot directly split the each record with ",". since some of the column value has got "," as a value not as separator. e.g "H,H" in the first record,

You will need a regex to do the splitting as below,

```<code>def parseRating(str: String): Rating = {
val fields = str.split("\\,(?=([^\"]*\"[^\"]*\")*[^\"]*$)")
Rating(fields(6), fields(1), 1.0D)
}
</code>```

Also, your first line is the header.Read it with header true while loading the data file or filter the first line once its loaded.

Title: Data Frame Mapping in spark scala?

Body:
I have a data set like below

INo,Sc,Desc,Quan,IDate,UPice,CID,Country
1,2,"H,H",6,12-1-2010 8:26,2.55,c1,United Kingdom
2,3,"WE,RN",6,12-1-2010 8:26,3.39,c2,United Kingdom
3,3,CREAM ,8,12-1-2010 8:26,2.75,c3,United Kingdom
4,4,KLE,6,12-1-2010 8:26,3.39,c4,United Kingdom
5,5,"DI,AMR,ROR, ",2,1-7-2011 13:55,11.02,c5,United Kingdom
6,6,SU"asasa,1,12-9-2010 16:26,11.02,c6,United Kingdom

I have created Data frame by executing below code:

case class Rating(CID: String, SC: String, rating: Double)
def parseRating(str: String): Rating = {
val fields = str.split(",")
Rating(fields(6), fields(1), 1.0D)
}
val ratings = spark.read.textFile("C:/Users/test/Desktop/test123.txt").map(parseRating).toDF().dropDuplicates("CID", "SC")
ratings.collect().map(t => println(t))
ratings.show()

I am getting output like below

+---------------+---+------+
|            CID| SC|rating|
+---------------+---+------+
|12-9-2010 16:26|  6|   1.0|
|             c3|  3|   1.0|
|            CID| Sc|   1.0|
|             c4|  4|   1.0|
|           3.39|  3|   1.0|
|              2|  5|   1.0|
|           2.55|  2|   1.0|
+---------------+---+------+

Here I came to because of field=str.split(",").input data is
6,6,"SET,CO,SU",1,12-9-2010 16:26,11.02,c6,United Kingdom

But my expected output is

+---------------+---+------+
|            CID| SC|rating|
+---------------+---+------+
|             c6|  6|   1.0|
|             c3|  3|   1.0|
|             c2|  3|   1.0|
|             c4|  4|   1.0|
|             c5|  5|   1.0|
|             c1|  2|   1.0|
+---------------+---+------+

Please help me on this.

Body:
You cannot directly split the each record with ",". since some of the column value has got "," as a value not as separator. e.g "H,H" in the first record,

You will need a regex to do the splitting as below,

def parseRating(str: String): Rating = {
val fields = str.split("\\,(?=([^\"]*\"[^\"]*\")*[^\"]*$)")
Rating(fields(6), fields(1), 1.0D)
}

Also, your first line is the header.Read it with header true while loading the data file or filter the first line once its loaded.


问:
Multi selection spinner in android without AlertDialog
i want the same as this link  https://www.gorecess.com/ first spinner . multi selection spinner in android with checkbox .Show the spinner in dropdown. anyone know answer... </p>

答:
multi select spinner :

1- create a spinner in your own xml ,like this

```<code> <Spinner
    android:id="@+id/mySpinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_marginTop="1dp"/>
</code>```

2-create a custom dapter for spinner like this :

```<code>public class AdapterTagSpinnerItem extends ArrayAdapter<TagListSimpleSearch>
{
    private LayoutInflater mInflater;
    private List<TagListSimpleSearch> listState;
    public Spinner mySpinner = null;

    public AdapterTagSpinnerItem(Context context, int resource, List<TagListSimpleSearch> objects, Spinner mySpinner)
    {
        super(context, resource, objects);
        this.listState = objects;
        this.mySpinner = mySpinner;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent)
    {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(final int position, View convertView, ViewGroup parent)
    {
        String text = "";
        final ViewHolder holder;
        if (convertView == null)
        {
            holder = new ViewHolder();
            mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.spinner_item, null, false);
            holder.mTextView = convertView.findViewById(R.id.tvSpinnerItem);
            convertView.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }
        /**
         * check position , if position is zero we put space on top of list of spinner
         */
        if ((position == 0))
            text = oneSpace;
        /**
         * check position , if position is one we put cross mark before text to show that position used to be for clear all selected items on spinner
         */
        else if ((position == 1))
            text = "  " + String.valueOf((char) crossMarkAroundBox) + " " + listState.get(position).getTagText();
        /**
         * check position , if position is two we put check mark before text to show that position used to be for select all items on spinner
         */
        else if ((position == 2))
            text = "  " + String.valueOf((char) tikMarkAroundBox) + " " + listState.get(position).getTagText();
        /**
         * check position , if position is bigger than two we have to check that position is selected before or not and put check mark or dash before text
         */
        else
        {
            if (listState.get(position).isSelected())
            {
                text = "  " + String.valueOf((char) tikMark) + " " + listState.get(position).getTagText();
            }
            else
            {
                text = "  " + String.valueOf(dash) + " " + listState.get(position).getTagText();
            }
        }
        holder.mTextView.setText(text);
        holder.mTextView.setTag(position);
        holder.mTextView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                /**
                 * if you want open spinner after click on text for first time we have to open spinner programmatically
                 */
                mySpinner.performClick();
                int getPosition = (Integer) v.getTag();
                listState.get(getPosition).setSelected(!listState.get(getPosition).isSelected());
                notifyDataSetChanged();

                /**
                 * if clicked position is one
                 * that means you want clear all select item in list
                 */
                if (getPosition == 1)
                {
                    clearList();
                }
                /**
                 * if clicked position is two
                 * that means you want select all item in list
                 */
                else if (getPosition == 2)
                {
                    fillList();
                }
            }
        });
        return convertView;
    }

    /**
     * clear all items in list
     */
    public void clearList()
    {
        for (TagListSimpleSearch items : listState)
        {
            items.setSelected(false);
        }
        notifyDataSetChanged();
    }

    /**
     * select all items in list
     */
    public void fillList()
    {
        for (TagListSimpleSearch items : listState)
        {
            items.setSelected(true);
        }
        notifyDataSetChanged();
    }

    /**
     * view holder
     */
    private class ViewHolder
    {
        private TextView mTextView;
    }
}
</code>```

3- now you have to create object for adapter

```<code>public class TagListSimpleSearch {

    private String TagId;
    private String TagText;
    private boolean selected;

    public String getTagId() {
        return TagId;
    }

    public void setTagId(String TagId) {
        this.TagId = TagId;
    }

    public String getTagText() {
        return TagText;
    }

    public void setTagText(String tagText) {
        TagText = tagText;
    }

    public boolean isSelected()
    {
        return selected;
    }

    public void setSelected(boolean selected)
    {
        this.selected = selected;
    }
}
</code>```

4-fill spinner adapter in your activity

```<code>public static String oneSpace =" ";
public static int tikMark =0X2714;
public static int crossMark =0X2715;
public static int tikMarkAroundBox =0X2611;
public static int crossMarkAroundBox =0X274E;
public static String dash ="-";
private Spinner mySpinner;

mySpinner= (Spinner) findViewById(R.id.mySpinner);
List<TagListSimpleSearch> tagsNames = new ArrayList<>();
TagListSimpleSearch tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("0");
tagSpecific.setTagText(oneSpace);
tagsNames.add(tagSpecific);

tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("1");
tagSpecific.setTagText("select All Items");
tagsNames.add(tagSpecific);

tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("2");
tagSpecific.setTagText("remove All Items");
tagsNames.add(tagSpecific);

tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("0");
tagSpecific.setTagText("Item 0");
tagsNames.add(tagSpecific);

tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("1");
tagSpecific.setTagText("Item 1");
tagsNames.add(tagSpecific);

tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("2");
tagSpecific.setTagText("Item 2");
tagsNames.add(tagSpecific);

tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("3");
tagSpecific.setTagText("Item 3");
tagsNames.add(tagSpecific);

final AdapterTagSpinnerItem adapterTagSpinnerItem = new AdapterTagSpinnerItem(this, 0, tagsNames,mySpinner);
mySpinner.setAdapter(adapterTagSpinnerItem);
</code>```

Body:
multi select spinner :

1- create a spinner in your own xml ,like this

 <Spinner
    android:id="@+id/mySpinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_marginTop="1dp"/>

2-create a custom dapter for spinner like this :

public class AdapterTagSpinnerItem extends ArrayAdapter<TagListSimpleSearch>
{
    private LayoutInflater mInflater;
    private List<TagListSimpleSearch> listState;
    public Spinner mySpinner = null;

    public AdapterTagSpinnerItem(Context context, int resource, List<TagListSimpleSearch> objects, Spinner mySpinner)
    {
        super(context, resource, objects);
        this.listState = objects;
        this.mySpinner = mySpinner;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent)
    {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(final int position, View convertView, ViewGroup parent)
    {
        String text = "";
        final ViewHolder holder;
        if (convertView == null)
        {
            holder = new ViewHolder();
            mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.spinner_item, null, false);
            holder.mTextView = convertView.findViewById(R.id.tvSpinnerItem);
            convertView.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }
        /**
         * check position , if position is zero we put space on top of list of spinner
         */
        if ((position == 0))
            text = oneSpace;
        /**
         * check position , if position is one we put cross mark before text to show that position used to be for clear all selected items on spinner
         */
        else if ((position == 1))
            text = "  " + String.valueOf((char) crossMarkAroundBox) + " " + listState.get(position).getTagText();
        /**
         * check position , if position is two we put check mark before text to show that position used to be for select all items on spinner
         */
        else if ((position == 2))
            text = "  " + String.valueOf((char) tikMarkAroundBox) + " " + listState.get(position).getTagText();
        /**
         * check position , if position is bigger than two we have to check that position is selected before or not and put check mark or dash before text
         */
        else
        {
            if (listState.get(position).isSelected())
            {
                text = "  " + String.valueOf((char) tikMark) + " " + listState.get(position).getTagText();
            }
            else
            {
                text = "  " + String.valueOf(dash) + " " + listState.get(position).getTagText();
            }
        }
        holder.mTextView.setText(text);
        holder.mTextView.setTag(position);
        holder.mTextView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                /**
                 * if you want open spinner after click on text for first time we have to open spinner programmatically
                 */
                mySpinner.performClick();
                int getPosition = (Integer) v.getTag();
                listState.get(getPosition).setSelected(!listState.get(getPosition).isSelected());
                notifyDataSetChanged();

                /**
                 * if clicked position is one
                 * that means you want clear all select item in list
                 */
                if (getPosition == 1)
                {
                    clearList();
                }
                /**
                 * if clicked position is two
                 * that means you want select all item in list
                 */
                else if (getPosition == 2)
                {
                    fillList();
                }
            }
        });
        return convertView;
    }

    /**
     * clear all items in list
     */
    public void clearList()
    {
        for (TagListSimpleSearch items : listState)
        {
            items.setSelected(false);
        }
        notifyDataSetChanged();
    }

    /**
     * select all items in list
     */
    public void fillList()
    {
        for (TagListSimpleSearch items : listState)
        {
            items.setSelected(true);
        }
        notifyDataSetChanged();
    }

    /**
     * view holder
     */
    private class ViewHolder
    {
        private TextView mTextView;
    }
}

3- now you have to create object for adapter

public class TagListSimpleSearch {

    private String TagId;
    private String TagText;
    private boolean selected;

    public String getTagId() {
        return TagId;
    }

    public void setTagId(String TagId) {
        this.TagId = TagId;
    }

    public String getTagText() {
        return TagText;
    }

    public void setTagText(String tagText) {
        TagText = tagText;
    }

    public boolean isSelected()
    {
        return selected;
    }

    public void setSelected(boolean selected)
    {
        this.selected = selected;
    }
}

4-fill spinner adapter in your activity

public static String oneSpace =" ";
public static int tikMark =0X2714;
public static int crossMark =0X2715;
public static int tikMarkAroundBox =0X2611;
public static int crossMarkAroundBox =0X274E;
public static String dash ="-";
private Spinner mySpinner;

mySpinner= (Spinner) findViewById(R.id.mySpinner);
List<TagListSimpleSearch> tagsNames = new ArrayList<>();
TagListSimpleSearch tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("0");
tagSpecific.setTagText(oneSpace);
tagsNames.add(tagSpecific);

tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("1");
tagSpecific.setTagText("select All Items");
tagsNames.add(tagSpecific);

tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("2");
tagSpecific.setTagText("remove All Items");
tagsNames.add(tagSpecific);

tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("0");
tagSpecific.setTagText("Item 0");
tagsNames.add(tagSpecific);

tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("1");
tagSpecific.setTagText("Item 1");
tagsNames.add(tagSpecific);

tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("2");
tagSpecific.setTagText("Item 2");
tagsNames.add(tagSpecific);

tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("3");
tagSpecific.setTagText("Item 3");
tagsNames.add(tagSpecific);

final AdapterTagSpinnerItem adapterTagSpinnerItem = new AdapterTagSpinnerItem(this, 0, tagsNames,mySpinner);
mySpinner.setAdapter(adapterTagSpinnerItem);


问:
RxSwift/Moya - Sequence won't start if it is returned via function
I try to start a network request via Moya.

```<code>    let provider = MoyaProvider<User>()

    provider.rx.request(.Auth(username: username, password: password))
        .filterSuccessfulStatusAndRedirectCodes()
        .debug()
        .mapOptional(to: Authentication.self)
        .observeOn(MainScheduler.instance)
        .subscribe {
            event in
            print(event)
        }.disposed(by: disposeBag)
</code>```

When I do it the above way everything works fine.

But if I do it this way:

```<code>func logIn(username: username, password: password) -> Single<Authentication?> {

    let provider = MoyaProvider<User>()

    return provider.rx.request(.Auth(username: username, password: password))
        .filterSuccessfulStatusAndRedirectCodes()
        .debug()
        .mapOptional(to: Authentication.self)
}
</code>```

And then calling the function:

```<code>self.loginIn(username: username, password: password)
        .observeOn(MainScheduler.instance)
        .subscribe {
            event in
            print(event)
        }
        .disposed(by: disposeBag)
</code>```

The debug output states that it get subscribed, but it won't start the sequence if i return it via the function.

答:
I have solved the error. You need to retain the provider. Store it in an instance variable and it will not be disposed.

https://github.com/Moya/Moya/issues/1460

Body:
I try to start a network request via Moya.

    let provider = MoyaProvider<User>()

    provider.rx.request(.Auth(username: username, password: password))
        .filterSuccessfulStatusAndRedirectCodes()
        .debug()
        .mapOptional(to: Authentication.self)
        .observeOn(MainScheduler.instance)
        .subscribe {
            event in
            print(event)
        }.disposed(by: disposeBag)

When I do it the above way everything works fine.

But if I do it this way:

func logIn(username: username, password: password) -> Single<Authentication?> {

    let provider = MoyaProvider<User>()

    return provider.rx.request(.Auth(username: username, password: password))
        .filterSuccessfulStatusAndRedirectCodes()
        .debug()
        .mapOptional(to: Authentication.self)
}

And then calling the function:

self.loginIn(username: username, password: password)
        .observeOn(MainScheduler.instance)
        .subscribe {
            event in
            print(event)
        }
        .disposed(by: disposeBag)

The debug output states that it get subscribed, but it won't start the sequence if i return it via the function.


问:
ERROR 1062 (23000): Duplicate entry '' for key 'PRIMARY'
I have a MySQL table in which already store many important data, but it's doesn't have any primary key and auto increment ids. Now I want to set primary key on my ID column but I don't need a Auto_increment ids in any column in my table. So when I try to set primary key on ID column then this error is coming "ERROR 1062 (23000): Duplicate entry '' for key 'PRIMARY'"

So..How can I solve this prob. Can I set Primary key without Auto_increment ids?

答:
Just restore the dump with -f (--force) or --insert-ignore to carry the process it will encounter the errors and proceeds the dump or insert </p>

```<code>mysql -u root -p -f <NAME OF DB> < <BACKUP DB>.sql
</code>```

Body:
Just restore the dump with -f (--force) or --insert-ignore to carry the process it will encounter the errors and proceeds the dump or insert

mysql -u root -p -f <NAME OF DB> < <BACKUP DB>.sql


问:
Converting substrings of music from BASIC to C++
In many versions of Basic, Music can be played with the statement PLAY. It accepts as its arguments, notes, octaves, etc, but also substrings.
as an example, A$="BCD": B$="FDE": PLAY "XA$;O3XB$;" is equivalent to PLAY "BCDO3FDE"

I want to do the same in C++. I know that is is difficult, as BASIC is interpreted and C++ compiled, but is there a way ?

To be more precise, I already have a function PlayString(AnsiString ss), that is able to play a string made of notes (e.g. "BCD"), octaves (prefix O plus a digit, e.g."O2"), note length (prefix L plus a number, e.g."L4"), so a string to play could be "BCDO3FDE" (the same as above).

I want to add to it the necessary code to play a substring, say with prefix X, so that code as in the line below would work :

```<code>AnsiString aa="BCD", bb="FDE";PlayString("Xaa;O3Xbb;");
</code>```

and be equivalent to

```<code>PlayString("BCDO3FDE");
</code>```

Idea(s), anyone ?

答:
As written, this cannot work. The reason is exactly what you suspected: C++ is compiled. Variable names do not exist at run time. But PlayString interprets its argument only at run time. You need

```<code>PlayString(aa+"O3"+bb);
</code>```

Body:
In many versions of Basic, Music can be played with the statement PLAY. It accepts as its arguments, notes, octaves, etc, but also substrings.
as an example, A$="BCD": B$="FDE": PLAY "XA$;O3XB$;" is equivalent to PLAY "BCDO3FDE"

I want to do the same in C++. I know that is is difficult, as BASIC is interpreted and C++ compiled, but is there a way ?

To be more precise, I already have a function PlayString(AnsiString ss), that is able to play a string made of notes (e.g. "BCD"), octaves (prefix O plus a digit, e.g."O2"), note length (prefix L plus a number, e.g."L4"), so a string to play could be "BCDO3FDE" (the same as above).

I want to add to it the necessary code to play a substring, say with prefix X, so that code as in the line below would work :

AnsiString aa="BCD", bb="FDE";PlayString("Xaa;O3Xbb;");

and be equivalent to

PlayString("BCDO3FDE");

Idea(s), anyone ?

Body:
As written, this cannot work. The reason is exactly what you suspected: C++ is compiled. Variable names do not exist at run time. But PlayString interprets its argument only at run time. You need

PlayString(aa+"O3"+bb);


问:
django ajax MultiValueDictKeyError
I am receiving this error:

```<code>MultiValueDictKeyError at /orders/ajax/add_order_line
"'cart'"
</code>```

Here is my script

```<code>var cart = {
    0: {
        id: "1",
        quantity: 50
    }
}

$.ajax({
    url: myURL,
    type: "post",
    data: {cart: cart},
    success: function() {},
    error: function(){}
});
</code>```

Meanwhile in my django views, the error was found in this line:

```<code>def something(request):
    cart = request.POST['cart']
</code>```

答:
Use get method of multivaluedict

```<code>request.POST.get('cart')
</code>```

Title: django ajax MultiValueDictKeyError

Body:
I am receiving this error:

MultiValueDictKeyError at /orders/ajax/add_order_line
"'cart'"

Here is my script

var cart = {
    0: {
        id: "1",
        quantity: 50
    }
}

$.ajax({
    url: myURL,
    type: "post",
    data: {cart: cart},
    success: function() {},
    error: function(){}
});

Meanwhile in my django views, the error was found in this line:

def something(request):
    cart = request.POST['cart']

Body:
Use get method of multivaluedict

request.POST.get('cart')


问:
Update data frame in R with another one
I have two data frames. Df1 that is the main one and Df2 that is updated one. I am trying to get value from df2 to df1 but anyting I do seems not to me working. Match / merge gives NAs and all sort of join commands do not work either. </p>

```<code>V1 <- c("AB1002017103", "AB1002017103", "AB1002017103"
,"AB1002017104"
,"AB1002017105"
,"AB1002017106"
,"AB1002017107"
,"AB1002017108"
,"AB1002017109"
,"AB1002017111")
V2 <- c(249,242,253,211,264,237,291,286,232,0)
df1 <- data.frame(V1,V2)
df1$V1 <- as.character(as.factor(df1$V1))

V1 <- c("AB1002017111"); V2 <- 165
df2 <- data.frame(V1,V2)
df2$V1 <- as.character(as.factor(df2$V1))
</code>```

<p>The output should be all from df1 with the last value 165. Any ideas please? Just and example of the match I use: </p>

```<code>df1$V2 <- df2$V2[match(df1$V1,df2$V1)]
</code>```

答:
Based on help from akrun (much appreciated) below code was found working.

df1$V2[match(df2$V1,df1$V1, nomatch=0)] <- df2$V2[match(df1$V1,df2$V1, nomatch = 0)]

Thanks again akrun!

Title: Update data frame in R with another one

Body:
I have two data frames. Df1 that is the main one and Df2 that is updated one. I am trying to get value from df2 to df1 but anyting I do seems not to me working. Match / merge gives NAs and all sort of join commands do not work either.

V1 <- c("AB1002017103", "AB1002017103", "AB1002017103"
,"AB1002017104"
,"AB1002017105"
,"AB1002017106"
,"AB1002017107"
,"AB1002017108"
,"AB1002017109"
,"AB1002017111")
V2 <- c(249,242,253,211,264,237,291,286,232,0)
df1 <- data.frame(V1,V2)
df1$V1 <- as.character(as.factor(df1$V1))

V1 <- c("AB1002017111"); V2 <- 165
df2 <- data.frame(V1,V2)
df2$V1 <- as.character(as.factor(df2$V1))

The output should be all from df1 with the last value 165. Any ideas please? Just and example of the match I use:

df1$V2 <- df2$V2[match(df1$V1,df2$V1)]


问:
JQuery:Not able to fetch value of "td" when onclick on button happens second time
Following is the code of my table. In the action column i have a buttons named accept and reject. On click on reject I want to get the values of 2 and 3 "td" present in that "tr".

```<code><table class="w3-table" id="tbl_task" width="100%">
<tr>
    {% for ele in d|slice:":1" %} {% for key in ele.keys %}
    <th>{{ key }}</th>
    {% endfor %} {% endfor %}
    <th>Action</th>
</tr>
{% for ele in d %}
<tr class="class_1">
    {% for k, v in ele.iteritems %} {% if k in "Assigned_Users" %}
    <td>
        {% if v|length > 2 %}
        <div style="width: 80%;max-height: 37px;overflow:auto;margin-left: 32px;">
            {% for ch in v %} {{ ch|linebreaksbr }} {% endfor %}
        </div>
        {% else %} {% for ch in v %} {{ ch }} {% endfor %} {% endif %}
    </td>
    {% else %}
    <td>
        {{ v }}
    </td>
    {% endif %} {% endfor %}
    <td class="noexcel">
        <div id="td_button_div">
            <button id="status_accepted" class="btn btn-default btn-sm" name="accept">
                <span class="glyphicon glyphicon-ok"></span> Approve
            </button>
            <button id="status_rejected" class="btn btn-default btn-sm" name="reject" data-toggle="modal" data-target="#myModal">
                <span class="glyphicon glyphicon-remove"></span> Reject
            </button>
            <!-- Modal -->
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                            <h4 class="modal-title" id="myModalLabel">Modal title
                            </h4>
                        </div>
                        <div class="modal-body">
                            <label>Remarks</label>
                            <textarea name="textarea" style="color:black;width:100%"></textarea>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close
                            </button>
                            <button type="button" class="btn btn-primary" id="save_remarks">Save changes
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </td>
</tr>
{% endfor %}
</code>```

At first time I am getting data properly but at second click only modal is displayed with the existing values.

Following is my JQuery code:

```<code>$('#status_rejected').on('click', function(e){

        var current_row = ' ';
        var task_name = ' ';
        var current_status = ' ';
        var notes = ' ';

        alert("inside reject function");

        current_row = $(this).closest('tr');

        task_name = current_row.find("td:eq(2)").text();

        current_status = current_row.find("td:eq(0)").text();

        alert("cstatus--->"+$.trim(current_status)+"\n"+"tname"+$.trim(task_name));
        var status = "reject"

        $("textarea").val(" ");

        $("#save_remarks").on('click',function(){
            alert("inside save changes on click");

            notes = $.trim($("textarea").val());
            alert("cstatus"+$.trim(current_status)+"\n"+"tname"+$.trim(task_name));

        });
});// end of show model
</code>```

Need help with this?

答:
I was able resolve this in the following way:</p>

```<code>$('.noexcel #status_rejected').on('click', function(e){

            var current_row = ' ';
            var task_name = ' ';
            var current_status = ' ';
            var notes = ' ';
            var cnt = 0;

            current_row = $(this).closest('tr');

            task_name = current_row.find("td:eq(2)").text();

            current_status = current_row.find("td:eq(0)").text();

            var status = "reject"

            $("textarea").val(" ");

            $("#save_remarks").on('click',function(){

                notes = $.trim($("textarea").val());

                if(current_status != ' ' && task_name != ' ' && notes != ' ' && current_row != ' '){
                    ajax_call(current_row, current_status, task_name, notes, status);
                    current_row = current_status = task_name = notes = ' ';
                }
            }); // end of onclick of modal save button
    });// end of show model

function ajax_call(current_row, current_status, task_name, notes, status){
    $.ajax({
            type:'post',
            url:'/ajax/change_ftrack_status/',
            data:{
                currentStatus : current_status,
                taskName : task_name,
                status : status,
                notes : notes
            },
            success:function(data){
                $.each(data, function(key, value){
                if (key == "ftrack_status"){
                    current_row.find("td:eq(0)").html(value);
                }
                else if (key == "updated_on"){
                    current_row.find("td:eq(1)").html(value);
                }
            }); // end of for each
            // disable the reject button
            current_row.find("td #status_rejected").prop("disabled", true);
            }
           }); //end of ajax
}
</code>```

Body:
Following is the code of my table. In the action column i have a buttons named accept and reject. On click on reject I want to get the values of 2 and 3 "td" present in that "tr".

    {% for ele in d|slice:":1" %} {% for key in ele.keys %}
    {{ key }}
    {% endfor %} {% endfor %}
    Action

{% for ele in d %}

    {% for k, v in ele.iteritems %} {% if k in "Assigned_Users" %}

        {% if v|length > 2 %}

            {% for ch in v %} {{ ch|linebreaksbr }} {% endfor %}

        {% else %} {% for ch in v %} {{ ch }} {% endfor %} {% endif %}

    {% else %}

        {{ v }}

    {% endif %} {% endfor %}

            <button id="status_accepted" class="btn btn-default btn-sm" name="accept">
                 Approve
            </button>
            <button id="status_rejected" class="btn btn-default btn-sm" name="reject" data-toggle="modal" data-target="#myModal">
                 Reject
            </button>

                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                ×
                            </button>

Modal title

                            Remarks
                            <textarea name="textarea" style="color:black;width:100%"></textarea>

                            <button type="button" class="btn btn-default" data-dismiss="modal">Close
                            </button>
                            <button type="button" class="btn btn-primary" id="save_remarks">Save changes
                            </button>

{% endfor %}

At first time I am getting data properly but at second click only modal is displayed with the existing values.

Following is my JQuery code:

$('#status_rejected').on('click', function(e){

        var current_row = ' ';
        var task_name = ' ';
        var current_status = ' ';
        var notes = ' ';

        alert("inside reject function");

        current_row = $(this).closest('tr');

        task_name = current_row.find("td:eq(2)").text();

        current_status = current_row.find("td:eq(0)").text();

        alert("cstatus--->"+$.trim(current_status)+"\n"+"tname"+$.trim(task_name));
        var status = "reject"

        $("textarea").val(" ");

        $("#save_remarks").on('click',function(){
            alert("inside save changes on click");

            notes = $.trim($("textarea").val());
            alert("cstatus"+$.trim(current_status)+"\n"+"tname"+$.trim(task_name));

        });
});// end of show model

Need help with this?

Body:
I was able resolve this in the following way:

$('.noexcel #status_rejected').on('click', function(e){

            var current_row = ' ';
            var task_name = ' ';
            var current_status = ' ';
            var notes = ' ';
            var cnt = 0;

            current_row = $(this).closest('tr');

            task_name = current_row.find("td:eq(2)").text();

            current_status = current_row.find("td:eq(0)").text();

            var status = "reject"

            $("textarea").val(" ");

            $("#save_remarks").on('click',function(){

                notes = $.trim($("textarea").val());

                if(current_status != ' ' && task_name != ' ' && notes != ' ' && current_row != ' '){
                    ajax_call(current_row, current_status, task_name, notes, status);
                    current_row = current_status = task_name = notes = ' ';
                }
            }); // end of onclick of modal save button
    });// end of show model

function ajax_call(current_row, current_status, task_name, notes, status){
    $.ajax({
            type:'post',
            url:'/ajax/change_ftrack_status/',
            data:{
                currentStatus : current_status,
                taskName : task_name,
                status : status,
                notes : notes
            },
            success:function(data){
                $.each(data, function(key, value){
                if (key == "ftrack_status"){
                    current_row.find("td:eq(0)").html(value);
                }
                else if (key == "updated_on"){
                    current_row.find("td:eq(1)").html(value);
                }
            }); // end of for each
            // disable the reject button
            current_row.find("td #status_rejected").prop("disabled", true);
            }
           }); //end of ajax
}


问:
ES6 Display div to none when button is clicked
I'm new at ES6 and I'm trying to display to none a div when an inner button is clicked.

I tried this but it's not working:

const hide = () => {
  const z = document.getElementById('button')
  const y = document.getElementById('block')
  z.onclick = () => {
    y.style.display='none'
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="block">
  <button id="button" onClick="hide()">my button</button>
</div></code>```

Any help please?

答:
You are attaching an event handler for first time. After the second time it will work and will again attach an event handler.

You don't need to use inline event handler, avoid this type of event handler attachement. You can just remove the hide function part serving the content. When your code runs, it will attach the event handler

const z = document.getElementById('button');
const y = document.getElementById('block');

z.onclick = () => {
    y.style.display = 'none';
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="block">
  <button id="button">my button</button>
</div></code>```

Body:
I'm new at ES6 and I'm trying to display to none a div when an inner button is clicked.

I tried this but it's not working:

const hide = () => {
  const z = document.getElementById('button')
  const y = document.getElementById('block')
  z.onclick = () => {
    y.style.display='none'
  }
}

  <button id="button" onClick="hide()">my button</button>

Any help please?

Body:
You are attaching an event handler for first time. After the second time it will work and will again attach an event handler.

You don't need to use inline event handler, avoid this type of event handler attachement. You can just remove the hide function part serving the content. When your code runs, it will attach the event handler

const z = document.getElementById('button');
const y = document.getElementById('block');

z.onclick = () => {
    y.style.display = 'none';
};

<div id="block">
  <button id="button">my button</button>
</div>


问:
Google Spreadsheet, Substitute Integer with String
Hey there and thanks in advance.

I'm exporting the API of an application onto my spreadsheet, which works fine. Due to how the API was programmed however, some of the columns now contain the TypeID (an integer representing the "name") and not the actual name. I know what TypeID represents what Name, so what I'm looking for is a way to substitute all entries of said column with the actual name.

I have already begun to make a humongus switch case in the script editor that just checks every cell in that column and based of the contents substitues the right name, but as you can probably imagine that would take a while.

Just wondering if there is a "cleaner" and more effective way.

答:
I'd recommend making a JSON object to represent your switch case and call that

i.e :

```<code>var jsonMap = {"TYPEID":"NAME"};
</code>```

Then call :

```<code> jsonMap[fieldValue]
</code>```

To return the correct value for that field

You could have the script trigger on row modification and have it translate that way.

Alternatively I'd recommend mapping the field before it is exported into sheets using the language you're exporting in and have the data enter the sheet correctly

Body:
I'd recommend making a JSON object to represent your switch case and call that

i.e :

var jsonMap = {"TYPEID":"NAME"};

Then call :

 jsonMap[fieldValue]

To return the correct value for that field

You could have the script trigger on row modification and have it translate that way.

Alternatively I'd recommend mapping the field before it is exported into sheets using the language you're exporting in and have the data enter the sheet correctly


问:
Whats a good use case for an EIMI?
EIMI being an explicit interface member implementation. So instead of:

```<code>public int SomeValue{get;}
</code>```

you have

```<code>int SomeInterface.SomeValue {get;}
</code>```

I'm currently considering using one as i'm using an internal interface (to decouple, yet restrict) and I don't want to make the methods on the implementing object to appear in its public API.

Is this a good use case?

答:
Yep, that's a good use case. According to C# Language Specification on MSDN:

Explicit interface member implementations serve two primary purposes:

Because explicit interface member implementations are not accessible through class or struct instances, they allow interface implementations to be excluded from the public interface of a class or struct. This is particularly useful when a class or struct implements an internal interface that is of no interest to a consumer of that class or struct.

Explicit interface member implementations allow disambiguation of interface members with the same signature. Without explicit interface member implementations it would be impossible for a class or struct to have different implementations of interface members with the same signature and return type, as would it be impossible for a class or struct to have any implementation at all of interface members with the same signature but with different return types.

OwnerDisplayName: Quarrelsome

Title: Whats a good use case for an EIMI?

Body:
EIMI being an explicit interface member implementation. So instead of:

public int SomeValue{get;}

you have

int SomeInterface.SomeValue {get;}

I'm currently considering using one as i'm using an internal interface (to decouple, yet restrict) and I don't want to make the methods on the implementing object to appear in its public API.

Is this a good use case?

OwnerDisplayName: Vojislav Stojkovic


问:
How to convert NSString to NSArray in Objective C
I need to convert NSString to NSArray. if, few objects contains double quotes, few objects are doesn't contain anything.

```<code>NSString *string = @"["Line", "Operations(UK)", "Operations(USA)", "Total of Invoice", "", "Star", "10040101", "31.Jan.2001", "31.Jan.2001", "", "USD", "1653", "28,145.00", 163.48, "Stock, Ms.Pat", "MGR", "14.Nov.2006", "01-000-2210-0000-000", "V1- New York City", 20343, 5]";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:nil error:&e];
</code>```

I have tried to convert using replacing characters like [, ", ] and did "componentsSeparatedByString:" with comma. but its not working properly.

答:
As i see, you are doing right way to convert from NSString to NSArray. When you declare a NSString, you have to use \" instead of ". It works with me.

```<code>NSString *string = @"[\"Line\", \"Operations(UK)\", \"Operations(USA)\", \"Total of Invoice\", \"\", \"Star\", \"10040101\", \"31.Jan.2001\", \"31.Jan.2001\", \"\", \"USD\", \"1653\", \"28,145.00\", 163.48, \"Stock, Ms.Pat\", \"MGR\", \"14.Nov.2006\", \"01-000-2210-0000-000\", \"V1- New York City\", 20343, 5]";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:nil error:&error];
</code>```

Body:
I need to convert NSString to NSArray. if, few objects contains double quotes, few objects are doesn't contain anything.

NSString *string = @"["Line", "Operations(UK)", "Operations(USA)", "Total of Invoice", "", "Star", "10040101", "31.Jan.2001", "31.Jan.2001", "", "USD", "1653", "28,145.00", 163.48, "Stock, Ms.Pat", "MGR", "14.Nov.2006", "01-000-2210-0000-000", "V1- New York City", 20343, 5]";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:nil error:&e];

I have tried to convert using replacing characters like [, ", ] and did "componentsSeparatedByString:" with comma. but its not working properly.

Body:
As i see, you are doing right way to convert from NSString to NSArray. When you declare a NSString, you have to use \" instead of ". It works with me.

NSString *string = @"[\"Line\", \"Operations(UK)\", \"Operations(USA)\", \"Total of Invoice\", \"\", \"Star\", \"10040101\", \"31.Jan.2001\", \"31.Jan.2001\", \"\", \"USD\", \"1653\", \"28,145.00\", 163.48, \"Stock, Ms.Pat\", \"MGR\", \"14.Nov.2006\", \"01-000-2210-0000-000\", \"V1- New York City\", 20343, 5]";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:nil error:&error];