问:
Trying to fixed the navigation bar
I've been trying to fixed the problem with my navigation bar.

What I'd like to do, is to put always the home icon on the left and setting on the right while the navigation title on the center as shown in the image.

But still look like this

when view in smallest/large screen other than my laptop 1366px wide

Is there anyone can help me with the same problem?

here the code.

```<code><nav>
  <div class="nav__container">
    <div class="nav__container--left">
      <div class="">
        <a href="http://localhost/mpci_virtual_office/" title="Return Home">
          <i class="fa fa-home fa-lg" aria-hidden="true"></i>
        </a>
      </div>
    </div>
    <div class="nav__container--center">
      <strong>Home</strong>
    </div>
    <div class="nav__container--toggle">
      <a id="push" class="visible-xs visible-sm visible-md"><i class="fa fa-bars "></i></a>
    </div>
    <div class="nav__container--right">
      <a class="dropdown-toggle" data-toggle="dropdown" title="Settings">
        <i class="fa fa-gear fa-lg"></i>
      </a>
      <ul class="dropdown-menu">
        <li><a href="http://localhost/mpci_virtual_office/office/view_profile/index/1">View Profile</a></li>
        <li><a href="http://localhost/mpci_virtual_office/office/account_preference">Settings</a></li>
        <li><a href="http://localhost/mpci_virtual_office/auth/logout">Logout</a></li>
      </ul>
    </div>
  </div>
</nav>
</code>```

And this is my CSS

```<code>/* Naviation Style */
.nav__container {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 6;
}
.nav__container--left,
.nav__container--center,
.nav__container--toggle,
.nav__container--right {
  width: 50px;
  height: 100%;
  position: absolute;

  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: center;
  align-items:center;
  align-content:  center;
}
.nav__container--left { }
.nav__container--left div { }
.nav__container--left div a { }
.nav__container--center {
  width: 100%;
  z-index: -1;
  text-align: center;
}
.nav__container--toggle {
  right: 50px;
}
.nav__container--right {
  right: 0;
}
</code>```

答:
```<code>nav {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}
</code>```

<p>try out this css snippet. if you set position you allways have to set top|bottom and left|right </p>

Title: Trying to fixed the navigation bar

Body:
I've been trying to fixed the problem with my navigation bar.

What I'd like to do, is to put always the home icon on the left and setting on the right while the navigation title on the center as shown in the image.

But still look like this

when view in smallest/large screen other than my laptop 1366px wide

Is there anyone can help me with the same problem?

here the code.

      Home

View Profile

Settings

Logout

And this is my CSS

/* Naviation Style */
.nav__container {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 6;
}
.nav__container--left,
.nav__container--center,
.nav__container--toggle,
.nav__container--right {
  width: 50px;
  height: 100%;
  position: absolute;

  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: center;
  align-items:center;
  align-content:  center;
}
.nav__container--left { }
.nav__container--left div { }
.nav__container--left div a { }
.nav__container--center {
  width: 100%;
  z-index: -1;
  text-align: center;
}
.nav__container--toggle {
  right: 50px;
}
.nav__container--right {
  right: 0;
}

Body:
nav {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}

try out this css snippet. if you set position you allways have to set top|bottom and left|right


来源: stackexchange

问:
install FFMPEG on PHP 7.0.6 - Xampp
I am new to php. I am trying to convert video uploaded by the user.
Somehow, I have done all the php work except conversion. I came to know about FFMPEG, I have installed it and tried with CLI and it worked perfect.

When I tried it in ph using shell_exec() command. It gives me nothing, Then by google, I should activate the extension of ffmpeg in my php.ini file.

```<code>shell_exec("ffmpeg -i video/Wildlife.wmv video/output.mp4");
</code>```

I have googled but there is no help regarding this php version.
Any idea or guideline will be very helpful.

This may be a duplicate question but there is nothing with php 7 version on stackoverflow.

答:
FFMPEG is standalone library. You don't have to install any php extensions.
Try run your command directly from bash shell and check the results.

Problem may be caused by corrupted FFMPEG installation.

Another problem may be with your php configuration.
You can find in documetation informaction, that shell_exec function is disabled, when you use safe mode.

Check also disable_functions entry in your php.ini file.

ContentLicense: CC BY-SA 3.0

Title: install FFMPEG on PHP 7.0.6 - Xampp

Body:
I am new to php. I am trying to convert video uploaded by the user.
Somehow, I have done all the php work except conversion. I came to know about FFMPEG, I have installed it and tried with CLI and it worked perfect.

When I tried it in ph using shell_exec() command. It gives me nothing, Then by google, I should activate the extension of ffmpeg in my php.ini file.

shell_exec("ffmpeg -i video/Wildlife.wmv video/output.mp4");

I have googled but there is no help regarding this php version.
Any idea or guideline will be very helpful.

This may be a duplicate question but there is nothing with php 7 version on stackoverflow.


问:
Query inside query on google spreadsheet
I need to query data from table and for where clause use result from another query

For example:

How to query for rows at this tab where date on column A is greater or equal date from another query on the tab shown at second image below. I want to write only the project number on the query or put a cell with the current project number and query for start and end dates where project is equal current project.

The query will be something like this:

Can you help me?

答:
Sure it's possible if you use appropriate syntax.

I suggest query + filter combination:

Sheet1

```<code>Date    Col1    Col2
3/29/2017   a   a2
3/30/2017   b   b3
3/31/2017   c   c4
4/1/2017    d   d5
4/2/2017    e   e6
4/3/2017    f   f7
4/4/2017    g   g8
4/5/2017    h   h9
4/6/2017    i   i10
4/7/2017    j   j11
4/8/2017    k   k12
</code>```

Sheet2

```<code>Project   Date1         Date2
1         3/29/2017     4/1/2017
2         4/2/2017      4/5/2017
3         4/6/2017      4/8/2017
</code>```

Sheet3: Resulting formula

The formula is:

=QUERY({Sheet1!A:C},"select * where Col1 >= date '"&TEXT(FILTER(Sheet2!B:B,Sheet2!A:A=1),"YYYY-MM-DD")&"' and Col1 <= date '"&TEXT(FILTER(Sheet2!C:C,Sheet2!A:A=1),"YYYY-MM-DD")&"'")

The result:

```<code>Date    Col1    Col2
3/29/2017   a   a2
3/30/2017   b   b3
3/31/2017   c   c4
4/1/2017    d   d5
</code>```

It's better to use filter once:

=FILTER(Sheet2!B:C,Sheet2!A:A=1)

to get dates for project #1 and then reference it's result.

Or even convert it to date format:

=FILTER(text(Sheet2!B:C,"\dat\e 'YYYY-MM-DD'"),Sheet2!A:A=1)

and get 2 strings:

```<code>date '2017-03-29'   date '2017-04-01'
</code>```

I've also tried to use shorter query: select * where Col1 between date '2017-03-29' and date '2017-04-01' but between keyword is not supported.

Body:
Sure it's possible if you use appropriate syntax.

I suggest query + filter combination:

Sheet1

Date    Col1    Col2
3/29/2017   a   a2
3/30/2017   b   b3
3/31/2017   c   c4
4/1/2017    d   d5
4/2/2017    e   e6
4/3/2017    f   f7
4/4/2017    g   g8
4/5/2017    h   h9
4/6/2017    i   i10
4/7/2017    j   j11
4/8/2017    k   k12

Sheet2

Project   Date1         Date2
1         3/29/2017     4/1/2017
2         4/2/2017      4/5/2017
3         4/6/2017      4/8/2017

Sheet3: Resulting formula

The formula is:

=QUERY({Sheet1!A:C},"select * where Col1 >= date '"&TEXT(FILTER(Sheet2!B:B,Sheet2!A:A=1),"YYYY-MM-DD")&"' and Col1 <= date '"&TEXT(FILTER(Sheet2!C:C,Sheet2!A:A=1),"YYYY-MM-DD")&"'")

The result:

Date    Col1    Col2
3/29/2017   a   a2
3/30/2017   b   b3
3/31/2017   c   c4
4/1/2017    d   d5

It's better to use filter once:

=FILTER(Sheet2!B:C,Sheet2!A:A=1)

to get dates for project #1 and then reference it's result.

Or even convert it to date format:

=FILTER(text(Sheet2!B:C,"\dat\e 'YYYY-MM-DD'"),Sheet2!A:A=1)

and get 2 strings:

date '2017-03-29'   date '2017-04-01'

I've also tried to use shorter query: select * where Col1 between date '2017-03-29' and date '2017-04-01' but between keyword is not supported.


问:
How to post a value in Firebase using Vapor?
I followed some tutorials with Vapor and despite that I understood how to Get or Put or Patch some JSON values on the server, I have no idea how to send dictionary to Firebase from within the app.

I've tried to write some data on Firebase using Postman and I have no problem, but I have no idea how to handle the parameters of the request using Vapor ?

Can anyone, please, tell me where I have to put the URL of the database and how to make the request? Or even better, if there's some example on GitHub, I can look at?

答:
There is no Firebase SDK for Server-Side-Swift so you can handle JSON values using REST API of Firebase.

See this topic.


问:
Why are my units "compiled with a different version" of my own files?
I'm building a program that uses plugins.  Unfortunately, the plugin framework's dynamic linking forces the RTL and VCL out of my project EXE and into the BPL versions, and they don't have debug info enabled.

So I built a testing framework that links to my plugins statically so I can actually see what I'm doing while tracing through the code.  But now, every time I try to recompile, I get an error: "unit turbu_skills was compiled with a different version of turbu_database.GDatabase"

I've seen this error before, but only when I've been changing things I probably shouldn't have been, like the RTL or VCL libraries.  I don't understand why it's doing that with my own code.  The turbu_skills and turbu_database units are both units I wrote myself. GDatabase is a global singleton variable, whose class definition I haven't changed in weeks.  Any change that triggers a recompile causes this error, even if I haven't touched anything in either of the units.

Doing a full build (SHIFT-F9) causes it to compile correctly.  But if I then press SPACE in a unit (any unit) and hit F9, I get the error again.  What's going on and how do I stop it?  This doesn't happen in the main app, only the testing framework.

EDIT: I have the source to all of my units.  Deleting DCUs and similar files doesn't help.  Copying the entire project to a different computer, deleting all DCUs, and building there doesn't help.  There's an objective, reproducible conflict between the layout of my program and the compiler, and I want to be rid of it.

The source can be found at http://www.turbu-rpg.com/downloads/Turbu_source_setup.exe if anyone wants to test it. It requires Delphi 2009 with the JVCL already installed; the installer package will take care of the rest. Maybe having the source code available will help someone track this down. I certainly hope so, because wherever the issue is, it's beyond me. The problem can be found in testing.exe and also in turbu.exe in turbu.groupproj.

EDIT 2:  Turns out this was another cross-unit generics issue.  Grr.  I managed to code a workaround. I just hope they get the generics problems fixed soon.

答: Check that you don't have an strained old dcu file somewhere in source dir.</p>

OwnerDisplayName: Mason Wheeler

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Mason Wheeler

OwnerDisplayName: dmajkic


问:
'git push origin MyBranchName' throws error "HTTP Basic: Access denied"
I am new to Git (just started 2 days ago). I'm attempting to create a project to practice the basic commands I've learned from here.

Where I am, so far:

[success] Create a new public git project (because I tried private and internal before but I could not clone it, and I don't know why). Here it is.

Added a README.md into the project.

[success] Create a new branch named develop.

[success] In my local folder C:\gitprojects, set global user.name and user.email with the commands:

git config --global user.name <my user name>

git config --global user.email <my-email>

[success] Clone the project into my local folder C:\gitprojects with the command git clone https://flamedenise19@gitlab.com/flamedenise19/speedtyping.git

[success] Create a local branch with the command git checkout -b "develop".

[success] Manually add a new file test.txt on local root folder for test pushing.

[success] Commit the new file with the command git commit -m "adds test.txt"

[attempting] Push the commit with the command git push origin develop

And now, I'm stuck with the push part. After entering git push origin develop, a new window pops up, asking for my credentials (see screenshot below):

So I did enter my credentials (the very same username and password I use when logging in to gitlab.com), but after that, I got this error (also see screenshot below):

```<code>remote: HTTP Basic: Access denied
fatal: Authentication failed for 'https://gitlab.com/flamedenise19/speedtyping.git/'
</code>```

QUESTIONS:

Why can't I push successfully, even with the correct username and password? Am I missing something or have I done something wrong along the way?

Is there a way to remove the step of having to enter my credentials everytime I push something?

Please help.

NOTE: I have seen THIS ONE, and the answers are mentioning Tortoise. Is it always required to use tortoise in order to
  use Git?

SOME BACKGROUND INFO:

Two-Factor Authentication is disabled for my account (see screenshot below):

答:
These are my ideas:

Try if it works on the Git Bash

Have you added a ssh key to your account? If yes remove it and try again. If not add one and try the ssh url.

You don't necessarily need Tortoise Git but it may also work around your problem

Try to re-install Git without the Git Credential Manager for Windows

When you've fixed the push problem you will also be able to clone it when it is private or internal.

ContentLicense: CC BY-SA 4.0

Body:
I am new to Git (just started 2 days ago). I'm attempting to create a project to practice the basic commands I've learned from here.

Where I am, so far:

[success] Create a new public git project (because I tried private and internal before but I could not clone it, and I don't know why). Here it is.

Added a README.md into the project.

[success] Create a new branch named develop.

[success] In my local folder C:\gitprojects, set global user.name and user.email with the commands:

git config --global user.name <my user name>

git config --global user.email <my-email>

[success] Clone the project into my local folder C:\gitprojects with the command git clone https://flamedenise19@gitlab.com/flamedenise19/speedtyping.git

[success] Create a local branch with the command git checkout -b "develop".

[success] Manually add a new file test.txt on local root folder for test pushing.

[success] Commit the new file with the command git commit -m "adds test.txt"

[attempting] Push the commit with the command git push origin develop

And now, I'm stuck with the push part. After entering git push origin develop, a new window pops up, asking for my credentials (see screenshot below):

So I did enter my credentials (the very same username and password I use when logging in to gitlab.com), but after that, I got this error (also see screenshot below):

remote: HTTP Basic: Access denied
fatal: Authentication failed for 'https://gitlab.com/flamedenise19/speedtyping.git/'

QUESTIONS:

Why can't I push successfully, even with the correct username and password? Am I missing something or have I done something wrong along the way?

Is there a way to remove the step of having to enter my credentials everytime I push something?

Please help.

NOTE: I have seen THIS ONE, and the answers are mentioning Tortoise. Is it always required to use tortoise in order to
  use Git?

SOME BACKGROUND INFO:

Two-Factor Authentication is disabled for my account (see screenshot below):


问:
Laravel Passport with Dropzonejs
I am working on a project that has an API layer which is running Laravel Passport.  I have added the createFreshApiToken to my application and all of my jQuery ajax requests are working just fine.

Today I am integrating DropzoneJS and when I try to upload a file it is getting a 401 Unauthorized.  I checked the request headers and the laravel_token is set in the cookie header.

What would cause Laravel Passport to throw a 401 Unauthorized response when the laravel_token is contained in the request header?

```<code>General
Request URL:http://api.ryno.dev/api/post/photo
Request Method:POST
Status Code:401 Unauthorized
Remote Address:127.0.0.1:80

Response Headers
Cache-Control:no-cache
Connection:Keep-Alive
Content-Length:28
Content-Type:application/json
Date:Wed, 15 Mar 2017 16:36:27 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.2.31 (Unix) mod_wsgi/3.5 Python/2.7.12 PHP/7.0.12   mod_ssl/2.2.31 OpenSSL/1.0.2j DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.24.0
X-Powered-By:PHP/7.0.12
X-RateLimit-Limit:60
X-RateLimit-Remaining:59

Request Headers
Accept:application/json
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
api-version:1
Cache-Control:no-cache
Connection:keep-alive
Content-Length:4802
Content-Type:multipart/form-data; boundary=---- WebKitFormBoundaryEqAfOqBqekRWHC6B
Cookie:laravel_token=eyJpdiI6InJzRG5SNkVmYW1GMDJmd3pPTUhnWmc9PSIsInZhbHVlIjoiUk1iU01XVm9Ydytyb3NXUDlEVngwUnlGUXNhSkdvcFFpaXhwNSt6XC9XXC9TOHlcL3MxWjl2MkVxU1NCNjV6bmNka2w3dlNlTmJrRXVTVkVhQnZOd1dwZTRpaXdscll1WHVsUm1CMHBkbVdiNVprZXZmT2pRaTdySjRXRzhWY1FGV25JNm5qXC9TNzV6dEJzKzlsclZwRDVMczF6TVduODJIa0s1MVNQSXRMc2dteWtuU1lpdGJUQVJRS3BlS2E5dmd2Vlg2QXJzMldHQUM2Uk15RldUWnF4bXlcL1AzNTgwc1Q3YWpTVWIyVHYrYjN5QllzNGt3TDJcL1VsYmt6UFpudDVFaTdpK2JMZ01RcTRcL2lySUFRQ1hxaXF3PT0iLCJtYWMiOiJmODZiMzg1M2QyYjNlYmUwZWI2NWI3OWY0OTZjMDIxNjYwYjc3MGQxZGZjYzg2ZmQ1M2FjMTA1NDRiODAwZWVmIn0%3D; XSRF-TOKEN=eyJpdiI6IlNha2syNGFldngrM2FZUU9ZeEpNWUE9PSIsInZhbHVlIjoiVEM1RllaaGl1XC9UUWg4b2RuVkNlcnhod1EzXC9xSG9SN0w2dEZiV3RKbDJwQXdTeWtZS0pMODBEOFJvM1V1emNZdEJmOGJISFwvUjNkd2pBK2NXcTRlM2c9PSIsIm1hYyI6IjljMjg0MTI2NDFmNmYzNGU2ZmJiMWE4ODg3OGE4NWVmNmVhYzc5YzI4ZmNkYTRjZDI2M2Y1YWYwZjIzNzc2NGIifQ%3D%3D; laravel_session=eyJpdiI6IjBzRHhqcWRPdmdleVhlcURuOG4rYVE9PSIsInZhbHVlIjoiTkYzOHpiQ2dyY2tHSmV2Znl4RUpiNWdHZVBMaVJNaEI5YWdOcXVRRzdsSEZqMFp5cXFWOVBjYjBobmxLSXhJUFBab1JRbTZxUVhkekZVNjY3OUVkYmc9PSIsIm1hYyI6ImIxNjA0Y2E1NDdjNDc5YzA4NGYxNTgyMTNiMjdiY2RlODg0MzFjMDQ3N2ZjMTZiNDlmN2Q5Zjg3NWU0YTc1NWEifQ%3D%3D
Host:api.ryno.dev
Origin:http://api.ryno.dev
Pragma:no-cache
Referer:http://api.ryno.dev/post
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
X-Requested-With:XMLHttpRequest

Request Payload
------WebKitFormBoundaryEqAfOqBqekRWHC6B
Content-Disposition: form-data; name="file";        filename="10690061_724847794275121_4784866042446245380_n.jpg"
Content-Type: image/jpeg

------WebKitFormBoundaryEqAfOqBqekRWHC6B--
</code>```

答:
As per Laravel documentation for API Authentication with Javascript:

If you are using a different JavaScript framework, you should make
  sure it is configured to send the X-CSRF-TOKEN and X-Requested-With
  headers with every outgoing request.

I see the X-CSRF-TOKEN missing from your POST request. Can you try adding that and see if it works.

Title: Laravel Passport with Dropzonejs

Body:
I am working on a project that has an API layer which is running Laravel Passport.  I have added the createFreshApiToken to my application and all of my jQuery ajax requests are working just fine.

Today I am integrating DropzoneJS and when I try to upload a file it is getting a 401 Unauthorized.  I checked the request headers and the laravel_token is set in the cookie header.

What would cause Laravel Passport to throw a 401 Unauthorized response when the laravel_token is contained in the request header?

General
Request URL:http://api.ryno.dev/api/post/photo
Request Method:POST
Status Code:401 Unauthorized
Remote Address:127.0.0.1:80

Response Headers
Cache-Control:no-cache
Connection:Keep-Alive
Content-Length:28
Content-Type:application/json
Date:Wed, 15 Mar 2017 16:36:27 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.2.31 (Unix) mod_wsgi/3.5 Python/2.7.12 PHP/7.0.12   mod_ssl/2.2.31 OpenSSL/1.0.2j DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.24.0
X-Powered-By:PHP/7.0.12
X-RateLimit-Limit:60
X-RateLimit-Remaining:59

Request Headers
Accept:application/json
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
api-version:1
Cache-Control:no-cache
Connection:keep-alive
Content-Length:4802
Content-Type:multipart/form-data; boundary=---- WebKitFormBoundaryEqAfOqBqekRWHC6B
Cookie:laravel_token=eyJpdiI6InJzRG5SNkVmYW1GMDJmd3pPTUhnWmc9PSIsInZhbHVlIjoiUk1iU01XVm9Ydytyb3NXUDlEVngwUnlGUXNhSkdvcFFpaXhwNSt6XC9XXC9TOHlcL3MxWjl2MkVxU1NCNjV6bmNka2w3dlNlTmJrRXVTVkVhQnZOd1dwZTRpaXdscll1WHVsUm1CMHBkbVdiNVprZXZmT2pRaTdySjRXRzhWY1FGV25JNm5qXC9TNzV6dEJzKzlsclZwRDVMczF6TVduODJIa0s1MVNQSXRMc2dteWtuU1lpdGJUQVJRS3BlS2E5dmd2Vlg2QXJzMldHQUM2Uk15RldUWnF4bXlcL1AzNTgwc1Q3YWpTVWIyVHYrYjN5QllzNGt3TDJcL1VsYmt6UFpudDVFaTdpK2JMZ01RcTRcL2lySUFRQ1hxaXF3PT0iLCJtYWMiOiJmODZiMzg1M2QyYjNlYmUwZWI2NWI3OWY0OTZjMDIxNjYwYjc3MGQxZGZjYzg2ZmQ1M2FjMTA1NDRiODAwZWVmIn0%3D; XSRF-TOKEN=eyJpdiI6IlNha2syNGFldngrM2FZUU9ZeEpNWUE9PSIsInZhbHVlIjoiVEM1RllaaGl1XC9UUWg4b2RuVkNlcnhod1EzXC9xSG9SN0w2dEZiV3RKbDJwQXdTeWtZS0pMODBEOFJvM1V1emNZdEJmOGJISFwvUjNkd2pBK2NXcTRlM2c9PSIsIm1hYyI6IjljMjg0MTI2NDFmNmYzNGU2ZmJiMWE4ODg3OGE4NWVmNmVhYzc5YzI4ZmNkYTRjZDI2M2Y1YWYwZjIzNzc2NGIifQ%3D%3D; laravel_session=eyJpdiI6IjBzRHhqcWRPdmdleVhlcURuOG4rYVE9PSIsInZhbHVlIjoiTkYzOHpiQ2dyY2tHSmV2Znl4RUpiNWdHZVBMaVJNaEI5YWdOcXVRRzdsSEZqMFp5cXFWOVBjYjBobmxLSXhJUFBab1JRbTZxUVhkekZVNjY3OUVkYmc9PSIsIm1hYyI6ImIxNjA0Y2E1NDdjNDc5YzA4NGYxNTgyMTNiMjdiY2RlODg0MzFjMDQ3N2ZjMTZiNDlmN2Q5Zjg3NWU0YTc1NWEifQ%3D%3D
Host:api.ryno.dev
Origin:http://api.ryno.dev
Pragma:no-cache
Referer:http://api.ryno.dev/post
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
X-Requested-With:XMLHttpRequest

Request Payload
------WebKitFormBoundaryEqAfOqBqekRWHC6B
Content-Disposition: form-data; name="file";        filename="10690061_724847794275121_4784866042446245380_n.jpg"
Content-Type: image/jpeg

------WebKitFormBoundaryEqAfOqBqekRWHC6B--


问:
get the username of who triggered pipeline job ( manually or scm trigger)
I have a job that gets built in two ways :

IF someone commits to the github repo , triggering the job.

IF someone manually builds the job.

within my pipeline, I need to get the name/info of person who triggered the build either directly (manually) or indirectly(SCM commit). I have the following code:

```<code>node('slave'){
    wrap([$class: 'BuildUser']) {
      return BUILD_USER
    }
}
</code>```

This gets me the name using the https://wiki.jenkins-ci.org/display/JENKINS/Build+User+Vars+Plugin plugin.

This works on manual but always gives SCM trigger when through SCM trigger. How do I get the name/info of the person who committed for the trigger to happen via SCM ?

答:
ScmTrigger does not hold information about the user who committed to git.
You can get the user who commited by using git command:

```<code>git log --format='%an <%ae>' GIT_COMMIT_ID
</code>```

%an is the author's name

%ae is the author's email

Another option is to use a git hook that will trigger the job instead of SCM polling. in that case you can pass the commiter from the hook to the job. (for example https://www.fourkitchens.com/blog/article/trigger-jenkins-builds-pushing-github)

Body:
I have a job that gets built in two ways :

IF someone commits to the github repo , triggering the job.

IF someone manually builds the job.

within my pipeline, I need to get the name/info of person who triggered the build either directly (manually) or indirectly(SCM commit). I have the following code:

node('slave'){
    wrap([$class: 'BuildUser']) {
      return BUILD_USER
    }
}

This gets me the name using the https://wiki.jenkins-ci.org/display/JENKINS/Build+User+Vars+Plugin plugin.

This works on manual but always gives SCM trigger when through SCM trigger. How do I get the name/info of the person who committed for the trigger to happen via SCM ?

Body:
ScmTrigger does not hold information about the user who committed to git.
You can get the user who commited by using git command:

git log --format='%an <%ae>' GIT_COMMIT_ID

%an is the author's name

%ae is the author's email

Another option is to use a git hook that will trigger the job instead of SCM polling. in that case you can pass the commiter from the hook to the job. (for example https://www.fourkitchens.com/blog/article/trigger-jenkins-builds-pushing-github)


问:
matlab - line equation to 2D matrix with values of 1 and 0
As the title says, I want to covert a line(or any equation) to 2D matrix.

For example: If I have a line equation y = x, then I want it to be like:

```<code>0 0 0 0 0 1
0 0 0 0 1 0
0 0 0 1 0 0
0 0 1 0 0 0
0 1 0 0 0 0
1 0 0 0 0 0
</code>```

and the length of rows and columns can be variable.

Is there a function or method to implement that?

答:
use meshgrid to get x-y grids:

```<code>% set resolution parameters
xmin = 1;
xmax = 100;
dx = 0.1;
ymin = 1;
ymax = 100;
dy = 0.1;
% set x-y grid
[xg, yg] = meshgrid(xmin:dx:xmax, ymin:dy:ymax);
% define your function
f = @(x) (x - 30).^2;
% apply it on the x grid and get close y values
D = abs(f(xg) - yg);
bw = D <= 1;
figure;
imshow(bw);
% flip y axis
set(gca,'YDir','normal')
</code>```

you get:

and then you can further dilate/erode/skeletonize the output

Body:
As the title says, I want to covert a line(or any equation) to 2D matrix.

For example: If I have a line equation y = x, then I want it to be like:

0 0 0 0 0 1
0 0 0 0 1 0
0 0 0 1 0 0
0 0 1 0 0 0
0 1 0 0 0 0
1 0 0 0 0 0

and the length of rows and columns can be variable.

Is there a function or method to implement that?

Body:
use meshgrid to get x-y grids:

% set resolution parameters
xmin = 1;
xmax = 100;
dx = 0.1;
ymin = 1;
ymax = 100;
dy = 0.1;
% set x-y grid
[xg, yg] = meshgrid(xmin:dx:xmax, ymin:dy:ymax);
% define your function
f = @(x) (x - 30).^2;
% apply it on the x grid and get close y values
D = abs(f(xg) - yg);
bw = D <= 1;
figure;
imshow(bw);
% flip y axis
set(gca,'YDir','normal')

you get:

and then you can further dilate/erode/skeletonize the output


问:
Tapping the Firebase notification is not work when app is killed(inactive)
I am coding my company iphone app by IOS, Swift3. The app have 3 webviews. When my App is in Forground and Background, Firebase's notification worked well. When Taping it, I can view URL page at the webview. When it is in inactive (Killed the app), I can receive the notification. but when tapping it, I can NOT view the URL page, only launching the app by default. Plz inform me the smart solution.

This is the part of my AppDelegate.

```<code>func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    FIRMessaging.messaging().appDidReceiveMessage(userInfo)
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)

    //notification tapping
    let openpUrl = userInfo["openURL"] as? String
    //let openpUrl = userInfo["openURL"] as? String
    if ((openpUrl?.range(of: "blog.naver.com")) != nil) {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "naverblogPushNotification"), object: userInfo)
    }else{
        if ((openpUrl?.range(of: "facebook.com")) != nil) {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "facebookPushNotification"), object: userInfo)
        }else{
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "inspotPushNotification"), object: userInfo)
        }
    }
</code>```

}

the following is sending JASON

```<code>{"aps":{"alert":"Testing.. (40)","badge":1,"sound":"default"}, "openURL":"http://blog.naver.com/ins2020/22056541"}
</code>```

I tried to search this site and follow it, but NOT worked. I appreciate your answer.

答:
Whenever the user taps on the notification. it may be on

UIApplicationStateActive

UIApplicationStateBackground

UIApplicationStateInactive

states properly handle each cases and your problem will get solved.

```<code>    -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{

            if(a
pplication.applicationState == UIApplicationStateActive) {

            //app is currently active

        }else if(application.applicationState == UIApplicationStateBackground){

            //app is in background

        }else if(application.applicationState == UIApplicationStateInactive){

            //app is transitioning from background to foreground (user taps notification), do what you need when user taps here

           // Add your code to navigate to viewcontroller here..

        }
</code>```

Body:
I am coding my company iphone app by IOS, Swift3. The app have 3 webviews. When my App is in Forground and Background, Firebase's notification worked well. When Taping it, I can view URL page at the webview. When it is in inactive (Killed the app), I can receive the notification. but when tapping it, I can NOT view the URL page, only launching the app by default. Plz inform me the smart solution.

This is the part of my AppDelegate.

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    FIRMessaging.messaging().appDidReceiveMessage(userInfo)
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)

    //notification tapping
    let openpUrl = userInfo["openURL"] as? String
    //let openpUrl = userInfo["openURL"] as? String
    if ((openpUrl?.range(of: "blog.naver.com")) != nil) {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "naverblogPushNotification"), object: userInfo)
    }else{
        if ((openpUrl?.range(of: "facebook.com")) != nil) {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "facebookPushNotification"), object: userInfo)
        }else{
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "inspotPushNotification"), object: userInfo)
        }
    }

}

the following is sending JASON

{"aps":{"alert":"Testing.. (40)","badge":1,"sound":"default"}, "openURL":"http://blog.naver.com/ins2020/22056541"}

I tried to search this site and follow it, but NOT worked. I appreciate your answer.

Body:
Whenever the user taps on the notification. it may be on

UIApplicationStateActive

UIApplicationStateBackground

UIApplicationStateInactive

states properly handle each cases and your problem will get solved.

    -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{

            if(a
pplication.applicationState == UIApplicationStateActive) {

            //app is currently active

        }else if(application.applicationState == UIApplicationStateBackground){

            //app is in background

        }else if(application.applicationState == UIApplicationStateInactive){

            //app is transitioning from background to foreground (user taps notification), do what you need when user taps here

           // Add your code to navigate to viewcontroller here..

        }


问:
Fill a ListView from Postgres Database in WPF C#
I'm using WPF C# Visual Studio 2012. I have a Listview in my xaml like:

```<code><ListView
    Name="listview"
    Grid.Column="0"
    Grid.ColumnSpan="2"
    Grid.Row="1"
    Grid.RowSpan="15"
    Margin="5"
    BorderThickness="0"
    Background="WhiteSmoke">
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn
                    Header="column1"
                    DisplayMemberBinding="{Binding path}" />
                <!--other path-->
            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>
</code>```

The code behind to fill this Listview (in xaml.cs):

```<code>NpgsqlConnection connection = new NpgsqlConnection("Server = " + myModule.Server + ";Port = " + myModule.Port + ";User ID = " + myModule.UserID + ";Password = " + myModule.Password + ";Database = " + myModule.Database);
connection.Open();
NpgsqlCommand command = new NpgsqlCommand("select * from tblstudents_secure order by stud_id ASC", connection);

command.Connection = connection;
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(command);

DataSet ds=new DataSet ();
adapter.Fill(ds);
listview.ItemsSource = ds.Tables[0].DefaultView;
</code>```

When I run my program, I know that it fills the listview because I can see it's rows when I hover my mouse on that, but I cannot see any text on those rows!

What did I miss?

答:
Well It's hard to help you with this little information about your entities...
But I would bet the entities in your DB dont have a path property.

This example worked for me:

```<code>   <ListView
            Name="listview"
            Grid.Column="0"
            Grid.ColumnSpan="2"
            Grid.Row="1"
            Grid.RowSpan="15"
            Margin="5"
            BorderThickness="0"
            Background="WhiteSmoke">
        <ListView.View>
            <GridView>
                <GridView.Columns>
                    <GridViewColumn
                            Header="column1"
                            DisplayMemberBinding="{Binding Path}" />
                    <!--other path-->
                </GridView.Columns>
            </GridView>
        </ListView.View>
    </ListView>
</code>```

CodeBehind:

```<code>   public partial class MainWindow : Window
   {
    public MainWindow()
   {
       InitializeComponent();
       var bla = new ObservableCollection<Car>()
       {
          new Car()
       };

       listview.ItemsSource = bla;
   }
 }

 public class Car
 {
   public Car()
  {
     Path = "bla";
  }
   public string Path { get; set; }
 }
</code>```

notice the Property Path on my Car class and the line
DisplayMemberBinding="{Binding Path}" in the view.

regards

Body:
I'm using WPF C# Visual Studio 2012. I have a Listview in my xaml like:

<ListView
    Name="listview"
    Grid.Column="0"
    Grid.ColumnSpan="2"
    Grid.Row="1"
    Grid.RowSpan="15"
    Margin="5"
    BorderThickness="0"
    Background="WhiteSmoke">
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn
                    Header="column1"
                    DisplayMemberBinding="{Binding path}" />

            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>

The code behind to fill this Listview (in xaml.cs):

NpgsqlConnection connection = new NpgsqlConnection("Server = " + myModule.Server + ";Port = " + myModule.Port + ";User ID = " + myModule.UserID + ";Password = " + myModule.Password + ";Database = " + myModule.Database);
connection.Open();
NpgsqlCommand command = new NpgsqlCommand("select * from tblstudents_secure order by stud_id ASC", connection);

command.Connection = connection;
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(command);

DataSet ds=new DataSet ();
adapter.Fill(ds);
listview.ItemsSource = ds.Tables[0].DefaultView;

When I run my program, I know that it fills the listview because I can see it's rows when I hover my mouse on that, but I cannot see any text on those rows!

What did I miss?

Body:
Well It's hard to help you with this little information about your entities...
But I would bet the entities in your DB dont have a path property.

This example worked for me:

   <ListView
            Name="listview"
            Grid.Column="0"
            Grid.ColumnSpan="2"
            Grid.Row="1"
            Grid.RowSpan="15"
            Margin="5"
            BorderThickness="0"
            Background="WhiteSmoke">
        <ListView.View>
            <GridView>
                <GridView.Columns>
                    <GridViewColumn
                            Header="column1"
                            DisplayMemberBinding="{Binding Path}" />
                    <!--other path-->
                </GridView.Columns>
            </GridView>
        </ListView.View>
    </ListView>

CodeBehind:

   public partial class MainWindow : Window
   {
    public MainWindow()
   {
       InitializeComponent();
       var bla = new ObservableCollection<Car>()
       {
          new Car()
       };

       listview.ItemsSource = bla;
   }
 }

 public class Car
 {
   public Car()
  {
     Path = "bla";
  }
   public string Path { get; set; }
 }

notice the Property Path on my Car class and the line
DisplayMemberBinding="{Binding Path}" in the view.

regards


问:
recursive batch-file for movin *.doc, *.pdf, etc
I recovered the files from a HDD with windows 7 installed
now I have a mess in a folder, with thousands and thousands of files and folders, I really don't know much about batch coding but by watching some youtube videos I could get to the next below, but that batch-file only looks for files in the current folder where I execute the batch, I want it to look in the folders inside that folder and so..
Sorry for my bad English</p>

```<code>@echo off

move /y "*.xml" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\xml"

move /y "*.pdf" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\documentos"

move /y "*.cat" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\cat"

move /y "*.dll" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\dll"
</code>```

答:
Look at this:

```<code>@echo off
for /R %temp% %%f in (*.*) do (
echo %%f )
</code>```

There you can see a for-loop with the parameter "/R". "/R" makes the loop recursive to look also into the subfolders.

Body:
I recovered the files from a HDD with windows 7 installed
now I have a mess in a folder, with thousands and thousands of files and folders, I really don't know much about batch coding but by watching some youtube videos I could get to the next below, but that batch-file only looks for files in the current folder where I execute the batch, I want it to look in the folders inside that folder and so..
Sorry for my bad English

@echo off

move /y "*.xml" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\xml"

move /y "*.pdf" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\documentos"

move /y "*.cat" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\cat"

move /y "*.dll" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\dll"

Body:
Look at this:

@echo off
for /R %temp% %%f in (*.*) do (
echo %%f )

There you can see a for-loop with the parameter "/R". "/R" makes the loop recursive to look also into the subfolders.


问:
How to correctly reload .vimrc file so it will be equal to restart of vim?
I use MacVim and in my .vimrc file I have map ,V :source $MYVIMRC<CR> binding that allows me to apply the newest version of .vimrc in a case it was recently modified.
However I noticed that strange things can happen, relaunch can slow down vim and some plugins can start to conflict after pressing ,V, when everything works fine if I just close and relaunch MacVim from the scratch.

I'd be very thankful if you could give me a hint on the reason of this behavior as I'd like to have a possibility to update .vimrc file that will completely clear internal vim state and grab new configuration file

答:
The only viable way to re-apply your config to a pristine Vim is actually to restart it.

But the most likely cause of slow downs is the overuse/misuse of autocommands.

Autocommands are added without checking for existing ones. One consequence is that they tend to pile-up if you don't manage them properly and every individual autocommand corresponding to a specific event is executed when that event is triggered, leading to dreadful slow downs.

Here are the two ways you are supposed to use autocommands in your vimrc:

Method #1

```<code>" anywhere
augroup nameofthegroup
    autocmd!
    autocmd EventName pattern commandtoexecute
    autocmd AnotherEventName anotherpattern anothercommandtoexecute
augroup END
</code>```

Method #2

```<code>" near the top of your vimrc
augroup nameofthegroup
    autocmd!
augroup END

" anywhere
autocmd nameofthegroup EventName pattern commandtoexecute
autocmd nameofthegroup AnotherEventName anotherpattern anothercommandtoexecute
</code>```

The idea is to create a group of autocommands that clears itself whenever it is invoked and thus prevents them from piling-up.

Body:
The only viable way to re-apply your config to a pristine Vim is actually to restart it.

But the most likely cause of slow downs is the overuse/misuse of autocommands.

Autocommands are added without checking for existing ones. One consequence is that they tend to pile-up if you don't manage them properly and every individual autocommand corresponding to a specific event is executed when that event is triggered, leading to dreadful slow downs.

Here are the two ways you are supposed to use autocommands in your vimrc:

Method #1

" anywhere
augroup nameofthegroup
    autocmd!
    autocmd EventName pattern commandtoexecute
    autocmd AnotherEventName anotherpattern anothercommandtoexecute
augroup END

Method #2

" near the top of your vimrc
augroup nameofthegroup
    autocmd!
augroup END

" anywhere
autocmd nameofthegroup EventName pattern commandtoexecute
autocmd nameofthegroup AnotherEventName anotherpattern anothercommandtoexecute

The idea is to create a group of autocommands that clears itself whenever it is invoked and thus prevents them from piling-up.


问:
systemverilog return dynamic array from function
I am trying to return dynamic array from function,
i did dome job but i dont know how to do that fully dynamic,
which mean without declare the "data_len"
thanks for helping,</p>

```<code>module test1();

typedef integer dyn_arr[];

function dyn_arr get_register_name();
    int data_len = 3;
    get_register_name = new [data_len] ;
    get_register_name[0] = 5;
    get_register_name[1] = 2;

endfunction

 dyn_arr my_q;

  initial begin
       my_q = get_register_name();
      $display("%d",my_q[1]);
      $display("%d",my_q[0]);
  end

endmodule
</code>```

答:
You can pass the dynamic array by reference in the function for your purpose.

Here is the sample code for it.

```<code>module tp();
  integer a[];

  initial
  begin
    return_x(a);
    $display("a - %p", a);
  end
endmodule

function automatic void return_x(ref integer x[]);
  x = new [3];
  x = '{3,3,3};
endfunction

// Output -
// a - '{3, 3, 3}
</code>```

Body:
I am trying to return dynamic array from function,
i did dome job but i dont know how to do that fully dynamic,
which mean without declare the "data_len"
thanks for helping,

module test1();

typedef integer dyn_arr[];

function dyn_arr get_register_name();
    int data_len = 3;
    get_register_name = new [data_len] ;
    get_register_name[0] = 5;
    get_register_name[1] = 2;

endfunction

 dyn_arr my_q;

  initial begin
       my_q = get_register_name();
      $display("%d",my_q[1]);
      $display("%d",my_q[0]);
  end

endmodule

Body:
You can pass the dynamic array by reference in the function for your purpose.

Here is the sample code for it.

module tp();
  integer a[];

  initial
  begin
    return_x(a);
    $display("a - %p", a);
  end
endmodule

function automatic void return_x(ref integer x[]);
  x = new [3];
  x = '{3,3,3};
endfunction

// Output -
// a - '{3, 3, 3}


问:
Assign multiple private IPs to a VM in Azure
I have 2 Virtual Networks and each of them has a subnet. I want to assign 2 private IP's to a virtual machine. One private IP resides in 1st Virtual Network while second private IP is in 2nd Virtual Network.

I have tried attaching 2 NIC's to the VM, and attached the first private IP to first NIC and second private IP to second NIC.

When I deploy the ARM template it says that second NIC is referring to a subnet which is not in same Virtual Network?

How can I achieve this in Azure?

答:
How can I achieve this in Azure ?

As far as I know, Azure does not support this.

For now, Azure just support multiple NICs on the same virtual network.

Q:Are there any limitations to this feature that customers must be aware
  of?

  A:Multiple NIC is supported on Azure VMs (IaaS, Standard SKUs) only;
  and VMs must be in an Azure Virtual Network.

More information about multiple NICs, please refer to this link.


问:
Redirect user to page with specific URL based on his/her username
I want to redirect a page to another page based on user's username. For Example, If I have a page with URL something like "sitename/store" and when user open that page, it should redirect to page with URL like "sitename/store/username". In this scenario, username is variable. Is there any code which is available in functions.php? or is there any way to achieve this.

Thanks

答:
You can try this:</p>

```<code> <?php
  header("Location: sitename/store/". $usernameVariable);
  ?>
</code>```

Body:
You can try this:

 <?php
  header("Location: sitename/store/". $usernameVariable);
  ?>


问:
How to provide parameter to url containing colon
I am using retrofit2 to make some REST api calls in my app. However, there are some api's which have endpoints like /profile/:id i.e. they contain colons in the endpoint. I need to provide :id at runtime to make api call. This seems similar to url's which contain paths for e.g. /profile/{id}, for which documentation is present at official page of Retrofit. However, I cannot find anything for url's containing colon. So, is there anyway I can do this in retrofit?

答:
If you come here because your url parameter contains ":" or "("

in itself like "skills:(android-app-development)":

https://www.upwork.com/ab/feed/jobs/atom?&q=skills:(android-app-development)&sequrityToken="blablabla"

Try using dynamic links in retrofit:

Since normal request string with params like:

```<code>@Query("&q") String q4,
@Query("&securityToken") String q5,
</code>```

is broken by this ":" or "(".

Body:
If you come here because your url parameter contains ":" or "("

in itself like "skills:(android-app-development)":

https://www.upwork.com/ab/feed/jobs/atom?&q=skills:(android-app-development)&sequrityToken="blablabla"

Try using dynamic links in retrofit:

Since normal request string with params like:

@Query("&q") String q4,
@Query("&securityToken") String q5,

is broken by this ":" or "(".


问:
Simplest way to read JSON from a URL in Java
This might be a dumb question but what is the simplest way to read and parse JSON from URL in Java?

In Groovy, it's a matter of few lines of code. Java examples that I find are ridiculously long (and have huge exception handling block).

All I want to do is to read the content of this link.

答:
Use HttpClient to grab the contents of the URL.  And then use the library from json.org to parse the JSON.  I've used these two libraries on many projects and they have been robust and simple to use.

Other than that you can try using a Facebook API java library.  I don't have any experience in this area, but there is a question on stack overflow related to using a Facebook API in java. You may want to look at RestFB as a good choice for a library to use.


问:
Firebase load data dynamically on scrolling
I need know how to load data dynamically on scrolling with Firebase. If I query data with Firebase, all data must be loaded once time or always data changed. I want load data with Firebase per limit, and after reach this limit, load more data and more and more.

It would basically be like a timeline of Facebook - as a social network.

For example: I want to get the latest records from Firebase at limit 50. After reach this limit, I will download the next 50 data. I would like use RecyclerView and not FirebaseRecycler class.

FirebaseRecyclerAdapter not solve my question. Thanks for help. Trully, i need loadind data like facebook timeline of point view layout, and load data Firebase (50 to 50. Download 50 data, reach limit, load more data of bottom layout to 50) of point view Database.

Could you help me?

答:
This works perfectly fine.
  Infinite-Scroll-Endless-Scrolling-Tutorial</p>

```<code>    private RecyclerView recyclerView;
    boolean userScrolled=false;

    private boolean loading = true;
    int pastVisiblesItems, visibleItemCount, totalItemCount;

    LinearLayoutManager mLayoutManager;

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        mLayoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

// Implement scroll listener
public void implementScrollListener() {

    recyclerView
        .addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView,
                                             int newState) {

                super.onScrollStateChanged(recyclerView, newState);

                // If scroll state is touch scroll then set userScrolled
                // true
                if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                    userScrolled = true;

                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx,
                                   int dy) {
                super.onScrolled(recyclerView, dx, dy);

                // Here get the child count, item count and visibleitems
                // from layout manager

                visibleItemCount = mLayoutManager.getChildCount();
                totalItemCount = mLayoutManager.getItemCount();
                pastVisiblesItems = mLayoutManager
                        .findFirstVisibleItemPosition();

                // Now check if userScrolled is true and also check if
                // the item is end then update recycler view and set
                // userScrolled to false
                if (userScrolled
                        && (visibleItemCount + pastVisiblesItems) == totalItemCount) {
                    userScrolled = false;

                    RefreshData(oldestPostId);
                }
            }
        });
}
</code>```

Body:
This works perfectly fine.
  Infinite-Scroll-Endless-Scrolling-Tutorial

    private RecyclerView recyclerView;
    boolean userScrolled=false;

    private boolean loading = true;
    int pastVisiblesItems, visibleItemCount, totalItemCount;

    LinearLayoutManager mLayoutManager;

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        mLayoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

// Implement scroll listener
public void implementScrollListener() {

    recyclerView
        .addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView,
                                             int newState) {

                super.onScrollStateChanged(recyclerView, newState);

                // If scroll state is touch scroll then set userScrolled
                // true
                if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                    userScrolled = true;

                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx,
                                   int dy) {
                super.onScrolled(recyclerView, dx, dy);

                // Here get the child count, item count and visibleitems
                // from layout manager

                visibleItemCount = mLayoutManager.getChildCount();
                totalItemCount = mLayoutManager.getItemCount();
                pastVisiblesItems = mLayoutManager
                        .findFirstVisibleItemPosition();

                // Now check if userScrolled is true and also check if
                // the item is end then update recycler view and set
                // userScrolled to false
                if (userScrolled
                        && (visibleItemCount + pastVisiblesItems) == totalItemCount) {
                    userScrolled = false;

                    RefreshData(oldestPostId);
                }
            }
        });
}


问:
"pip install unroll": "python setup.py egg_info" failed with error code 1
I'm trying to install some packages with pip.

But pip install unroll gives me

Command "python setup.py egg_info" failed with error code 1 in
C:\Users\MARKAN~1\AppData\Local\Temp\pip-build-wa7uco0k\unroll\

How can I solve this?

答:
That means some packages in pip are old or not correctly installed.

Try checking version and then upgrading pip.Use auto remove if that works.

If the pip command shows an error all the time for any command or it freezes, etc.

The best solution is to uninstall it or remove it completely.

Install a fresh pip and then update and upgrade your system.

I have given a solution to installing pip fresh here - python: can't open file get-pip.py error 2] no such file or directory


问:
Qml listView mirroring layout current Index
I am working with ListView component and I have trouble with currentIndex property. I want to do some action on

```<code>onCurrentIndexChanged:
</code>```

But when I use

```<code>LayoutMirroring.enabled: true
</code>```

currentIndex is not updated anymore. There is no action in onCurrentIndexChanged and currentIndex is equal to 0 all the time.
I've also tried to use

layoutDirection: Qt.RightToLeft
but problem is the same ( no currentIndex updates when listView is moved).

I've read ListView documentation and there was information, that if you use

```<code>snapMode: ListView.SnapToItem
</code>```

you also need to add

```<code>highlightRangeMode:  ListView.StrictlyEnforceRange
</code>```

in order to currentIndex is update properly. Maybe there is something similar for mirror layout?

Here is the whole code:

```<code>ListView
    {
        id: id_couplingControlView

        model: id_multiCouplingMeasurePopup.p_iCouplingsCount
        orientation: ListView.Horizontal
        snapMode: ListView.SnapToItem
        highlightRangeMode:  ListView.StrictlyEnforceRange          //To update the currentIndex as the list is moved
        preferredHighlightBegin: id_multiCouplingMeasurePopup.p_bViewRotated ? id_couplingControlView.width : id_couplingControlView.leftMargin
        LayoutMirroring.enabled:  id_multiCouplingMeasurePopup.p_bViewRotated
        //layoutDirection: id_multiCouplingMeasurePopup.p_bViewRotated ? Qt.RightToLeft : Qt.LeftToRight

        delegate: QmlSHMultiCouplingMeasureControl
        {
            id: id_CouplingMeasureControl

            p_iIndex: index
            Component.onCompleted:
            {
                InitializeCouplingControl ( id_CouplingMeasureControl )
            }
        }

        //Need to to something here
        onCurrentIndexChanged:
        {
            console.log ( "onCurrentIndexChanged:: " + id_couplingControlView.currentIndex )
            id_multiCouplingMeasurePopup.UpdateMiniTrainCouplingList( id_couplingControlView.currentIndex );
        }
    }
</code>```

So my question is: what I need to do to have currentIndex updated while scrolling listView when using LayoutMirroring.enabled: true or layoutDirection: Qt.RightToLeft.

答:
Ok I got the solution!

The problem was beacuse of this line:

```<code>preferredHighlightBegin: id_multiCouplingMeasurePopup.p_bViewRotated ? id_couplingControlView.width : id_couplingControlView.leftMargin
</code>```

For rotated view I was setting preferredHighlightBegin as wide as width of listView itself. That's why currentIndex was not updated. Mirroring the listView had nothing to do about it.

Body:
I am working with ListView component and I have trouble with currentIndex property. I want to do some action on

onCurrentIndexChanged:

But when I use

LayoutMirroring.enabled: true

currentIndex is not updated anymore. There is no action in onCurrentIndexChanged and currentIndex is equal to 0 all the time.
I've also tried to use

layoutDirection: Qt.RightToLeft
but problem is the same ( no currentIndex updates when listView is moved).

I've read ListView documentation and there was information, that if you use

snapMode: ListView.SnapToItem

you also need to add

highlightRangeMode:  ListView.StrictlyEnforceRange

in order to currentIndex is update properly. Maybe there is something similar for mirror layout?

Here is the whole code:

ListView
    {
        id: id_couplingControlView

        model: id_multiCouplingMeasurePopup.p_iCouplingsCount
        orientation: ListView.Horizontal
        snapMode: ListView.SnapToItem
        highlightRangeMode:  ListView.StrictlyEnforceRange          //To update the currentIndex as the list is moved
        preferredHighlightBegin: id_multiCouplingMeasurePopup.p_bViewRotated ? id_couplingControlView.width : id_couplingControlView.leftMargin
        LayoutMirroring.enabled:  id_multiCouplingMeasurePopup.p_bViewRotated
        //layoutDirection: id_multiCouplingMeasurePopup.p_bViewRotated ? Qt.RightToLeft : Qt.LeftToRight

        delegate: QmlSHMultiCouplingMeasureControl
        {
            id: id_CouplingMeasureControl

            p_iIndex: index
            Component.onCompleted:
            {
                InitializeCouplingControl ( id_CouplingMeasureControl )
            }
        }

        //Need to to something here
        onCurrentIndexChanged:
        {
            console.log ( "onCurrentIndexChanged:: " + id_couplingControlView.currentIndex )
            id_multiCouplingMeasurePopup.UpdateMiniTrainCouplingList( id_couplingControlView.currentIndex );
        }
    }

So my question is: what I need to do to have currentIndex updated while scrolling listView when using LayoutMirroring.enabled: true or layoutDirection: Qt.RightToLeft.

Body:
Ok I got the solution!

The problem was beacuse of this line:

preferredHighlightBegin: id_multiCouplingMeasurePopup.p_bViewRotated ? id_couplingControlView.width : id_couplingControlView.leftMargin

For rotated view I was setting preferredHighlightBegin as wide as width of listView itself. That's why currentIndex was not updated. Mirroring the listView had nothing to do about it.


问:
How to get a list of AppV virtual processes using C#
I am trying to get a list of all Virtual Processes started by Microsoft AppV using C#.

I tried using Powershell in C# but I get this error:

System.Management.Automation.CommandNotFoundException: 'The 'Get-AppvVirtualProcess' command was found in the module 'AppvClient', but the module could not be loaded. For more information, run 'Import-Module AppvClient'.'

The weird thing is that if I use the Powershell command line, it works just fine and lists the virtual processes.

So in C# I did a:

```<code>ps.Commands.AddCommand("Get-Command");
</code>```

and it shows Get-AppvVirtualProcess listed as a command:

The result:

Function Get-AppvVirtualProcess 1.0.0.0 A

I tried loading the module in C# manually using:

```<code>InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] {@"C:\Program Files\Microsoft Application Virtualization\Client\AppvClient\AppvClient.psd1" });
</code>```

and

```<code>ps.Commands.AddCommand("Import-Module").AddArgument("AppvClient");
</code>```

But it still gives me the same error mentioned above.

The code in C# looks like this:

```<code>public static void powershellCommand()
{
    Collection<PSObject> result;

    using (Runspace myRunSpace = RunspaceFactory.CreateRunspace())
    {
        InitialSessionState initial = InitialSessionState.CreateDefault();
        initial.ImportPSModule(new string[] {@"C:\Program Files\Microsoft Application Virtualization\Client\AppvClient\AppvClient.psd1" });
        Runspace runspace = RunspaceFactory.CreateRunspace(initial);
        runspace.Open();
        PowerShell ps = PowerShell.Create();
        ps.Runspace = runspace;
        ps.Commands.AddCommand("Import-Module").AddArgument("AppvClient");

        ps.Commands.AddCommand("Get-AppvVirtualProcess");

        result = ps.Invoke();
            var builder = new StringBuilder();
            foreach (PSObject psObject in result)
            {

                builder.Append(psObject.ToString() + "\n");
                builder.ToString();

            }

            Console.WriteLine("Virtual Process: {0}", builder.ToString());
        }

}
</code>```

Instead of Runspace, I tried this as well but I get the same error:

```<code>public static void p()
{
    using (var powershell = PowerShell.Create())
    {
        powershell.AddCommand("Get-AppvVirtualProcess");

        powershell.Invoke();
    }
}
</code>```

答:
You could try to iterate through all the running process, and find those that loaded either AppVEntSubsystems32.dll or AppVEntSubsystems64.dll.

You can read more about this here: https://blogs.msdn.microsoft.com/gladiator/2014/09/04/app-v-5-on-application-launch/

Body:
I am trying to get a list of all Virtual Processes started by Microsoft AppV using C#.

I tried using Powershell in C# but I get this error:

System.Management.Automation.CommandNotFoundException: 'The 'Get-AppvVirtualProcess' command was found in the module 'AppvClient', but the module could not be loaded. For more information, run 'Import-Module AppvClient'.'

The weird thing is that if I use the Powershell command line, it works just fine and lists the virtual processes.

So in C# I did a:

ps.Commands.AddCommand("Get-Command");

and it shows Get-AppvVirtualProcess listed as a command:

The result:

Function Get-AppvVirtualProcess 1.0.0.0 A

I tried loading the module in C# manually using:

InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] {@"C:\Program Files\Microsoft Application Virtualization\Client\AppvClient\AppvClient.psd1" });

and

ps.Commands.AddCommand("Import-Module").AddArgument("AppvClient");

But it still gives me the same error mentioned above.

The code in C# looks like this:

public static void powershellCommand()
{
    Collection<PSObject> result;

    using (Runspace myRunSpace = RunspaceFactory.CreateRunspace())
    {
        InitialSessionState initial = InitialSessionState.CreateDefault();
        initial.ImportPSModule(new string[] {@"C:\Program Files\Microsoft Application Virtualization\Client\AppvClient\AppvClient.psd1" });
        Runspace runspace = RunspaceFactory.CreateRunspace(initial);
        runspace.Open();
        PowerShell ps = PowerShell.Create();
        ps.Runspace = runspace;
        ps.Commands.AddCommand("Import-Module").AddArgument("AppvClient");

        ps.Commands.AddCommand("Get-AppvVirtualProcess");

        result = ps.Invoke();
            var builder = new StringBuilder();
            foreach (PSObject psObject in result)
            {

                builder.Append(psObject.ToString() + "\n");
                builder.ToString();

            }

            Console.WriteLine("Virtual Process: {0}", builder.ToString());
        }

}

Instead of Runspace, I tried this as well but I get the same error:

public static void p()
{
    using (var powershell = PowerShell.Create())
    {
        powershell.AddCommand("Get-AppvVirtualProcess");

        powershell.Invoke();
    }
}


问:
Cannot pass immutable value of type 'UnsafeRawPointer?' as inout argument
```<code>var keyCallbacks = kCFTypeDictionaryKeyCallBacks
var valueCallbacks = kCFTypeDictionaryValueCallBacks

var keys = [Unmanaged.passUnretained(kSecClass).toOpaque(), Unmanaged.passUnretained(kSecAttrApplicationTag).toOpaque(), Unmanaged.passUnretained(kSecAttrKeyType).toOpaque(), Unmanaged.passUnretained(kSecReturnRef).toOpaque()]
var values = [Unmanaged.passUnretained(kSecClassKey).toOpaque(), Unmanaged<AnyObject>.passUnretained(privateTag as AnyObject).toOpaque(), Unmanaged.passUnretained(kSecAttrKeyTypeRSA).toOpaque(), Unmanaged.passUnretained(kCFBooleanTrue).toOpaque()]

// let queryKey = CFDictionaryCreate(kCFAllocatorDefault, &keys, &values, 4, &keyCallbacks, &valueCallbacks)//Error-- for "keys" this error show cannot pass immutable value of type 'UnsafeRawPointer?' as inout argument.
let queryKey = CFDictionaryCreate(kCFAllocatorDefault, &keys, &values, 4, &keyCallbacks, &valueCallbacks)

// Get the key.
var extractedItem: AnyObject?
let resultCode = SecItemCopyMatching(queryKey, &extractedItem)//cannot pass immutable value of type 'UnsafeRawPointer?' as inout argument

guard let keyItem = extractedItem, resultCode == noErr else {

return nil
</code>```

答:
Don't use CFDictionary in Swift. It is not impossible, but not
worth the hassle. CFDictionary is toll-free bridged to NSDictionary
which in turn can be instantiated from a Swift Dictionary:

```<code>let query: NSDictionary = [
    kSecClass: kSecClassKey,
    kSecAttrApplicationTag: privateTag,
    kSecAttrKeyType: kSecAttrKeyTypeRSA,
    kSecReturnRef: true
]
var extractedItem: AnyObject?
let resultCode = SecItemCopyMatching(query, &extractedItem)
</code>```

Body:
Don't use CFDictionary in Swift. It is not impossible, but not
worth the hassle. CFDictionary is toll-free bridged to NSDictionary
which in turn can be instantiated from a Swift Dictionary:

let query: NSDictionary = [
    kSecClass: kSecClassKey,
    kSecAttrApplicationTag: privateTag,
    kSecAttrKeyType: kSecAttrKeyTypeRSA,
    kSecReturnRef: true
]
var extractedItem: AnyObject?
let resultCode = SecItemCopyMatching(query, &extractedItem)


问:
android button drawableleft icon inside triangle shape
I have drawn a triangle on button left side using drawableleft (@drawable/triangle.xml). I need to place an icon inside that triangle. But the code below it shows left to drawn triangle. Thanks in advance

triangle.xml

```<code>    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <rotate
            android:fromDegrees="45"
            android:pivotX="13%"
            android:pivotY="-38%"
            android:toDegrees="45" >
            <shape
                android:shape="rectangle" >
                <size android:width="135dp" android:height="135dp" />
                <solid android:color="@color/yellow" />
            </shape>
        </rotate>
    </item>
     <item android:drawable="@mipmap/app_icon"
        android:width="40dp"
        android:height="40dp" />
</layer-list>
</code>```

Button in layout:

```<code><Button
    android:id="@+id/sample_button"
    android:layout_width="0px"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:height="100dp"
    android:background="@color/grey"
    android:drawableLeft="@drawable/triangle"
    android:gravity="center|left"
    android:text="@string/sample"
    android:textColor="@android:color/white" />
</code>```

答:
Try by adding the drawable as background.</p>

```<code>    android:background="@drawable/triangle"
</code>```

Body:
I have drawn a triangle on button left side using drawableleft (@drawable/triangle.xml). I need to place an icon inside that triangle. But the code below it shows left to drawn triangle. Thanks in advance

triangle.xml

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <rotate
            android:fromDegrees="45"
            android:pivotX="13%"
            android:pivotY="-38%"
            android:toDegrees="45" >
            <shape
                android:shape="rectangle" >
                <size android:width="135dp" android:height="135dp" />
                <solid android:color="@color/yellow" />
            </shape>
        </rotate>
    </item>
     <item android:drawable="@mipmap/app_icon"
        android:width="40dp"
        android:height="40dp" />
</layer-list>

Button in layout:

<Button
    android:id="@+id/sample_button"
    android:layout_width="0px"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:height="100dp"
    android:background="@color/grey"
    android:drawableLeft="@drawable/triangle"
    android:gravity="center|left"
    android:text="@string/sample"
    android:textColor="@android:color/white" />

Body:
Try by adding the drawable as background.

    android:background="@drawable/triangle"


问:
Spacy import errors out Undefined Symbol
I've already asked to the developers on their GitHub issues page, but nothing is helping so far
https://github.com/explosion/spaCy/issues/855

Created a new env with conda

conda create -n spacy python=3.5 ipython

and then install spacy (1.6.0) with pip (conda still has version 0.101.0)

pip install spacy

But I still get this error.

```<code>In [1]: import spacy
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-c080f6458562> in <module>()
 ----> 1 import spacy

 /home/alexis/anaconda3/envs/spacy/lib/python3.5/site- packages/spacy/__init__.py in <module>()
      4 from .about import __version__
      5
----> 6 from . import en
      7 from . import de
      8 from . import zh

/home/alexis/anaconda3/envs/spacy/lib/python3.5/site-packages/spacy/en/__init__.py in <module>()
      6 from ..util import match_best_version
      7 from ..util import get_data_path
----> 8 from ..language import Language
      9 from ..lemmatizer import Lemmatizer
     10 from ..vocab import Vocab

/home/alexis/anaconda3/envs/spacy/lib/python3.5/site-packages/spacy/language.py in <module>()
     15
     16
---> 17 from .tokenizer import Tokenizer
     18 from .vocab import Vocab
     19 from .tagger import Tagger

ImportError: /home/alexis/anaconda3/envs/spacy/lib/python3.5/site-packages/spacy/tokenizer.cpython-35m-x86_64-linux-gnu.so: undefined symbol: _ZTINSt8ios_base7failureB5cxx11E
</code>```

I did source the new conda environment and pip is the one from that new env. I'm running out of options here.

There is a similar issue here explosion/sense2vec#19 but that solution did not help.

Operating System: Ubuntu 16.04.1 LTS

Note, I don't have that problem on MacOS Sierra.

Update

I've exported my conda environment from MacOS (where it's working) and created a new one on the machine where it doesn't work. Same stack trace.

答: I saw on a sense2vec issues page https://github.com/explosion/sense2vec/issues/19 to do conda install libgcc and it worked for me.

Body:
I've already asked to the developers on their GitHub issues page, but nothing is helping so far
https://github.com/explosion/spaCy/issues/855

Created a new env with conda

conda create -n spacy python=3.5 ipython

and then install spacy (1.6.0) with pip (conda still has version 0.101.0)

pip install spacy

But I still get this error.

In [1]: import spacy
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-c080f6458562> in <module>()
 ----> 1 import spacy

 /home/alexis/anaconda3/envs/spacy/lib/python3.5/site- packages/spacy/__init__.py in <module>()
      4 from .about import __version__
      5
----> 6 from . import en
      7 from . import de
      8 from . import zh

/home/alexis/anaconda3/envs/spacy/lib/python3.5/site-packages/spacy/en/__init__.py in <module>()
      6 from ..util import match_best_version
      7 from ..util import get_data_path
----> 8 from ..language import Language
      9 from ..lemmatizer import Lemmatizer
     10 from ..vocab import Vocab

/home/alexis/anaconda3/envs/spacy/lib/python3.5/site-packages/spacy/language.py in <module>()
     15
     16
---> 17 from .tokenizer import Tokenizer
     18 from .vocab import Vocab
     19 from .tagger import Tagger

ImportError: /home/alexis/anaconda3/envs/spacy/lib/python3.5/site-packages/spacy/tokenizer.cpython-35m-x86_64-linux-gnu.so: undefined symbol: _ZTINSt8ios_base7failureB5cxx11E

I did source the new conda environment and pip is the one from that new env. I'm running out of options here.

There is a similar issue here explosion/sense2vec#19 but that solution did not help.

Operating System: Ubuntu 16.04.1 LTS

Note, I don't have that problem on MacOS Sierra.

Update

I've exported my conda environment from MacOS (where it's working) and created a new one on the machine where it doesn't work. Same stack trace.


问:
How did C look like before I was born?
Here is the question, How did C (K&R C) look like? The question is about the first ten or twenty years of C's life?

I know, well I heard them from a prof in my uni, that C didn't have the standard libraries that we get with ANSI C today. They used to write IO routines in wrapped assembly! The second thing is that K&R book, is one the best books ever for a programmer to read, This is what my prof told us :)

I would like to know more about good ol' C. For example, what major difference you know about it compared to ANSI C, or how did C change programmers mind about programming?

Just for record, I am asking this question after reading mainly these two papers:

Evolving a language in and for the   real world: C++ 1991-2006

A History of C++: 1979-1991

They are about C++, I know! thats why I wanna know more about C, because these two papers are about how C++ was born out of C. I am now asking about how it looked before that. Thanks Lazarus for pointing out to 1st edition of K&R, but I am still keen to know more about C from SO gurus ;)

答: 16 bit integers were quite common in the ol' days.</p>

Title: How did C look like before I was born?


问:
Hazelcast exception with hazelcast-hibernate5
I am using Hibernate OGM 5.1.0.Final and hazelcast-hibernate5 1.1.3 ( even checked with 1.2 ). The OGM compatible hibernate ORM dependency is 5.1.5 , which is present in POM.

```<code>Caused by: java.lang.IncompatibleClassChangeError: Expected static method org.hibernate.cache.internal.DefaultCacheKeysFactory.createEntityKey(Ljava/lang/Object;Lorg/hibernate/persister/entity/EntityPersister;Lorg/hibernate/engine/spi/SessionFactoryIm
    at com.hazelcast.hibernate.region.EntityRegionAccessStrategyAdapter.generateCacheKey(EntityRegionAccessStrategyAdapter.java:66)
    at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:198)
    at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:125)
    at org.hibernate.ogm.loader.impl.OgmLoader.initializeEntitiesAndCollections(OgmLoader.java:807)
    at org.hibernate.ogm.loader.impl.OgmLoader.doQuery(OgmLoader.java:393)
    at org.hibernate.ogm.loader.impl.OgmLoader.doQueryAndInitializeNonLazyCollections(OgmLoader.java:283)
    at org.hibernate.ogm.loader.impl.OgmLoader.loadEntity(OgmLoader.java:201)
    at org.hibernate.ogm.loader.impl.OgmLoader.loadEntitiesFromTuples(OgmLoader.java:220)
    at org.hibernate.ogm.loader.entity.impl.DynamicBatchingEntityLoaderBuilder$DynamicBatchingEntityLoader.loadEntitiesFromTuples(DynamicBatchingEntityLoaderBuilder.java:127)
    at org.hibernate.ogm.query.impl.OgmQueryLoader.listOfEntities(OgmQueryLoader.java:92)
    at org.hibernate.ogm.query.impl.OgmQueryLoader.list(OgmQueryLoader.java:78)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
    at org.hibernate.ogm.query.impl.OgmQueryTranslator.list(OgmQueryTranslator.java:129)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1339)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)
    at com.olp.jpa.common.AbstractRepositoryImpl.findAll(AbstractRepositoryImpl.java:137)
</code>```

The issue looked similar to the one reported here - https://github.com/hazelcast/hazelcast-hibernate5/issues/13 , however I cannot upgrade ORM to 5.2, since it is not supported by OGM yet. Please suggest if there is a solution/workaround for the issue.

答:
Version 1.1.3 and 1.2 of hazelcast-hibernate5 depend on Hibernate version 5.0.9.Final. You might need to exclude that in your Maven configuration and declare Hibernate dependency with version 5.1.5 yourself.

Update

It seems hazelcast-hibernate5 doesn't support Hibernate 5.1.5. So I have modified hazelcast-hibernate5 code to support Hibernate 5.1.5 and released a custom version which can be found here. Note that this is not available on Maven central and it's not an official release of the plugin, just a quick change to support Hibernate 5.1.5 for your use case. It means that you have to install it to your local Maven repository first (or embed the JAR directly to your project). You can see the changes I have made in this branch to examine the code, or build from the source yourself.

Body:
I am using Hibernate OGM 5.1.0.Final and hazelcast-hibernate5 1.1.3 ( even checked with 1.2 ). The OGM compatible hibernate ORM dependency is 5.1.5 , which is present in POM.

Caused by: java.lang.IncompatibleClassChangeError: Expected static method org.hibernate.cache.internal.DefaultCacheKeysFactory.createEntityKey(Ljava/lang/Object;Lorg/hibernate/persister/entity/EntityPersister;Lorg/hibernate/engine/spi/SessionFactoryIm
    at com.hazelcast.hibernate.region.EntityRegionAccessStrategyAdapter.generateCacheKey(EntityRegionAccessStrategyAdapter.java:66)
    at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:198)
    at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:125)
    at org.hibernate.ogm.loader.impl.OgmLoader.initializeEntitiesAndCollections(OgmLoader.java:807)
    at org.hibernate.ogm.loader.impl.OgmLoader.doQuery(OgmLoader.java:393)
    at org.hibernate.ogm.loader.impl.OgmLoader.doQueryAndInitializeNonLazyCollections(OgmLoader.java:283)
    at org.hibernate.ogm.loader.impl.OgmLoader.loadEntity(OgmLoader.java:201)
    at org.hibernate.ogm.loader.impl.OgmLoader.loadEntitiesFromTuples(OgmLoader.java:220)
    at org.hibernate.ogm.loader.entity.impl.DynamicBatchingEntityLoaderBuilder$DynamicBatchingEntityLoader.loadEntitiesFromTuples(DynamicBatchingEntityLoaderBuilder.java:127)
    at org.hibernate.ogm.query.impl.OgmQueryLoader.listOfEntities(OgmQueryLoader.java:92)
    at org.hibernate.ogm.query.impl.OgmQueryLoader.list(OgmQueryLoader.java:78)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
    at org.hibernate.ogm.query.impl.OgmQueryTranslator.list(OgmQueryTranslator.java:129)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1339)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)
    at com.olp.jpa.common.AbstractRepositoryImpl.findAll(AbstractRepositoryImpl.java:137)

The issue looked similar to the one reported here - https://github.com/hazelcast/hazelcast-hibernate5/issues/13 , however I cannot upgrade ORM to 5.2, since it is not supported by OGM yet. Please suggest if there is a solution/workaround for the issue.


问:
Find row-wise duplicates by groups
I have a data-set that may have duplicate products. If there are duplicate products, we would mark that order as "Y", and vice versa.

Here are my data:

```<code>dput(Test_File)
structure(list(Order = c(1234, 1234, 2345, 2345, 2345, 3456,
3456, 4567, 5678, 5678, 5678, 5678, 9999, 9999), Product = c("A12960",
"12960", "B3560", "3560", "A3850", "3850", "A3850", "A2920",
"2930", "2921", "A2921", "A2930", "A1234", "2345"), ASKU = c("Y",
"N", "N", "N", "Y", "N", "Y", "Y", "N", "N", "Y", "Y", "Y", "N"
)), .Names = c("Order", "Product", "ASKU"), row.names = c(NA,
14L), class = "data.frame")
</code>```

Commentary about the data: I have a column that says ASKU. This is mainly to identify whether a particular SKU starts with A. Also, please note that A1234 and 1234 would be considered duplicate. A1234 and 23456 wouldn't be considered duplicate. Similarly, B1234 and 1234 won't be considered duplicates. So, to identify duplicates, one would ignore A in ASKU column.

Expected Output:

```<code>dput(Output_File)
structure(list(Order = c(1234, 2345, 3456, 4567, 5678, 9999),
    Duplicate = c("Y", "N", "Y", "N", "Y", "N")), .Names = c("Order",
"Duplicate"), row.names = c(NA, 6L), class = "data.frame")
</code>```

My code (non-working):

I tried this code, but I am getting an error. The idea is to do row-wise comparison of SKUs after extracting string from SKU name.

Error: Duplicate identifiers for rows (3, 4), (8, 9), (10, 11)

```<code>Test_File$New_SKU<-NA_character_

Test_File[grepl("^A",Test_File$Product,ignore.case = TRUE),"New_SKU"]<-sub("^A","",Test_File[grepl("^A",Test_File$Product,ignore.case = TRUE),"Product"])

Test_File[Test_File$ASKU=="N","New_SKU"]<-Test_File[Test_File$ASKU=="N","Product"]

Test_File %>%
  dplyr::group_by(Order) %>%
  dplyr::mutate(DCount = n_distinct(ASKU)) %>%
  dplyr::filter(DCount>=2) %>%
  dplyr::ungroup() %>%
  dplyr::select(Order,New_SKU,ASKU) %>%
  dplyr::distinct() %>%
  tidyr::spread(key = ASKU,value = New_SKU)
</code>```

Can someone please help me? I would appreciate if you could help me with dplyr-based solution and data.table-based solution.

答:
Here is an option using data.table

```<code>library(data.table)
setDT(Test_File)[, .(Duplicate = c("N", "Y")[(anyDuplicated(sub("^A",
                  "", Product)) > 0)+1]), Order]
#    Order Duplicate
#1:  1234         Y
#2:  2345         N
#3:  3456         Y
#4:  4567         N
#5:  5678         Y
#6:  9999         N
</code>```

Or with base R

```<code>i1 <- with(Test_File, tapply(sub("^A", "", Product), Order, FUN = anyDuplicated)>0)
stack(split(i1, names(i1)))[2:1]
</code>```

Title: Find row-wise duplicates by groups

Body:
I have a data-set that may have duplicate products. If there are duplicate products, we would mark that order as "Y", and vice versa.

Here are my data:

dput(Test_File)
structure(list(Order = c(1234, 1234, 2345, 2345, 2345, 3456,
3456, 4567, 5678, 5678, 5678, 5678, 9999, 9999), Product = c("A12960",
"12960", "B3560", "3560", "A3850", "3850", "A3850", "A2920",
"2930", "2921", "A2921", "A2930", "A1234", "2345"), ASKU = c("Y",
"N", "N", "N", "Y", "N", "Y", "Y", "N", "N", "Y", "Y", "Y", "N"
)), .Names = c("Order", "Product", "ASKU"), row.names = c(NA,
14L), class = "data.frame")

Commentary about the data: I have a column that says ASKU. This is mainly to identify whether a particular SKU starts with A. Also, please note that A1234 and 1234 would be considered duplicate. A1234 and 23456 wouldn't be considered duplicate. Similarly, B1234 and 1234 won't be considered duplicates. So, to identify duplicates, one would ignore A in ASKU column.

Expected Output:

dput(Output_File)
structure(list(Order = c(1234, 2345, 3456, 4567, 5678, 9999),
    Duplicate = c("Y", "N", "Y", "N", "Y", "N")), .Names = c("Order",
"Duplicate"), row.names = c(NA, 6L), class = "data.frame")

My code (non-working):

I tried this code, but I am getting an error. The idea is to do row-wise comparison of SKUs after extracting string from SKU name.

Error: Duplicate identifiers for rows (3, 4), (8, 9), (10, 11)

Test_File$New_SKU<-NA_character_

Test_File[grepl("^A",Test_File$Product,ignore.case = TRUE),"New_SKU"]<-sub("^A","",Test_File[grepl("^A",Test_File$Product,ignore.case = TRUE),"Product"])

Test_File[Test_File$ASKU=="N","New_SKU"]<-Test_File[Test_File$ASKU=="N","Product"]

Test_File %>%
  dplyr::group_by(Order) %>%
  dplyr::mutate(DCount = n_distinct(ASKU)) %>%
  dplyr::filter(DCount>=2) %>%
  dplyr::ungroup() %>%
  dplyr::select(Order,New_SKU,ASKU) %>%
  dplyr::distinct() %>%
  tidyr::spread(key = ASKU,value = New_SKU)

Can someone please help me? I would appreciate if you could help me with dplyr-based solution and data.table-based solution.

Body:
Here is an option using data.table

library(data.table)
setDT(Test_File)[, .(Duplicate = c("N", "Y")[(anyDuplicated(sub("^A",
                  "", Product)) > 0)+1]), Order]
#    Order Duplicate
#1:  1234         Y
#2:  2345         N
#3:  3456         Y
#4:  4567         N
#5:  5678         Y
#6:  9999         N

Or with base R

i1 <- with(Test_File, tapply(sub("^A", "", Product), Order, FUN = anyDuplicated)>0)
stack(split(i1, names(i1)))[2:1]


问:
Javascript factory function not working properly
according to the tutorial i'm watching this code is supposed to return "John Doe." Presently, it only returns "[object, Object]", what am I doing wrong?

```<code><p id="para"></p>

function createPerson(firstName, lastName) {
    return {
        firstName: firstName,
        lastName: lastName,
        getFullName: function() {
            return this.firstName + " " + this.lastName;
        }
    };
}

var person = createPerson("John", "Doe");

document.getElementById("para").innerHTML = person;
</code>```

Any thoughts?

答:
```<code>function createPerson(firstName, lastName) {
  return {
    firstName: firstName,
    lastName: lastName,
    getFullName: function() {
      return this.firstName + " " + this.lastName;
    }
  };
}
</code>```

var person = createPerson("John", "Doe");

it only returns "[object, Object]"

because person is an object there

```<code>document.getElementById("para").innerHTML = person;
</code>```

if you want to print firstname

```<code>document.getElementById("para").innerHTML = person.firstName
</code>```

if you wnat to print lastName

```<code>document.getElementById("para").innerHTML = person.lastName
</code>```

if you want to print fullname

```<code>document.getElementById("para").innerHTML = person.getFullName()
</code>```

not the last one you have to invoke the function .

Body:
according to the tutorial i'm watching this code is supposed to return "John Doe." Presently, it only returns "[object, Object]", what am I doing wrong?

function createPerson(firstName, lastName) {
    return {
        firstName: firstName,
        lastName: lastName,
        getFullName: function() {
            return this.firstName + " " + this.lastName;
        }
    };
}

var person = createPerson("John", "Doe");

document.getElementById("para").innerHTML = person;

Any thoughts?

Body:
function createPerson(firstName, lastName) {
  return {
    firstName: firstName,
    lastName: lastName,
    getFullName: function() {
      return this.firstName + " " + this.lastName;
    }
  };
}

var person = createPerson("John", "Doe");

it only returns "[object, Object]"

because person is an object there

document.getElementById("para").innerHTML = person;

if you want to print firstname

document.getElementById("para").innerHTML = person.firstName

if you wnat to print lastName

document.getElementById("para").innerHTML = person.lastName

if you want to print fullname

document.getElementById("para").innerHTML = person.getFullName()

not the last one you have to invoke the function .


问:
How many watchers we can have at max in a single page in an angular applicaiton without affecting the performance?
How many watchers or scope variable can be kept in a page without affecting its performance of the page loading. Whether there is any limit for the scopes which used in terms of number or memory size?</p>

答:
I think it's more about what you watch and not how many watchers. I mean, an extremely heavy object / Array of objects watcher could affect performance while ten string watchers wouldn't.

I had a huge formController object in $scope.form being watched in my application which would change as we move through tabs (all tabs containing such forms). That watcher was consuming 7.x% of total computing when measured in chrome devtools with timeline.

So, coming back to your question,  I don't think there can be a precise answer to that. Maybe your interviewer intended to see whether you know that there isn't a specific limit that only x number of watchers are allowed and it's more about what you are watching.


问:
Why is gdb printing registers values in that way
So I have a task, where I have to compare like 128 bit numbers using 32 bit registers. So I thought about checking every bit (from the left), and comparing it with the othe number. I have this situation:

I've got a .txt file, where I have two 16-byte numbers written (no spaces or newlines), like this:

00000000000000010000000000000003

I read them using syscalls (x86 not 64 bit) and store in 2 buffers. When I want to take a byte from them, I do:

```<code>movl $15, %eax
addl $NUMBER1, %eax
movzbl (%eax), %eax
</code>```

So now I have the last byte of that number in %eax (indices of course begin from zero). Then I go for:
btl $0, %eax.

So in this case it shoudl be easy. I got a byte 1 stored in eax. I check its first bit (from the right side, of course), so 32 bit 1 = 000000000000000000000000000000001, so I should get 1 in carry flag. I check it with jc carry_1 - of course, it works. But then, I tried to check for something else. Cause obviously I shouldn't compare two numbers starting from the least significant digits, I should start from the left. So I go for btl $31, %eax, and yes, of course in this case I get 0 in carry flag. So I just wanted to check how my %eax looks, just to make sure I didn't get anything by an accident.

So in gdb I launched my executable. I got to the line with movzbl, I've gone through that line. Now it's time to check:

print /t $eax. I though I will get: 000000000000000000000000000000001, but no. The thing I saw:

```<code>33      movzbl (%eax), %eax
(gdb) s
34      btl $31, %eax
(gdb) print /t $eax
$1 = 110001
</code>```

So why is it 110001? When I checked for the 3 it was 110011, so the end of this is correct, but whats with those 11 at the beggining? I mean its for sure not a sign bit from twos complement (cuz there would be only one + it would be zero as my numbers are positive). So do you know what is it?

I am compiling it on a Manjaro 64 bit with as --32 and ld -melf_i1386

答:
So why is it 110001?

You've left out important parts of your code, like the one where you read the numbers from the text file. But it seems very likely that you just read all the characters and stored them somewhere. The ASCII code for the character '1' is 49, which in binary (the /t switch gives you binary) is 110001. So if what you've got in memory is the character '1', then this output is entirely expected.

Body:
So I have a task, where I have to compare like 128 bit numbers using 32 bit registers. So I thought about checking every bit (from the left), and comparing it with the othe number. I have this situation:

I've got a .txt file, where I have two 16-byte numbers written (no spaces or newlines), like this:

00000000000000010000000000000003

I read them using syscalls (x86 not 64 bit) and store in 2 buffers. When I want to take a byte from them, I do:

movl $15, %eax
addl $NUMBER1, %eax
movzbl (%eax), %eax

So now I have the last byte of that number in %eax (indices of course begin from zero). Then I go for:
btl $0, %eax.

So in this case it shoudl be easy. I got a byte 1 stored in eax. I check its first bit (from the right side, of course), so 32 bit 1 = 000000000000000000000000000000001, so I should get 1 in carry flag. I check it with jc carry_1 - of course, it works. But then, I tried to check for something else. Cause obviously I shouldn't compare two numbers starting from the least significant digits, I should start from the left. So I go for btl $31, %eax, and yes, of course in this case I get 0 in carry flag. So I just wanted to check how my %eax looks, just to make sure I didn't get anything by an accident.

So in gdb I launched my executable. I got to the line with movzbl, I've gone through that line. Now it's time to check:

print /t $eax. I though I will get: 000000000000000000000000000000001, but no. The thing I saw:

33      movzbl (%eax), %eax
(gdb) s
34      btl $31, %eax
(gdb) print /t $eax
$1 = 110001

So why is it 110001? When I checked for the 3 it was 110011, so the end of this is correct, but whats with those 11 at the beggining? I mean its for sure not a sign bit from twos complement (cuz there would be only one + it would be zero as my numbers are positive). So do you know what is it?

I am compiling it on a Manjaro 64 bit with as --32 and ld -melf_i1386


问:
QWebElement information where on page it is rendered?
Looks like access to DOM and rendering details of HTML tags are not availabel in qt 4.5.x .
Current snapshot  QWebElement looks like proper class to be used there
Anybody can give me info if is it possible to get from  QWebElement information where on page it was rendered ?
Or there are other ways to get that information ?
TIA, regards</p>

答: Just for reference's sake: for 4.6 and up, QWebElement.geometry() is the best way to do this.  Otherwise, user134841's answer about calling into JavaScript is really the only alternative.</p>


问:
Why "0 not equivalent to "_1 when arguments are one dimensional arrays?
Why these two expression not equivalent in this situation?

```<code>   0 1 2 ,"(0)/ 0 1
0 0
0 1

1 0
1 1

2 0
2 1

   0 1 2 ,"(_1)/ 0 1
|length error
|   0 1 2    ,"(_1)/0 1
</code>```

Actually what I'm trying to do...

```<code>a =: 0 1 2 3 4 5 ; 0 1 2 ; 0 1
</code>```

Want to get all possible combinations

```<code>,"0/&>/ a
</code>```

This code doesn't work

This works though:

```<code>0 1 2 3 4 5 ,"(0 1)/ 0 1 2 ,"(0 0)/ 0 1
</code>```

But, of course, I want to write in short form

```<code>,"0/&>/ a
</code>```

The problem is that all terms should be

```<code>,"(0 1)/
</code>```

but last

```<code>,"(0 0)/
</code>```

答:
"_1 is equivalent to "0"_

In other words, "_1 forms a verb which looks at all the data to find its rank and then derives another verb to work at one rank lower than that.

Body:
Why these two expression not equivalent in this situation?

   0 1 2 ,"(0)/ 0 1
0 0
0 1

1 0
1 1

2 0
2 1

   0 1 2 ,"(_1)/ 0 1
|length error
|   0 1 2    ,"(_1)/0 1

Actually what I'm trying to do...

a =: 0 1 2 3 4 5 ; 0 1 2 ; 0 1

Want to get all possible combinations

,"0/&>/ a

This code doesn't work

This works though:

0 1 2 3 4 5 ,"(0 1)/ 0 1 2 ,"(0 0)/ 0 1

But, of course, I want to write in short form

,"0/&>/ a

The problem is that all terms should be

,"(0 1)/

but last

,"(0 0)/


问:
Flashing label in javafx gui
I'm looking to make a label blink in and out ever 0.1 seconds in javafx. The text appears on top of an ImageView gif that is running in the background. How would I go about doing this or if you have any suggestions on the best method?

Thanks

答:
@fabian's solution is nice. Nevertheless, in this case, you could use a FadeTransition. It alters the opacity of the node and is a good fit for your use-case.

```<code>FadeTransition fadeTransition = new FadeTransition(Duration.seconds(0.1), label);
fadeTransition.setFromValue(1.0);
fadeTransition.setToValue(0.0);
fadeTransition.setCycleCount(Animation.INDEFINITE);
</code>```

MCVE

```<code>import javafx.animation.Animation;
import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class LabelBlink extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Label label = new Label("Blink");
        FadeTransition fadeTransition = new FadeTransition(Duration.seconds(0.1), label);
        fadeTransition.setFromValue(1.0);
        fadeTransition.setToValue(0.0);
        fadeTransition.setCycleCount(Animation.INDEFINITE);
        fadeTransition.play();
        Scene scene = new Scene(new StackPane(label));
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        Application.launch();
    }
}
</code>```

Title: Flashing label in javafx gui

Body:
@fabian's solution is nice. Nevertheless, in this case, you could use a FadeTransition. It alters the opacity of the node and is a good fit for your use-case.

FadeTransition fadeTransition = new FadeTransition(Duration.seconds(0.1), label);
fadeTransition.setFromValue(1.0);
fadeTransition.setToValue(0.0);
fadeTransition.setCycleCount(Animation.INDEFINITE);

MCVE

import javafx.animation.Animation;
import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class LabelBlink extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Label label = new Label("Blink");
        FadeTransition fadeTransition = new FadeTransition(Duration.seconds(0.1), label);
        fadeTransition.setFromValue(1.0);
        fadeTransition.setToValue(0.0);
        fadeTransition.setCycleCount(Animation.INDEFINITE);
        fadeTransition.play();
        Scene scene = new Scene(new StackPane(label));
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        Application.launch();
    }
}


问:
Displaying legend from single plot when using multiple plots
I have the following code, when using the legend, the marker from both plots is used (as default), however, I would like to only use the markers from the second plot.

Is there a simple way to do this?

```<code>hold on
plot(C,d,'color', [0.9, 0.9, 0.9], 'LineWidth',15);
plot(k,d,'x','MarkerSize',7);
legend(strcat(text),'Box','off','Location','best');
</code>```

答:
use graphic handles as input to legend:

```<code>hold on
h1 = plot(C,d,'color', [0.9, 0.9, 0.9], 'LineWidth',15);
h2 = plot(k,d,'x','MarkerSize',7);
legend(h2, strcat(text),'Box','off','Location','best');
</code>```

Body:
I have the following code, when using the legend, the marker from both plots is used (as default), however, I would like to only use the markers from the second plot.

Is there a simple way to do this?

hold on
plot(C,d,'color', [0.9, 0.9, 0.9], 'LineWidth',15);
plot(k,d,'x','MarkerSize',7);
legend(strcat(text),'Box','off','Location','best');

Body:
use graphic handles as input to legend:

hold on
h1 = plot(C,d,'color', [0.9, 0.9, 0.9], 'LineWidth',15);
h2 = plot(k,d,'x','MarkerSize',7);
legend(h2, strcat(text),'Box','off','Location','best');