问:
Difference between user and app-only auth?
I've been read the Twitter docs but must be missing something.

User auth and app-only auth have different rate limits and capabilities, but I'm struggling to get a handle on use cases for each.

Is user auth just for "Sign in with Twitter" style apps, and so because you're acting on behalf of the user you can do more?

What is app only auth? I have generated a key manually for an account I have - because I created this manually without a user is that app only?

Very confused! Any help appreciated.

答:
UPDATE Dec, 2020: Twitter recently launched API v2 and rate limits related to user or app auth are better described in twitter official docs.

This means you can access this API function with an app auth or a user auth tokens. In some requests you only can access with user auth token.

App Auth number: Is the highest number of requests your app can do in a 15min window, with 'app auth' token.

User Auth number: Is the highest number of requests your app can do in a 15min window, with 'user auth' token.

You need to know how your library/module is getting auth. Source

Edit:
App Auth and User Auth are the two ways API twitter can manage OAuth. You can do with this python example using Twython module:

from twython import Twython

# App Auth
tw_auth = Twython(APP_KEY, APP_SECRET, oauth_version=2)
token = tw_auth.obtain_access_token()
twitter = Twython(APP_KEY, access_token=token)
```

<p>By other way, if you want to authenticate with User Tokens:</p>
<pre class="lang-py prettyprint-override"><code>from twython import Twython

# User Auth
tw_auth = Twython(APP_KEY, APP_SECRET)
token = tw_auth.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, auth['oauth_token'],
          auth['oauth_token_secret'])
</code>```

(...this last method is a bit longer, because with the authentication tokens you need to .get_authorized_tokens(prompted_pin) to make a new Twython method call. This is only an example to show you need 4 keys/tokens instead 2)

Now, if you make a request, the counter for your 15min window depends on how you are authenticated:

# Now you are authenticated with *App Auth* or *User Auth*
# Limits will be 450 for AppAuth and 180 for UserAuth in 15min window
results = twitter.search(q='StackOverflow',result_type='recent', count='10')
```

These differences exists because not all API methods support application-only authentication. Some methods require a user context.

Edit:

I could do with real world scenarios where you would use one over the other?

Of course! look this chart about Twitter rate limits and compare. Sometimes you can't make requests with appAuth-only, for example user related actions. Limits are different for each auth, if you want GET statuses/user_timeline maybe you prefer AppAuth, but if you want GET lists/members maybe you would prefer UserAuth, because it has some advantage with rate limits.

Body:
UPDATE Dec, 2020: Twitter recently launched API v2 and rate limits related to user or app auth are better described in twitter official docs.

This means you can access this API function with an app auth or a user auth tokens. In some requests you only can access with user auth token.

App Auth number: Is the highest number of requests your app can do in a 15min window, with 'app auth' token.

User Auth number: Is the highest number of requests your app can do in a 15min window, with 'user auth' token.

You need to know how your library/module is getting auth. Source

Edit:
App Auth and User Auth are the two ways API twitter can manage OAuth. You can do with this python example using Twython module:

from twython import Twython

# App Auth
tw_auth = Twython(APP_KEY, APP_SECRET, oauth_version=2)
token = tw_auth.obtain_access_token()
twitter = Twython(APP_KEY, access_token=token)

By other way, if you want to authenticate with User Tokens:

from twython import Twython

# User Auth
tw_auth = Twython(APP_KEY, APP_SECRET)
token = tw_auth.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, auth['oauth_token'],
          auth['oauth_token_secret'])

(...this last method is a bit longer, because with the authentication tokens you need to .get_authorized_tokens(prompted_pin) to make a new Twython method call. This is only an example to show you need 4 keys/tokens instead 2)

Now, if you make a request, the counter for your 15min window depends on how you are authenticated:

# Now you are authenticated with *App Auth* or *User Auth*
# Limits will be 450 for AppAuth and 180 for UserAuth in 15min window
results = twitter.search(q='StackOverflow',result_type='recent', count='10')

These differences exists because not all API methods support application-only authentication. Some methods require a user context.

Edit:

I could do with real world scenarios where you would use one over the other?

Of course! look this chart about Twitter rate limits and compare. Sometimes you can't make requests with appAuth-only, for example user related actions. Limits are different for each auth, if you want GET statuses/user_timeline maybe you prefer AppAuth, but if you want GET lists/members maybe you would prefer UserAuth, because it has some advantage with rate limits.


来源: stackexchange

问:
Best practices if your Build is taking too long in Visual Studio
I have moderate size solution in Visual Studio which takes around 5 minutes to build (It take that long because of FxCop and other post build steps).
My problem is, Visual Studio stops responding while it's building. You can't continue working as VS almost hangs. I tried using two VS instances, just using one for build, but it keeps crashing every now and then.

My question is, How to not waste time looking at Visual Studio building your large/moderate project. Are there any best practices for this?

答: You can create classes in another project by stubbing the classes that you would need to make the code compiles. This way, you can test and document your new code. After this, you just include it to the real project and you compile "for real". By the time it compiles, you are already working on another snippet of the project because you are 95% it will successfully compiles. Or, by the time it compiles, you can also write your unit tests..</p>

ContentLicense: CC BY-SA 2.5


问:
How to embed images in email
I need to embed an image in e-mail. How do I do it?

I do not want to use third party tool, nor am I interested in language specific answer (but it is PHP, in case you are wondering).

I am merely interested in format of resulting e-mail body.

答: Generally I handle this by setting up an HTML formatted SMTP message, with IMG tags pointing to a content server.  Just make sure you have both text and HTML versions since some email clients cannot support HTML emails.</p>

Title: How to embed images in email


问:
Why can't TypeScript find name 'Express'?
I'm starting an express application using TypeScript.

Here's the code in app.ts:

```<code>import express = require("express");

let app: Express = express();
</code>```

I have installed Express using

```<code>npm install --save express
</code>```

And I've installed @types/express using:

```<code>npm install --save @types/express
</code>```

I'm using Visual Studio Code (1.10.2).
When I hover over the express() function, intellisense suggests that it returns an object of type "Express". So, I've declared the "app" variable as that type, but VS Code puts a red squiggly under it and complains it "cannot find name 'Express'".

Why can't it find it? Or is that the wrong type? If so, why does the intellisense suggest it?

答:
It would appear the variable should actually be of type express.Application.</p>

```<code>let app: express.Application = express();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm starting an express application using TypeScript.

Here's the code in app.ts:

import express = require("express");

let app: Express = express();

I have installed Express using

npm install --save express

And I've installed @types/express using:

npm install --save @types/express

I'm using Visual Studio Code (1.10.2).
When I hover over the express() function, intellisense suggests that it returns an object of type "Express". So, I've declared the "app" variable as that type, but VS Code puts a red squiggly under it and complains it "cannot find name 'Express'".

Why can't it find it? Or is that the wrong type? If so, why does the intellisense suggest it?

Body:
It would appear the variable should actually be of type express.Application.

let app: express.Application = express();


问:
Unexpected results when trying to match string pattern
Given a string, return true if the first instance of "x" in the string is immediately followed by another "x". It will not work for the case of doubleX("axxbb"). It should return true but gives false.</p>

```<code>boolean doubleX(String str) {
  for (int i = 0; i < str.length(); i++) {
    if (str.substring(i) == "x") {
      if ( str.substring(i) == str.substring(i + 1)){
      return true;
      }

    }

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

答:
The substring method gives you the substring of i to the end of the string. For instance:

```<code>str = "test string";
System.out.println(str.substring(3));
</code>```

Would give you a string from 3 to the end of the string ("t string")

Instead of substring use charAt: https://www.tutorialspoint.com/java/java_string_charat.htm

Body:
Given a string, return true if the first instance of "x" in the string is immediately followed by another "x". It will not work for the case of doubleX("axxbb"). It should return true but gives false.

boolean doubleX(String str) {
  for (int i = 0; i < str.length(); i++) {
    if (str.substring(i) == "x") {
      if ( str.substring(i) == str.substring(i + 1)){
      return true;
      }

    }

  }
  return false;
}

Body:
The substring method gives you the substring of i to the end of the string. For instance:

str = "test string";
System.out.println(str.substring(3));

Would give you a string from 3 to the end of the string ("t string")

Instead of substring use charAt: https://www.tutorialspoint.com/java/java_string_charat.htm


问:
Approaches of sending file from server to browser without asking to click on download link
What i am trying to ask is, i have a website which takes the user profile and generates some kind of user specific reports in pdf. Pdf is generated at back end. So when user clicks on "generate" button, it should show blocking message and once the file is generated blocking message is removed and file is displayed with  tag.

I am able to do this with help of socket.io and to be very Frank I copied this solution from one blog without understanding much. So my stack is Python and socket.io is on node. While it worked perfectly on my dev machine but on server its keep on throwing connection error message in JavaScript and post message fails on back end. So I am currently having issues with front and back end. And thanks to my blindly copy paste thing I am kind of clueless about the fix.

Is there any alternative to this approach? I can think of using Python based socket io (this time I will read and implement ) but something similar can be achieved by any other approach? I am using this to only send the  generated pad back to client there is no other communication b/w client and server.

Adding code

It works like, client opens the download/generate page and gets the ID assigned, once generate button is clicked ID is sent to back-end, now celery generates the PDF (converts to base64) and then posts that on nodejs/notify with ID. Now the socket.io is already listening on /notify url, so once the data is posted its displayed in browser.

Browser -> sock (register) -> AJAX -> Celery (task) ->  on nodejs/notify -> browser sockio client displays the data

Here is the code,

Client / Browser code

```<code> // func called on generate btn press
 $client.on('notify', function(result) {
        $.unblockUI();
        // alert('In Receiving function...');
        var $obj = $('#dynamic-pdf');
        $obj.hide();
        $obj.attr('data', result);
        $obj.show();
        $('button#view-again').removeClass('disabled');
        $('#previe').modal('show');
    });

    blockWithMsg("Generating PDF, Please Wait...");

    $.ajax({
        url: $url,
        data: {clientId: $clientId},
        method: 'POST',
        cache: false,
        headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'},
    });
    // func finished

   <!-- register client on page load -->
   <script src="http://localhost:3000/socket.io/socket.io.js"></script>
   <script>
      var $client = io('http://localhost:3000'),
          $clientId = null;

      $client.on('register', function(id) {
          $clientId = id;
      });

    </script>
</code>```

Node js code

```<code>var app = require('express')(),
    server = require('http').Server(app),
    io = require('socket.io')(server),
    bodyParser = require('body-parser');

// Accept URL-encoded body in POST request.
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true, parameterLimit: 50000}));
app.use(require('morgan')('dev'));

// Echo the client's ID back to them when they connect.
io.on('connection', function(client) {
    client.emit('register', client.id);
});

// Forward task results to the clients who initiated them.
app.post('/notify', function(request, response) {
    var client = io.sockets.connected[request.body.clientId];
    client.emit('notify', request.body.result);
    response.type('text/plain');
    response.send('Result broadcast to client.');
});

server.listen(3000);
</code>```

I am getting emit on undefined value error

答:
(Posted on behalf of the OP).

The error was I started site on different domain than one mentioned in the socket.io connection (which was still localhost) in browser JavaScript.

Body:
What i am trying to ask is, i have a website which takes the user profile and generates some kind of user specific reports in pdf. Pdf is generated at back end. So when user clicks on "generate" button, it should show blocking message and once the file is generated blocking message is removed and file is displayed with  tag.

I am able to do this with help of socket.io and to be very Frank I copied this solution from one blog without understanding much. So my stack is Python and socket.io is on node. While it worked perfectly on my dev machine but on server its keep on throwing connection error message in JavaScript and post message fails on back end. So I am currently having issues with front and back end. And thanks to my blindly copy paste thing I am kind of clueless about the fix.

Is there any alternative to this approach? I can think of using Python based socket io (this time I will read and implement ) but something similar can be achieved by any other approach? I am using this to only send the  generated pad back to client there is no other communication b/w client and server.

Adding code

It works like, client opens the download/generate page and gets the ID assigned, once generate button is clicked ID is sent to back-end, now celery generates the PDF (converts to base64) and then posts that on nodejs/notify with ID. Now the socket.io is already listening on /notify url, so once the data is posted its displayed in browser.

Browser -> sock (register) -> AJAX -> Celery (task) ->  on nodejs/notify -> browser sockio client displays the data

Here is the code,

Client / Browser code

 // func called on generate btn press
 $client.on('notify', function(result) {
        $.unblockUI();
        // alert('In Receiving function...');
        var $obj = $('#dynamic-pdf');
        $obj.hide();
        $obj.attr('data', result);
        $obj.show();
        $('button#view-again').removeClass('disabled');
        $('#previe').modal('show');
    });

    blockWithMsg("Generating PDF, Please Wait...");

    $.ajax({
        url: $url,
        data: {clientId: $clientId},
        method: 'POST',
        cache: false,
        headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'},
    });
    // func finished

Node js code

var app = require('express')(),
    server = require('http').Server(app),
    io = require('socket.io')(server),
    bodyParser = require('body-parser');

// Accept URL-encoded body in POST request.
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true, parameterLimit: 50000}));
app.use(require('morgan')('dev'));

// Echo the client's ID back to them when they connect.
io.on('connection', function(client) {
    client.emit('register', client.id);
});

// Forward task results to the clients who initiated them.
app.post('/notify', function(request, response) {
    var client = io.sockets.connected[request.body.clientId];
    client.emit('notify', request.body.result);
    response.type('text/plain');
    response.send('Result broadcast to client.');
});

server.listen(3000);

I am getting emit on undefined value error


问:
Vim - Syntax Highlighting - Javascript - string and boolean same color
I noticed that string and boolean syntax are both highlighted the same in javascript, no matter what color scheme I choose.

Is there a way to change it so boolean shows up the same color as const? I installed https://github.com/jelera/vim-javascript-syntax which has a syntax/ folder, but I don't know if this is where I am supposed to edit things to change their color.

In python boolean and string are different colors, so if someone could point me where to look to replicate that, that'd work too.

答:
In the plugin that you're linking to, booleans are linked to the Boolean highlight group, and const is linked to the Keyword highlight group (here and here).

You can create a link from the former to the latter, which would make booleans look similar to keywords:

```<code># ~/.vim/syntax/javascript.vim
hi link Boolean Keyword
</code>```

To give booleans their own color, you can use something like this:

```<code># ~/.vim/syntax/javascript.vim
hi Boolean ctermfg=Green
</code>```

More info here.

Body:
In the plugin that you're linking to, booleans are linked to the Boolean highlight group, and const is linked to the Keyword highlight group (here and here).

You can create a link from the former to the latter, which would make booleans look similar to keywords:

# ~/.vim/syntax/javascript.vim
hi link Boolean Keyword

To give booleans their own color, you can use something like this:

# ~/.vim/syntax/javascript.vim
hi Boolean ctermfg=Green

More info here.


问:
Jenkins Pipeline Error
I am using the pipeline plugin in Jenkins, but unable to run shell commands. I am receiving the following error:

```<code>[develop - pipeline] Running shell script
nohup: failed to run command ‘sh’: No such file or directory
</code>```

The node is an Ubuntu instance.

```<code>node ('aws-ondemand') {

//println env.BUILD_NUMBER

try {
    stage 'Checkout and Build'

    git url: 'git@github.com:MyAndroidRepo.git',
    branch: 'develop'
    sh 'git submodule init'
    sh 'git submodule update'
    sh './gradlew clean build'

}catch (e) {
    //currentBuild.result = "FAILED"
    //notifyFailed()
    throw e
  }
}
</code>```

答: Nevermind. Script is fine.  I was injecting env variables in the build step. I removed it and now its working.</p>

Title: Jenkins Pipeline Error

Body:
I am using the pipeline plugin in Jenkins, but unable to run shell commands. I am receiving the following error:

[develop - pipeline] Running shell script
nohup: failed to run command ‘sh’: No such file or directory

The node is an Ubuntu instance.

node ('aws-ondemand') {

//println env.BUILD_NUMBER

try {
    stage 'Checkout and Build'

    git url: 'git@github.com:MyAndroidRepo.git',
    branch: 'develop'
    sh 'git submodule init'
    sh 'git submodule update'
    sh './gradlew clean build'

}catch (e) {
    //currentBuild.result = "FAILED"
    //notifyFailed()
    throw e
  }
}


问:
Padding left and right don't work on link on menu
I have links on a menu with underlines sliding in out when hovered. I'm trying to add padding left and right to my links on my fixed menu, but for some reason the padding don't show.

Heres an image of what I'm trying to achieve (notice how the active links underline is padded left and right, you can see how the line is covering more than just the text)

Heres my fiddle

Ive read here on stack overflow that the problem could be the display, i changed it to inline-block or block and that didn't work.

My HTML:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav_Wrapper_dk">

<nav id="dk_Nav" role="navigation" class="cf">

    <div><a href="#home" class="link_Button sliding-u-l-r scroll">Home</a>   </div>
    <div><a href="#about" class="link_Button sliding-u-l-r scroll">About us</a></div>
    <div><a href="#link3" class="link_Button sliding-u-l-r">Gallery</a></div>
    <div><a href="#link4" class="link_Button sliding-u-l-r">Find Us</a></div>
    <div><a href="#link5" class="link_Button sliding-u-l-r">Contact</a></div>
    <div><a href="#link6" class="link_Button sliding-u-l-r">Catering</a></div>
    <div><a href="#link7" class="link_Button sliding-u-l-r">Blog</a></div>

</nav>

</div>

<div id="home"></div>

<div id="about"></div>
</code>```

My CSS:

```<code>#nav_Wrapper_dk {
    position: fixed;
    width: 100%;
    height: 50px;
    background: white;
    border-bottom: 1px solid #f1f1f1;
}

#dk_Nav {
    max-width: 1280px;
    /* width: 742.6167px; */
    height: 50px;
    margin-left: auto;
    margin-right: auto;
    top: 0;
    right: 0;
    left: 0;
    z-index: 2001;
}

    #dk_Nav div {
        margin-top: 11px;
    }

    #dk_Nav #logo_dk {
        margin-top: 0px;
    }

    .link_Button {
        display: block;
        float: left;
        height: 40px;
        font-family: 'Open Sans', sans-serif;
        font-size: .7em;
        color: black;
        line-height: 3.3em;
        text-transform: uppercase;
        letter-spacing: .2em;
        padding-left: 12px;
    }

    /* LEFT TO RIGHT */
    .sliding-u-l-r {
        display: inline-block;
    }

    .sliding-u-l-r:after {
        content: '';
        display: block;
        height: 3px;
        width: 0;
        background: transparent;
        transition: width .3s ease, background-color .3s ease;
    }

    .sliding-u-l-r:hover:after {
        width: 100%;
        background: black;
    }

    .sliding-u-l-r.active:after {
      width: 100%;
      background: black;
    }

#home {
  width: 100%;
  height: 1000px;
  background: #ccc;
}

#about {
  width: 100%;
  height: 1000px;
  background: white;
}
</code>```

My JAVASCRIPT

```<code>// Scroll Menu
$(function() {

  $("nav  a").click(function() {
    //**Add class active to current clicked menu item  and remove class active from other menu item**//
        $(this).addClass('active').parent().siblings().children().removeClass('active');
//** Smooth scroll Logic **?
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')     && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
  if (target.length) {
    $('html, body').animate({
      scrollTop: target.offset().top
    }, 1000);
        return false;
      }
    }
  });
});
</code>```

Can someone tell me what i'm doing wrong?

Thanks in advance!

答:
Easy solution

```<code>.sliding-u-l-r:after {
    content: '';
    display: block;
    height: 3px;
    width: 0;
    background: transparent;
    transition: width .3s ease, background-color .3s ease;
    padding-left: 6px;
    padding-right: 6px;
    position: relative;
    left: -6px;
}
</code>```

Better solution

Apply the underline effect :after on the parent of the a tag

e.g.

```<code><div class="item">
    <a href="#home" class="link_Button sliding-u-l-r scroll">Home</a>
</div>
</code>```

```<code>.item:after {
    content: '';
    display: block;
    height: 3px;
    width: 0;
    background: transparent;
    transition: width .3s ease, background-color .3s ease;
}
</code>```

See demo: https://jsfiddle.net/Lv0bx99k/5/ (made some changes to make this idea work)

Body:
I have links on a menu with underlines sliding in out when hovered. I'm trying to add padding left and right to my links on my fixed menu, but for some reason the padding don't show.

Heres an image of what I'm trying to achieve (notice how the active links underline is padded left and right, you can see how the line is covering more than just the text)

Heres my fiddle

Ive read here on stack overflow that the problem could be the display, i changed it to inline-block or block and that didn't work.

My HTML:

Home

About us

Gallery

Find Us

Contact

Catering

Blog

My CSS:

#nav_Wrapper_dk {
    position: fixed;
    width: 100%;
    height: 50px;
    background: white;
    border-bottom: 1px solid #f1f1f1;
}

#dk_Nav {
    max-width: 1280px;
    /* width: 742.6167px; */
    height: 50px;
    margin-left: auto;
    margin-right: auto;
    top: 0;
    right: 0;
    left: 0;
    z-index: 2001;
}

    #dk_Nav div {
        margin-top: 11px;
    }

    #dk_Nav #logo_dk {
        margin-top: 0px;
    }

    .link_Button {
        display: block;
        float: left;
        height: 40px;
        font-family: 'Open Sans', sans-serif;
        font-size: .7em;
        color: black;
        line-height: 3.3em;
        text-transform: uppercase;
        letter-spacing: .2em;
        padding-left: 12px;
    }

    /* LEFT TO RIGHT */
    .sliding-u-l-r {
        display: inline-block;
    }

    .sliding-u-l-r:after {
        content: '';
        display: block;
        height: 3px;
        width: 0;
        background: transparent;
        transition: width .3s ease, background-color .3s ease;
    }

    .sliding-u-l-r:hover:after {
        width: 100%;
        background: black;
    }

    .sliding-u-l-r.active:after {
      width: 100%;
      background: black;
    }

#home {
  width: 100%;
  height: 1000px;
  background: #ccc;
}

#about {
  width: 100%;
  height: 1000px;
  background: white;
}

My JAVASCRIPT

// Scroll Menu
$(function() {

  $("nav  a").click(function() {
    //**Add class active to current clicked menu item  and remove class active from other menu item**//
        $(this).addClass('active').parent().siblings().children().removeClass('active');
//** Smooth scroll Logic **?
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')     && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
  if (target.length) {
    $('html, body').animate({
      scrollTop: target.offset().top
    }, 1000);
        return false;
      }
    }
  });
});

Can someone tell me what i'm doing wrong?

Thanks in advance!

Body:
Easy solution

.sliding-u-l-r:after {
    content: '';
    display: block;
    height: 3px;
    width: 0;
    background: transparent;
    transition: width .3s ease, background-color .3s ease;
    padding-left: 6px;
    padding-right: 6px;
    position: relative;
    left: -6px;
}

Better solution

Apply the underline effect :after on the parent of the a tag

e.g.

<div class="item">
    <a href="#home" class="link_Button sliding-u-l-r scroll">Home</a>
</div>

.item:after {
    content: '';
    display: block;
    height: 3px;
    width: 0;
    background: transparent;
    transition: width .3s ease, background-color .3s ease;
}

See demo: https://jsfiddle.net/Lv0bx99k/5/ (made some changes to make this idea work)


问:
Passing the data-id from anchor tag to html.beginform
I have table and
 of this table is getting filled from the list in the model.

The list has id for each item which is getting assigned to data-id in anchor tag

```<code><tbody>

    @foreach (var item in Model.eList.ToList())
    {
        <tr>
            <td><a href="@Url">@item.FullName</a></td>
            <td>@item.Title</td>
            <td><a data-id="@item.Id" data-open="Event">Event</a></td>
        </tr>
    }

</tbody>
</code>```

I have div with Id Event like this

```<code><div id="Event" class="reveal" data-reveal>
    @using (Html.BeginForm("Cancel", "Profile", new { id = data-id}, FormMethod.Post))
    {
        <label>confirm</label>
        <input type="submit" value="Save" class="button" id="Edits" />
    }
</div>
</code>```

When user clicks on anchor tag it will open the div with id="Event". But how do I pass data-id for that particular record to div with id="Event", from there it will be posted to controller with action cancel.

Thank you

答:
You can keep a hidden input element inside that form.

```<code><div id="Event" class="reveal" data-reveal>
    @using (Html.BeginForm("Cancel", "Profile"))
    {
        <input id="dataId" name="id" value="" type="hidden" />
        <label>confirm</label>
        <input type="submit" value="Save" class="button" id="Edits" />
    }
</div>
</code>```

and when user clicks the anchor tag, read the value from the data-id attribute of the clicked element and set it as the value of the hidden element.

```<code>$(function(){
   $("[data-id]").click(function(e){
      e.preventDefault();
      var id=$(this).data("id");
      $("#dataId").val(id);

      // your existing code to open the div with form
      / /$("#Event").show();
  });

});
</code>```

When the user submits the form, the id value we set to the hidden input will also be submitted.

Here is a js bin sample.

Body:
I have table and
 of this table is getting filled from the list in the model.

The list has id for each item which is getting assigned to data-id in anchor tag

    @foreach (var item in Model.eList.ToList())
    {

            @item.FullName
            @item.Title
            Event

    }

I have div with Id Event like this

    @using (Html.BeginForm("Cancel", "Profile", new { id = data-id}, FormMethod.Post))
    {
        confirm
        <input type="submit" value="Save" class="button" id="Edits" />
    }

When user clicks on anchor tag it will open the div with id="Event". But how do I pass data-id for that particular record to div with id="Event", from there it will be posted to controller with action cancel.

Thank you

Body:
You can keep a hidden input element inside that form.

<div id="Event" class="reveal" data-reveal>
    @using (Html.BeginForm("Cancel", "Profile"))
    {
        <input id="dataId" name="id" value="" type="hidden" />
        <label>confirm</label>
        <input type="submit" value="Save" class="button" id="Edits" />
    }
</div>

and when user clicks the anchor tag, read the value from the data-id attribute of the clicked element and set it as the value of the hidden element.

$(function(){
   $("[data-id]").click(function(e){
      e.preventDefault();
      var id=$(this).data("id");
      $("#dataId").val(id);

      // your existing code to open the div with form
      / /$("#Event").show();
  });

});

When the user submits the form, the id value we set to the hidden input will also be submitted.

Here is a js bin sample.


问:
Having to press Shift along with CTRL A
TO start, I have looked extensively at the answers and haven't found a method.

I have a text box that gets ctl+A to select all.
I also have a list box that traps the kb to select all items.

The listbox is my issue.

```<code>if(e.Control && e.KeyCode == Keys.A  )
</code>```

and also

```<code>if(e.Control && e.KeyCode.ToString().ToLower() == "a"  )
</code>```

are requiring ctl + shift + a, as the keys.A is always uppercase, even when I lowercase it. If I don't press shift, it starts cycling through the items that start with "a".
Using keypress to grab the keys, I can't find the char for the control key anywhere. Using key up and down to flag control: if I press control, keypress event stops firing.

All I want to do is have ctl + lowercase a = The code that selects all of the items in the listbox.

This cannot be that hard, right?

答:
I am so embarrassed, but I will leave this here for anyone else who has this issue. Literally the easiest and fastest fix I managed to overlook for many weeks and many clumps of hair...

I randomly started changing the listbox properties to see if anything helped. This was the result of us needing it in "multi Extended, rather than "MultiSimple" as we shift and select a range of files to alter, but also often need to quickly select all with standard(er) Quick keys.
I added this to the keydown event just prior to checking against selectall...

```<code> if(e.Shift)
            {
                FinalNameList.SelectionMode = SelectionMode.MultiExtended;
            }
            else{
                FinalNameList.SelectionMode = SelectionMode.MultiSimple;
            }
</code>```

Title: Having to press Shift along with CTRL A

Body:
TO start, I have looked extensively at the answers and haven't found a method.

I have a text box that gets ctl+A to select all.
I also have a list box that traps the kb to select all items.

The listbox is my issue.

if(e.Control && e.KeyCode == Keys.A  )

and also

if(e.Control && e.KeyCode.ToString().ToLower() == "a"  )

are requiring ctl + shift + a, as the keys.A is always uppercase, even when I lowercase it. If I don't press shift, it starts cycling through the items that start with "a".
Using keypress to grab the keys, I can't find the char for the control key anywhere. Using key up and down to flag control: if I press control, keypress event stops firing.

All I want to do is have ctl + lowercase a = The code that selects all of the items in the listbox.

This cannot be that hard, right?

Body:
I am so embarrassed, but I will leave this here for anyone else who has this issue. Literally the easiest and fastest fix I managed to overlook for many weeks and many clumps of hair...

I randomly started changing the listbox properties to see if anything helped. This was the result of us needing it in "multi Extended, rather than "MultiSimple" as we shift and select a range of files to alter, but also often need to quickly select all with standard(er) Quick keys.
I added this to the keydown event just prior to checking against selectall...

 if(e.Shift)
            {
                FinalNameList.SelectionMode = SelectionMode.MultiExtended;
            }
            else{
                FinalNameList.SelectionMode = SelectionMode.MultiSimple;
            }


问:
force cmake specific sh path
I have incompatible sh.exe and make.exe in my path due to multiple toolchains for embedded development. I want to force use of the one not in my path.

cmake used the wrong make (the one in the path) to check GCC functionnality and I could force the correct make with SET(CMAKE_MAKE_PROGRAM .../make.exe)

How to do the same for sh.exe ?

答:
Turning my comment into an answer

To make CMake to ignore the toolchain in your path you can utilize CMAKE_IGNORE_PATH with something like:

```<code>cmake -DCMAKE_IGNORE_PATH="/path/to/your/toolchain/bin" ..
</code>```

Just be aware that the path has to be exact string match for the path (in CMake format with / slashes and it's case sensitive).

For more details: Environment variable used by CMake to detect Visual C++ compiler tools for Ninja

Title: force cmake specific sh path

Body:
Turning my comment into an answer

To make CMake to ignore the toolchain in your path you can utilize CMAKE_IGNORE_PATH with something like:

cmake -DCMAKE_IGNORE_PATH="/path/to/your/toolchain/bin" ..

Just be aware that the path has to be exact string match for the path (in CMake format with / slashes and it's case sensitive).

For more details: Environment variable used by CMake to detect Visual C++ compiler tools for Ninja


问:
Program won't load to selected database, makes a copy in debug folder
This program is supposed to take a csv file and load it to a sqlite database that the use specifies a path to. Rather than trying to load the values to the selected database it creates a copy of the database in the debug folder and then throws an error because the table doesn't exist in the new db. I can't find where it's deciding to make a new file rather than using the existing one.

```<code>using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=" + db3FilePath + "; Synchronous=Off"))
{
    using (System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn))
    {
        conn.Open();

        foreach (KeyValuePair<string, CSVRecord> kvp in csvDictionary.Skip(1))
        {
            //checks for duplicate records
            cmd.CommandText = "SELECT COUNT(*) FROM Accounts WHERE SDM_ACCT='" + kvp.Value.sdmacct + "'";
            int count = Convert.ToInt32(cmd.ExecuteScalar());

            if (count < 1)
            {
                WritetoDatabase.WritetoAccountsTable(kvp.Value.description, kvp.Value.priority, db3FilePath);
                WritetoDatabase.WritetoDirectoryTable(kvp.Value.number, kvp.Value.active, db3FilePath);

                recordCount++;
                //updates the progress bar and text field showing %
                int progress = y++ * 100 / (csvDictionary.Keys.Count -1);
                progressBar1.Invoke((MethodInvoker)(() => progressBar1.Value = progress));
                progressBar1.Invoke((MethodInvoker)(() => progressBar1.Update()));
                lblStatus.Invoke((MethodInvoker)(() => lblStatus.Text = "Writing records to database: " + progress.ToString() + "% Complete"));
                lblStatus.Invoke((MethodInvoker)(() => lblStatus.Update()));
            }
            else
            {
                WritetoDatabase.WritetoDirectoryTable(kvp.Value.number, kvp.Value.active, db3FilePath);
                y++;
            }
        }
        conn.Close();
    }
}
</code>```

Here is a copy of the method that writes to the database.

```<code>public static int WritetoAccountsTable(string Comment, int PriorityInt, string filePath)
        {
            using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=" + filePath + "; Synchronous=Off"))
            {
                using (System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn))
                {
                    conn.Open();
                    cmd.CommandText = @"INSERT INTO Accounts(Description,Priority)
                                                        values(@Comment,@PriorityInt)";
                    cmd.Parameters.AddWithValue("@Comment", Comment);
                    cmd.Parameters.AddWithValue("@PriorityInt", PriorityInt);
                    return cmd.ExecuteNonQuery();
                }
            }
        }
</code>```

I've changed everything I can think of trying to find what's causing the problem. Maybe you will see something I can't.

答: One of the all-time dumbest things I have seen break a program. The Connection String using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=" + filePath + "; Synchronous=Off")) has "data source". If it is not capitalized, "Data Source", it doesn't recognize it and goes to a default setting.

Body:
This program is supposed to take a csv file and load it to a sqlite database that the use specifies a path to. Rather than trying to load the values to the selected database it creates a copy of the database in the debug folder and then throws an error because the table doesn't exist in the new db. I can't find where it's deciding to make a new file rather than using the existing one.

using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=" + db3FilePath + "; Synchronous=Off"))
{
    using (System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn))
    {
        conn.Open();

        foreach (KeyValuePair<string, CSVRecord> kvp in csvDictionary.Skip(1))
        {
            //checks for duplicate records
            cmd.CommandText = "SELECT COUNT(*) FROM Accounts WHERE SDM_ACCT='" + kvp.Value.sdmacct + "'";
            int count = Convert.ToInt32(cmd.ExecuteScalar());

            if (count < 1)
            {
                WritetoDatabase.WritetoAccountsTable(kvp.Value.description, kvp.Value.priority, db3FilePath);
                WritetoDatabase.WritetoDirectoryTable(kvp.Value.number, kvp.Value.active, db3FilePath);

                recordCount++;
                //updates the progress bar and text field showing %
                int progress = y++ * 100 / (csvDictionary.Keys.Count -1);
                progressBar1.Invoke((MethodInvoker)(() => progressBar1.Value = progress));
                progressBar1.Invoke((MethodInvoker)(() => progressBar1.Update()));
                lblStatus.Invoke((MethodInvoker)(() => lblStatus.Text = "Writing records to database: " + progress.ToString() + "% Complete"));
                lblStatus.Invoke((MethodInvoker)(() => lblStatus.Update()));
            }
            else
            {
                WritetoDatabase.WritetoDirectoryTable(kvp.Value.number, kvp.Value.active, db3FilePath);
                y++;
            }
        }
        conn.Close();
    }
}

Here is a copy of the method that writes to the database.

public static int WritetoAccountsTable(string Comment, int PriorityInt, string filePath)
        {
            using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=" + filePath + "; Synchronous=Off"))
            {
                using (System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn))
                {
                    conn.Open();
                    cmd.CommandText = @"INSERT INTO Accounts(Description,Priority)
                                                        values(@Comment,@PriorityInt)";
                    cmd.Parameters.AddWithValue("@Comment", Comment);
                    cmd.Parameters.AddWithValue("@PriorityInt", PriorityInt);
                    return cmd.ExecuteNonQuery();
                }
            }
        }

I've changed everything I can think of trying to find what's causing the problem. Maybe you will see something I can't.


问:
Best way to move API from CodeIgniter to Django
In the beginning we made a project using CodeIgniter and we had some controllers that were used to connect an external NAS to the database via it's web interface, to cut a long story short we had a bunch of URL that required an API key to have access to avoid general hackery from outside sources calling the API.

The API existed for various tasks the NAS had to do (manage orders, upload data/images etc.), so we had a few different controllers (ie. one for Orders, Images, etc.) So the API folder looked something like this:

```<code>controllers/apiv1/
   orders.php
   images.php
   ...
</code>```

Something along the lines of this:

```<code>class Orders extends ApiController {

function Orders()
{
    parent::ApiController();
}

function get_paid()
{
    $shop = self::get_shop();

    $this->load->model('order');
    echo json_encode($this->order->by_status($shop->shop_id, Order::STATUS_PAID));
}
}
</code>```

Where the ApiController just checked the APIKey against the Shop that it was trying to access.

Now we are moving the project to Django, and I was just wondering the be way to setup this api again. I was thinking of making an API app for the project and importing the models in to the views.py and make some functions for everything, my problem here is there a way to break everything up nicely (into separate files for each of the various things)? Or should I just have the views.py full of everything and worry about it in the urls.

Or is there a better way? If possible I would like to separate the api into versions like (api/v1, api/v2, etc.) so that we can just route the urls to the new api without affecting the old. This may come in handy if we have various NAS's using different versions of the API (Hard to explain why...)

答:
You could try using something like Django Piston or Django-tastypie to quickly get something working. The big advantage over using normal Django views is that you get most of the CRUD and serialization to JSON/Yaml/XML done for you.

Tastypie comes with a built-in shared-secret key authentication mechanism, and it's not difficult to find the equivalent code for Piston.

EDIT: BTW, I've been working with both Piston and Tastypie recently. I find Tastypie is easier to setup and the code base looks cleaner. That said, it lacks some features (coming on 1.0 though) that makes it impossible for me to use it at the moment. Piston is very easy to shoehorn into whatever you need, but the code seems to be growing stagnant, the author doesn't seem to be very responsive about open issues and you'll probably end up having your own fork with the bugfixes you need for your application to work properly. Not an ideal situation.

Body:
In the beginning we made a project using CodeIgniter and we had some controllers that were used to connect an external NAS to the database via it's web interface, to cut a long story short we had a bunch of URL that required an API key to have access to avoid general hackery from outside sources calling the API.

The API existed for various tasks the NAS had to do (manage orders, upload data/images etc.), so we had a few different controllers (ie. one for Orders, Images, etc.) So the API folder looked something like this:

controllers/apiv1/
   orders.php
   images.php
   ...

Something along the lines of this:

class Orders extends ApiController {

function Orders()
{
    parent::ApiController();
}

function get_paid()
{
    $shop = self::get_shop();

    $this->load->model('order');
    echo json_encode($this->order->by_status($shop->shop_id, Order::STATUS_PAID));
}
}

Where the ApiController just checked the APIKey against the Shop that it was trying to access.

Now we are moving the project to Django, and I was just wondering the be way to setup this api again. I was thinking of making an API app for the project and importing the models in to the views.py and make some functions for everything, my problem here is there a way to break everything up nicely (into separate files for each of the various things)? Or should I just have the views.py full of everything and worry about it in the urls.

Or is there a better way? If possible I would like to separate the api into versions like (api/v1, api/v2, etc.) so that we can just route the urls to the new api without affecting the old. This may come in handy if we have various NAS's using different versions of the API (Hard to explain why...)


问:
reflection for orika customMap of different fieldNames
Suppose we have 2 DTOs:

```<code>public class ClassA {
    private String elementAClassA;
    private String elementBClassA;
    private Integer elementCClassA;
}

public class ClassB {
    private String elementAClassB;
    private String elementBClassB;
    private Integer elementCClassB;
}
</code>```

How to map these DTOs using generic code (or reflection/customised), ie without simply using:

```<code>MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        mapperFactory.classMap(ClassA.class, ClassB.class)
                .field("elementAClassA", "elementAClassB")
                .field("elementBClassA", "elementBClassB")
                .field("elementCClassA", "elementCClassB").register();
</code>```

答:
```<code>I found the solution and hope will help others.
Steps are as below:

1. Overide newClassMapBuilder of Factory class.
2. fetch fields of both classes using Field reflection.
3. map new field to build, if elementName matched.
4. Then, create factory and pass this overiden class.

-- Point 1-3 are in below code:
import java.lang.reflect.Field;
import ma.glasnost.orika.DefaultFieldMapper;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.metadata.ClassMapBuilder;
import ma.glasnost.orika.metadata.ClassMapBuilder.Factory;
import ma.glasnost.orika.metadata.Type;
import ma.glasnost.orika.property.PropertyResolverStrategy;

public class PlainElementToStdElementMapper extends Factory {

    @Override
    protected <A, B> ClassMapBuilder<A, B> newClassMapBuilder(
            Type<A> aType, Type<B> bType,
            MapperFactory mapperFactory,
            PropertyResolverStrategy propertyResolver,
            DefaultFieldMapper[] defaults) {
        final ClassMapBuilder<A, B> newBuilder = super.newClassMapBuilder(
                aType, bType, mapperFactory, propertyResolver, defaults);

        Field[] sourceFields = aType.getRawType().getDeclaredFields();
        Field[] destFields = bType.getRawType().getDeclaredFields();

        for (int elementA = 0; elementA < sourceFields.length; elementA++) {
            for (int elementB = 0; elementB < destFields.length; elementB++) {
                if (sourceFields[elementA].getName().equalsIgnoreCase( "Std"+destFields[elementB].getName())) {
                    newBuilder.field(sourceFields[elementA].getName(), destFields[elementB].getName());
                }
            }
        }
        return newBuilder;
    }
}

4. Create factory:

        final MapperFactory factory = new DefaultMapperFactory.Builder().
                    classMapBuilderFactory(new PlainElementToStdElementMapper()).build();

         factory.classMap(ClassA.class, ClassB.class).byDefault().register();
                MapperFacade mapperFacade = factory.getMapperFacade();
</code>```

Body:
Suppose we have 2 DTOs:

public class ClassA {
    private String elementAClassA;
    private String elementBClassA;
    private Integer elementCClassA;
}

public class ClassB {
    private String elementAClassB;
    private String elementBClassB;
    private Integer elementCClassB;
}

How to map these DTOs using generic code (or reflection/customised), ie without simply using:

MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        mapperFactory.classMap(ClassA.class, ClassB.class)
                .field("elementAClassA", "elementAClassB")
                .field("elementBClassA", "elementBClassB")
                .field("elementCClassA", "elementCClassB").register();


答:
You can post Id in either -

Query String as new {id = item }, or

Hidden Field as <input type="hidden" name="id" value="@item">

For example,

```<code><tbody>
    @foreach (var item in Model.eList.ToList())
    {
        <tr>
            <td><a href="@Url">@item.FullName</a></td>
            <td>@item.Title</td>
            <td>
                @using (Html.BeginForm("Cancel", "Profile", new {id = item },
                   FormMethod.Post))
                {
                    <a data-id="@item.Id" data-open="Event">Event</a>
                    <input type="hidden" name="id" value="@item">
                    <div id="Event" class="reveal" data-reveal>
                        <label>confirm</label>
                        <input type="submit" value="Save" class="button" id="Edits" />
                    </div>
                }
            </td>
        </tr>
    }
</tbody>
</code>```

Title: Passing the data-id from anchor tag to html.beginform

Body:
You can post Id in either -

Query String as new {id = item }, or

Hidden Field as <input type="hidden" name="id" value="@item">

For example,

<tbody>
    @foreach (var item in Model.eList.ToList())
    {
        <tr>
            <td><a href="@Url">@item.FullName</a></td>
            <td>@item.Title</td>
            <td>
                @using (Html.BeginForm("Cancel", "Profile", new {id = item },
                   FormMethod.Post))
                {
                    <a data-id="@item.Id" data-open="Event">Event</a>
                    <input type="hidden" name="id" value="@item">
                    <div id="Event" class="reveal" data-reveal>
                        <label>confirm</label>
                        <input type="submit" value="Save" class="button" id="Edits" />
                    </div>
                }
            </td>
        </tr>
    }
</tbody>


问:
how to create a soap request for client saaj of given xml
I am new to SOAP. I want to create a soap request of given below xml.

xml

```<code><?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <soap:Body>
        <SendRequest xmlns="http://tempuri.org/">
        <request xsi:type="RegisterCheckRequest" Id="7a646d45-ee2f-4b1c-8de8-780c416fbbd0" Service="42" xmlns="http://paygo24.com/v3/protocol">
        <PaymentParameters xmlns="">
        <Parameter Name="account" Value="08374829" />
        </PaymentParameters>
        </request>
        <pointId>46</pointId>
        <password>4QrcOUm6Wau+VuBX8g+IPg==</password>
         </SendRequest>
          </soap:Body>
          </soap:Envelope>
</code>```

I was using below sample java file, to create soap request but I am not able to do so, can anyone give me support.

Sample Java File to create soap request

```<code>import javax.xml.soap.*;

public class SOAPClientSAAJ {

    public static void main(String args[]) throws Exception {
        // Create SOAP Connection
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        // Send SOAP Message to SOAP Server
        String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
        SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

        // print SOAP Response
        System.out.print("Response SOAP Message:");
        soapResponse.writeTo(System.out);

        soapConnection.close();
    }

    private static SOAPMessage createSOAPRequest() throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI = "http://ws.cdyne.com/";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("example", serverURI);

        /*
        Constructed SOAP Request Message:
        <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
            <SOAP-ENV:Header/>
            <SOAP-ENV:Body>
                <example:VerifyEmail>
                    <example:email>mutantninja@gmail.com</example:email>
                    <example:LicenseKey>123</example:LicenseKey>
                </example:VerifyEmail>
            </SOAP-ENV:Body>
        </SOAP-ENV:Envelope>
         */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
        soapBodyElem1.addTextNode("mutantninja@gmail.com");
        SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
        soapBodyElem2.addTextNode("123");

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");

        soapMessage.saveChanges();

        /* Print the request message */
        System.out.print("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println();

        return soapMessage;
    }

}
</code>```

答:
This is how you build soap request</p>

```<code> private static SOAPMessage createSOAPRequest() throws Exception {

    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.removeNamespaceDeclaration(envelope.getPrefix());
    envelope.addNamespaceDeclaration("soap","http://schemas.xmlsoap.org/soap/envelope/");
    envelope.setPrefix("soap");
    envelope.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema-instance");
    envelope.addNamespaceDeclaration("xsd","http://www.w3.org/2001/XMLSchema");
    SOAPHeader header=soapMessage.getSOAPHeader();
    header.setPrefix("soap");
    SOAPBody soapBody = envelope.getBody();
    soapBody.setPrefix("soap");
    SOAPElement root=soapBody.addChildElement(new QName("http://tempuri.org/","SendRequest"));
    SOAPElement request=root.addChildElement(new QName("http://paygo24.com/v3/protocol","request"));
    request.setAttribute("xsi:type", "RegisterCheckRequest");
    request.setAttribute("Id","7a646d45-ee2f-4b1c-8de8-780c416fbbd0");
    request.setAttribute("Service","42");
    SOAPElement paymentParameters =request.addChildElement(new QName(" ","PaymentParameters"));
    SOAPElement parameter=paymentParameters.addChildElement("Parameter");
    parameter.setAttribute("Name","account");
    parameter.setAttribute("Value", "08374829");
    root.addChildElement("pointId").setValue("46");
    root.addChildElement("password").setValue("4QrcOUm6Wau+VuBX8g+IPg==");
    soapMessage.saveChanges();

    soapMessage.writeTo(System.out);

    return soapMessage;
}
</code>```

Body:
I am new to SOAP. I want to create a soap request of given below xml.

xml

<?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <soap:Body>
        <SendRequest xmlns="http://tempuri.org/">
        <request xsi:type="RegisterCheckRequest" Id="7a646d45-ee2f-4b1c-8de8-780c416fbbd0" Service="42" xmlns="http://paygo24.com/v3/protocol">
        <PaymentParameters xmlns="">
        <Parameter Name="account" Value="08374829" />
        </PaymentParameters>
        </request>
        <pointId>46</pointId>
        <password>4QrcOUm6Wau+VuBX8g+IPg==</password>
         </SendRequest>
          </soap:Body>
          </soap:Envelope>

I was using below sample java file, to create soap request but I am not able to do so, can anyone give me support.

Sample Java File to create soap request

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    public static void main(String args[]) throws Exception {
        // Create SOAP Connection
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        // Send SOAP Message to SOAP Server
        String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
        SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

        // print SOAP Response
        System.out.print("Response SOAP Message:");
        soapResponse.writeTo(System.out);

        soapConnection.close();
    }

    private static SOAPMessage createSOAPRequest() throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI = "http://ws.cdyne.com/";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("example", serverURI);

        /*
        Constructed SOAP Request Message:
        <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
            <SOAP-ENV:Header/>
            <SOAP-ENV:Body>
                <example:VerifyEmail>
                    <example:email>mutantninja@gmail.com</example:email>
                    <example:LicenseKey>123</example:LicenseKey>
                </example:VerifyEmail>
            </SOAP-ENV:Body>
        </SOAP-ENV:Envelope>
         */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
        soapBodyElem1.addTextNode("mutantninja@gmail.com");
        SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
        soapBodyElem2.addTextNode("123");

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");

        soapMessage.saveChanges();

        /* Print the request message */
        System.out.print("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println();

        return soapMessage;
    }

}

Body:
This is how you build soap request

 private static SOAPMessage createSOAPRequest() throws Exception {

    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.removeNamespaceDeclaration(envelope.getPrefix());
    envelope.addNamespaceDeclaration("soap","http://schemas.xmlsoap.org/soap/envelope/");
    envelope.setPrefix("soap");
    envelope.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema-instance");
    envelope.addNamespaceDeclaration("xsd","http://www.w3.org/2001/XMLSchema");
    SOAPHeader header=soapMessage.getSOAPHeader();
    header.setPrefix("soap");
    SOAPBody soapBody = envelope.getBody();
    soapBody.setPrefix("soap");
    SOAPElement root=soapBody.addChildElement(new QName("http://tempuri.org/","SendRequest"));
    SOAPElement request=root.addChildElement(new QName("http://paygo24.com/v3/protocol","request"));
    request.setAttribute("xsi:type", "RegisterCheckRequest");
    request.setAttribute("Id","7a646d45-ee2f-4b1c-8de8-780c416fbbd0");
    request.setAttribute("Service","42");
    SOAPElement paymentParameters =request.addChildElement(new QName(" ","PaymentParameters"));
    SOAPElement parameter=paymentParameters.addChildElement("Parameter");
    parameter.setAttribute("Name","account");
    parameter.setAttribute("Value", "08374829");
    root.addChildElement("pointId").setValue("46");
    root.addChildElement("password").setValue("4QrcOUm6Wau+VuBX8g+IPg==");
    soapMessage.saveChanges();

    soapMessage.writeTo(System.out);

    return soapMessage;
}


问:
Use dplyr to take first and last row in a sequence by group
I'm trying to use dplyr to take the first and last rows of repeated values by group. I'm doing this for efficiency reasons, particularly so that graphing is faster.

This is not a duplicate of Select first and last row from grouped data because I'm not asking for the strict first and last row in a group; I'm asking for the first and last row in a group by level (in my case 1's and 0's) that may appear in multiple chunks.

Here's an example. Say I want to remove all the redundant 1's and 0's from column C while keeping A and B intact.

```<code>df = data.frame(
    A = rep(c("a", "b"), each = 10),
    B = rep(c(1:10), 2),
    C = c(1,0,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,1))

A  B C
a  1 1
a  2 0
a  3 0
a  4 0
a  5 0
a  6 0
a  7 1
a  8 1
a  9 1
a 10 1
b  1 0
b  2 0
b  3 0
b  4 1
b  5 0
b  6 0
b  7 0
b  8 0
b  9 0
b 10 1
</code>```

The end result should look like this:

```<code>A  B C
a  1 1
a  2 0
a  6 0
a  7 1
a 10 1
b  1 0
b  3 0
b  4 1
b  5 0
b  9 0
b 10 1
</code>```

Using unique will either not remove anything or just take one of the 1's or 0's without retaining the start-and-end quality that I'm trying to achieve. Is there a way to do this without a loop, perhaps using dplyr or forcats?

答:
One solution:</p>

```<code>C_filter <- function(x) {
    !sapply(1:length(x), function(i) {
        identical(x[i], x[i-1])
    }) | !sapply(1:length(x), function(i) {
        identical(x[i], x[i+1])
    })
}
df %>% group_by(A) %>% filter(C_filter(C))

   A  B C
1  a  1 1
2  a  2 0
3  a  6 0
4  a  7 1
5  a 10 1
6  b  1 0
7  b  3 0
8  b  4 1
9  b  5 0
10 b  9 0
11 b 10 1
</code>```

Body:
I'm trying to use dplyr to take the first and last rows of repeated values by group. I'm doing this for efficiency reasons, particularly so that graphing is faster.

This is not a duplicate of Select first and last row from grouped data because I'm not asking for the strict first and last row in a group; I'm asking for the first and last row in a group by level (in my case 1's and 0's) that may appear in multiple chunks.

Here's an example. Say I want to remove all the redundant 1's and 0's from column C while keeping A and B intact.

df = data.frame(
    A = rep(c("a", "b"), each = 10),
    B = rep(c(1:10), 2),
    C = c(1,0,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,1))

A  B C
a  1 1
a  2 0
a  3 0
a  4 0
a  5 0
a  6 0
a  7 1
a  8 1
a  9 1
a 10 1
b  1 0
b  2 0
b  3 0
b  4 1
b  5 0
b  6 0
b  7 0
b  8 0
b  9 0
b 10 1

The end result should look like this:

A  B C
a  1 1
a  2 0
a  6 0
a  7 1
a 10 1
b  1 0
b  3 0
b  4 1
b  5 0
b  9 0
b 10 1

Using unique will either not remove anything or just take one of the 1's or 0's without retaining the start-and-end quality that I'm trying to achieve. Is there a way to do this without a loop, perhaps using dplyr or forcats?

Body:
One solution:

C_filter <- function(x) {
    !sapply(1:length(x), function(i) {
        identical(x[i], x[i-1])
    }) | !sapply(1:length(x), function(i) {
        identical(x[i], x[i+1])
    })
}
df %>% group_by(A) %>% filter(C_filter(C))

   A  B C
1  a  1 1
2  a  2 0
3  a  6 0
4  a  7 1
5  a 10 1
6  b  1 0
7  b  3 0
8  b  4 1
9  b  5 0
10 b  9 0
11 b 10 1


问:
Get json from request flask
Client code:

```<code>import requests
import json

url = 'http://127.0.0.1:5050/login'
user = "newUser"
password = "password"
headers = {'content-type': 'application/json'}
response = requests.post(url, data={"user": user,"pass": password}, headers = headers)
</code>```

Server code:

```<code>from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/login', methods=['GET','POST'])
def login():
 if request.method == 'POST':

    username = request.form.get("user")
    password = request.form.get("pass")
    //more code
    return make_response("",200)

if __name__ == "__main__":
     app.run(host = "127.0.0.1", port = 5050)
</code>```

The problem is that my username and password are always None.

I also tried using:

```<code>content = request.get_json(force = True)
password = content['pass']
</code>```

and

```<code>request.form['user']
</code>```

When I print the content I have: < Request 'http://127.0.0.1:5050/login' [POST]> .So I cannot find the json send from the client.

EDIT:

I did add json.dumps and used request.get_json() and it worked

答:
My initial guess is that since you aren't setting the Content-Type header in your request Flask doesn't understand that it should be able to parse the data.  Try adding Content-Type header with the value application/json and see if that gets you where you want.

Another thing to note is when I hit my login page the browser sets the Content-Type header to
application/x-www-form-urlencoded and encodes the data as user=asdf&passwd=asdf

Title: Get json from request flask

Body:
Client code:

import requests
import json

url = 'http://127.0.0.1:5050/login'
user = "newUser"
password = "password"
headers = {'content-type': 'application/json'}
response = requests.post(url, data={"user": user,"pass": password}, headers = headers)

Server code:

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/login', methods=['GET','POST'])
def login():
 if request.method == 'POST':

    username = request.form.get("user")
    password = request.form.get("pass")
    //more code
    return make_response("",200)

if __name__ == "__main__":
     app.run(host = "127.0.0.1", port = 5050)

The problem is that my username and password are always None.

I also tried using:

content = request.get_json(force = True)
password = content['pass']

and

request.form['user']

When I print the content I have: < Request 'http://127.0.0.1:5050/login' [POST]> .So I cannot find the json send from the client.

EDIT:

I did add json.dumps and used request.get_json() and it worked


问:
Trouble with react native layout
I have a problem with my react native layout iPhone 5c.

But iPhone 7 and iPad look good.

How to fix it?

My buttons code:

```<code>  _renderButton(title, onPress, active) {
    var style = (active) ? styles.activeButtonText : styles.buttonText;

    return (
      <TouchableHighlight style={styles.button} onPress={onPress}>
        <Text style={style}>
          {title}
        </Text>
      </TouchableHighlight>
    );
  }

  render() {

    return (
      <View style={styles.container}>
        <View style={styles.controls}>
           {this._renderButton("LISTEN", () => {this._playOriginalAudio()})}
           {this._renderButton(this.state.recordingText, () => {this._record()}, this.state.recording )}
           {this._renderButton("LISTEN TO RECORDING", () => {this._play()} )}
           {this._renderButton("SUBMIT", () => {this._send()} )}
        </View>
      </View>
      );
    }
  }

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#2b608a",
  },
  controls: {
    justifyContent: 'center',
    alignItems: 'center',
    flex: 1,
  },
  button: {
    padding: 20
  },
  disabledButtonText: {
    color: '#eee'
  },
  buttonText: {
    fontSize: 20,
    color: "#fff"
  },
  activeButtonText: {
    fontSize: 20,
    color: "#B81F00"
  },
  points: {
    backgroundColor: 'transparent',
    position: 'absolute',
    top: 72,
    left: 56,
    width: 90,
    textAlign: 'center',
    color: '#69d2e7',
    fontSize: 50,
    fontWeight: "100"
  },
  headerText: {
    paddingBottom: 10,
    fontSize: 20,
    color: "#69d2e7"
  }

});
</code>```

I've tried to test app with iPhone 5 simulator, and I have no any style problem. Looks like the problem only with real iPhone 5 device. Maybe it is bug.

答:
It might help to see your specific style sheet, but I am guessing you would benefit by importing the Dimensions module that React Native provides.

Dimensions Module

Then you can get the height and width of the device your app is running on, to change the styles appropriately.

Title: Trouble with react native layout

Body:
I have a problem with my react native layout iPhone 5c.

But iPhone 7 and iPad look good.

How to fix it?

My buttons code:

  _renderButton(title, onPress, active) {
    var style = (active) ? styles.activeButtonText : styles.buttonText;

    return (
      <TouchableHighlight style={styles.button} onPress={onPress}>
        <Text style={style}>
          {title}
        </Text>
      </TouchableHighlight>
    );
  }

  render() {

    return (
      <View style={styles.container}>
        <View style={styles.controls}>
           {this._renderButton("LISTEN", () => {this._playOriginalAudio()})}
           {this._renderButton(this.state.recordingText, () => {this._record()}, this.state.recording )}
           {this._renderButton("LISTEN TO RECORDING", () => {this._play()} )}
           {this._renderButton("SUBMIT", () => {this._send()} )}
        </View>
      </View>
      );
    }
  }

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#2b608a",
  },
  controls: {
    justifyContent: 'center',
    alignItems: 'center',
    flex: 1,
  },
  button: {
    padding: 20
  },
  disabledButtonText: {
    color: '#eee'
  },
  buttonText: {
    fontSize: 20,
    color: "#fff"
  },
  activeButtonText: {
    fontSize: 20,
    color: "#B81F00"
  },
  points: {
    backgroundColor: 'transparent',
    position: 'absolute',
    top: 72,
    left: 56,
    width: 90,
    textAlign: 'center',
    color: '#69d2e7',
    fontSize: 50,
    fontWeight: "100"
  },
  headerText: {
    paddingBottom: 10,
    fontSize: 20,
    color: "#69d2e7"
  }

});

I've tried to test app with iPhone 5 simulator, and I have no any style problem. Looks like the problem only with real iPhone 5 device. Maybe it is bug.


问:
std::shared_ptr<Parent> to std::shared_ptr<Child>
I have an "interface" as .h file that has a virtual method like this:

```<code>class ISomeInterface {
    public:
        virtual std::shared_ptr<Parent> getX() = 0;
}
</code>```

now that parent is "abstract" and in the implementors of the interface I use an actual class. So I wanted to do this:

```<code>class Implementor : public ISomeInterface {
    public:
        std::shared_ptr<Child> getX() = { return this->x; }
}
</code>```

But then I get:

Could not convert ‘((Implementor*)this)->Implementor::parent’ from ‘std::shared_ptr’ to ‘std::shared_ptr’

So, basically the std::shared_ptr is a wrapper and the compiler does not know how to come from wrapper<apple> to wrapper<fruit>, even though apple extends fruit.

How can I circumvent that behaviour?

Edit: Looks like this is still not possible in c++, as covariant types are only working for pointers/references, not inside wrappers like std::shared_ptr... a shame :(

答:
You could satisfy both the virtual interface and provide additional information to those who have access to the derived class by having two member functions:

```<code>struct Implementor : ISomeInterface
{
    shared_ptr<Parent> getX() override { return getX_fromImplementor(); }

    shared_ptr<Child> getX_fromImplementor()  // not virtual!
    {
        // real implementation here
    }
};
</code>```

Body:
I have an "interface" as .h file that has a virtual method like this:

class ISomeInterface {
    public:
        virtual std::shared_ptr<Parent> getX() = 0;
}

now that parent is "abstract" and in the implementors of the interface I use an actual class. So I wanted to do this:

class Implementor : public ISomeInterface {
    public:
        std::shared_ptr<Child> getX() = { return this->x; }
}

But then I get:

Could not convert ‘((Implementor*)this)->Implementor::parent’ from ‘std::shared_ptr’ to ‘std::shared_ptr’

So, basically the std::shared_ptr is a wrapper and the compiler does not know how to come from wrapper<apple> to wrapper<fruit>, even though apple extends fruit.

How can I circumvent that behaviour?

Edit: Looks like this is still not possible in c++, as covariant types are only working for pointers/references, not inside wrappers like std::shared_ptr... a shame :(

Body:
You could satisfy both the virtual interface and provide additional information to those who have access to the derived class by having two member functions:

struct Implementor : ISomeInterface
{
    shared_ptr<Parent> getX() override { return getX_fromImplementor(); }

    shared_ptr<Child> getX_fromImplementor()  // not virtual!
    {
        // real implementation here
    }
};


问:
app declares a dependency from configuration 'compile' to configuration 'default' which is not declared in the descriptor for project
I am importing a library module named "wear" in my project and while building, I am getting this:

```<code>Error : A problem occurred configuring project ':app'.
Could not resolve all dependencies for configuration ':app:_debugApk'.
Project :app declares a dependency from configuration 'compile' to configuration 'default' which is not declared in the descriptor for project :wear.
</code>```

What does it mean? How can I get rid of this?

答:
I ran into a similar issue with a different set of modules.  I was finally able to resolve it by reinstalling the necessary modules via npm but with the --save flag.  i.e. npm install --save module-name

It looks like if you just have the .iml file in the module folder, it's not enough for the android studio to resolve it.

Good luck.

ContentLicense: CC BY-SA 4.0

Body:
I am importing a library module named "wear" in my project and while building, I am getting this:

Error : A problem occurred configuring project ':app'.
Could not resolve all dependencies for configuration ':app:_debugApk'.
Project :app declares a dependency from configuration 'compile' to configuration 'default' which is not declared in the descriptor for project :wear.

What does it mean? How can I get rid of this?


问:
JSON data format changed & function building unordered list out of it stopped working?
I pass some data converting it into json & json outputs like;

```<code>[{"msg":"1: AVAILABLE: should be publicly available"},{"msg":"1: API USAGE: Uses api
of twitter to develop messaging service \n PUBLICALLY AVAILABLE: Should be publically
available"},{"msg":"1: EX_DES_EXP: Help novice users to exchange \n design experiences
through specifications messages"}]
</code>```

I use following script to build an unordered list using this json data:

```<code> <script type="text/javascript" language="javascript">
 jQuery(document).ready(function() {
 jQuery.getJSON("http://127.0.0.1/conn_msg2_qua.php", function (jsonData) {
 var markup;
 markup = [];
 jQuery.each(jsonData, function (i, j) {
    markup.push("<li>");
    markup.push(j.msg);
    markup.push("</li>");
 });
 jQuery('#msg_q').append(markup.join(""));
 });});
 </script>

  <script>
</code>```

Now I change implementation of data that was converted to json as bit & json appears like

```<code>["1 AVAILABLE: should be publicly available","2 API USAGE: Uses api of twitter to
 develop messaging service \n PUBLICALLY AVAILABLE: Should be publically available","3
 EX_DES_EXP: Help novice users to exchange \n design experiences through
 specifications messages"]
</code>```

and my function stopped printing it as unordered list. Whats the problem causes this. How do I again make it work.

答:
Replace:

```<code>markup.push(j.msg);
</code>```

with:

```<code>markup.push(j);
</code>```

Update:

I'd also recommend to change the way you inject text into your HTML. Instead of:

```<code>markup.push("<li>");
markup.push(j);
markup.push("</li>");
[...]
jQuery('#msg_q').append(markup.join(""));
</code>```

... use something like:

```<code>var li = $("<li></li>");
li.text(j);
markup.push(li);
[...]
jQuery('#msg_q').append(markup);
</code>```

Body:
I pass some data converting it into json & json outputs like;

[{"msg":"1: AVAILABLE: should be publicly available"},{"msg":"1: API USAGE: Uses api
of twitter to develop messaging service \n PUBLICALLY AVAILABLE: Should be publically
available"},{"msg":"1: EX_DES_EXP: Help novice users to exchange \n design experiences
through specifications messages"}]

I use following script to build an unordered list using this json data:

Body:
Replace:

markup.push(j.msg);

with:

markup.push(j);

Update:

I'd also recommend to change the way you inject text into your HTML. Instead of:

markup.push("<li>");
markup.push(j);
markup.push("</li>");
[...]
jQuery('#msg_q').append(markup.join(""));

... use something like:

var li = $("<li></li>");
li.text(j);
markup.push(li);
[...]
jQuery('#msg_q').append(markup);


问:
mysql slow log query
Question - When i am looking into mysql-slowquery.log then there i found queries having high query_time, even when one query has row examine = 1. This log is of a heavily populated database. From php website. Can you explain the reason and why are they used(if any idea about queries) ?</p>

```<code>Query type 1 :

# Query_time: 0.198267  Lock_time: 0.000121 Rows_sent: 1  Rows_examined: 10636
use mysql;
SET timestamp=1490832000;
SELECT count(name) FROM information_schema.innodb_sys_tables
    WHERE name like '%/#sql-%';

Query type 2:

# Query_time: 0.007362  Lock_time: 0.000127 Rows_sent: 0  Rows_examined: 1
use mysql;
SET timestamp=1490835900;
SELECT count(*) from mysql.rds_history
    WHERE action = 'disable set master'
    GROUP BY action_timestamp, called_by_user, action, mysql_version ,master_host,
             master_port, master_user, master_log_file , master_log_pos,
             master_ssl
    ORDER BY action_timestamp LIMIT 1;
</code>```

答: Yes it's returning 1 row but also see number of rows has been checked Rows_examined: 10636. Also, it may take long time if by the time SELECT is executed there is an exclusive or write lock present on the table due to any DML operation. In such case SELECT has to wait until the lock is released (considering the fact that transaction isolation level is READ COMMITED)

Title: mysql slow log query

Body:
Question - When i am looking into mysql-slowquery.log then there i found queries having high query_time, even when one query has row examine = 1. This log is of a heavily populated database. From php website. Can you explain the reason and why are they used(if any idea about queries) ?

Query type 1 :

# Query_time: 0.198267  Lock_time: 0.000121 Rows_sent: 1  Rows_examined: 10636
use mysql;
SET timestamp=1490832000;
SELECT count(name) FROM information_schema.innodb_sys_tables
    WHERE name like '%/#sql-%';

Query type 2:

# Query_time: 0.007362  Lock_time: 0.000127 Rows_sent: 0  Rows_examined: 1
use mysql;
SET timestamp=1490835900;
SELECT count(*) from mysql.rds_history
    WHERE action = 'disable set master'
    GROUP BY action_timestamp, called_by_user, action, mysql_version ,master_host,
             master_port, master_user, master_log_file , master_log_pos,
             master_ssl
    ORDER BY action_timestamp LIMIT 1;


问:
Background-Color grey, rather than transparent
So when I try to remove the background-color attribute, the background stay a grey sort of color, rather than becoming transparent. Code:

CSS:

```<code>    #contact-form button[type="submit"] {
    position: absolute;
    width: 100%;
    margin: 100px 0 5px;
    padding: 10px;
    font-size: 15px;
    height: 50px;
    max-width: 372px;
    border: 1px solid white;
    border-radius: 15px;
    color: white;
    text-align: center;
    text-decoration: none;
    cursor: pointer;
    transition: 0.5s;
}

#contact-form button[type="submit"]:hover {
    background-color: #fff;
    color: #2D2D2D;
}
</code>```

答:
If you want to make the button hidden until moused over, just add background:transparent; to the first CSS rule. I added the form background to make it clear how it works.

#contact-form button[type="submit"] {
  position: absolute;
  width: 100%;
  margin: 100px 0 5px;
  padding: 10px;
  font-size: 15px;
  height: 50px;
  max-width: 372px;
  border: 1px solid white;
  border-radius: 15px;
  color: white;
  text-align: center;
  text-decoration: none;
  cursor: pointer;
  transition: 0.5s;
  background: transparent; /* This is all that was needed */
}

#contact-form button[type="submit"]:hover {
  background-color: #fff;
  color: #2D2D2D;
}

form {
  background-color: red;
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="contact-form">

  <button type="submit" value="Submit">Click Me!</button>

</form></code>```

Body:
So when I try to remove the background-color attribute, the background stay a grey sort of color, rather than becoming transparent. Code:

CSS:

    #contact-form button[type="submit"] {
    position: absolute;
    width: 100%;
    margin: 100px 0 5px;
    padding: 10px;
    font-size: 15px;
    height: 50px;
    max-width: 372px;
    border: 1px solid white;
    border-radius: 15px;
    color: white;
    text-align: center;
    text-decoration: none;
    cursor: pointer;
    transition: 0.5s;
}

#contact-form button[type="submit"]:hover {
    background-color: #fff;
    color: #2D2D2D;
}

Body:
If you want to make the button hidden until moused over, just add background:transparent; to the first CSS rule. I added the form background to make it clear how it works.

#contact-form button[type="submit"] {
  position: absolute;
  width: 100%;
  margin: 100px 0 5px;
  padding: 10px;
  font-size: 15px;
  height: 50px;
  max-width: 372px;
  border: 1px solid white;
  border-radius: 15px;
  color: white;
  text-align: center;
  text-decoration: none;
  cursor: pointer;
  transition: 0.5s;
  background: transparent; /* This is all that was needed */
}

#contact-form button[type="submit"]:hover {
  background-color: #fff;
  color: #2D2D2D;
}

form {
  background-color: red;
  height: 200px;
}

<form id="contact-form">

  <button type="submit" value="Submit">Click Me!</button>

</form>


问:
PostgreSQL Insertion in JAVA via JSP Incrementing Primary Key
I am writing a JSP application where the user enters a food item and it is entered in a PostgreSQL database. I had no problems implementing this when the user manually had to enter the next primary key, but I removed this ability so that the primary key would be automatically assigned when the enter button is clicked. I would like the query to fetch the current maximum FID (Food ID) and set the new food item's FID to the previous + 1.

```<code>try {

    conn = ConnectionProvider.getCon();
    String sql = "select fid from project.food order by fid desc limit 1";
    pst = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    status = pst.getResultSetType();
    f.setFood_id(status + 1);

    pst = conn.prepareStatement("insert into project.food values(?,?,?,?,?,?)");
    pst.setInt(1, f.getFood_id());
    pst.setString(2, f.getFood_name()); //set name
    pst.setInt(3, f.getCount()); //set count
    pst.setInt(4, f.getPrice_per_item()); //set price
    pst.setInt(5, f.getThreshold()); //set threshold
    pst.setString(6, "false");
    status = pst.executeUpdate();
    conn.close();
    pst.close();
} catch (Exception ex) {
    System.out.println(ex);
}
return status;
}
</code>```

The first food item is successfully inserted into the database in row 1006, instead of the 7th row, which is the first available in the database. Additionally, the second insert fails due to the failure of the primary key to the incremented by 1. The program again tries to insert the next tuple in the same row and thus violates the primary key constraint.

```<code>    org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "food_pkey"
    Detail: Key (fid)=(1006) already exists.
</code>```

答:
Make your primary key autoincrement in the database by declaring it SERIAL datatype (basically an auto incrementing INT) so a sequence is created to automatically assign values to it.

Then convert your update statement to specify all columns except for the primary key (i.e. insert into project.food(foo, bar, baz) values (?, ?, ?), and remove one ? placeholder and the pst.setInt(1,f.getFood_id()); line. This will insert values to all the other columns, and the primary key will be generated by the database.

This way you don't need to do a select when you want to insert (which was a really bad idea anyway), and you let the database do what it does best. You don't need to care about the value of the primary key after that.

Body:
I am writing a JSP application where the user enters a food item and it is entered in a PostgreSQL database. I had no problems implementing this when the user manually had to enter the next primary key, but I removed this ability so that the primary key would be automatically assigned when the enter button is clicked. I would like the query to fetch the current maximum FID (Food ID) and set the new food item's FID to the previous + 1.

try {

    conn = ConnectionProvider.getCon();
    String sql = "select fid from project.food order by fid desc limit 1";
    pst = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    status = pst.getResultSetType();
    f.setFood_id(status + 1);

    pst = conn.prepareStatement("insert into project.food values(?,?,?,?,?,?)");
    pst.setInt(1, f.getFood_id());
    pst.setString(2, f.getFood_name()); //set name
    pst.setInt(3, f.getCount()); //set count
    pst.setInt(4, f.getPrice_per_item()); //set price
    pst.setInt(5, f.getThreshold()); //set threshold
    pst.setString(6, "false");
    status = pst.executeUpdate();
    conn.close();
    pst.close();
} catch (Exception ex) {
    System.out.println(ex);
}
return status;
}

The first food item is successfully inserted into the database in row 1006, instead of the 7th row, which is the first available in the database. Additionally, the second insert fails due to the failure of the primary key to the incremented by 1. The program again tries to insert the next tuple in the same row and thus violates the primary key constraint.

    org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "food_pkey"
    Detail: Key (fid)=(1006) already exists.


问:
Losing rows on Google BigQuery after doing a WHERE / through unnesting/flattening
I got daily tables from Google Analytics about a website. In the table are 167.286 rows. The main target is to create a new table (CSV) with only the needed columns and rows. Using Legacy SQL I have this query:

```<code>SELECT
  CONCAT(CAST(visitId AS string), CAST(fullVisitorId AS string), CAST(visitNumber AS string), CAST(hits.hitNumber AS string)) AS identifier,
  hits.hitNumber as hitNumber,
  hits.page.pagePath as pagePath,
  hits.page.pagePathLevel1 as pagePathLevel1,
  hits.page.pagePathLevel2 as pagePathLevel2,
  hits.appInfo.exitScreenName as exitScreenName,
  hits.eventInfo.eventCategory as eventCategory,
  hits.eventInfo.eventAction as eventAction,
  hits.eventInfo.eventLabel as eventLabel,
  hits.customDimensions.value as value,
  hits.customDimensions.index as index,
  visitId,
  fullVisitorId,
  date,
  visitNumber,
  totals.hits as hits,
  totals.pageviews as pageviews,
  device.deviceCategory as deviceCategory,
  geoNetwork.city,
  channelGrouping,
  trafficSource.campaign as campaign,
  trafficSource.source as source,
  trafficSource.medium as medium
FROM
  [project:dataset.table]
WHERE NOT hits.customDimensions.value = "PrivateUser" AND NOT hits.customDimensions.value = "LoggedIn"
</code>```

At the first moment I am using a WHERE statement I am losing rows which should not be effected by the WHERE statement.

After this I got a total number of 77.250 rows.  But each of the excluded values has 23.825 rows. I get the 23.825 rows when I modify the WHERE statement to WHERE hits.customDimensions.value = "PrivateUser". The same goes for "LoggedIn".

167.286 - 2*23.825 = 119.636 and not 77.250. So I am losing 42.386 rows and I don´t have a clue why.
Has anybody an idea why this is happening? I just want to have all the rows except the rows where value is not PrivateUser and LoggedIn. And that should be more than 77.250.

This problem appears in Legacy and Standard SQL. This is the same query but in Standard SQL:

```<code>SELECT
    columns (modified like the unnesting statement)
FROM
    `project.dataset.table`, UNNEST(hits) as h, UNNEST(h.customDimensions) as c
WHERE
    NOT c.value = "PrivateUser" AND NOT c.value = "LoggedIn"
</code>```

I am losing 42.386 rows again and dont kow why :(

I think I am coming more near to the cause of this problem: The nested schema.

If I doing the Standard SQL query without the WHERE statement I get a total number of 124.900 rows. So here are 42.386 rows missing again.
It seems that the reason for this is the unnesting or flattening of the data.

Maybe a better question is "How can I unnesting or flattening my data without a loss of my data?".

If I click on the button "Hide Options". selecting an output table and and activating "Allow Large Results" and "Flatten Results" I get the error message "Cannot FLATTEN non-repeated field hits_1" f.e.

答:
Maybe a better question is "How can I unnesting or flattening my data without a loss of my data?".

This issue has nothing to do with unnesting or flattening your data

Rather it is just how WHERE clause works:

The WHERE clause filters out rows by evaluating each row against bool_expression, and discards all rows that do not return TRUE (that is, rows that return FALSE or NULL).

So, in your case those rows where c.value IS NULL - they are being excluded because for such rows your WHERE clause returns NULL, thus being filtered out

You can see this with below simplified example

#standardSQL
WITH t AS (
  SELECT NULL AS value UNION ALL
  SELECT 'a' UNION ALL
  SELECT 'b' )
SELECT * FROM t WHERE NOT value = 'a'
```

<p>the result is   </p>

<pre class="lang-sql prettyprint-override"><code>value
-----
b
</code>```

As you can see rows with 'a' and NULL are being filtered out

So, as Elliott suggested, you should explicitly state that you want to keep NULLs in your result, as in below (for example)

#standardSQL
WITH t AS (
  SELECT NULL AS value UNION ALL
  SELECT 'a' UNION ALL
  SELECT 'b' )
SELECT * FROM t WHERE NOT value = 'a' OR value IS NULL
```

<p>As expected, now result is:   </p>

<pre class="lang-sql prettyprint-override"><code>value
-----
b
null
</code>```

As an option (depends on coding preferences) you can do as below

SELECT * FROM t WHERE NOT IFNULL(value, '') = 'a'
```

<p>If, as it is in your example, you want to exclude multiple values - repeating of <code>IFNULL(value, '')</code> for each is not what you want so you can use below approach   </p>

<pre class="lang-sql prettyprint-override"><code>SELECT * FROM t WHERE NOT IFNULL(value, '') IN ('a', 'b', 'c')
</code>```

Body:
I got daily tables from Google Analytics about a website. In the table are 167.286 rows. The main target is to create a new table (CSV) with only the needed columns and rows. Using Legacy SQL I have this query:

SELECT
  CONCAT(CAST(visitId AS string), CAST(fullVisitorId AS string), CAST(visitNumber AS string), CAST(hits.hitNumber AS string)) AS identifier,
  hits.hitNumber as hitNumber,
  hits.page.pagePath as pagePath,
  hits.page.pagePathLevel1 as pagePathLevel1,
  hits.page.pagePathLevel2 as pagePathLevel2,
  hits.appInfo.exitScreenName as exitScreenName,
  hits.eventInfo.eventCategory as eventCategory,
  hits.eventInfo.eventAction as eventAction,
  hits.eventInfo.eventLabel as eventLabel,
  hits.customDimensions.value as value,
  hits.customDimensions.index as index,
  visitId,
  fullVisitorId,
  date,
  visitNumber,
  totals.hits as hits,
  totals.pageviews as pageviews,
  device.deviceCategory as deviceCategory,
  geoNetwork.city,
  channelGrouping,
  trafficSource.campaign as campaign,
  trafficSource.source as source,
  trafficSource.medium as medium
FROM
  [project:dataset.table]
WHERE NOT hits.customDimensions.value = "PrivateUser" AND NOT hits.customDimensions.value = "LoggedIn"

At the first moment I am using a WHERE statement I am losing rows which should not be effected by the WHERE statement.

After this I got a total number of 77.250 rows.  But each of the excluded values has 23.825 rows. I get the 23.825 rows when I modify the WHERE statement to WHERE hits.customDimensions.value = "PrivateUser". The same goes for "LoggedIn".

167.286 - 2*23.825 = 119.636 and not 77.250. So I am losing 42.386 rows and I don´t have a clue why.
Has anybody an idea why this is happening? I just want to have all the rows except the rows where value is not PrivateUser and LoggedIn. And that should be more than 77.250.

This problem appears in Legacy and Standard SQL. This is the same query but in Standard SQL:

SELECT
    columns (modified like the unnesting statement)
FROM
    `project.dataset.table`, UNNEST(hits) as h, UNNEST(h.customDimensions) as c
WHERE
    NOT c.value = "PrivateUser" AND NOT c.value = "LoggedIn"

I am losing 42.386 rows again and dont kow why :(

I think I am coming more near to the cause of this problem: The nested schema.

If I doing the Standard SQL query without the WHERE statement I get a total number of 124.900 rows. So here are 42.386 rows missing again.
It seems that the reason for this is the unnesting or flattening of the data.

Maybe a better question is "How can I unnesting or flattening my data without a loss of my data?".

If I click on the button "Hide Options". selecting an output table and and activating "Allow Large Results" and "Flatten Results" I get the error message "Cannot FLATTEN non-repeated field hits_1" f.e.

Body:
Maybe a better question is "How can I unnesting or flattening my data without a loss of my data?".

This issue has nothing to do with unnesting or flattening your data

Rather it is just how WHERE clause works:

The WHERE clause filters out rows by evaluating each row against bool_expression, and discards all rows that do not return TRUE (that is, rows that return FALSE or NULL).

So, in your case those rows where c.value IS NULL - they are being excluded because for such rows your WHERE clause returns NULL, thus being filtered out

You can see this with below simplified example

#standardSQL
WITH t AS (
  SELECT NULL AS value UNION ALL
  SELECT 'a' UNION ALL
  SELECT 'b' )
SELECT * FROM t WHERE NOT value = 'a'

the result is

value
-----
b

As you can see rows with 'a' and NULL are being filtered out

So, as Elliott suggested, you should explicitly state that you want to keep NULLs in your result, as in below (for example)

#standardSQL
WITH t AS (
  SELECT NULL AS value UNION ALL
  SELECT 'a' UNION ALL
  SELECT 'b' )
SELECT * FROM t WHERE NOT value = 'a' OR value IS NULL

As expected, now result is:

value
-----
b
null

As an option (depends on coding preferences) you can do as below

SELECT * FROM t WHERE NOT IFNULL(value, '') = 'a'

If, as it is in your example, you want to exclude multiple values - repeating of IFNULL(value, '') for each is not what you want so you can use below approach

SELECT * FROM t WHERE NOT IFNULL(value, '') IN ('a', 'b', 'c')


问:
Unable to keep the top level control position fix in winforms - user controls
I have a user control which has 5 panels.
on form load, 5 user controls gets added to the respective panels and eventually all panels gets added as well to user control.

If I set the user control autoscroll property to true, I do get the vertical scroll bar. Using vertical scroll, if I move down to enter values in last control...
the control at the top goes off i.e. it moves up and down based on my user control scroll position...

Is there any way I can keep the first 2 user control steady when I move the scroll bar down to the last control?

edit: Providing more information.
I can say that the first user control is like header which has save button in it... and thus I want that portion to be fixed.

答:
Don't set autoscroll on the outer user control.

Put the fixed user control(s) inside the outer user control (optionally inside panels if you need to). Then put another panel inside the outer user control and set the panel's AutoScroll property to true. Put the remaining user controls (wrapped in panels if necessary) inside the scrollable panel.

(*) Note: unless there is some other reason (that is not apparent in the question) there is no need for the extra panels wrapping the inner user controls.


问:
how to get literal array value stored inside script tag on html page using javascript or protractor
I'm using Protractor, a nodejs based test automation tool with Javascript language for test scripts creation.

I need to get a specific data from HTML page source that have scripttag that have some Literal array stored inside as the followings:

```<code><script type="text/javascript">
var propertypv_obj =[{"listing_id":1545780,"cat":8733,"loc":5687,"purpose":2,"type":4}]
</script>
</code>```

答:
Use executeScript to return the data to Protractor:</p>

```<code>browser.executeScript('return propertypv_obj;').then(function(result) {
    expect(result[0].cat).toEqual(8733);
}
</code>```

Body:
Use executeScript to return the data to Protractor:

browser.executeScript('return propertypv_obj;').then(function(result) {
    expect(result[0].cat).toEqual(8733);
}