问:
How to scrape pod level info using prometheus kubernetes?
I am trying to scrape pod level info using prometheus kubernetes. Here is the config i am using:

```<code> - job_name: 'kubernetes-pods'

  kubernetes_sd_configs:
  - api_servers:
    - 'https://kubernetes.default'
    role: pod
  relabel_configs:
  - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
    action: keep
    regex: true
  - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
    action: replace
    target_label: __metrics_path__
    regex: (.+)
  - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
    action: replace
    regex: (.+):(?:\d+);(\d+)
    replacement: ${1}:${2}
    target_label: __address__
  - action: labelmap
    regex: __meta_kubernetes_pod_label_(.+)
  - source_labels: [__meta_kubernetes_pod_namespace]
    action: replace
    target_label: kubernetes_namespace
  - source_labels: [__meta_kubernetes_pod_name]
    action: replace
    target_label: kubernetes_pod_name
</code>```

But i don't see any info on grafana. Do I need to make any changes in my apps?
snapshot

答:
Be aware,

there is a configuration mistake here:
__meta_kubernetes_pod_namespace does not exist and should be __meta_kubernetes_namespace

Best regards,

Bart

Body:
I am trying to scrape pod level info using prometheus kubernetes. Here is the config i am using:

 - job_name: 'kubernetes-pods'

  kubernetes_sd_configs:
  - api_servers:
    - 'https://kubernetes.default'
    role: pod
  relabel_configs:
  - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
    action: keep
    regex: true
  - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
    action: replace
    target_label: __metrics_path__
    regex: (.+)
  - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
    action: replace
    regex: (.+):(?:\d+);(\d+)
    replacement: ${1}:${2}
    target_label: __address__
  - action: labelmap
    regex: __meta_kubernetes_pod_label_(.+)
  - source_labels: [__meta_kubernetes_pod_namespace]
    action: replace
    target_label: kubernetes_namespace
  - source_labels: [__meta_kubernetes_pod_name]
    action: replace
    target_label: kubernetes_pod_name

But i don't see any info on grafana. Do I need to make any changes in my apps?
snapshot


来源: stackexchange

问:
PHP Login form need to be submited 2x
I have got problem, that I can't figure out. All of my other forms work correctly. But Login Form, need to be completed 2 times, before it executes.

I need to input username and password, submit form, and page refreshes.
When I input username/password and submit second time, function works and goes to profile.php

Login.php

```<code>    <?php
    require_once("../Style/user-navigation.php");
    require_once("../System/class.user.php");

    $user = new USER();

    if($user->is_loggedin()!=""){
    ?><script> location.replace("Home.php?action=select&id=<?php echo $userRow['id']; ?>"); </script>
    <?php
    }

    if(isset($_POST['btn-login'])){
        $username = strip_tags($_POST['username']);
        $password = strip_tags($_POST['password']);

        if($user->doLogin($username,$password)){ ?>
        <script> location.replace("Home.php?action=select&id=<?php echo $userRow['id']; ?>"); </script>
        <?php
        }
    }

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body class="nav-md" style="background-image: url('https://zellox.com/wp-content/uploads/2016/05/background-website-%E2%80%AB1%E2%80%AC-1600x900.gif');">

        <!-- page content -->
        <div class="clearfix"></div>

        <a class="hiddenanchor" id="signin"></a>

        <div class="login_wrapper">
        <div class="animate form login_form">
          <section class="login_content">
            <form method="post">
              <h1>Login Form</h1>
              <div>
                <input type="text" class="form-control" name="username" placeholder="Username" required="" />
              </div>
              <div>
                <input type="password" class="form-control" name="password" placeholder="Password" required="" />
              </div>
              <div>
               <button type="submit" name="btn-login" class="btn btn-primary ">Log In</button>
                <a class="reset_pass" href="#">Lost your password?</a>
              </div>

              <div class="clearfix"></div>

              <div class="separator">
                <p class="change_link">New to site?
                  <a href="Register.php" class="to_register"> Create Account </a>
                </p>

                <div class="clearfix"></div>
                <br />

              </div>
            </form>
          </section>
        </div>
        </div>
      </div>
        <!-- /page content -->
  </body>
</html>
</code>```

And backend code "class.user.php" Login function

```<code>public function doLogin($username,$password){
        try
        {
            $stmt = $this->conn->prepare("SELECT id, username, password FROM users WHERE username=:username");
            $stmt->execute(array(':username'=>$username));
            $userRow=$stmt->fetch(PDO::FETCH_ASSOC);
            if($stmt->rowCount() == 1)
            {
                if($password= $userRow['password'])
                {
                    $_SESSION['user_session'] = $userRow['id'];
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }
</code>```

答:
Add it before using sessions and HTML:

session_start();

ContentLicense: CC BY-SA 3.0

Title: PHP Login form need to be submited 2x

Body:
I have got problem, that I can't figure out. All of my other forms work correctly. But Login Form, need to be completed 2 times, before it executes.

I need to input username and password, submit form, and page refreshes.
When I input username/password and submit second time, function works and goes to profile.php

Login.php

    <?php
    require_once("../Style/user-navigation.php");
    require_once("../System/class.user.php");

    $user = new USER();

    if($user->is_loggedin()!=""){
    ?>
    <?php
    }

    if(isset($_POST['btn-login'])){
        $username = strip_tags($_POST['username']);
        $password = strip_tags($_POST['password']);

        if($user->doLogin($username,$password)){ ?>

        <?php
        }
    }

?>

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

            <form method="post">

Login Form

                <input type="text" class="form-control" name="username" placeholder="Username" required="" />

                <input type="password" class="form-control" name="password" placeholder="Password" required="" />

               <button type="submit" name="btn-login" class="btn btn-primary ">Log In</button>
                Lost your password?

New to site?
                   Create Account

            </form>

And backend code "class.user.php" Login function

public function doLogin($username,$password){
        try
        {
            $stmt = $this->conn->prepare("SELECT id, username, password FROM users WHERE username=:username");
            $stmt->execute(array(':username'=>$username));
            $userRow=$stmt->fetch(PDO::FETCH_ASSOC);
            if($stmt->rowCount() == 1)
            {
                if($password= $userRow['password'])
                {
                    $_SESSION['user_session'] = $userRow['id'];
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }


问:
run a mysql command from java
hi I have a JAVA project in which I want to display the MySQL databases.
i write this code:

```<code>try {
     String []command={"mysql -u root -pmanager","show databases"};
        Process p= Runtime.getRuntime().exec("mysql -u root -pmanager");
        Process p1= Runtime.getRuntime().exec("show databases");
        if (p.waitFor()==0){System.out.println("backup done...");}
        else{System.out.println("!!!");}
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

but it give me this error:

```<code>Cannot run program "show": CreateProcess error=2, The system cannot find the file specified
</code>```

what it should be do?
thanks...

答:
You need to specify what is 'mysql' to command prompt...
example - C:\Program Files\MySQL\MySQL Server 5.7\bin\mysql</p>

Title: run a mysql command from java

Body:
hi I have a JAVA project in which I want to display the MySQL databases.
i write this code:

try {
     String []command={"mysql -u root -pmanager","show databases"};
        Process p= Runtime.getRuntime().exec("mysql -u root -pmanager");
        Process p1= Runtime.getRuntime().exec("show databases");
        if (p.waitFor()==0){System.out.println("backup done...");}
        else{System.out.println("!!!");}
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

but it give me this error:

Cannot run program "show": CreateProcess error=2, The system cannot find the file specified

what it should be do?
thanks...


问:
Initializing a getter in python after converting to string
I need these two getters to return the string converted version of the x input or y input.
Please take a look at my code, and let me know where I faulter. Thanks! </p>

```<code>class V:
    def __init__(self, conv, convy):
        conv = conv
        convy = convy

        self.conv = str(conv)
        self.convy = str(convy)

    def getX(self):
        return self.__conv

    def getY(self):
        return self.__convy
</code>```

答:
Your getter is defined as:

```<code>def getX(self):
    return self.__conv
</code>```

But self.__conv does not exist. Instead, you defined self.conv.

Therefore, your getter should be:

```<code>def getX(self):
    return self.conv
</code>```

In addtion, in your __init__ method, you assign conv and convy to themselves, which is absolutely useless:

```<code>def __init__(self, conv, convy):
    conv = conv
    convy = convy
</code>```

You should get rid of these two lines that serve no purpose.

Body:
I need these two getters to return the string converted version of the x input or y input.
Please take a look at my code, and let me know where I faulter. Thanks!

class V:
    def __init__(self, conv, convy):
        conv = conv
        convy = convy

        self.conv = str(conv)
        self.convy = str(convy)

    def getX(self):
        return self.__conv

    def getY(self):
        return self.__convy

Body:
Your getter is defined as:

def getX(self):
    return self.__conv

But self.__conv does not exist. Instead, you defined self.conv.

Therefore, your getter should be:

def getX(self):
    return self.conv

In addtion, in your __init__ method, you assign conv and convy to themselves, which is absolutely useless:

def __init__(self, conv, convy):
    conv = conv
    convy = convy

You should get rid of these two lines that serve no purpose.


问:
Is there any way to achieve move elision
When running the following code:

```<code>struct Copy
{
    Copy() {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy(const Copy & other) {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy & operator=(const Copy & other) {std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this;}
    Copy(Copy && other) {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy & operator=(Copy && other) {std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this;}
    ~Copy() {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
};

char buffer[1024];

template <typename Type>
Type * push(Type value)
{
    return new(buffer) Type(std::move(value));
};

int main()
{
    push(Copy());

    return 0;
}
</code>```

I get the following output:

```<code>Copy::Copy()
Copy::Copy(Copy &&)
Copy::~Copy()
</code>```

Is there anyway to elide the move constructor?

I was hoping that with -O3, it would be constructed in place, but by my testing, that doesn't seem to be the case.

答:
Use an emplace function with perfect argument forwarding. There are a few more things to say since you're about to embark on an adventure in placement new:

Use std::aligned_storage_t<> for the storage. It guarantees that your objects will be properly aligned.

Do read and use the return value of placement new. In simple cases it won't be different from the address you provide. However the standard allows it to be, and in complex class hierarchies it might be.

updated example:

```<code>#include <iostream>

struct Copy
{
    Copy() {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy(const Copy & other) {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy & operator=(const Copy & other) {std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this;}
    Copy(Copy && other) {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy & operator=(Copy && other) {std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this;}
    ~Copy() {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
};

std::aligned_storage_t<sizeof(Copy), alignof(Copy)> buffer[4];

template <typename Type, typename LegalStorage, typename...Args>
auto emplace(LegalStorage* buffer, Args&&...args) -> Type*
{

    return new(buffer) Type(std::forward<Args>(args)...);
};

int main()
{
    auto p1 = emplace<Copy>(buffer /* constructor arguments go here*/);
    auto p2 = emplace<Copy>(&buffer[1]/* constructor arguments go here*/);
    auto p3 = emplace<Copy>(buffer + 2/* constructor arguments go here*/);
    auto p4 = emplace<Copy>(buffer + 3/* constructor arguments go here*/);

    return 0;
}
</code>```

Body:
When running the following code:

struct Copy
{
    Copy() {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy(const Copy & other) {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy & operator=(const Copy & other) {std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this;}
    Copy(Copy && other) {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy & operator=(Copy && other) {std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this;}
    ~Copy() {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
};

char buffer[1024];

template <typename Type>
Type * push(Type value)
{
    return new(buffer) Type(std::move(value));
};

int main()
{
    push(Copy());

    return 0;
}

I get the following output:

Copy::Copy()
Copy::Copy(Copy &&)
Copy::~Copy()

Is there anyway to elide the move constructor?

I was hoping that with -O3, it would be constructed in place, but by my testing, that doesn't seem to be the case.

Body:
Use an emplace function with perfect argument forwarding. There are a few more things to say since you're about to embark on an adventure in placement new:

Use std::aligned_storage_t<> for the storage. It guarantees that your objects will be properly aligned.

Do read and use the return value of placement new. In simple cases it won't be different from the address you provide. However the standard allows it to be, and in complex class hierarchies it might be.

updated example:

#include <iostream>

struct Copy
{
    Copy() {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy(const Copy & other) {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy & operator=(const Copy & other) {std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this;}
    Copy(Copy && other) {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy & operator=(Copy && other) {std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this;}
    ~Copy() {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
};

std::aligned_storage_t<sizeof(Copy), alignof(Copy)> buffer[4];

template <typename Type, typename LegalStorage, typename...Args>
auto emplace(LegalStorage* buffer, Args&&...args) -> Type*
{

    return new(buffer) Type(std::forward<Args>(args)...);
};

int main()
{
    auto p1 = emplace<Copy>(buffer /* constructor arguments go here*/);
    auto p2 = emplace<Copy>(&buffer[1]/* constructor arguments go here*/);
    auto p3 = emplace<Copy>(buffer + 2/* constructor arguments go here*/);
    auto p4 = emplace<Copy>(buffer + 3/* constructor arguments go here*/);

    return 0;
}


问:
How can I add a submit button inside my texbox using angular material?
I'm trying to add a 'send' button on the right side of my text input in angular material.

<md-input-container>
 <input type="text" style="bottom:0; width:90%; height: 15%; position: fixed; border-top: 1px solid black">
 <md-button class="md-raised md-primary" id="send" style="position:absolute;">Send</md-button>
</md-input-container>```

But my send button doesn't appear close to my textbox. How can I get the button inside the textbox?

答:
The way to separate things in your form is using the layout containers

```<code><div layout="row">
  <!-- Textbox -->
  <md-input-container>
    <label>Name</label>
    <input ng-model="yourModelHere">
  </md-input-container>
  <!-- Send Button -->
  <md-input-container>
    <md-button id="send" class="md-raised md-primary">Send</md-button>
  </md-input-container>
</div>
</code>```

Result

Keep rocking!

Body:
I'm trying to add a 'send' button on the right side of my text input in angular material.

<md-input-container>
 <input type="text" style="bottom:0; width:90%; height: 15%; position: fixed; border-top: 1px solid black">
 <md-button class="md-raised md-primary" id="send" style="position:absolute;">Send</md-button>
</md-input-container>

But my send button doesn't appear close to my textbox. How can I get the button inside the textbox?

Body:
The way to separate things in your form is using the layout containers

<div layout="row">
  <!-- Textbox -->
  <md-input-container>
    <label>Name</label>
    <input ng-model="yourModelHere">
  </md-input-container>
  <!-- Send Button -->
  <md-input-container>
    <md-button id="send" class="md-raised md-primary">Send</md-button>
  </md-input-container>
</div>

Result

Keep rocking!


问:
Random NullPointerExceptions with missing stacktrace in DispatcherServlet
I see random NullPointerException when one of my endpoints is accessed.

I know what an NPE is, but please bear with me, I have many issues here :

problem happens maybe once in every 10000 calls

if I replay the same request a second time it works OK

it looks as if it doesn't get to the code in my controller (no statements are logged)

and, most annoying... I don't have a stacktrace to help me pinpoint the problem.

This is what it is logged :

```<code>[p-nio-80-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
</code>```

Annnnnd, that's it, nothing more...

The code of the controller is rather straithforward, it looks like this :

```<code>@RepositoryRestController
@ResponseBody
public class AnimalImportEndpoint {

    @Inject
    private animalImportService;

    @RequestMapping(value = "/animals/import", method = RequestMethod.POST)
    public AnimalImportResult import(@Valid @RequestBody Animal animal) {
        return animalImportService.import(animal);
    }

    @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Illegal arguments")
    @ExceptionHandler(IllegalArgumentException.class)
    public void illegalArguments() {
    }
}
</code>```

The class is annoted with @RepositoryRestController instead of @RestController because Spring Data Rest also exposes /animals.

Any pointers or advice on how to troubleshoot this ?

Edit : other interesting fact, I use sleuth to trace requests. When I get this NullPointerException, I can see that there is no spanId/traceId in my logs ...

答:
Add this JVM argument to disable stacktrace removal optimization</p>

```<code>-XX:-OmitStackTraceInFastThrow
</code>```

Body:
I see random NullPointerException when one of my endpoints is accessed.

I know what an NPE is, but please bear with me, I have many issues here :

problem happens maybe once in every 10000 calls

if I replay the same request a second time it works OK

it looks as if it doesn't get to the code in my controller (no statements are logged)

and, most annoying... I don't have a stacktrace to help me pinpoint the problem.

This is what it is logged :

[p-nio-80-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null

Annnnnd, that's it, nothing more...

The code of the controller is rather straithforward, it looks like this :

@RepositoryRestController
@ResponseBody
public class AnimalImportEndpoint {

    @Inject
    private animalImportService;

    @RequestMapping(value = "/animals/import", method = RequestMethod.POST)
    public AnimalImportResult import(@Valid @RequestBody Animal animal) {
        return animalImportService.import(animal);
    }

    @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Illegal arguments")
    @ExceptionHandler(IllegalArgumentException.class)
    public void illegalArguments() {
    }
}

The class is annoted with @RepositoryRestController instead of @RestController because Spring Data Rest also exposes /animals.

Any pointers or advice on how to troubleshoot this ?

Edit : other interesting fact, I use sleuth to trace requests. When I get this NullPointerException, I can see that there is no spanId/traceId in my logs ...

Body:
Add this JVM argument to disable stacktrace removal optimization

-XX:-OmitStackTraceInFastThrow


问:
autogeneration of config.xml and package.json
I m a newbie
i m try to suppress

```<code><plugin name="cordova-plugin-wkwebview-engine" spec="git+https://github.com/driftyco/cordova-plugin-wkwebview-engine.git" />
</code>```

from config.xml in order to resolve build problems with that plugin

every time i run

ionic cordova build --release android

the line   appears again automatically in config.xml idem in package.json

where is the source(s) generating theses config.xml and package.json files and what is the process

thank a lot guys, i'stuck for hours with this problem because i can build properly

答:
Probably you have added this plugin to your project.
You will have to remove it:

```<code>cordova plugin rm cordova-plugin-wkwebview-engine
</code>```

You can read the docs about plugin/platform management.

Body:
I m a newbie
i m try to suppress

<plugin name="cordova-plugin-wkwebview-engine" spec="git+https://github.com/driftyco/cordova-plugin-wkwebview-engine.git" />

from config.xml in order to resolve build problems with that plugin

every time i run

ionic cordova build --release android

the line   appears again automatically in config.xml idem in package.json

where is the source(s) generating theses config.xml and package.json files and what is the process

thank a lot guys, i'stuck for hours with this problem because i can build properly

Body:
Probably you have added this plugin to your project.
You will have to remove it:

cordova plugin rm cordova-plugin-wkwebview-engine

You can read the docs about plugin/platform management.


问:
Associate a file to any row in any table of my database
We are designing a system where our customer asks to be able to associate a file to any entity belonging to any table in the system.

Is this possible? How can our files table reference any entity in any table? We are thinking of GUIDs. But don't know if this is the correct way of implementing this feature or even if it's possible at all.

答:
You create table with files listing.

Then you create reference to that record from any table you want.

Files table

```<code>id  FilePath
 1  C:\myfile
</code>```

Some other table

```<code>id  fileReference   SomeOtherColumn
 1              1    some other data
</code>```

Or if you really want to go this road then Files table will be

```<code>id  FilePath     OtherTableName   RecordIDinOtherTable
 1  C:\myfile    SomeOtherTable                      1
</code>```

Body:
You create table with files listing.

Then you create reference to that record from any table you want.

Files table

id  FilePath
 1  C:\myfile

Some other table

id  fileReference   SomeOtherColumn
 1              1    some other data

Or if you really want to go this road then Files table will be

id  FilePath     OtherTableName   RecordIDinOtherTable
 1  C:\myfile    SomeOtherTable                      1


问:
Microsoft graph service subscription ExpirationDateTime never expire
I have an Office365 Web API to fetch mail from the following URL:

https://graph.microsoft.com/v1.0/me

I have created a subscription for getting notifications from the graph service. However, I can not set the expiration time for the subscription to more than 4230 minutes. While I searched in Microsoft website I got this default time. While I add more than 4230 minutes in the request to the Graph I get BadRequest error code.

Following is the request code:

```<code>Subscription subscription = new Subscription
{
    Resource = "me/mailFolders('Inbox')/messages",
    ChangeType = "created",
    NotificationUrl = ConfigurationManager.AppSettings["ida:NotificationUrl"],
    ClientState = Guid.NewGuid().ToString(), ExpirationDateTime = DateTime.UtcNow +
                  new TimeSpan(0, 0, 11115, 0) // shorter duration useful for testing
};
</code>```

Can anyone suggest me how to override the default time in the graph API?

答: If you read the documentation, it tells you that the maximum expiration time is 4230 minutes

Body:
I have an Office365 Web API to fetch mail from the following URL:

https://graph.microsoft.com/v1.0/me

I have created a subscription for getting notifications from the graph service. However, I can not set the expiration time for the subscription to more than 4230 minutes. While I searched in Microsoft website I got this default time. While I add more than 4230 minutes in the request to the Graph I get BadRequest error code.

Following is the request code:

Subscription subscription = new Subscription
{
    Resource = "me/mailFolders('Inbox')/messages",
    ChangeType = "created",
    NotificationUrl = ConfigurationManager.AppSettings["ida:NotificationUrl"],
    ClientState = Guid.NewGuid().ToString(), ExpirationDateTime = DateTime.UtcNow +
                  new TimeSpan(0, 0, 11115, 0) // shorter duration useful for testing
};

Can anyone suggest me how to override the default time in the graph API?


问:
opentsdb install process error with code 127
In Order to install openTSDB ,i have already install java(java8) and hbase ,and both of them are worked successfully. But i follow the steps of  OpenTSDB doc, in

./build.sh it came error like this.
enter image description here

so how can i slove this problem

答: You need to install Python. If you see the error message carefully it says 'python: command not found'.</p>


问:
VBA Clear cells in named range that contain specfic character
All,
I'm am completely unfamiliar w/ VBA, but want to get a code for a fantasy football draft simulation that will "reset" the draft selections.

Parameters: the size of the data is 12 teams (columns), and 18 rounds (rows). The data is not adjacent, so I named the the range that I want to reset "DataVal"

The league is a keeper league which means that there are players already in selected cells prior to the draft, so I don't want those cleared. To differentiate between kept and unkept players, the unkept players have their positions in parentheses.

Request: I want a code that clears all cells containing "(" or if that's not possible, "(RB)" , "(QB)" , "(WR)" , "(TE)" , "(TD)" , "(PK)" within range "DataVal"  which I can attach to a Button

答:
Try adding this code in a regular module:

```<code>Sub ClearCells()

Dim rng as Range

With Range("DataVal") 'You had a named range named "DataVal" right?
    For each rng in .cells
        If Left(rng.value, 1) = "(" Then 'All values that start with "("
           rng.ClearContents
        End If
    Next rng
End With
End Sub
</code>```

It loops over each cell in your named range, if the first character in the cell is "(" it'll clear that cell.

Next, add a button and attach the "ClearCells" macro to it.

Still read How do I ask a good question before posting your next one though.

Body:
Try adding this code in a regular module:

Sub ClearCells()

Dim rng as Range

With Range("DataVal") 'You had a named range named "DataVal" right?
    For each rng in .cells
        If Left(rng.value, 1) = "(" Then 'All values that start with "("
           rng.ClearContents
        End If
    Next rng
End With
End Sub

It loops over each cell in your named range, if the first character in the cell is "(" it'll clear that cell.

Next, add a button and attach the "ClearCells" macro to it.

Still read How do I ask a good question before posting your next one though.


问:
Scala: delay code bloc execution or cancel it
I'm pretty new to Scala and have a background in Java.

The problem I'm facing is that I'd like to execute a function after 5 minutes. And also be able to cancel this at any time.

In java I would basically use TimerTask, and set it to 5 min. If I would like to cancel, I just call cancel method. The nice thing is, I can use that Java class in Scala. But as I'm still learning Scala, I'm just wondering if I'm missing any better way of accomplishing that in a better way. I ran into Future and Await.result Scala classes, but I'm having a hard time figuring it out.

Any advices?

答:
The Future in the scala library is not cancellable. What you'd have to do would be to implement some sort of a condition and make sure you "thing" only runs as long as that condition is true.

You might want to look at monix.Task, which is cancellable: https://monix.io/docs/2x/eval/task.html

From their docs:

```<code>import monix.eval.Task
import monix.execution.CancelableFuture
import concurrent.duration._

val task = Task(1 + 1).delayExecution(1.second)

val result: CancelableFuture[Int] =
  task.runAsync

// If we change our mind
result.cancel()
</code>```

Body:
The Future in the scala library is not cancellable. What you'd have to do would be to implement some sort of a condition and make sure you "thing" only runs as long as that condition is true.

You might want to look at monix.Task, which is cancellable: https://monix.io/docs/2x/eval/task.html

From their docs:

import monix.eval.Task
import monix.execution.CancelableFuture
import concurrent.duration._

val task = Task(1 + 1).delayExecution(1.second)

val result: CancelableFuture[Int] =
  task.runAsync

// If we change our mind
result.cancel()


问:
Cannot load system cursor: CopyDrop.32x32 exception in Java on Centos 7
I installed netbeans 8.2 on Centos 7.

I get this error:

```<code>java.lang.RuntimeException: failed to load system cursor: DnD.Cursor.CopyDrop : cannot load system cursor: CopyDrop.32x32
    at java.awt.dnd.DragSource.load(DragSource.java:135)
    at java.awt.dnd.DragSource.<clinit>(DragSource.java:148)
</code>```

Java version :

```<code>openjdk version "1.8.0_111"
OpenJDK Runtime Environment (build 1.8.0_111-b15)
OpenJDK 64-Bit Server VM (build 25.111-b15, mixed mode)
</code>```

How can I fix this?

答:
My Java code uses Drag&Drop in JTree, which get broken after upgrade from CentOS 6 to CentOS 7. Same hardware, same OpenJDK, same Java code, but different graphic driver. The workaround with kernel command line setting "nomodeset" helps, but causes poor graphic & flickering.
Here is a pure Java workaround:</p>

```<code>  //workaround for used Drag&Drop cursors which are unsupported by graphics driver
  public static void initUnsupportedCursors() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
  {
    String cursors[] = new String[]{
        "DnD.Cursor.CopyDrop",
        "DnD.Cursor.MoveDrop",
        "DnD.Cursor.LinkDrop",
        "DnD.Cursor.CopyNoDrop",
        "DnD.Cursor.MoveNoDrop",
        "DnD.Cursor.LinkNoDrop"
        };
   List <String> unsupportedCursors =  new ArrayList <String>();
   for (String c : cursors)
   {
     try
     {
       if (Toolkit.getDefaultToolkit().getDesktopProperty(c) == null)
       {
         throw new Exception("Can't find cursor " + c);
       }
     }
     catch (Exception e)
     {
       unsupportedCursors.add(c);
     }
   }
   if (!unsupportedCursors.isEmpty())
   {
     Field propsFiled = Toolkit.class.getDeclaredField("desktopProperties");
     propsFiled.setAccessible(true);
     Map props = (Map) propsFiled.get(Toolkit.getDefaultToolkit());
     for (String unsupportedCursor : unsupportedCursors)
     {
       System.out.println("Replacing unsupported " + unsupportedCursor + " by " + Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
       props.put(unsupportedCursor, Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
     }
   }
  }
</code>```

Body:
I installed netbeans 8.2 on Centos 7.

I get this error:

java.lang.RuntimeException: failed to load system cursor: DnD.Cursor.CopyDrop : cannot load system cursor: CopyDrop.32x32
    at java.awt.dnd.DragSource.load(DragSource.java:135)
    at java.awt.dnd.DragSource.<clinit>(DragSource.java:148)

Java version :

openjdk version "1.8.0_111"
OpenJDK Runtime Environment (build 1.8.0_111-b15)
OpenJDK 64-Bit Server VM (build 25.111-b15, mixed mode)

How can I fix this?

Body:
My Java code uses Drag&Drop in JTree, which get broken after upgrade from CentOS 6 to CentOS 7. Same hardware, same OpenJDK, same Java code, but different graphic driver. The workaround with kernel command line setting "nomodeset" helps, but causes poor graphic & flickering.
Here is a pure Java workaround:

  //workaround for used Drag&Drop cursors which are unsupported by graphics driver
  public static void initUnsupportedCursors() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
  {
    String cursors[] = new String[]{
        "DnD.Cursor.CopyDrop",
        "DnD.Cursor.MoveDrop",
        "DnD.Cursor.LinkDrop",
        "DnD.Cursor.CopyNoDrop",
        "DnD.Cursor.MoveNoDrop",
        "DnD.Cursor.LinkNoDrop"
        };
   List <String> unsupportedCursors =  new ArrayList <String>();
   for (String c : cursors)
   {
     try
     {
       if (Toolkit.getDefaultToolkit().getDesktopProperty(c) == null)
       {
         throw new Exception("Can't find cursor " + c);
       }
     }
     catch (Exception e)
     {
       unsupportedCursors.add(c);
     }
   }
   if (!unsupportedCursors.isEmpty())
   {
     Field propsFiled = Toolkit.class.getDeclaredField("desktopProperties");
     propsFiled.setAccessible(true);
     Map props = (Map) propsFiled.get(Toolkit.getDefaultToolkit());
     for (String unsupportedCursor : unsupportedCursors)
     {
       System.out.println("Replacing unsupported " + unsupportedCursor + " by " + Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
       props.put(unsupportedCursor, Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
     }
   }
  }


问:
Migrating to PHP7.x, Deprecated functions
So here's the problem, the script I purchase is written on PHP 5.x, and I'm using xampp with PHP7.x installed for development. Now I want to migrate my script to PHP7.x. Now I know this was asked a million times already but do you mind if you could take a look at my code and give your thoughts about it, or simply share your knowledge. I would deeply appreciate it.

Here is the code for my config.php

```<code><?php
// mySQL information
$server = 'localhost';                   // MySql server
$username = 'admin';                      // MySql Username
$password = 'admin' ;                         // MySql Password
$database = 'arcade';                  // MySql Database

// The following should not be edited

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

  $con = mysql_connect($server, $username, $password);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db($database, $con);

// Get settings
if (!isset($install)) {
    $sql = mysql_query("SELECT * FROM ava_settings");
    while ($get_setting = mysql_fetch_array($sql)) {
        $setting[$get_setting['name']] = $get_setting['value'];
    }
}
?>
</code>```

The deprecated functions are:

mysql_connect()

     mysql_error()

     mysql_fetch_array()

     mysql_query()

     mysql_select_db()

Now, I don't want to use the PDO approach, I want to use mysqli instead. Am I suppose to just replace the mysql_* into mysqli_*? So it will become like these? I don't want to hide/surpress the deprecate warnings.

mysqli_connect()

     mysqli_error()

     mysqli_fetch_array()

     mysqli_query()

     mysqli_select_db()

答:
I just offer you that migrate to PDO driver. Because every update you may see a lot of deprecation errors.

But if you can not do it the first thing to do would probably be to replace every mysql_* function call with its equivalent mysqli_*, at least if you are willing to use the procedural API -- which would be the easier way, considering you already have some code based on the MySQL API, which is a procedural one.

Note that, for some functions, you may need to check the parameters carefully: Maybe there are some differences here and there -- but not that many, I'd say: both mysql and mysqli are based on the same library (libmysql ; at least for PHP <= 5.2)

Body:
So here's the problem, the script I purchase is written on PHP 5.x, and I'm using xampp with PHP7.x installed for development. Now I want to migrate my script to PHP7.x. Now I know this was asked a million times already but do you mind if you could take a look at my code and give your thoughts about it, or simply share your knowledge. I would deeply appreciate it.

Here is the code for my config.php

<?php
// mySQL information
$server = 'localhost';                   // MySql server
$username = 'admin';                      // MySql Username
$password = 'admin' ;                         // MySql Password
$database = 'arcade';                  // MySql Database

// The following should not be edited

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

  $con = mysql_connect($server, $username, $password);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db($database, $con);

// Get settings
if (!isset($install)) {
    $sql = mysql_query("SELECT * FROM ava_settings");
    while ($get_setting = mysql_fetch_array($sql)) {
        $setting[$get_setting['name']] = $get_setting['value'];
    }
}
?>

The deprecated functions are:

mysql_connect()

     mysql_error()

     mysql_fetch_array()

     mysql_query()

     mysql_select_db()

Now, I don't want to use the PDO approach, I want to use mysqli instead. Am I suppose to just replace the mysql_* into mysqli_*? So it will become like these? I don't want to hide/surpress the deprecate warnings.

mysqli_connect()

     mysqli_error()

     mysqli_fetch_array()

     mysqli_query()

     mysqli_select_db()


问:
call data-id on ajax success response
Originally I have a "like button" that is working very smoothly, and it looked like this:

```<code><a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <span><?php echo likes($row['id']); ?></span></a>
</code>```

Here is the Ajax code:

```<code><script>
    $(function(){
        $(".like").click(function(){

            var postid = $(this).attr("id");
              $.ajax({
                type:'POST',
                url:'addlike.php',
                data:'id='+postid,
                success:function(data){
                   if(data=="you already liked this post"){
                       alert(data);
                     }
                   else{
                      $('a#'+postid).html(data);
                      }
                }
            });

        });
    });

</script>
</code>```

If AJAX is successful, addlike.php will have two kinds of response, either alert "you already liked the post" if the user already liked it, or the updated number of likes. For example, if there are currently 10 likes, when the user clicked the button, $('a#'+postid).html(data) will change 10 to 11, because in this case the data will be the updated number of likes, and $('a#'+postid) selects the "like button" that is just being clicked.

For some reason, I have to use data-id instead of id for the html id of the button. For more detailed explanation, see here:Disable boostrap toggle collapse for one class and enable it for another

Now I have to call the element which has a data-id instead of id on ajax success response, how can I do it? I tried the following:

```<code>     $('a#data-id'+postid).html(data);
     $('.[data-id="postid"]').html(data);
     $('a[data-id='+postid']').html(data);
     $('a#'+"[data-id=postid"]).text(data);
</code>```

but none of them works. Thanks in advance.

答:
You already have a reference to that button in $(this) inside the click handler.  I suggest you copy that into a variable and use that:</p>

```<code><script>
    $(function(){
        $(".like").click(function(){
            var $linkClicked = $(this);
            var postid = $(this).attr("id");
              $.ajax({
                type:'POST',
                url:'addlike.php',
                data:'id='+postid,
                success:function(data){
                   if(data=="you already liked this post"){
                       alert(data);
                     }
                   else{
                      $linkClicked.html(data);
                      }
                }
            });

        });
    });

</script>
</code>```

Title: call data-id on ajax success response

Body:
Originally I have a "like button" that is working very smoothly, and it looked like this:

<a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <?php echo likes($row['id']); ?>

Here is the Ajax code:

If AJAX is successful, addlike.php will have two kinds of response, either alert "you already liked the post" if the user already liked it, or the updated number of likes. For example, if there are currently 10 likes, when the user clicked the button, $('a#'+postid).html(data) will change 10 to 11, because in this case the data will be the updated number of likes, and $('a#'+postid) selects the "like button" that is just being clicked.

For some reason, I have to use data-id instead of id for the html id of the button. For more detailed explanation, see here:Disable boostrap toggle collapse for one class and enable it for another

Now I have to call the element which has a data-id instead of id on ajax success response, how can I do it? I tried the following:

     $('a#data-id'+postid).html(data);
     $('.[data-id="postid"]').html(data);
     $('a[data-id='+postid']').html(data);
     $('a#'+"[data-id=postid"]).text(data);

but none of them works. Thanks in advance.

Body:
You already have a reference to that button in $(this) inside the click handler.  I suggest you copy that into a variable and use that:

<script>
    $(function(){
        $(".like").click(function(){
            var $linkClicked = $(this);
            var postid = $(this).attr("id");
              $.ajax({
                type:'POST',
                url:'addlike.php',
                data:'id='+postid,
                success:function(data){
                   if(data=="you already liked this post"){
                       alert(data);
                     }
                   else{
                      $linkClicked.html(data);
                      }
                }
            });

        });
    });

</script>


问:
How to return values from function - React native
How to return a boolean value from react native function?</p>

答:
If your function is in a class, you can do this (check toggleBool):</p>

```<code>class IsTrue extends Component
{
    state = {isTrue: false}

    componentWillMount = () =>
    {
        const   newVal = this.toggleBool();

        this.setState({isTrue: newVal});
    }

    toggleBool = () =>
    {
        if (this.state.isTrue === false)
            return (true);
        return (false);
    }

    render = () => <Text>{this.state.isTrue}</Text>
}
</code>```

Body:
If your function is in a class, you can do this (check toggleBool):

class IsTrue extends Component
{
    state = {isTrue: false}

    componentWillMount = () =>
    {
        const   newVal = this.toggleBool();

        this.setState({isTrue: newVal});
    }

    toggleBool = () =>
    {
        if (this.state.isTrue === false)
            return (true);
        return (false);
    }

    render = () => <Text>{this.state.isTrue}</Text>
}


问:
Multiple XSD files with same entities defined
Thanks for any help,

We have two XSD files, both of them shares some same entities and some others different.  Note that the one with differences are called differently.

We want to generate C# code that can Serialize / Deserialize those entities, without ending up with two entities that share the same name and same content in two different namespaces.  An exemple of those are enums.

We did try with XSD.exe and SVCUTIL.exe, but could not found a proper way to do so.

Thanks again, gladly appreciated,

Patrick

答:
Trying using this

wsdl XMLSchema1.xsd XMLSchema2.xsd /language:c# /sharetypes

ContentLicense: CC BY-SA 2.5


问:
Copy text innerHTML of element to clipboard
I was try many solutions in stackoverflow, but it not work.(here and here)

I try it in Website and use chrome extension for run code (chrome 59.0.3071.104 64bit)

```<code><h4 align="center">text data to copy</h4>

var copy_text = document.getElementsByTagName("h4")[0];
copy_text.select(); //-> error: select is not a function
</code>```

and

```<code>var range = document.createRange();
range.selectNode(copy_text);
window.getSelection().addRange(range);
document.execCommand("copy"); //-> clipboard not change
</code>```

Any solution for this?
Thankyou.

Edit: I think my problem is page loading (security brower), all solution work with user interactive

答:
Here is a quick hacky way to do what you want, there is a hidden input that we put the data in and then copy it from there. (The text area is just somewhere to paste into)

function copyText(e) {
  var textToCopy = document.querySelector(e);
  var textBox = document.querySelector(".clipboard");
  textBox.setAttribute('value', textToCopy.innerHTML);

  textBox.select();
  document.execCommand('copy');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  position: fixed;
  bottom: 0;
  right: 0;
  pointer-events: none;
  opacity: 0;
  transform: scale(0);
}</code>```

Text data to copy

<button onclick="copyText('.text')" class="copy">Copy</button>

<textarea></textarea>

<input class="clipboard hidden" />```

ContentLicense: CC BY-SA 4.0

Body:
I was try many solutions in stackoverflow, but it not work.(here and here)

I try it in Website and use chrome extension for run code (chrome 59.0.3071.104 64bit)

text data to copy

var copy_text = document.getElementsByTagName("h4")[0];
copy_text.select(); //-> error: select is not a function

and

var range = document.createRange();
range.selectNode(copy_text);
window.getSelection().addRange(range);
document.execCommand("copy"); //-> clipboard not change

Any solution for this?
Thankyou.

Edit: I think my problem is page loading (security brower), all solution work with user interactive

Body:
Here is a quick hacky way to do what you want, there is a hidden input that we put the data in and then copy it from there. (The text area is just somewhere to paste into)

function copyText(e) {
  var textToCopy = document.querySelector(e);
  var textBox = document.querySelector(".clipboard");
  textBox.setAttribute('value', textToCopy.innerHTML);

  textBox.select();
  document.execCommand('copy');
}

.hidden {
  position: fixed;
  bottom: 0;
  right: 0;
  pointer-events: none;
  opacity: 0;
  transform: scale(0);
}

<h4 class="text" align="center">Text data to copy</h4>

<button onclick="copyText('.text')" class="copy">Copy</button>
<br><br>
<textarea></textarea>

<input class="clipboard hidden" />


问:
loading only some images in HTML and angularJS
In this images shows what happen
HTML code is here- In this some of my images showing in webpage and some of is not..how should i fix it</p>

```<code><img src="img/uploadFiles/{{room.imageLocation.split('//')[6]}}/{{room.imageLocation.split('-')[1]}}" alt="Image Loading Failed"/>
</code>```

答:
```<code><img src="img/uploadFiles/{{room.imageLocation.split('//')[6]}}/{{room.imageLocation.split('-')[1]}}" alt="Image Loading Failed" onError="this.src='./assets/img/placeholder.png'" />
</code>```


问:
Get button click from reusable cell in collection view (xib file)
I have created reusable cell with include a button in a XIB for a collection.

I can change the text of labels and buttons in the collection view but i can't get on click event.

I have tried below options:

a.   This in UICollectionViewCell :  Not working

```<code>class cellVC: UICollectionViewCell {
    @IBOutlet weak var sampleLabel: UILabel!
    @IBOutlet weak var buttonClicked: UIButton!

    @IBAction func buttonTest(_ sender: Any) {
        print("dsfsdf   111111")
    }
}
</code>```

b. I have also tried : Not working

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{

    let cell : cellVC = collectionView.dequeueReusableCell(withReuseIdentifier: "cellVC", for: indexPath) as! cellVC
    cell.sampleLabel. = "sample text"
    cell.buttonClicked.tag = indexPath.row
    cell.buttonClicked.addTarget(self, action: #selector(masterAction(sender:)), for: .touchUpInside)

    cell.buttonClicked.backgroundColor = UIColor.cyan
    return cell
}

func masterAction(_ sender: UIButton) {
    print ("button click")
}
</code>```

As both solutions are not working, how do i achieve this.

Thanks

答:
This sometimes happen when the button is linked to the File's Owner instead of your cell.

Right click on the button in IB and check if the referencing outlet is correct, this should be your cell and not the File's Owner like in the image below:

Body:
I have created reusable cell with include a button in a XIB for a collection.

I can change the text of labels and buttons in the collection view but i can't get on click event.

I have tried below options:

a.   This in UICollectionViewCell :  Not working

class cellVC: UICollectionViewCell {
    @IBOutlet weak var sampleLabel: UILabel!
    @IBOutlet weak var buttonClicked: UIButton!

    @IBAction func buttonTest(_ sender: Any) {
        print("dsfsdf   111111")
    }
}

b. I have also tried : Not working

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{

    let cell : cellVC = collectionView.dequeueReusableCell(withReuseIdentifier: "cellVC", for: indexPath) as! cellVC
    cell.sampleLabel. = "sample text"
    cell.buttonClicked.tag = indexPath.row
    cell.buttonClicked.addTarget(self, action: #selector(masterAction(sender:)), for: .touchUpInside)

    cell.buttonClicked.backgroundColor = UIColor.cyan
    return cell
}

func masterAction(_ sender: UIButton) {
    print ("button click")
}

As both solutions are not working, how do i achieve this.

Thanks


问:
Rails 3 on dreamhost?
I'd like to deploy a small Rails 3 app on dreamhost (just for testing purposes, nothing serious) and I am wondering if anyone has done it already... Please choose one of the following:

I did it and it's super easy, here's how: ...

Though I didn't try it, it should be easy, here's how: ...

It's quite complicated, but this should get you started: ....

NO WAI!!!1!one!1 Set it up on slicehost or another non-shared hosting or you'll die a painful death trying to force it on DH

Thoughts?

答: The dreamhost machine I have allocated space on, pisces, appears to have upgraded to Rails 3.0.3 yesterday.  I only noticed because a Redmine instance broke horribly :(</p>

Title: Rails 3 on dreamhost?


问:
Yocto Jethro: Is root login completely disabled when I remove "debug-tweaks"
I removed "debug-tweaks" from EXTRA_IMAGE_FEATURES in my local.conf.
Does this completely disable root logins? Or just that root password has defaulted to some other password?

I do not see anything set to EXTRA_IMAGE_FEATURES

```<code>$ bitbake -e | grep "^EXTRA_IMAGE_FEATURES"
EXTRA_IMAGE_FEATURES=""
</code>```

答:
http://www.yoctoproject.org/docs/2.0/ref-manual/ref-manual.html#ref-features-image

If you don't enable debug-tweaks (or more specifically, empty-root-password) then it is up to you to set the root password.  If you didn't set it then the root user has no password, so they can't login.

To set users and passwords you can use the extrausers class:

http://www.yoctoproject.org/docs/2.0/ref-manual/ref-manual.html#ref-classes-extrausers

Body:
I removed "debug-tweaks" from EXTRA_IMAGE_FEATURES in my local.conf.
Does this completely disable root logins? Or just that root password has defaulted to some other password?

I do not see anything set to EXTRA_IMAGE_FEATURES

$ bitbake -e | grep "^EXTRA_IMAGE_FEATURES"
EXTRA_IMAGE_FEATURES=""


问:
TypeError: Cannot read property 'Roboto-Regular.ttf' of undefined
Trying to build a PDF using the JS API PdfMake :

```<code><script type="text/javascript" src="/app/js/vfs_fonts.js"></script>
<script type="text/javascript" src="/app/js/pdfmake.min.js"></script>
</code>```

Then according to this Helloworld , i run :

```<code> var docDef={ content: 'This is an sample PDF printed with pdfMake' }
 pdfMake.createPdf(docDef).download('optionalName.pdf');
</code>```

i've got this error :

Uncaught TypeError: Cannot read property 'Roboto-Regular.ttf' of
undefined

Does Roboto-Regular.ttf File is required ?

And Where to put it ,if so ?

答:
I had the same issue, but including the files using script tags, by the correct order, or with the require JS fix didn't work.

What worked for me was replacing vfs_fonts.js for its latest version from the pdfmake GitHub repository.

Body:
Trying to build a PDF using the JS API PdfMake :

Then according to this Helloworld , i run :

 var docDef={ content: 'This is an sample PDF printed with pdfMake' }
 pdfMake.createPdf(docDef).download('optionalName.pdf');

i've got this error :

Uncaught TypeError: Cannot read property 'Roboto-Regular.ttf' of
undefined

Does Roboto-Regular.ttf File is required ?

And Where to put it ,if so ?


问:
connect ionic3 with socket clusters websocket or socket.io
I have working code with cordova but want to transform it to ionic3 but unable to find any reference. I don't want to use Fire-base i have my own socket server.  I know i could have added some of my code to it but i am only able to find of ionic 2#

答:
You can use some Angularjs websocket wrapper, like this.</p>

```<code>import {$WebSocket} from 'angular2-websocket/angular2-websocket'
const ws = new $WebSocket("url");
ws.send(event);
</code>```

Body:
You can use some Angularjs websocket wrapper, like this.

import {$WebSocket} from 'angular2-websocket/angular2-websocket'
const ws = new $WebSocket("url");
ws.send(event);


问:
How to write builder pattern using java 8 lambda or lombok
I have pojo classes as shown below.

```<code>public class Car {
    private Engine engine;
    private List<Wheel> wheelList;
}
</code>```

I am using Below pojo classes as parameters in "Car" pojo class.

```<code>public class Engine {
    private int power;
    private int type;
}

public class Wheel {
    private int size;
    private int type;
    private int colour;
}
</code>```

Can you please help how to write builder pattern using java 8 lambda or lombok.

答:
The builder patten is often used to construct objects with many
  properties. It makes it easier to read initialisations by having
  parameters named at the callsite, while helping you only allow the
  construction of valid objects.

Builder implementations tend to either rely on the constructed object
  being mutable, and setting fields as you go, or on duplicating all the
  settable fields within the builder.

Since Java 8, I find myself frequently creating lightweight builders
  by defining an interface for each initialisation stage.

you should definitely read this -

http://benjiweber.co.uk/blog/2014/11/02/builder-pattern-with-java-8-lambdas/

Body:
I have pojo classes as shown below.

public class Car {
    private Engine engine;
    private List<Wheel> wheelList;
}

I am using Below pojo classes as parameters in "Car" pojo class.

public class Engine {
    private int power;
    private int type;
}

public class Wheel {
    private int size;
    private int type;
    private int colour;
}

Can you please help how to write builder pattern using java 8 lambda or lombok.


问:
I just want to display data according to the day
I'm developing a Timetable app for my department and I want to display Schedule for the day according to the day (i.e. Mon,tue,Wed etc)

```<code>package com.example.aravinth1.timetable;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Date;

public class Today extends Fragment {
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle("Today");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    //code for getting day
    Date currentDate = new Date(System.currentTimeMillis());
    String date = currentDate.toString();
    String arr[] = date.split(" ");
    String dayOfWeek = arr[0];
    //switch to select the layout
    //according to the day
    switch (dayOfWeek){
        case "Mon":
            return inflater.inflate(R.layout.moday, container, false);
        break;
        case "Tue":
            return inflater.inflate(R.layout.tuesday, container, false);
        break;
        case "Wed":
            return inflater.inflate(R.layout.wednesday, container, false);
        break;
        case "Thu":
            return inflater.inflate(R.layout.thursday, container, false);
        break;
        case "Fri":
            return inflater.inflate(R.layout.friday, container, false);
        break;
        case "Sat":
            return inflater.inflate(R.layout.saturday, container, false);
        break;
        case "Sun":
            return inflater.inflate(R.layout.sunday, container, false);
        break;
    }
    //how to return the inflated view
}
}
</code>```

In the before mentioned code how do i return the inflated view according to the day? Is using switch statement corrent in this context?

答:
Use the Calendar class to get the current day of the week in Android.</p>

```<code>Calendar calendar = Calendar.getInstance();
int today = calendar.get(Calendar.DAY_OF_WEEK);

switch (today) {
    case Calendar.MONDAY:
        return inflater.inflate(R.layout.moday, container, false);

    case Calendar.TUESDAY:
        return inflater.inflate(R.layout.tuesday, container, false);

    case Calendar.WEDNESDAY:
        //etc...
}
</code>```

Body:
I'm developing a Timetable app for my department and I want to display Schedule for the day according to the day (i.e. Mon,tue,Wed etc)

package com.example.aravinth1.timetable;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Date;

public class Today extends Fragment {
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle("Today");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    //code for getting day
    Date currentDate = new Date(System.currentTimeMillis());
    String date = currentDate.toString();
    String arr[] = date.split(" ");
    String dayOfWeek = arr[0];
    //switch to select the layout
    //according to the day
    switch (dayOfWeek){
        case "Mon":
            return inflater.inflate(R.layout.moday, container, false);
        break;
        case "Tue":
            return inflater.inflate(R.layout.tuesday, container, false);
        break;
        case "Wed":
            return inflater.inflate(R.layout.wednesday, container, false);
        break;
        case "Thu":
            return inflater.inflate(R.layout.thursday, container, false);
        break;
        case "Fri":
            return inflater.inflate(R.layout.friday, container, false);
        break;
        case "Sat":
            return inflater.inflate(R.layout.saturday, container, false);
        break;
        case "Sun":
            return inflater.inflate(R.layout.sunday, container, false);
        break;
    }
    //how to return the inflated view
}
}

In the before mentioned code how do i return the inflated view according to the day? Is using switch statement corrent in this context?

Body:
Use the Calendar class to get the current day of the week in Android.

Calendar calendar = Calendar.getInstance();
int today = calendar.get(Calendar.DAY_OF_WEEK);

switch (today) {
    case Calendar.MONDAY:
        return inflater.inflate(R.layout.moday, container, false);

    case Calendar.TUESDAY:
        return inflater.inflate(R.layout.tuesday, container, false);

    case Calendar.WEDNESDAY:
        //etc...
}


问:
Case sensitive sybase query: Invalid column name
Details:

2 databases: sybase version 15 and sybase version 16

1 table each (identical): AuthRole with columns id, rolename and description

Tried both jTDS and jconn drivers

Query:

```<code>SELECT t1.roleName FROM AuthRole t1;
</code>```

Results:

Sybase 15: rows returned successfully. 'roleName' could be upper, lower or a mix of case, i.e. not case sensitive

Sybase 16: Invalid column name 'roleName'. It will only work with 'rolename' which is the exact case of the column. Anyone know why this would happen and how to resolve it?

答:
Sounds like an issue with the sort order, eg:

ASE 15 is configured with a case-insensitive sort order

ASE 16 is configured with a case-sensitive sort order

You should be able to confirm the above by running sp_helpsort.

In ASE, case (in)sensitivity applies to data as well as identifiers (eg, table/column names).

To get ASE 16 to function like ASE 15, the DBA will need to change the sort order in the ASE 16 dataserver (I'd suggest they also verify the character set while they're at it).

Keep in mind that changing the sort order (and/or character set) is a dataserver-wide configuration and will require (at a minimum) a rebuild of all indexes and re-running of update index statistics. [For more info the DBA should refer to the ASE System Administration Guide, Chapter on Configuring Character Sets, Sort Orders and Languages.]

Body:
Details:

2 databases: sybase version 15 and sybase version 16

1 table each (identical): AuthRole with columns id, rolename and description

Tried both jTDS and jconn drivers

Query:

SELECT t1.roleName FROM AuthRole t1;

Results:

Sybase 15: rows returned successfully. 'roleName' could be upper, lower or a mix of case, i.e. not case sensitive

Sybase 16: Invalid column name 'roleName'. It will only work with 'rolename' which is the exact case of the column. Anyone know why this would happen and how to resolve it?


问:
One should choose recursion over iteration?
Why should one choose recursion over iteration, when a solution has the same time complexity for both cases but better space complexity for iterative?</p>

答: Here's a particular example of a case where there are extra considerations. Tree search algorithms can be defined recursively (because each subtree of a tree is a tree) or iteratively (with a stack). However, while a recursive search can work perfectly for finding the first leaf with a certain property or searching over all leaves, it does not lend itself to producing a well-behaved iterator: an object or function state that returns a leaf, and later when called again returns the next leaf, etc. In an iterative design the search stack can be stored as a static member of the object or function, but in a recursive design the call stack is lost whenever the function returns and is difficult or expensive to recreate.</p>


问:
Convert method to Delegate?
I want to call for example TryDo.Do(MessageBox.Show(""), null);

how can I do that??

```<code>using System;

namespace TryCatchHandlers
{
    public static class TryDo
    {
        public static CallResult Do(Delegate action, params object[] args)
        {
            try
            {
                return new CallResult (action.DynamicInvoke(args), action.Method.ReturnType, true);
            }
            catch
            {
                return new CallResult(null, null, false);
            }
        }
    }

    public class CallResult
    {
        public CallResult() { }

        internal CallResult(object result, Type resultType, bool isSuccessful)
        {
            Result = result;
            ResultType = resultType;
            IsSuccessful = isSuccessful;
        }
        public object Result { get; private set; }
        public Type ResultType { get; private set; }
        public bool IsSuccessful { get; private set; }
    }
}
</code>```

答:
It's because MessageBox.Show("") is a method call, not a delegate, so

```<code>TryDo.Do(MessageBox.Show(""),null);
</code>```

actually tries to call TryDo.Do with the result of the MessageBox.Show call.

You actually need to transfer a delegate that contains the method you are trying to call, because

```<code>TryDo.Do(MessageBox.Show,null);
</code>```

will also fail, with an error that a Method cannot be cast as delegate.

The simplest way to create a delegate from a method is to use the Func<..> and Action<...> generic delegates (Func for those methods that return something, Action for those that are void), like this:

```<code>var myDelegate = new Func<string, DialogResult>(MessageBox.Show);
TryDo.Do(myDelegate, null)
</code>```

Title: Convert method to Delegate?

Body:
I want to call for example TryDo.Do(MessageBox.Show(""), null);

how can I do that??

using System;

namespace TryCatchHandlers
{
    public static class TryDo
    {
        public static CallResult Do(Delegate action, params object[] args)
        {
            try
            {
                return new CallResult (action.DynamicInvoke(args), action.Method.ReturnType, true);
            }
            catch
            {
                return new CallResult(null, null, false);
            }
        }
    }

    public class CallResult
    {
        public CallResult() { }

        internal CallResult(object result, Type resultType, bool isSuccessful)
        {
            Result = result;
            ResultType = resultType;
            IsSuccessful = isSuccessful;
        }
        public object Result { get; private set; }
        public Type ResultType { get; private set; }
        public bool IsSuccessful { get; private set; }
    }
}

Body:
It's because MessageBox.Show("") is a method call, not a delegate, so

TryDo.Do(MessageBox.Show(""),null);

actually tries to call TryDo.Do with the result of the MessageBox.Show call.

You actually need to transfer a delegate that contains the method you are trying to call, because

TryDo.Do(MessageBox.Show,null);

will also fail, with an error that a Method cannot be cast as delegate.

The simplest way to create a delegate from a method is to use the Func<..> and Action<...> generic delegates (Func for those methods that return something, Action for those that are void), like this:

var myDelegate = new Func<string, DialogResult>(MessageBox.Show);
TryDo.Do(myDelegate, null)


问:
Drools list type field
How can I add a field of type list in my xmlrequest?

for example I have following class

```<code>public class app{
    private java.util.List<java.lang.Integer> test;
    private int age;
     public int getAge()
     {
        return this.age;
      }

    public void setAge(int age)
    {
        this.age = age;
     }
    public java.util.List<java.lang.Integer> getTest()
      {
         return this.test;
       }

   public void setTest(java.util.List<java.lang.Integer> test)
        {
            this.test = test;
          }

        }
</code>```

and following is xmlrequest format.

```<code><batch-execution lookup="defaultStatelessKieSession">
 <insert>
<com.redhat.loandemo.app>
  <age>41</age>
  <test></test>
   </com.redhat.loandemo.app>
  </insert>
  <fire-all-rules/>
   <get-objects out-identifier="output"/>
  </batch-execution>
</code>```

here test is list of integers. so how can I add it to xmlrequest?

答:
Your XML request should be:

```<code><batch-execution lookup="defaultStatelessKieSession">
<insert>
    <com.redhat.loandemo.app>
        <age>41</age>
        <test>1</test>
        <test>2</test>
        <test>3</test>
        <test>4</test>
    </com.redhat.loandemo.app>
</insert>
<fire-all-rules/>
<get-objects out-identifier="output"/>
</code>```

Title: Drools list type field

Body:
How can I add a field of type list in my xmlrequest?

for example I have following class

public class app{
    private java.util.List<java.lang.Integer> test;
    private int age;
     public int getAge()
     {
        return this.age;
      }

    public void setAge(int age)
    {
        this.age = age;
     }
    public java.util.List<java.lang.Integer> getTest()
      {
         return this.test;
       }

   public void setTest(java.util.List<java.lang.Integer> test)
        {
            this.test = test;
          }

        }

and following is xmlrequest format.

<batch-execution lookup="defaultStatelessKieSession">
 <insert>
<com.redhat.loandemo.app>
  <age>41</age>
  <test></test>
   </com.redhat.loandemo.app>
  </insert>
  <fire-all-rules/>
   <get-objects out-identifier="output"/>
  </batch-execution>

here test is list of integers. so how can I add it to xmlrequest?

Body:
Your XML request should be:

<batch-execution lookup="defaultStatelessKieSession">
<insert>
    <com.redhat.loandemo.app>
        <age>41</age>
        <test>1</test>
        <test>2</test>
        <test>3</test>
        <test>4</test>
    </com.redhat.loandemo.app>
</insert>
<fire-all-rules/>
<get-objects out-identifier="output"/>


问:
NotFound route always showing with static routes - [React Router 4]
How can I define a notFound component with React Router 4 and static routes?

I use the nextversion of react-router-redux. So, in my client:

```<code>export default function appRoutes(history) {
  return (
    <ConnectedRouter history={history}>
      <div>
        {routes.map((route, key) => (
          <Route key={key} {...route} />
        ))}
      </div>
    </ConnectedRouter>
  );
}
</code>```

And routes is:

```<code>export const routes = [
  {
    path: '/',
    component: App
  },
  {
    path: '/:lang/chat',
    component: Chat
  },
  {
    path: '/:lang',
    component: Listing
  },
  ...
  {
    path: '*',
    component: NotFound,
    status: 404
  },
];
</code>```

With this approach, the component not found is always showing along with the matched route.

I have read that instead of wrapping the appRoutes method described above, with a div, I have to use Switch. But with this approach, the routes never match.

EDIT

I want to display, for example, App component and Listing component at the same time but the NotFound is also displaying.

So, what I'm doing wrong?

答: React router V4 displays all routes that match. If you would like to display just one use Switch component.</p>

Body:
How can I define a notFound component with React Router 4 and static routes?

I use the nextversion of react-router-redux. So, in my client:

export default function appRoutes(history) {
  return (
    <ConnectedRouter history={history}>

        {routes.map((route, key) => (
          <Route key={key} {...route} />
        ))}

    </ConnectedRouter>
  );
}

And routes is:

export const routes = [
  {
    path: '/',
    component: App
  },
  {
    path: '/:lang/chat',
    component: Chat
  },
  {
    path: '/:lang',
    component: Listing
  },
  ...
  {
    path: '*',
    component: NotFound,
    status: 404
  },
];

With this approach, the component not found is always showing along with the matched route.

I have read that instead of wrapping the appRoutes method described above, with a div, I have to use Switch. But with this approach, the routes never match.

EDIT

I want to display, for example, App component and Listing component at the same time but the NotFound is also displaying.

So, what I'm doing wrong?


答:
Off the top of my head:

In older versions of Sybase ASE you had to carefully set the case-sensitivity at server installation time.  The installer defaults to case-sensitive. Maybe the admin who installed ASE15 noticed this (and changed the default to case-insensitive), whereas the admin who installed your ASE16 didn't.

Yes, case-Sensitivity is a property of the Server. You can change it at a later time with sp_configure or ALTER DATABASE, or both (I don't remember and I don't have the time to look it up). You can also use a graphical admin tool to change the server default sort order.

In any case  only databases created after that configuration change will be affected. Confusingly, older databases will still be case-sensitive, or lots of warnings will be issued. This is because in your older tables, all primary keys (PK)  are implemented as indices, in assume case-sensitivity, and PKs and the PK indices cannot be changed by an installer or a config wizard.
In fact, you have to drop and re-create the indices and run dbcc something (again I don't remember).

For small databases, this drop-and-recreate of indices can of cause be done (use a script or a database reengineering tool to do so). For larger databases this can take some time.

Maybe it's different for ASE16 -check the docuemntation

Title: Case sensitive sybase query: Invalid column name


问:
JSF: Insert String Date Of Month-Day-Year Into Mysql
I have Date in my java blue print that is format as month-day-year.
This is the code for it

```<code>public String getFormattedDate() {
    return new SimpleDateFormat("MM-dd-yyyy").format(dueDate);
}
</code>```

I want to convert or insert this date into mysql prepared statement using the same format at month-day-year. But some how I can't get it to work.
I have something like this

```<code>ps.setString(5, out.getFormattedDate());
</code>```

and when I run my code I get this error message

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date
  value: '04-01-2017' for column 'DueDate' at row 1

This is my the insert statement I am using, I case if it help

```<code>String query = "INSERT INTO Checkout (FirstName, LastName, EmailAddress, BookTitle, DueDate) "
            + "VALUE (?, ?, ?, ?, ?)";
</code>```

I was hoping that some could help me.

答:
You're setting a String value into a Date value.
Your DueDate column is a date value, so you have to change it to varchar or when you execute a select you have to use the DATE_FORMAT function.
So you have two options:

*Use the DATE_FORMAT function:

SELECT DATE_FORMAT(DueDate,'%m/%d/%Y') AS 'FormatDate' FROM Checkout

(this select returns a String value)

*Change DueDate to varchar in MySQL.

Hope i solved your/someone else problem. (A little late).

Body:
I have Date in my java blue print that is format as month-day-year.
This is the code for it

public String getFormattedDate() {
    return new SimpleDateFormat("MM-dd-yyyy").format(dueDate);
}

I want to convert or insert this date into mysql prepared statement using the same format at month-day-year. But some how I can't get it to work.
I have something like this

ps.setString(5, out.getFormattedDate());

and when I run my code I get this error message

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date
  value: '04-01-2017' for column 'DueDate' at row 1

This is my the insert statement I am using, I case if it help

String query = "INSERT INTO Checkout (FirstName, LastName, EmailAddress, BookTitle, DueDate) "
            + "VALUE (?, ?, ?, ?, ?)";

I was hoping that some could help me.


问:
Show linked servers in PostgreSQL
I used the below to create a link to an Oracle server from Postgresql. I see there are methods to alter and drop the server but I can not find a command that lists all available servers that have been created.

Is the information stored anywhere in postgresql?
Where I can view it?

```<code>CREATE EXTENSION oracle_fdw;
CREATE SERVER oradb FOREIGN DATA WRAPPER oracle_fdw
</code>```

答:
You can also use the following commands in pgsql-client

\det+ - List of foreign tables

\des+ - List of foreign servers

Title: Show linked servers in PostgreSQL

Body:
I used the below to create a link to an Oracle server from Postgresql. I see there are methods to alter and drop the server but I can not find a command that lists all available servers that have been created.

Is the information stored anywhere in postgresql?
Where I can view it?

CREATE EXTENSION oracle_fdw;
CREATE SERVER oradb FOREIGN DATA WRAPPER oracle_fdw


问:
Simultaneously assign many instances' properties
Suppose I have a class:

```<code>class Foo:
    def __init__(self):
        self.prop = None
</code>```

I need to do:

```<code>[foo1.prop, foo2.prop, ..., fooN.prop] = [prop_value1, prop_value2, ..., prop_value3]
</code>```

Obviously, N is not the same always, so I should do it dynamically. The first approach is do it with a for loop:

```<code>for foo, value in zip(foo_list, value_list):
    foo.prop = value
</code>```

But the question is... Is there a better approach in Python? I mean higher performance.

By the way, N > 1000.

答:
One way you might get some improvement is assuming that you save your class variables already into a python-compatible dict (think pickle). Then you can do do something similar to

```<code>Foo.__dict__ = loaded_dict_value
</code>```

This might be faster than your proposed method due to the fact that

```<code>Foo.value = loaded_value
</code>```

Is equivalent to Foo.__dict__['value'] = loaded_value. This means one more search (For the memory location of 'value' in __dict__. However I don't suspect you will gain much performance out of this.

Body:
Suppose I have a class:

class Foo:
    def __init__(self):
        self.prop = None

I need to do:

[foo1.prop, foo2.prop, ..., fooN.prop] = [prop_value1, prop_value2, ..., prop_value3]

Obviously, N is not the same always, so I should do it dynamically. The first approach is do it with a for loop:

for foo, value in zip(foo_list, value_list):
    foo.prop = value

But the question is... Is there a better approach in Python? I mean higher performance.

By the way, N > 1000.

Body:
One way you might get some improvement is assuming that you save your class variables already into a python-compatible dict (think pickle). Then you can do do something similar to

Foo.__dict__ = loaded_dict_value

This might be faster than your proposed method due to the fact that

Foo.value = loaded_value

Is equivalent to Foo.__dict__['value'] = loaded_value. This means one more search (For the memory location of 'value' in __dict__. However I don't suspect you will gain much performance out of this.


问:
Hive SQL: Both left and right aliases encountered in JOIN
I have this valid T-SQL query:

```<code>select t1.*
    ,case when s1.period is not null then 'Y' else 'N' end as flag_cur
    ,case when s2.period is not null then 'Y' else 'N' end as flag_prev
    ,s1.cutoff_date as cutoff_date_cur ,s1.cutoff_dtkey as cutoff_dtkey_cur
    ,s2.cutoff_date as cutoff_date_prev ,s2.cutoff_dtkey as cutoff_dtkey_prev
into #tmp_leads2
from #tmp_leads t1
left join #param s1 on s1.period = '(a) Current' and s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date
left join #param s2 on s2.period = '(b) Previous' and s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date
</code>```

I tried to re-write it for Hive (v0.13) as:

```<code>create table tmp_leads2 as
select t1.*
    ,case when s1.period is not null then 'Y' else 'N' end as flag_cur
    ,case when s2.period is not null then 'Y' else 'N' end as flag_prev
    ,s1.cutoff_date as cutoff_date_cur ,s1.cutoff_dtkey as cutoff_dtkey_cur
    ,s2.cutoff_date as cutoff_date_prev ,s2.cutoff_dtkey as cutoff_dtkey_prev
from tmp_leads t1
left join param s1 on s1.period = '(a) Current'  and s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date
left join param s2 on s2.period = '(b) Previous' and s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date ;
</code>```

But I get the error:

```<code>Error occurred executing hive query: OK FAILED: SemanticException [Error 10017]: Line 8:53 Both left and right aliases encountered in JOIN 'CreatedDate'
</code>```

I see the fields it's talking about, but I'm not sure how to re-write this while keeping the query results identical.

答:
Here is something which would not cause inner join or alias issue and give you the expected results in Hive</p>

```<code>   create table tmp_leads2 as
   select final.*
       ,case when s1period is not null then 'Y' else 'N' end as flag_cur
       ,case when s2period is not null then 'Y' else 'N' end as flag_prev

    from
    (select t1.*,
       max(case when  s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date then s1.peroid else null end) as s1period,
       max(case when  s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date then s1.cutoff_date else null end) as cutoff_date_cur,
       max(case when  s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date then s1.cutoff_dtkey else null end) as cutoff_dtkey_cur,

       max(case when  s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date then s2.peroid else null end) as s2period,
       max(case when  s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date then s2.cutoff_date else null end) as cutoff_date_prev,
       max(case when  s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date then s2.cutoff_dtkey else null end) as cutoff_dtkey_prev,

   from tmp_leads t1
   left join param s1 on s1.period = '(a) Current'
   left join param s2 on s2.period = '(b) Previous'
   group by t1.* /* type all column names required from t1*/
   ) final ;
</code>```

Body:
I have this valid T-SQL query:

select t1.*
    ,case when s1.period is not null then 'Y' else 'N' end as flag_cur
    ,case when s2.period is not null then 'Y' else 'N' end as flag_prev
    ,s1.cutoff_date as cutoff_date_cur ,s1.cutoff_dtkey as cutoff_dtkey_cur
    ,s2.cutoff_date as cutoff_date_prev ,s2.cutoff_dtkey as cutoff_dtkey_prev
into #tmp_leads2
from #tmp_leads t1
left join #param s1 on s1.period = '(a) Current' and s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date
left join #param s2 on s2.period = '(b) Previous' and s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date

I tried to re-write it for Hive (v0.13) as:

create table tmp_leads2 as
select t1.*
    ,case when s1.period is not null then 'Y' else 'N' end as flag_cur
    ,case when s2.period is not null then 'Y' else 'N' end as flag_prev
    ,s1.cutoff_date as cutoff_date_cur ,s1.cutoff_dtkey as cutoff_dtkey_cur
    ,s2.cutoff_date as cutoff_date_prev ,s2.cutoff_dtkey as cutoff_dtkey_prev
from tmp_leads t1
left join param s1 on s1.period = '(a) Current'  and s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date
left join param s2 on s2.period = '(b) Previous' and s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date ;

But I get the error:

Error occurred executing hive query: OK FAILED: SemanticException [Error 10017]: Line 8:53 Both left and right aliases encountered in JOIN 'CreatedDate'

I see the fields it's talking about, but I'm not sure how to re-write this while keeping the query results identical.

Body:
Here is something which would not cause inner join or alias issue and give you the expected results in Hive

   create table tmp_leads2 as
   select final.*
       ,case when s1period is not null then 'Y' else 'N' end as flag_cur
       ,case when s2period is not null then 'Y' else 'N' end as flag_prev

    from
    (select t1.*,
       max(case when  s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date then s1.peroid else null end) as s1period,
       max(case when  s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date then s1.cutoff_date else null end) as cutoff_date_cur,
       max(case when  s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date then s1.cutoff_dtkey else null end) as cutoff_dtkey_cur,

       max(case when  s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date then s2.peroid else null end) as s2period,
       max(case when  s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date then s2.cutoff_date else null end) as cutoff_date_prev,
       max(case when  s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date then s2.cutoff_dtkey else null end) as cutoff_dtkey_prev,

   from tmp_leads t1
   left join param s1 on s1.period = '(a) Current'
   left join param s2 on s2.period = '(b) Previous'
   group by t1.* /* type all column names required from t1*/
   ) final ;


问:
Populate ComboBox with Enum in Delphi with MySQL
I have an Enum TRole

```<code>type
  TRole = (Admin, Common);
</code>```

In my database (MySQL), I have a table users with a column role of type INTEGER. I want to populate a ComboBox with the Roles in the following way:
The ComboBox should display "Administrator" in the role Admin and "Common User" in the role Common; when I save the value to the database, it should be save as 0 for the Admin role or 1 for the Common Role (their respective indexes).

Also, when displaying the role field, it should be displayed as the Strings showed above.

Can anyone please explain me how can I do that?

答:
I have used two different approaches to solve this problem. One is to use RTTI to derive the name from the enum, but that would not work in your case, so here is my other method, which is more brute force:

(You can adapt to your use - note my actual functions are from classes, but that is not important)

```<code>function EnumAsText(
  const pEnum: TRole): string;
const
  cResults : array[ TRole ] of string =
  (
     {Admin}            'Admintrator',
     {Common}           'Common User'
  );
begin
  Result := cResults[ pEnum ];
end;
</code>```

Then fill the drop down with something Like

```<code>procedure FillComboBox( Const pComboBox : TComboBox )
var
  iRole : TRole;
begin
  pComboBox.Items.Clear;
  for iRole := low( TRole ) to Hi(TRole) do
  begin
    pComboBox.Items.Add( EnumAsText( iRole ) );
  end;
end;
</code>```

The advantage of use the const array in EnumToText as opposed to a case statement (the obvious way to do it) is that if you extend the enum, the compiler will force you to modify the function accordingly.
The ItemIndex of the combo box corresponds to your integer field.

Body:
I have an Enum TRole

type
  TRole = (Admin, Common);

In my database (MySQL), I have a table users with a column role of type INTEGER. I want to populate a ComboBox with the Roles in the following way:
The ComboBox should display "Administrator" in the role Admin and "Common User" in the role Common; when I save the value to the database, it should be save as 0 for the Admin role or 1 for the Common Role (their respective indexes).

Also, when displaying the role field, it should be displayed as the Strings showed above.

Can anyone please explain me how can I do that?

Body:
I have used two different approaches to solve this problem. One is to use RTTI to derive the name from the enum, but that would not work in your case, so here is my other method, which is more brute force:

(You can adapt to your use - note my actual functions are from classes, but that is not important)

function EnumAsText(
  const pEnum: TRole): string;
const
  cResults : array[ TRole ] of string =
  (
     {Admin}            'Admintrator',
     {Common}           'Common User'
  );
begin
  Result := cResults[ pEnum ];
end;

Then fill the drop down with something Like

procedure FillComboBox( Const pComboBox : TComboBox )
var
  iRole : TRole;
begin
  pComboBox.Items.Clear;
  for iRole := low( TRole ) to Hi(TRole) do
  begin
    pComboBox.Items.Add( EnumAsText( iRole ) );
  end;
end;

The advantage of use the const array in EnumToText as opposed to a case statement (the obvious way to do it) is that if you extend the enum, the compiler will force you to modify the function accordingly.
The ItemIndex of the combo box corresponds to your integer field.


问:
Choose from options based on values from previous rows
** The data is a sample data of 20 orders across a universe of 3 stores.Trying to write an algorithm to identify which store would cater to which order based on the rules **

If there is more than 1 store eligible for an order, the store that has catered to the least quantities of order cumulatively will cater to the current order.
  For example, If S1, S2, & S3 has catered to 100, 150, 75 units of orders till order #3 and S1 & S2 are eligible for order #4, then S1 will cater to order #4

```<code>OrderNum|OrderQty|StoresEligible
------- |--------|--------------
1|12|S3
2|10|S1
3|19|S1,S2
4|7|S1,S2
5|14|S1,S2,S3
6|19|S2
7|5|S1,S2
8|17|S2
9|13|S3
10|5|S1
</code>```

In reality, there are 2,000 stores in the US and 1M orders

答:
OK this solves part of your problem, it's a function to add a new line to your data, taking as input the past data (to which I added the ChoosenStore information) the quantity and the eligible stores; it outputs the data.frame with the N+1 order completed:

You will have to apply iteratively this function to your past data to complete it.

```<code>library(dplyr); library(tidyr)
# initialise the data.frame with just the first 3 lines
df=data.frame(OrderNum=1:3, OrderQty=c(12,10,19),
              StoresEligible=c("S3", "S1", "S1, S2"),
              ChoosenStore=c("S3", "S1", "S2"),stringsAsFactors=FALSE)
# function to compute new incoming order
NewOrder = function(df, quantity, eligible){
  choosen <- df %>% filter(ChoosenStore %in% eligible) %>%
    group_by(ChoosenStore) %>%
    summarise(CumQty=sum(OrderQty)) %>%
    top_n(-1, CumQty) %>% .$ChoosenStore
  return(rbind(df, c(tail(df$OrderNum, 1)+1,
                     quantity,
                     paste0(eligible, collapse=", "),
                     choosen)))}
# try it with the 4th line
NewOrder(df, 7, c("S1", "S2"))
</code>```

Body:
** The data is a sample data of 20 orders across a universe of 3 stores.Trying to write an algorithm to identify which store would cater to which order based on the rules **

If there is more than 1 store eligible for an order, the store that has catered to the least quantities of order cumulatively will cater to the current order.
  For example, If S1, S2, & S3 has catered to 100, 150, 75 units of orders till order #3 and S1 & S2 are eligible for order #4, then S1 will cater to order #4

OrderNum|OrderQty|StoresEligible
------- |--------|--------------
1|12|S3
2|10|S1
3|19|S1,S2
4|7|S1,S2
5|14|S1,S2,S3
6|19|S2
7|5|S1,S2
8|17|S2
9|13|S3
10|5|S1

In reality, there are 2,000 stores in the US and 1M orders

Body:
OK this solves part of your problem, it's a function to add a new line to your data, taking as input the past data (to which I added the ChoosenStore information) the quantity and the eligible stores; it outputs the data.frame with the N+1 order completed:

You will have to apply iteratively this function to your past data to complete it.

library(dplyr); library(tidyr)
# initialise the data.frame with just the first 3 lines
df=data.frame(OrderNum=1:3, OrderQty=c(12,10,19),
              StoresEligible=c("S3", "S1", "S1, S2"),
              ChoosenStore=c("S3", "S1", "S2"),stringsAsFactors=FALSE)
# function to compute new incoming order
NewOrder = function(df, quantity, eligible){
  choosen <- df %>% filter(ChoosenStore %in% eligible) %>%
    group_by(ChoosenStore) %>%
    summarise(CumQty=sum(OrderQty)) %>%
    top_n(-1, CumQty) %>% .$ChoosenStore
  return(rbind(df, c(tail(df$OrderNum, 1)+1,
                     quantity,
                     paste0(eligible, collapse=", "),
                     choosen)))}
# try it with the 4th line
NewOrder(df, 7, c("S1", "S2"))


问:
MySQL: How to allow remote connection to mysql
I have installed MySQL Community Edition 5.5 on my local machine and I want to allow remote connections so that I can connect from external source.

How can I do that?

答:
If you installed MySQL from brew it really does only listen on the local interface by default. To fix that you need to edit /usr/local/etc/my.cnf and change the bind-address from 127.0.0.1 to *.

Then run brew services restart mysql.


问:
Linux file: File has 2 columns, Pipe delimited . I need to print the records from the 2nd col whose length is 5 or more chars
I just started learning awk and sed after my first 2 questions in stackOverflow. Thanks to Roman,Hek,Randomnir, Edmorton and many who corrected and helped me wholeheartedly.
Right now i could do changes to awk commands to suit my data requirements. I just need some help from all out here.I'm taking baby steps to fix all unix errors on my own.Some advice will be helpful

My data -

```<code>ID | Passcode
41-1|10551
1-105|5569
 4-7|10043
 78-3|217631
  3-1|19826
 12-1|19818912
</code>```

My output has to be

```<code> ID | Passcode
41-1|10551
  4-7|10043
 78-3|217631
   3-1|19826
 12-1|19818912
</code>```

All the records from the 2nd col which is less than 5char must be deleted or filtered . My o/p file should have only 5chars length or above Passcodes only.

答:
It is pretty simple, just use the length() function to get words of length greater than or equal to 5 after setting the input and output field separators to |

```<code>awk 'BEGIN{FS=OFS="|"} NR==1 || length($2)>=5' file
</code>```

Body:
I just started learning awk and sed after my first 2 questions in stackOverflow. Thanks to Roman,Hek,Randomnir, Edmorton and many who corrected and helped me wholeheartedly.
Right now i could do changes to awk commands to suit my data requirements. I just need some help from all out here.I'm taking baby steps to fix all unix errors on my own.Some advice will be helpful

My data -

ID | Passcode
41-1|10551
1-105|5569
 4-7|10043
 78-3|217631
  3-1|19826
 12-1|19818912

My output has to be

 ID | Passcode
41-1|10551
  4-7|10043
 78-3|217631
   3-1|19826
 12-1|19818912

All the records from the 2nd col which is less than 5char must be deleted or filtered . My o/p file should have only 5chars length or above Passcodes only.

Body:
It is pretty simple, just use the length() function to get words of length greater than or equal to 5 after setting the input and output field separators to |

awk 'BEGIN{FS=OFS="|"} NR==1 || length($2)>=5' file


问:
slow RS - SQL Server 2008 express
I'm having an issue with Reporting Services.
Whenever I start the application, loading of the report list and going through folders takes a lot of time (sometimes more than 10 mins), also goes for entering the report itself. After first report is opened then everything works smooth and folders and reports are opened instantly.
RS is running on IIS V6.0. I've set "shut down worker process after being idle" to 480 mins in the application pool.

Any idea is welcome.
Thank you

答: The problem was in the server itself.. defragmentation and registry cleanup solved most of the issues.</p>

Title: slow RS - SQL Server 2008 express