问:
Html / Javascript - Div Showing & Hiding
Little Layout
MDIV
ADIV = BDIV

I'm trying to hide and show divs with onclicks and failing miserably.

When function MA() button is clicked = ADIV to show and BDIV to hide

When function MB() button is clicked = BDIV to show and ADIV to hide

function MA() {

  document.getElementById("ADIV").style.display = "";
  document.getElementById("BDIV").style.display = "none";

}

function MB() {

  document.getElementById("ADIV").style.display = "none";
  document.getElementById("BDIV").style.display = "";

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="MDIV">
  <button onclick="MA()">MA</button>
  <button onclick="MB()">MB</button>
</div>

<div id="ADIV">
  <button onclick="A()">ADIV</button>
</div>
<div id="BDIV">
  <button onclick="B()">BDIV</button>
</div></code>```

Sidenote
Also if anyone can explain how to load with just MDIV - ADIV on page load.

Cheers in advance.

答:
Add a hidden style or CSS to the elements you want hidden on page load.  I have added inline styling here to hide "BDIV".

Don't use JavaScript for styling on page load unless you have to.  It is better to use CSS or styling.

```<code><html>
<head></head>
<body>

<div id="MDIV">
    <button onclick="MA()">MA</button>
    <button onclick="MB()">MB</button>
</div>

<div id="ADIV">
    <button onclick="A()">ADIV</button>
</div>

<div id="BDIV" style="display: none;">
    <button onclick="B()">BDIV</button>
</div>

</body>
</html>

<script>
//CACHE YOUR ELEMENTS

var mdiv = document.getElementById('MDIV');
var adiv = document.getElementById('ADIV');
var bdiv = document.getElementById('BDIV');

//helper functions
function hide(elm) { elm.style.display = 'none'; }
function show(elm) { elm.style.display = 'block'; }

function MA() {
  hide(adiv);
  show(bdiv);
}

function MB() {
  hide(adiv);
  show(bdiv);
}

</script>
</code>```

Body:
Little Layout
MDIV
ADIV = BDIV

I'm trying to hide and show divs with onclicks and failing miserably.

When function MA() button is clicked = ADIV to show and BDIV to hide

When function MB() button is clicked = BDIV to show and ADIV to hide

function MA() {

  document.getElementById("ADIV").style.display = "";
  document.getElementById("BDIV").style.display = "none";

}

function MB() {

  document.getElementById("ADIV").style.display = "none";
  document.getElementById("BDIV").style.display = "";

}

  <button onclick="MA()">MA</button>
  <button onclick="MB()">MB</button>

  <button onclick="A()">ADIV</button>

  <button onclick="B()">BDIV</button>

Sidenote
Also if anyone can explain how to load with just MDIV - ADIV on page load.

Cheers in advance.

Body:
Add a hidden style or CSS to the elements you want hidden on page load.  I have added inline styling here to hide "BDIV".

Don't use JavaScript for styling on page load unless you have to.  It is better to use CSS or styling.

<html>
<head></head>
<body>

<div id="MDIV">
    <button onclick="MA()">MA</button>
    <button onclick="MB()">MB</button>
</div>

<div id="ADIV">
    <button onclick="A()">ADIV</button>
</div>

<div id="BDIV" style="display: none;">
    <button onclick="B()">BDIV</button>
</div>

</body>
</html>

<script>
//CACHE YOUR ELEMENTS

var mdiv = document.getElementById('MDIV');
var adiv = document.getElementById('ADIV');
var bdiv = document.getElementById('BDIV');

//helper functions
function hide(elm) { elm.style.display = 'none'; }
function show(elm) { elm.style.display = 'block'; }

function MA() {
  hide(adiv);
  show(bdiv);
}

function MB() {
  hide(adiv);
  show(bdiv);
}

</script>


来源: stackexchange

问:
Getting the values of textboxes in Javascript
I have this html code:

```<code><table border="" cellpadding="3" cellspacing="0" id="mytable">

<tbody><tr><td>Song:</td> <td><input type="text" name="song" maxlength="64" size="48" /> </td></tr>
<tr><td>Artist:</td> <td><input type="text" name="artist" maxlength="16" size="48" /> </td></tr>
</code>```

How do I get the values of "song" and "artist"? I have tried:

```<code>var elTableCells = mytable.getElementsByTagName("td");
alert(elTableCells[2].value);
alert(elTableCells[4].value);
</code>```

but I keep getting "undefined" even when there is text inside the textbox

ContentLicense: CC BY-SA 3.0

Body:
I have this html code:

Song:	 <input type="text" name="song" maxlength="64" size="48" />

Artist:	 <input type="text" name="artist" maxlength="16" size="48" />

How do I get the values of "song" and "artist"? I have tried:

var elTableCells = mytable.getElementsByTagName("td");
alert(elTableCells[2].value);
alert(elTableCells[4].value);

but I keep getting "undefined" even when there is text inside the textbox

Body:
alert(document.getElementsByName("song")[0].value);
alert(document.getElementsByName("artist")[0].value);

ContentLicense: CC BY-SA 2.5


问:
How to animate UICollectionViewCell expansion?
I have a UICollectionView. When user taps on a cell I have to expand the size of the cell. I am doing this like this,

```<code>-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView performBatchUpdates:^{
        isExpandedMode = true;
        expandedPosition = indexPath.row;
        [self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil]];
    } completion:^(BOOL finished) {

    }];
}
</code>```

Now I update the cell size in here,

```<code>- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(isExpandedMode && expandedPosition == indexPath.row){
        CGFloat screenWidth = 568.0;
        CGFloat screenHeight = 293.0;
        return CGSizeMake(screenWidth, screenHeight);
    }
    else{
        CGFloat screenWidth = 172.0;
        CGFloat screenHeight = 293.0;
        return CGSizeMake(screenWidth, screenHeight);
    }
}
</code>```

Now I want to apply animation to the expansion of cell, where to write this code?

答: If you want your changes to be animated put them inside of a call to performBatchUpdates:completion:</p>

Body:
I have a UICollectionView. When user taps on a cell I have to expand the size of the cell. I am doing this like this,

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView performBatchUpdates:^{
        isExpandedMode = true;
        expandedPosition = indexPath.row;
        [self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil]];
    } completion:^(BOOL finished) {

    }];
}

Now I update the cell size in here,

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(isExpandedMode && expandedPosition == indexPath.row){
        CGFloat screenWidth = 568.0;
        CGFloat screenHeight = 293.0;
        return CGSizeMake(screenWidth, screenHeight);
    }
    else{
        CGFloat screenWidth = 172.0;
        CGFloat screenHeight = 293.0;
        return CGSizeMake(screenWidth, screenHeight);
    }
}

Now I want to apply animation to the expansion of cell, where to write this code?


问:
Google Analytics Event Tracking on an image not working
I am trying to set up Event Tracking through Google Analytics. Getting it to work on text links is easy but I can't seem to get it to work on images. I follow Google's example of how to add the code should be, but it results in an image link that can't be clicked (I click the banner and nothing happens, but I can right click the banner and open in new window and it works).

See below for my code on the link:

```<code><a href="http://keystonetech.com" target="_blank"
onclick="trackOutboundLink('http://keystonetech.com');return false;"><img
src="/wp-content/uploads/2017/09/keystone-direct-drive-led-t5.jpg" alt=""
width="617" height="128" /></a>
</code>```

And then below is the Google Analytics scripts - 1st one is the standard Universal Analytics GA Script and the bottom one is for tracking the links (again, per the Google link above).

```<code><!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-437557-
32"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments)};
  gtag('js', new Date());

  gtag('config', 'UA-437557-32');
</script>
<script>
/**
* Function that tracks a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL
string
* as the event label. Setting the transport method to 'beacon' lets the hit
be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var trackOutboundLink = function(url) {
   ga('send', 'event', 'outbound', 'click', url, {
     'transport': 'beacon',
     'hitCallback': function(){document.location = url;}
   });
}
</script>
</code>```

Any thoughts on where the issue lies would be much appreciated! Thanks much for reading.

答:
I think I can send you in the right direction. I'm pretty sure the issue is the difference between the various analytics tracking codes. you're using the newest Gtag.js, which appears to have a different event structure than analytics.js

I personally use google tag manager now, but I'm pretty sure the structure to call an event is different for Gtag.js. Here's the page specifically for that:

https://developers.google.com/analytics/devguides/collection/gtagjs/events#recommended-event-parameters

And if I were you, it looks like the actual function would look like:

```<code>gtag('event', 'event_name', {
'event_category': categoryName,
'event_label': labelName
});
</code>```

Which if I'm reading your code right would be basically:

```<code>gtag('event', 'click', {
'event_category': 'outbound',
'event_label': url
});
</code>```

Then be sure you properly trigger that function on the click, and be sure grab the chrome extension google analytics debugger and in the console make sure you see it fire that hit to GA. Tada!

Body:
I am trying to set up Event Tracking through Google Analytics. Getting it to work on text links is easy but I can't seem to get it to work on images. I follow Google's example of how to add the code should be, but it results in an image link that can't be clicked (I click the banner and nothing happens, but I can right click the banner and open in new window and it works).

See below for my code on the link:

And then below is the Google Analytics scripts - 1st one is the standard Universal Analytics GA Script and the bottom one is for tracking the links (again, per the Google link above).

Any thoughts on where the issue lies would be much appreciated! Thanks much for reading.

Body:
I think I can send you in the right direction. I'm pretty sure the issue is the difference between the various analytics tracking codes. you're using the newest Gtag.js, which appears to have a different event structure than analytics.js

I personally use google tag manager now, but I'm pretty sure the structure to call an event is different for Gtag.js. Here's the page specifically for that:

https://developers.google.com/analytics/devguides/collection/gtagjs/events#recommended-event-parameters

And if I were you, it looks like the actual function would look like:

gtag('event', 'event_name', {
'event_category': categoryName,
'event_label': labelName
});

Which if I'm reading your code right would be basically:

gtag('event', 'click', {
'event_category': 'outbound',
'event_label': url
});

Then be sure you properly trigger that function on the click, and be sure grab the chrome extension google analytics debugger and in the console make sure you see it fire that hit to GA. Tada!


问:
How to call function after submit form aspx
I want callback alert after submit form, but doesn't worked. Submit not execute.

Only $("#formImpressao").submit(); worked fine.

I try too use $(document).ready(function () { ... :( No Success

Whats wrong?

Sorry for my bad english

```<code><div id="HiddenFormTarget" style="display:none;">
    <form id="formImpressao" method="post" target="frmPrint" action="/VisualizarRelatorios/ImprimirRelatorio.aspx""></form>
</div>
<iframe id="frmPrint" name="frmPrint" width="0" height="0" runat="server">
</iframe>

<script language="javascript" type="text/javascript">
    $("#formImpressao").submit(function () {
       alert('Test');
    });
    $("#formImpressao").submit();

</script>
</code>```

答:
(1) There appears to be an extra quote in your form tag.

(2) Have you tried your approach without the target attribute in the form tag?

e.g. -

```<code><form id="formImpressao" method="post" action="/VisualizarRelatorios/ImprimirRelatorio.aspx"></form>
</code>```

Body:
I want callback alert after submit form, but doesn't worked. Submit not execute.

Only $("#formImpressao").submit(); worked fine.

I try too use $(document).ready(function () { ... :( No Success

Whats wrong?

Sorry for my bad english

    <form id="formImpressao" method="post" target="frmPrint" action="/VisualizarRelatorios/ImprimirRelatorio.aspx""></form>

Body:
(1) There appears to be an extra quote in your form tag.

(2) Have you tried your approach without the target attribute in the form tag?

e.g. -

<form id="formImpressao" method="post" action="/VisualizarRelatorios/ImprimirRelatorio.aspx"></form>


问:
Symfony 3.3 - How can the container know the tag of the service when autowiring is enabled?
I have a service which has two tags, extended_type and name.

With autowiring enabled, how can I define these tags?

Edit:
  This is my class form extension

```<code>use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
class DateTimeTypeExtension extends AbstractTypeExtension
{
    public function getExtendedType()
    {
        return DateTimeType::class;
    }

    public function buildView( FormView $view, FormInterface $form, array $options )
    {
        $view->vars['date_time_help'] = 'Format d-m-Y.';
    }

}
</code>```

Form type extension service need to define two tags extended_type and name

答:
Starting in Symfony 3.3, if you enable autoconfigure, then some tags are automatically applied for you like twig.extension.
enable autoconfigure does not work for all tags. Many tags have required attributes, like event listeners, where you also need to specify the event name and method in your tag. Autoconfigure works only for tags without any required tag attributes

In your case, you need to  override your sevice in the app/config/service.yml and explicitly define your tags like this:

```<code>AppBundle\Service\YourService:
        tags:
            - { name: service1, extended_type: service2 }
</code>```

Body:
I have a service which has two tags, extended_type and name.

With autowiring enabled, how can I define these tags?

Edit:
  This is my class form extension

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
class DateTimeTypeExtension extends AbstractTypeExtension
{
    public function getExtendedType()
    {
        return DateTimeType::class;
    }

    public function buildView( FormView $view, FormInterface $form, array $options )
    {
        $view->vars['date_time_help'] = 'Format d-m-Y.';
    }

}

Form type extension service need to define two tags extended_type and name

Body:
Starting in Symfony 3.3, if you enable autoconfigure, then some tags are automatically applied for you like twig.extension.
enable autoconfigure does not work for all tags. Many tags have required attributes, like event listeners, where you also need to specify the event name and method in your tag. Autoconfigure works only for tags without any required tag attributes

In your case, you need to  override your sevice in the app/config/service.yml and explicitly define your tags like this:

AppBundle\Service\YourService:
        tags:
            - { name: service1, extended_type: service2 }


问:
creating unshared namespaces
When running unshare command (man 1 unshare), which allows to execute a command in a separate namespace from the shell, why do I still see all processes from the host? Is PID namespace not unshared by design?

Thanks.

答:
unshare unshares only those namespace that you have set via options. Please, also take a special look at --mount-proc option (quote from unshare(1)):

Just  before running the program, mount the proc filesystem at mountpoint (default is /proc).  This is useful when
  creating a new PID namespace.  It also implies creating a new mount namespace since the /proc mount would otherwise mess up existing
  programs on the system.  The new proc filesystem is explicitly mounted as private (with MS_PRIVATE|MS_REC).

This is important as ps command read pids from /proc fs (see ps(1)):

This ps works by reading the virtual files in /proc.

See also pid_namespaces(7):

After creating a new PID namespace, it is useful for the child to
         <...> mount a new procfs instance at /proc so
         that tools such as ps(1) work correctly.

Title: creating unshared namespaces


问:
Using Delphi data-aware components - pros and cons
I want to know your opinion about using data-aware components in projects. Which are the 'strength' and 'weak' points of developing applications(win32 and web), by using Delphi and data-aware components(from Delphi's standard suite or third-party)?

Using FireBird I've worked a lot with IBObjects, which are a mature suite of components and worked very well.

But there are also a lot of other RDBMS (MySQL, MSSQL, DB2, Oracle, SQLite, Nexus, Paradox, Interbase, FireBird etc). If you have developed big projects, on which you've used a lot data-aware  components please answer with the database type and data-aware components suite name.

I'm also interested on DB2 (AS400). What components have you used with success, or which components are really a pain to work with?

答:
Data aware controls are great, but you have to make sure you get your business code in a separate layer.

That is not difficult, but you need to be aware on how you can do that.

One approach is to have your DataSet components in a DataModule (or other non visual container).

Another handy trick is to use a TClientDataSet to do the UI entry, and use that as an intermediate buffer between the UI and the business layer. The business layer then uses TDataSet components specific to your data layer.

--jeroen


问:
7-dimensional vector Java
I am very new to java and I have this assignment which I have been working on very intensivly for the last 14 days.

The assignement is to build a class vector with max. 7 dimensions:
what I came with to make the vector multi-dimensional is that I declared 7 variables

```<code>private double x, y,z,i,j,k,f;
</code>```

which then I will initialize in constructors etc..
Well, my first question: did I build a 7 dimensional vector in this way?

OR,

should I somehow work with arrays for this problem
like declaring an array;

```<code>double [][] = data; // which generates a 2D-Vector.
</code>```

AND,

```<code>double [][][][][][][] = data1; //which declare a 7D-Vector??!!!
</code>```

for any helpful information I will be very thankful

thanks all and
Best regards to you  :)

答:
You don't need a multidimensional array for a vector. By definition, a vector has only a single column; if it had multiple columns, it would be a matrix, not a vector.

If you want a vector of size n, just create a single-dimensional array of size n. You could use an ArrayList or something like that, but there's less of a point because you (presumably) know the size of the vector in advance. (If that's not the case, ArrayList could be good).

The most interesting part of a Vector class is actually the operations, so use whatever data structure allows you to retain order and conveniently perform your operations. Truthfully, that'll probably be an array of size n.

Title: 7-dimensional vector Java

Body:
I am very new to java and I have this assignment which I have been working on very intensivly for the last 14 days.

The assignement is to build a class vector with max. 7 dimensions:
what I came with to make the vector multi-dimensional is that I declared 7 variables

private double x, y,z,i,j,k,f;

which then I will initialize in constructors etc..
Well, my first question: did I build a 7 dimensional vector in this way?

OR,

should I somehow work with arrays for this problem
like declaring an array;

double [][] = data; // which generates a 2D-Vector.

AND,

double [][][][][][][] = data1; //which declare a 7D-Vector??!!!

for any helpful information I will be very thankful

thanks all and
Best regards to you  :)


问:
psycopg2.OperationalError: FATAL: database does not exist
I'm trying to populate a couple databases with psycopg2 within a server I am not the root user of (don't know if it's relevant or not). My code looks like

```<code>import json
from  psycopg2 import connect

cors = connect(user='jungal01', dbname='course')
req = connect(user="jungal01", dbname='requirement')

core = cors.cursor()
reqs = req.cursor()

with open('gened.json') as gens:
    geneds = json.load(gens)

for i in range(len(geneds)):
    core.execute('''insert into course (number, description, title)
                    values({0}, {1}, {2});''' .format(geneds[i]["number"], geneds[i]['description'], geneds[i]['title'] ))

reqs.execute('''insert into requirement (fulfills)
                values({0});''' .format(geneds[i]['fulfills'] ))
db.commit()
</code>```

when I execute the code, I get the above pycopg2 error. I know that these particular databases exist, but I just can't figure out why it won't connect to my databases. (side quest, I am also unsure about that commit statement. Should it be in the for loop, or outside of it? It suppose to be database specific?)

答:
Make sure you are giving the catalog name as database name and not the schema's under catalog.

Catalog is confusing and quite unnecessary. More details below: What's the difference between a catalog and a schema in a relational database?

Body:
I'm trying to populate a couple databases with psycopg2 within a server I am not the root user of (don't know if it's relevant or not). My code looks like

import json
from  psycopg2 import connect

cors = connect(user='jungal01', dbname='course')
req = connect(user="jungal01", dbname='requirement')

core = cors.cursor()
reqs = req.cursor()

with open('gened.json') as gens:
    geneds = json.load(gens)

for i in range(len(geneds)):
    core.execute('''insert into course (number, description, title)
                    values({0}, {1}, {2});''' .format(geneds[i]["number"], geneds[i]['description'], geneds[i]['title'] ))

reqs.execute('''insert into requirement (fulfills)
                values({0});''' .format(geneds[i]['fulfills'] ))
db.commit()

when I execute the code, I get the above pycopg2 error. I know that these particular databases exist, but I just can't figure out why it won't connect to my databases. (side quest, I am also unsure about that commit statement. Should it be in the for loop, or outside of it? It suppose to be database specific?)


问:
Safari. Wrong cursor when dragging
I'm trying to add drag-and-drop functionality to my project and using slip.js for this.

To decorate cursor I've add class="draggable" to each draggable
. The CSS for this class is:

```<code>.draggable:active {
  cursor: -webkit-grabbing;
  cursor:    -moz-grabbing;
  cursor:         grabbing;
}
</code>```

Drag-and-drop works fine, but in Safari when I'm dragging a table row the cursor looks like cursor: text

In Chrome the cursor is OK

Interesting that when I just click and hold without dragging the cursor is OK in Safari too

答:
As mentioned in chrome sets cursor to text while dragging, why?, I need to disable selection when dragging. My JavaScript for this:</p>

```<code>list = document.getElementById('demo1');

var flag_dragging = false;
list.addEventListener('mouseover', function(e){
  document.onselectstart = function(){ return false; }
});

list.addEventListener('mouseout', function(e){
  if(!flag_dragging){
    document.onselectstart = function(){ return true; }
  }
});

list.addEventListener('dragstart', function(e){
  flag_dragging = true;
});

list.addEventListener('dragstop', function(e){
  flag_dragging = false;
});
</code>```

Title: Safari. Wrong cursor when dragging

Body:
I'm trying to add drag-and-drop functionality to my project and using slip.js for this.

To decorate cursor I've add class="draggable" to each draggable
. The CSS for this class is:

.draggable:active {
  cursor: -webkit-grabbing;
  cursor:    -moz-grabbing;
  cursor:         grabbing;
}

Drag-and-drop works fine, but in Safari when I'm dragging a table row the cursor looks like cursor: text

In Chrome the cursor is OK

Interesting that when I just click and hold without dragging the cursor is OK in Safari too

Body:
As mentioned in chrome sets cursor to text while dragging, why?, I need to disable selection when dragging. My JavaScript for this:

list = document.getElementById('demo1');

var flag_dragging = false;
list.addEventListener('mouseover', function(e){
  document.onselectstart = function(){ return false; }
});

list.addEventListener('mouseout', function(e){
  if(!flag_dragging){
    document.onselectstart = function(){ return true; }
  }
});

list.addEventListener('dragstart', function(e){
  flag_dragging = true;
});

list.addEventListener('dragstop', function(e){
  flag_dragging = false;
});


问:
'git checkout' is not creating local branch to match remote tracking branch
On one machine, calling git checkout will not create a local branch.

For example, if I have a remote tracking branch origin/master, I can call git checkout origin/master, and it will work fine, putting me in a headless state.

But if I try to call git checkout master, I get the error error: pathspec 'master' did not match any file(s) known to git.

I tried this on another machine, and it worked just fine.

They have the exact same version of git installed (2.15.0.windows.1).  git config --list shows one difference.  The machine where it worked properly had the following line in its configuration:

```<code>remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
</code>```

What would put that in the local configuration, why might it be missing from one of the systems, and what is the proper thing to do to fix the problem?

答:
Answering the last part first:

and what is the proper thing to do to fix the problem?

the simplest thing at this point is to run:

```<code>git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'
</code>```

so as to get this configuration line added.

Description

This:

```<code>remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
</code>```

is the normal, standard setting for remote.origin.fetch.

What would put that in the local configuration,

Running:

```<code>git clone <url>
</code>```

will do that, as step 4 of this six-step clone process:

Create new directory if/when appropriate.  (You can point it to an existing, empty directory instead, if you like.)

Run git init in the empty directory.

Run any specified git config operations in the new, empty repository.

Run git remote add origin <url>.

Run git fetch origin.

Run git checkout <branch>, where <branch> usually defaults to master.

why might it be missing from one of the systems,

Not running git clone.  If you do the steps yourself, and do something odd instead of step 4, you will get this setup.  It's possible there is some kind of bug in some Windows version of Git since I have recently seen several questions where this has happened.

(Note: Running git clone --single-branch -b <branch> redirects the git remote add step to use -t <branch>, so that remote.origin.fetch will be set to something other than the standard setting.  The git config command at the top will overwrite the non-standard setting with the standard one.)

Body:
On one machine, calling git checkout will not create a local branch.

For example, if I have a remote tracking branch origin/master, I can call git checkout origin/master, and it will work fine, putting me in a headless state.

But if I try to call git checkout master, I get the error error: pathspec 'master' did not match any file(s) known to git.

I tried this on another machine, and it worked just fine.

They have the exact same version of git installed (2.15.0.windows.1).  git config --list shows one difference.  The machine where it worked properly had the following line in its configuration:

remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*

What would put that in the local configuration, why might it be missing from one of the systems, and what is the proper thing to do to fix the problem?

Body:
Answering the last part first:

and what is the proper thing to do to fix the problem?

the simplest thing at this point is to run:

git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'

so as to get this configuration line added.

Description

This:

remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*

is the normal, standard setting for remote.origin.fetch.

What would put that in the local configuration,

Running:

git clone <url>

will do that, as step 4 of this six-step clone process:

Create new directory if/when appropriate.  (You can point it to an existing, empty directory instead, if you like.)

Run git init in the empty directory.

Run any specified git config operations in the new, empty repository.

Run git remote add origin <url>.

Run git fetch origin.

Run git checkout <branch>, where <branch> usually defaults to master.

why might it be missing from one of the systems,

Not running git clone.  If you do the steps yourself, and do something odd instead of step 4, you will get this setup.  It's possible there is some kind of bug in some Windows version of Git since I have recently seen several questions where this has happened.

(Note: Running git clone --single-branch -b <branch> redirects the git remote add step to use -t <branch>, so that remote.origin.fetch will be set to something other than the standard setting.  The git config command at the top will overwrite the non-standard setting with the standard one.)


问:
optarg from getopt() is always null
I'm trying to process an argument parameter using the optarg parameter of getopt(), but it remains null. Could this be something to do with the c99 standard? I know I will need to actually copy the string from optarg but it never even gets set.</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *optarg;
    int ch;

    char *indir = NULL;

    while ((ch = getopt(argc, argv, "d:")) != -1) {
        switch(ch) {
            case 'd':
                indir = optarg;
                fprintf(stderr, "Optarg: %s\n", optarg);
                fprintf(stderr, "Dir name: %s\n", indir);
                break;
            default :
                fprintf(stderr, "Usage:  test -d <input directory>\n");
                exit(1);
        }
    }
    if(indir == NULL){
        fprintf(stderr, "Input directory required.\n");
        exit(1);
    }
    else{
        printf("Input dir: %s\n", indir);
    }

    return 0;
}
</code>```

答: optarg is something that's initialized by a call to getopt(), you're overwriting it by initializing it yourself. Remove the line "char* optarg;" and you should be good to go.</p>

Title: optarg from getopt() is always null

Body:
I'm trying to process an argument parameter using the optarg parameter of getopt(), but it remains null. Could this be something to do with the c99 standard? I know I will need to actually copy the string from optarg but it never even gets set.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *optarg;
    int ch;

    char *indir = NULL;

    while ((ch = getopt(argc, argv, "d:")) != -1) {
        switch(ch) {
            case 'd':
                indir = optarg;
                fprintf(stderr, "Optarg: %s\n", optarg);
                fprintf(stderr, "Dir name: %s\n", indir);
                break;
            default :
                fprintf(stderr, "Usage:  test -d <input directory>\n");
                exit(1);
        }
    }
    if(indir == NULL){
        fprintf(stderr, "Input directory required.\n");
        exit(1);
    }
    else{
        printf("Input dir: %s\n", indir);
    }

    return 0;
}


问:
How to plot using matplotlib (python) colah's deformed grid?
I need to create a visualization in Python just like colah's did on his site. However, I could not find any distortion to grid on matplotlib to perform exactly like he did here. Pls, help me if you can.

This is the plot I need to perform:

答:
I would guess the image is produced by adding some gaussian function to the grid.

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

def plot_grid(x,y, ax=None, **kwargs):
    ax = ax or plt.gca()
    segs1 = np.stack((x,y), axis=2)
    segs2 = segs1.transpose(1,0,2)
    ax.add_collection(LineCollection(segs1, **kwargs))
    ax.add_collection(LineCollection(segs2, **kwargs))
    ax.autoscale()

f = lambda x,y : ( x+0.8*np.exp(-x**2-y**2),y )

fig, ax = plt.subplots()

grid_x,grid_y = np.meshgrid(np.linspace(-3,3,20),np.linspace(-3,3,20))
plot_grid(grid_x,grid_y, ax=ax,  color="lightgrey")

distx, disty = f(grid_x,grid_y)
plot_grid(distx, disty, ax=ax, color="C0")

plt.show()
</code>```

Body:
I would guess the image is produced by adding some gaussian function to the grid.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

def plot_grid(x,y, ax=None, **kwargs):
    ax = ax or plt.gca()
    segs1 = np.stack((x,y), axis=2)
    segs2 = segs1.transpose(1,0,2)
    ax.add_collection(LineCollection(segs1, **kwargs))
    ax.add_collection(LineCollection(segs2, **kwargs))
    ax.autoscale()

f = lambda x,y : ( x+0.8*np.exp(-x**2-y**2),y )

fig, ax = plt.subplots()

grid_x,grid_y = np.meshgrid(np.linspace(-3,3,20),np.linspace(-3,3,20))
plot_grid(grid_x,grid_y, ax=ax,  color="lightgrey")

distx, disty = f(grid_x,grid_y)
plot_grid(distx, disty, ax=ax, color="C0")

plt.show()

ContentLicense: CC BY-SA 4.0


问:
Do server-side encrypted files in S3 get transitioned to AWS Glacier?
Question:
Do server-side encrypted (with S3 managed or KMS managed keys) files get transitioned to Glacier ?
If yes, are they decrypted using S3 or KMS key and then encrypted again using Glacier's internal key as all objects in Glacier are encrypted using an internal AES 256 keys ?

Problem statement:
I have some files in S3 encrypted using KMS managed key. I have a lifecycle rule to archive to Glacier after 1 day, but the files still show Storage class as 'Standard' even after 3 days.

答:
My lifecycle rules had filename-specific prefix like 'com/folder-name/Daily-'. I created new lifecycle rules so that they end with last parent folder-name and a trailing slash 'com/folder-name/'.

After this change and waiting for 24+ hours, both un-encrypted and SSE-kms encrypted files got transitioned to Amazon Glacier.

After transition, I do understand they both got encrypted internally using Glacier managed keys as documented in this FAQ. https://aws.amazon.com/glacier/faqs/#security.


问:
Compare two datetime values in a stored procedure using SQL Server?
Inside the stored procedure's SELECT statement, I have to get the max datetime value.

```<code>((SELECT MAX(MyDateTime)
  FROM MyTable
  WHERE MyId = MM.MyId)) as RecentDateTime,
</code>```

This works. I see the new column with the datetime value in the SQL Server Management Studio grid.

However, I need to compare this value with another datetime value to see if they are equal. I get a syntax error for the following statement inside the SELECT statement

```<code>((SELECT MAX(MyDateTime)
  FROM MyTable
  WHERE MyId = MM.MyId) = MM.MyDateTime) as RecentDateTime,
</code>```

Or:

```<code>@RecentDateTime = ((SELECT MAX(MyDateTime)
                    FROM MyTable
                    WHERE MyId = MM.MyId) = MM.MyDateTime)
</code>```

If I can store the result of the comparison to a variable, I can take this value and compare it to another value.

Not sure why I keep getting the syntax error or how to fix this. Any help is appreciated by a newbie.

答:
Not sure what you're expecting, the other date or the results of the comparison, but if you want only the result of comparing two dates, try:</p>

```<code>case when (SELECT MAX(MyDateTime)
          FROM MyTable
          WHERE MyId = MM.MyId) = MM.MyDateTime
then 1 else 0 end as isMaxMyDT_eq_myDT
</code>```

Body:
Inside the stored procedure's SELECT statement, I have to get the max datetime value.

((SELECT MAX(MyDateTime)
  FROM MyTable
  WHERE MyId = MM.MyId)) as RecentDateTime,

This works. I see the new column with the datetime value in the SQL Server Management Studio grid.

However, I need to compare this value with another datetime value to see if they are equal. I get a syntax error for the following statement inside the SELECT statement

((SELECT MAX(MyDateTime)
  FROM MyTable
  WHERE MyId = MM.MyId) = MM.MyDateTime) as RecentDateTime,

Or:

@RecentDateTime = ((SELECT MAX(MyDateTime)
                    FROM MyTable
                    WHERE MyId = MM.MyId) = MM.MyDateTime)

If I can store the result of the comparison to a variable, I can take this value and compare it to another value.

Not sure why I keep getting the syntax error or how to fix this. Any help is appreciated by a newbie.

Body:
Not sure what you're expecting, the other date or the results of the comparison, but if you want only the result of comparing two dates, try:

case when (SELECT MAX(MyDateTime)
          FROM MyTable
          WHERE MyId = MM.MyId) = MM.MyDateTime
then 1 else 0 end as isMaxMyDT_eq_myDT


问:
What is a simple way to show an MvxDialogFragment?
I am trying to use an MvxDialogFragment to show a data bound dialog from an activity.  My Dialog ViewModel is as follows:

```<code>public class ContainerDialogViewModel : MvxViewModel
{

    public string ShipperName;

    public void Init(string Name)
    {
        ShipperName = Name;
        LoadData();
    }

    public void LoadData()
    {
        Survey = SurveyDataSource.CurrSurvey;
    }

    private ShipmentSurvey _Survey;
    public ShipmentSurvey Survey
    {
        get
        {
            return _Survey;
        }
        set
        {
            _Survey = value;
            RaisePropertyChanged(() => Survey);
            RaisePropertyChanged(() => Containers);
        }
    }

    public List<ShipmentSurveyContainer> Containers
    {
        get
        {
            if (Survey == null)
                return new List<ShipmentSurveyContainer>();
            else
                return Survey.SurveyContainers.ToList();
        }
    }

}
</code>```

The MvxDialogFragment is coded as follows:

```<code>public class ContainerDialog : MvxDialogFragment<ContainerDialogViewModel>
{
    public override Dialog OnCreateDialog(Bundle savedState)
    {
        base.EnsureBindingContextSet(savedState);

        this.BindingInflate(Resource.Layout.ContainerDialog, null);

        return base.OnCreateDialog(savedState);
    }

}
</code>```

In my activity, I am trying to figure out the simplest way to launch the dialog.  Here is what I have tried:

```<code>public class SurveyView : MvxActivity
{
    public void ShowContainerDialog()
    {
        ContainerDialogViewModel vm = new ViewModels.ContainerDialogViewModel();
        vm.Init("Test Name");
        var dialogFragment = new ContainerDialog()
        {
            DataContext = vm
        };
        dialogFragment.Show(FragmentManager, "Containers");
    }
}
</code>```

I'm pretty sure my method of creating the view model is unorthodox, but I don't know another way to do it.  The biggest issue is that FragmentManager is cast to the wrong version.  Show is looking for an Android.Support.V4.App.FragmentManager and the FragmentManager that is exposed is an Android.App.FragmentManager.  I tried changing the MvxActivity to an MvxFragmentActivity, but this didn't seem to help.  Can someone point me in the right direction?

答:
MvvmCross didn't really support this when I was trying to do it, but I came across another instance where I needed this and alas, the functionality is there.  Thanks to @Martijn00 for pointing me at the solution.  This will be very basic, but I think it might help someone.

My Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
  <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      style="@style/TableHeaderTextView"
      android:text="Work Date"/>
  <MvxDatePicker
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="20dp"
    local:MvxBind="Value WorkDate" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Close"
        local:MvxBind="Click CloseCommand" />
</LinearLayout>
</code>```

My ViewModel:

```<code>public class HoursDateDialogViewModel : MvxViewModel<EstimateHours>
{
    private readonly IMvxNavigationService _navigationService;

    public HoursDateDialogViewModel(IMvxNavigationService navigationService)
    {
        _navigationService = navigationService;

        CloseCommand = new MvxAsyncCommand(async () => await _navigationService.Close(this));
    }

    public override System.Threading.Tasks.Task Initialize()
    {
        return base.Initialize();
    }

    public override void Prepare(EstimateHours parm)
    {
        base.Prepare();
        Hours = parm;
    }

    public IMvxAsyncCommand CloseCommand { get; private set; }

    private EstimateHours _Hours;
    public EstimateHours Hours
    {
        get
        {
            return _Hours;
                }
        set
        {
            _Hours = value;
            RaisePropertyChanged(() => Hours);
            RaisePropertyChanged(() => WorkDate);
        }
    }

    public DateTime WorkDate
    {
        get
        {
            return Hours.StartTime ?? DateTime.Today;
        }
        set
        {
            DateTime s = Hours.StartTime ?? DateTime.Today;
            DateTime d = new DateTime(value.Year, value.Month, value.Day, s.Hour, s.Minute, s.Second);
            Hours.StartTime = d;
            DateTime e = Hours.EndTime ?? DateTime.Today;
            d = new DateTime(value.Year, value.Month, value.Day, e.Hour, e.Minute, e.Second);
            Hours.EndTime = d;
            RaisePropertyChanged(() => WorkDate);
        }
    }

}
</code>```

My View:

```<code>[MvxDialogFragmentPresentation]
[Register(nameof(HoursDateDialogView))]
public class HoursDateDialogView : MvxDialogFragment<HoursDateDialogViewModel>
{
    public HoursDateDialogView()
    {
    }

    protected HoursDateDialogView(IntPtr javaReference, JniHandleOwnership transfer)
        : base(javaReference, transfer)
    {
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        var ignore = base.OnCreateView(inflater, container, savedInstanceState);

        var view = this.BindingInflate(Resource.Layout.HoursDateDialogView, null);

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

That's all there is to it.  I am able to pass a parameter object and bind part of the object to an MvxDatePicker.  In order to show this dialog, first in your Setup.cs, you need :

```<code>    protected override IMvxAndroidViewPresenter CreateViewPresenter()
    {
        return new MvxAppCompatViewPresenter(AndroidViewAssemblies);
    }
</code>```

In your viewmodel from which you will open the dialog, you need a constructor containing:

```<code>    private readonly IMvxNavigationService _navigationService;

    public LocalHourlyViewModel(IMvxNavigationService navigationService)
    {
        _navigationService = navigationService;
    }
</code>```

This injects the navigation service so you can work with it.  And finally, all you have to do to open the dialog is:

```<code>async () => await _navigationService.Navigate<HoursDateDialogViewModel, EstimateHours>(Item);
</code>```

I'm not even sure you have to await the call, but I was following the example.  You can see more examples at the link @Martijn00 provided:

https://github.com/MvvmCross/MvvmCross/tree/develop/TestProjects/Playground

Cheers!

Body:
I am trying to use an MvxDialogFragment to show a data bound dialog from an activity.  My Dialog ViewModel is as follows:

public class ContainerDialogViewModel : MvxViewModel
{

    public string ShipperName;

    public void Init(string Name)
    {
        ShipperName = Name;
        LoadData();
    }

    public void LoadData()
    {
        Survey = SurveyDataSource.CurrSurvey;
    }

    private ShipmentSurvey _Survey;
    public ShipmentSurvey Survey
    {
        get
        {
            return _Survey;
        }
        set
        {
            _Survey = value;
            RaisePropertyChanged(() => Survey);
            RaisePropertyChanged(() => Containers);
        }
    }

    public List<ShipmentSurveyContainer> Containers
    {
        get
        {
            if (Survey == null)
                return new List<ShipmentSurveyContainer>();
            else
                return Survey.SurveyContainers.ToList();
        }
    }

}

The MvxDialogFragment is coded as follows:

public class ContainerDialog : MvxDialogFragment<ContainerDialogViewModel>
{
    public override Dialog OnCreateDialog(Bundle savedState)
    {
        base.EnsureBindingContextSet(savedState);

        this.BindingInflate(Resource.Layout.ContainerDialog, null);

        return base.OnCreateDialog(savedState);
    }

}

In my activity, I am trying to figure out the simplest way to launch the dialog.  Here is what I have tried:

public class SurveyView : MvxActivity
{
    public void ShowContainerDialog()
    {
        ContainerDialogViewModel vm = new ViewModels.ContainerDialogViewModel();
        vm.Init("Test Name");
        var dialogFragment = new ContainerDialog()
        {
            DataContext = vm
        };
        dialogFragment.Show(FragmentManager, "Containers");
    }
}

I'm pretty sure my method of creating the view model is unorthodox, but I don't know another way to do it.  The biggest issue is that FragmentManager is cast to the wrong version.  Show is looking for an Android.Support.V4.App.FragmentManager and the FragmentManager that is exposed is an Android.App.FragmentManager.  I tried changing the MvxActivity to an MvxFragmentActivity, but this didn't seem to help.  Can someone point me in the right direction?

Body:
MvvmCross didn't really support this when I was trying to do it, but I came across another instance where I needed this and alas, the functionality is there.  Thanks to @Martijn00 for pointing me at the solution.  This will be very basic, but I think it might help someone.

My Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
  <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      style="@style/TableHeaderTextView"
      android:text="Work Date"/>
  <MvxDatePicker
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="20dp"
    local:MvxBind="Value WorkDate" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Close"
        local:MvxBind="Click CloseCommand" />
</LinearLayout>

My ViewModel:

public class HoursDateDialogViewModel : MvxViewModel<EstimateHours>
{
    private readonly IMvxNavigationService _navigationService;

    public HoursDateDialogViewModel(IMvxNavigationService navigationService)
    {
        _navigationService = navigationService;

        CloseCommand = new MvxAsyncCommand(async () => await _navigationService.Close(this));
    }

    public override System.Threading.Tasks.Task Initialize()
    {
        return base.Initialize();
    }

    public override void Prepare(EstimateHours parm)
    {
        base.Prepare();
        Hours = parm;
    }

    public IMvxAsyncCommand CloseCommand { get; private set; }

    private EstimateHours _Hours;
    public EstimateHours Hours
    {
        get
        {
            return _Hours;
                }
        set
        {
            _Hours = value;
            RaisePropertyChanged(() => Hours);
            RaisePropertyChanged(() => WorkDate);
        }
    }

    public DateTime WorkDate
    {
        get
        {
            return Hours.StartTime ?? DateTime.Today;
        }
        set
        {
            DateTime s = Hours.StartTime ?? DateTime.Today;
            DateTime d = new DateTime(value.Year, value.Month, value.Day, s.Hour, s.Minute, s.Second);
            Hours.StartTime = d;
            DateTime e = Hours.EndTime ?? DateTime.Today;
            d = new DateTime(value.Year, value.Month, value.Day, e.Hour, e.Minute, e.Second);
            Hours.EndTime = d;
            RaisePropertyChanged(() => WorkDate);
        }
    }

}

My View:

[MvxDialogFragmentPresentation]
[Register(nameof(HoursDateDialogView))]
public class HoursDateDialogView : MvxDialogFragment<HoursDateDialogViewModel>
{
    public HoursDateDialogView()
    {
    }

    protected HoursDateDialogView(IntPtr javaReference, JniHandleOwnership transfer)
        : base(javaReference, transfer)
    {
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        var ignore = base.OnCreateView(inflater, container, savedInstanceState);

        var view = this.BindingInflate(Resource.Layout.HoursDateDialogView, null);

        return view;
    }
}

That's all there is to it.  I am able to pass a parameter object and bind part of the object to an MvxDatePicker.  In order to show this dialog, first in your Setup.cs, you need :

    protected override IMvxAndroidViewPresenter CreateViewPresenter()
    {
        return new MvxAppCompatViewPresenter(AndroidViewAssemblies);
    }

In your viewmodel from which you will open the dialog, you need a constructor containing:

    private readonly IMvxNavigationService _navigationService;

    public LocalHourlyViewModel(IMvxNavigationService navigationService)
    {
        _navigationService = navigationService;
    }

This injects the navigation service so you can work with it.  And finally, all you have to do to open the dialog is:

async () => await _navigationService.Navigate<HoursDateDialogViewModel, EstimateHours>(Item);

I'm not even sure you have to await the call, but I was following the example.  You can see more examples at the link @Martijn00 provided:

https://github.com/MvvmCross/MvvmCross/tree/develop/TestProjects/Playground

Cheers!


问:
Formatting issue while exporting data to Excel using VBA macro
I am using below VBS code to export one chart (from QlikView) to excel.
Reason I am using Number format = ‘@’ and paste special because if I do not use it then values in the chart like ‘22001E-07’ gets converted to 2.20E-03

```<code>sub GPOTest1
set oXL=CreateObject("Excel.Application")
oXL.visible=True
oXL.Workbooks.Add
aSheetObj=Array("CH01")
for i=0 to UBound(aSheetObj)
oXL.Sheets.Add
Set oSH = oXL.ActiveSheet
oSH.Range("A1").Select
Set obj = ActiveDocument.GetSheetObject(aSheetObj(i))

obj.CopyTableToClipboard True
oSH.Columns("B").NumberFormat = "@" ‘In “B” column I get values like 22001E-07
oSH.PasteSpecial -4163

sCaption=obj.GetCaption.Name.v
set obj=Nothing
oSH.Rows("1:1").Select
oXL.Selection.Font.Bold = True
oSH.Cells.Select
oXL.Selection.Columns.AutoFit
oSH.Range("A1").Select
oSH.Name=left(sCaption,30)
set oSH=Nothing
next
set oXL=Nothing
end sub
</code>```

After running it for the first time, from 2nd time I get message

PasteSpecial method of Worksheet class failed

Referred following link, however, issue persists:
use macro to convert number format to text in Excel

答:
You shouldn't systematically create an Excel instance. Your code leaves Excel open. Once Excel is open, the next time around, you can get a reference to it using GetObject. See the approach taken in the code below, where I've also simplified a couple things:

```<code>Sub GPOTest1()
    On Error Resume Next
    Set oXL = CreateObject("Excel.Application")
    If oXL Is Nothing Then
        Set oXL = GetObject(Class:="Excel.Application")
    End If
    On Error GoTo 0

    oXL.Visible = True

    Set oWB = oXL.Workbooks.Add
    aSheetObj = Array("CH01")

    For i = 0 To UBound(aSheetObj)
        Set oSH = oWB.Sheets.Add

        Set obj = ActiveDocument.GetSheetObject(aSheetObj(i))
        obj.CopyTableToClipboard True

        oSH.Columns("B").NumberFormat = "@" 'In “B” column I get values like 22001E-07
        oSH.PasteSpecial -4163

        oSH.Rows("1:1").Font.Bold = True
        oSH.Columns.AutoFit
        oSH.Range("A1").Select
        oSH.Name = Left(obj.GetCaption.Name.v, 30)

        Set oSH = Nothing
        Set obj = Nothing
    Next

    Set oXL = Nothing
End Sub
</code>```

Body:
I am using below VBS code to export one chart (from QlikView) to excel.
Reason I am using Number format = ‘@’ and paste special because if I do not use it then values in the chart like ‘22001E-07’ gets converted to 2.20E-03

sub GPOTest1
set oXL=CreateObject("Excel.Application")
oXL.visible=True
oXL.Workbooks.Add
aSheetObj=Array("CH01")
for i=0 to UBound(aSheetObj)
oXL.Sheets.Add
Set oSH = oXL.ActiveSheet
oSH.Range("A1").Select
Set obj = ActiveDocument.GetSheetObject(aSheetObj(i))

obj.CopyTableToClipboard True
oSH.Columns("B").NumberFormat = "@" ‘In “B” column I get values like 22001E-07
oSH.PasteSpecial -4163

sCaption=obj.GetCaption.Name.v
set obj=Nothing
oSH.Rows("1:1").Select
oXL.Selection.Font.Bold = True
oSH.Cells.Select
oXL.Selection.Columns.AutoFit
oSH.Range("A1").Select
oSH.Name=left(sCaption,30)
set oSH=Nothing
next
set oXL=Nothing
end sub

After running it for the first time, from 2nd time I get message

PasteSpecial method of Worksheet class failed

Referred following link, however, issue persists:
use macro to convert number format to text in Excel

Body:
You shouldn't systematically create an Excel instance. Your code leaves Excel open. Once Excel is open, the next time around, you can get a reference to it using GetObject. See the approach taken in the code below, where I've also simplified a couple things:

Sub GPOTest1()
    On Error Resume Next
    Set oXL = CreateObject("Excel.Application")
    If oXL Is Nothing Then
        Set oXL = GetObject(Class:="Excel.Application")
    End If
    On Error GoTo 0

    oXL.Visible = True

    Set oWB = oXL.Workbooks.Add
    aSheetObj = Array("CH01")

    For i = 0 To UBound(aSheetObj)
        Set oSH = oWB.Sheets.Add

        Set obj = ActiveDocument.GetSheetObject(aSheetObj(i))
        obj.CopyTableToClipboard True

        oSH.Columns("B").NumberFormat = "@" 'In “B” column I get values like 22001E-07
        oSH.PasteSpecial -4163

        oSH.Rows("1:1").Font.Bold = True
        oSH.Columns.AutoFit
        oSH.Range("A1").Select
        oSH.Name = Left(obj.GetCaption.Name.v, 30)

        Set oSH = Nothing
        Set obj = Nothing
    Next

    Set oXL = Nothing
End Sub


问:
jQuery Cycle: Scroll back to the first slide after the last slide
I have a slider that looks like this:

```<code>$('#slider').cycle({
    fx: 'scrollHorz',
    speed: 1250,
    timeout: 5000,
    easing: 'easeInOutExpo',
    pager: '#slider-pagination',
    next: '#next-slide',
    prev: '#prev-slide',
    pause: 1
});
</code>```

By default, when it's on the last slide Cycle just scrolls to the left again to start over, as though it's an infinite loop. I want it to scroll back through all the slides and land on the first one again. Much like it does here (see the last slide): http://www.iconlicious.com/. I must use Cycle, so I can't use the same plugin as they are.

How can that be achieved?

Thanks

答:
Looking at your website, I can tell you already solved your problem, but I wanted to post this in case there were others who might find it valuable.

You used jquery.scrollable, which is a great solution and solved the same issue for me.

Body:
I have a slider that looks like this:

$('#slider').cycle({
    fx: 'scrollHorz',
    speed: 1250,
    timeout: 5000,
    easing: 'easeInOutExpo',
    pager: '#slider-pagination',
    next: '#next-slide',
    prev: '#prev-slide',
    pause: 1
});

By default, when it's on the last slide Cycle just scrolls to the left again to start over, as though it's an infinite loop. I want it to scroll back through all the slides and land on the first one again. Much like it does here (see the last slide): http://www.iconlicious.com/. I must use Cycle, so I can't use the same plugin as they are.

How can that be achieved?

Thanks


问:
MySQL - How to set to NOW() and NULL while inserting a row into a table?
```<code>INSERT INTO rental (rental_date, last_update, return_date)
    SET rental_date, last_update = NOW()
    AND return_date = NULL.
</code>```

I'm trying to insert rental_date, last_update and return_date into the table rental while also setting their timestamp to NOW() and NULL.

答:
You have to SELECT now(), you can't use a values clause:</p>

```<code>INSERT INTO rental
  (rental_date, last_update, return_date)
SELECT NOW(), NOW(), NULL;
</code>```

Body:
INSERT INTO rental (rental_date, last_update, return_date)
    SET rental_date, last_update = NOW()
    AND return_date = NULL.

I'm trying to insert rental_date, last_update and return_date into the table rental while also setting their timestamp to NOW() and NULL.

Body:
You have to SELECT now(), you can't use a values clause:

INSERT INTO rental
  (rental_date, last_update, return_date)
SELECT NOW(), NOW(), NULL;


问:
Close specific chrome profile using AutoHotkey
I am new to AHK and am trying to remap some of my keys to open and close certain applications on my pc to make my life easier. One of them is Google Chrome, I managed to open the profile I want of chrome but I am having trouble closing that specific profile. Below is what I have.

```<code>PgDn::
    Process, Exist, chrome.exe
If ErrorLevel <> 0
    Process, Close, chrome.exe
Else
    Run, "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1"
return
</code>```

This opens up the chrome to a profile I want but when I press the button again it closes any and every chrome window open. I understand that's because I close the chrome.exe process, I cannot figure out how to close that specific profile.

Ultimately what I want to do is when the Page Down key is pressed

```<code>If Chrome Profile 1 is not opened, open it.
If Chrome Profile 1 is minimized, maximize it.
and if Chrome Profile 1 is opened and maximized, close it.
</code>```

If someone could help I'd really appreciate it.

答:
If you want to toggle with the Page Down key (on the fysical keyboard),

You can use this autohotkey example code (AHK):

This code works on a Windows 10 System.

a - if Chrome browser is not running then run Chrome browser.

b - if Chrome browser is minimized then maximized it.

c - if Chrome browser is maximized then Close the Chrome Browser.

```<code>GroupAdd, Browser, ahk_class Chrome_WidgetWin_1 ; Chrome

; + = Shift
; ! = Alt
; ^ = Ctrl
; # = Win (Windows logo key)

a = 0 ; Empty

;a = 1 - Minimize
;a = 2 - Minimize to Maximize
;a = 3 - Close Chrome Browser

PgDn::
If Winactive("ahk_group Browser")
{

if (a=1)
{
sendinput #d ; if chrome browser is active then Minimize
a = 2
}else{

if (a=3)
{
sendinput !{F4} ; !=Alt (Alt+F4 = Close Chrome Browser)
}
}
} else {

if (a=2)
{
sendinput #d
sleep 250
sendinput !{Space}
sleep 250
sendinput x
a = 3
} else {
If Winexist("ahk_group Browser")
{
a = 1
} else {
Run, "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
a = 1
}
}
}
return
</code>```

Tip: If you use Autohotkey together with Buttoncommander Software Click Here

You can then make on your Screen Clickable Images with autohotkey commands - for example [Page Down Picture key] + [if you remove the codeline PgDn:: you can use The same Autohotkey script]
Push it with your Mouse or Touch Device and it will toggle.

Body:
I am new to AHK and am trying to remap some of my keys to open and close certain applications on my pc to make my life easier. One of them is Google Chrome, I managed to open the profile I want of chrome but I am having trouble closing that specific profile. Below is what I have.

PgDn::
    Process, Exist, chrome.exe
If ErrorLevel <> 0
    Process, Close, chrome.exe
Else
    Run, "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1"
return

This opens up the chrome to a profile I want but when I press the button again it closes any and every chrome window open. I understand that's because I close the chrome.exe process, I cannot figure out how to close that specific profile.

Ultimately what I want to do is when the Page Down key is pressed

If Chrome Profile 1 is not opened, open it.
If Chrome Profile 1 is minimized, maximize it.
and if Chrome Profile 1 is opened and maximized, close it.

If someone could help I'd really appreciate it.

Body:
If you want to toggle with the Page Down key (on the fysical keyboard),

You can use this autohotkey example code (AHK):

This code works on a Windows 10 System.

a - if Chrome browser is not running then run Chrome browser.

b - if Chrome browser is minimized then maximized it.

c - if Chrome browser is maximized then Close the Chrome Browser.

GroupAdd, Browser, ahk_class Chrome_WidgetWin_1 ; Chrome

; + = Shift
; ! = Alt
; ^ = Ctrl
; # = Win (Windows logo key)

a = 0 ; Empty

;a = 1 - Minimize
;a = 2 - Minimize to Maximize
;a = 3 - Close Chrome Browser

PgDn::
If Winactive("ahk_group Browser")
{

if (a=1)
{
sendinput #d ; if chrome browser is active then Minimize
a = 2
}else{

if (a=3)
{
sendinput !{F4} ; !=Alt (Alt+F4 = Close Chrome Browser)
}
}
} else {

if (a=2)
{
sendinput #d
sleep 250
sendinput !{Space}
sleep 250
sendinput x
a = 3
} else {
If Winexist("ahk_group Browser")
{
a = 1
} else {
Run, "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
a = 1
}
}
}
return

Tip: If you use Autohotkey together with Buttoncommander Software Click Here

You can then make on your Screen Clickable Images with autohotkey commands - for example [Page Down Picture key] + [if you remove the codeline PgDn:: you can use The same Autohotkey script]
Push it with your Mouse or Touch Device and it will toggle.


问:
Error implementing Vimeo-networking
I have tried many different ways of getting Vimeo networking into my app, but nothing has worked. If I remove the implementation it works just fine so I know this is the issue.
compile 'com.vimeo.networking:vimeo-networking:1.1.1'

gives me this error

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  > java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

I have searched all over and have yet to find a solution (yes I have tried cleaning and rebuilding the project)

答:
I believe this is the result of the vimeo-networking library including a dependency which you are also separately including in your gradle file. Looking at the gradle file for a hint, a prime suspect is the intellij annotations jar 'com.intellij:annotations:12.0@jar' dependency, which I have seen cause similar problems when also included in your main project as well as a sub-projects.

The solution to this is to exclude the annotations jar when compiling in the vimeo-networking library as follows:

```<code>compile ('com.vimeo.networking:vimeo-networking:1.1.1') {
    exclude group: 'org.jetbrains', module: 'annotations'
}
</code>```

Try this and see if it fixes your build exception. Generally I've seen that the cause for the Unable to merge dex error is that there are multiple definitions of the same class in the final dex file, usually resulting from the inclusion of a jar file multiple times.

Title: Error implementing Vimeo-networking

Body:
I believe this is the result of the vimeo-networking library including a dependency which you are also separately including in your gradle file. Looking at the gradle file for a hint, a prime suspect is the intellij annotations jar 'com.intellij:annotations:12.0@jar' dependency, which I have seen cause similar problems when also included in your main project as well as a sub-projects.

The solution to this is to exclude the annotations jar when compiling in the vimeo-networking library as follows:

compile ('com.vimeo.networking:vimeo-networking:1.1.1') {
    exclude group: 'org.jetbrains', module: 'annotations'
}

Try this and see if it fixes your build exception. Generally I've seen that the cause for the Unable to merge dex error is that there are multiple definitions of the same class in the final dex file, usually resulting from the inclusion of a jar file multiple times.


问:
Single Quote Params vs No Quote Params?
This is something that's been mind boggling to me for a while, some times I see people writing javascript objects like so with single quote params:

```<code>{
    'name': 'Teddy',
    'last': 'Monster'
}
</code>```

But then I also see the more common, no quote params:

```<code>{
    name: 'Teddy',
    last: 'Monster'
}
</code>```

Is there a reason one would use single quote params?
Is it faster to parse?

From what I can see, there is no speed difference, rather just cluttering the file with unnecessary quotes and increasing file size.

I'll change my mind if I can get a straight answer :)

答: Technically the second form is invalid according to the JSON spec, but it works fine in all mainstream Javascript engines.</p>

Title: Single Quote Params vs No Quote Params?

Body:
This is something that's been mind boggling to me for a while, some times I see people writing javascript objects like so with single quote params:

{
    'name': 'Teddy',
    'last': 'Monster'
}

But then I also see the more common, no quote params:

{
    name: 'Teddy',
    last: 'Monster'
}

Is there a reason one would use single quote params?
Is it faster to parse?

From what I can see, there is no speed difference, rather just cluttering the file with unnecessary quotes and increasing file size.

I'll change my mind if I can get a straight answer :)


问:
How to read the logs of a different app?
My application A works with application B already on the playstore.
Both applications read and write to the same database but application B keeps presenting problems when application A wants to work together and just shows the message:

Unfortunately application B has stopped

I don't have access to application's B source code but I need to see what is happening.

Is it possible to read the logs on application B?

I have 2 rooted android devices, one with android-6.0-marshmallow and the other one with android-8.0-oreo.

答:
You can use ADB to view the logs on a rooted phone.

This page has a fairly complete description of how to do that.

The short version.  Run a shell on the device using the adb shell command then navigate using the limited set of linux commands that are available.


问:
GLES: FrameBuffer object showing weird images

I'm currently trying to get FBOs working in my game using Android Studio.

I've already managed to set up an FBO and to draw a filled white rectangle (64x64px) to it.

But when I'm trying to render the FBO's color buffer onto the screen,
random noise and weird images appear.

Snapshot of the weird images which the FBO is producing

I neither know why my solid colored rectangle isn't showing up nor why
there is a profile picture of a Whatsapp chat, which isn't intended to be so.

This is how I initialize my FrameBuffer object:

```<code>private void initFrameBuffer() {

    int[] temp = new int[1];

    //Create a texture object and bind it. This will be the color buffer.
    glGenTextures(1, temp, 0);
    colorTexture = temp[0];

    glBindTexture(GL_TEXTURE_2D, colorTexture);

    //Set parameters. We're probably using non-power-of-two (NPOT) dimensions,
    //so some values may not be available for use!
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    //Create a texture storage:
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, null);

    //Create framebuffer object and bind it.
    glGenBuffers(1, temp, 0);
    frameBufferID = temp[0];
    glBindFramebuffer(GL_FRAMEBUFFER, frameBufferID);

    //Create a depth buffer and bind it.
    glGenRenderbuffers(1, temp, 0);
    depthBuffer = temp[0];

    glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer);

    //Allocate storage for the depth buffer.
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height);

    //Attach the depth buffer and the texture (color buffer) to the framebuffer object.
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
            GL_TEXTURE_2D, colorTexture, 0);

    //Check if GL ES is happy with all this ... :)
    int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if (status != GL_FRAMEBUFFER_COMPLETE) {
        throw new RuntimeException("Framebuffer not complete! StatusID: " + status);
    }

    //Switch back to the default framebuffer.
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
</code>```

How I'm drawing the whole scenery:

```<code>@Override
public void draw() {
    GLES20.glBindFramebuffer(GL_FRAMEBUFFER, frameBufferObject.getID());
        Graphics.setColor(new Color(255, 255, 255));
        Graphics.fillRect(0, 0, 64, 64);
    GLES20.glBindFramebuffer(GL_FRAMEBUFFER, 0);

    Graphics.drawFrameBuffer(frameBufferObject, 0, 0, frameBufferObject.getWidth(), frameBufferObject.getHeight());
}
</code>```

Last but not least, this is how I draw the FBO's color buffer to the screen using a simple shader program:

```<code>public static void drawFrameBuffer(FrameBufferObject frameBufferObject, int x, int y, int w, int h) {

    ImageMesh mesh = new ImageMesh(generateMesh(x, y, w, h));

    imageShader.start();

    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, frameBufferObject.getColorTexture());
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);

    //Enable generic vertex attribute array
    GLES20.glEnableVertexAttribArray(imageShader.positionHandle);

    //Prepare triangle coordinate data
    GLES20.glVertexAttribPointer(imageShader.positionHandle, 3, GLES20.GL_FLOAT, false, 0, mesh.baseMesh.vertexBuffer);

    //Enable generic vertex attribute array
    GLES20.glEnableVertexAttribArray(imageShader.texCoordLocation);

    //Prepare the textureCoordinates
    GLES20.glVertexAttribPointer(imageShader.texCoordLocation, 2, GLES20.GL_FLOAT, false, 0, mesh.uvBuffer);

    //Apply the projection and view transformation
    GLES20.glUniformMatrix4fv(imageShader.mtrxHandle, 1, false, Renderer.getUMVPMatrix(), 0);

    //Set the sampler texture unit to 0
    GLES20.glUniform1i(imageShader.samplerLoc, 0);

    //Draw the triangles
    GLES20.glDrawElements(GLES20.GL_TRIANGLES, mesh.baseMesh.indices.length, GLES20.GL_UNSIGNED_SHORT, mesh.baseMesh.drawListBuffer);

    //Disable vertex arrays
    GLES20.glDisableVertexAttribArray(imageShader.positionHandle);
    GLES20.glDisableVertexAttribArray(imageShader.texCoordLocation);

    //Unbind the texture
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);

    imageShader.stop();
}
</code>```

The Android API-Level I'm using is 22.
Also, the FBO I've created fits the screen size exactly,
which is 720x1280px.

This problem wasted a whole day of mine,
and I'm have no idea what could be causing this problem!

I'm really grateful for any kind of help! <3

答:
After a few hours I finally managed to get it working though!

The main reason for the error was, that I haven't set up my FBO correctly,
which resulted in this glitchy image.

So I watched an OpenGL tutorial by ThinMatrix tutorial on Youtube, and he was able to get me out of this bad situation. :)

Here's my updated FrameBuffer Object code:

```<code>public class FrameBufferObject {

private int width;
private int height;

private int frameBufferID;
private int texture;
private int depthTexture;
private int depthBuffer;

private Matrices.MatrixKit previousMatrixKit;

public FrameBufferObject(int width, int height) {
    this.width = width;
    this.height = height;

    initFrameBuffer();
}

private void initFrameBuffer() {

    frameBufferID = createFrameBuffer();
    texture = createTextureAttachment();
    depthTexture = createDepthTextureAttachment(width, height);
    depthBuffer = createDepthBufferAttachment();

    int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if (status != GL_FRAMEBUFFER_COMPLETE) {
        Logger.error("Framebuffer not Complete! STATUS: " + status + "\nWidth: " + width + "\nHeight: " + height);
    }

    glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

private int createFrameBuffer() {
    int[] ids = new int[1];
    glGenFramebuffers(1, ids, 0);
    int frameBufferID = ids[0];
    glBindFramebuffer(GL_FRAMEBUFFER, frameBufferID);

    int[] buffers = new int[] {GL_COLOR_ATTACHMENT0};

    GLES30.glDrawBuffers(1, buffers, 0);
    return frameBufferID;
}

private int createTextureAttachment() {
    int[] ids = new int[1];
    glGenTextures(1, ids, 0);
    int colorTexture = ids[0];

    glBindTexture(GL_TEXTURE_2D, colorTexture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, null);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture, 0);
    return colorTexture;
}

private int createDepthTextureAttachment(int width, int height) {
    int[] ids = new int[1];
    glGenTextures(1, ids, 0);
    int depthTextureID = ids[0];

    glBindTexture(GL_TEXTURE_2D, depthTextureID);
    //glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, null);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, null);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTextureID, 0);
    return depthTextureID;
}

private int createDepthBufferAttachment() {
    int[] ids = new int[1];
    glGenBuffers(1, ids, 0);
    int depthBuffer = ids[0];

    glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer);
    return depthBuffer;
}

public int getColorTexture() {
    return this.texture;
}

public void bindFrameBuffer() {
    glBindTexture(GL_TEXTURE_2D, 0); //just make sure the texture isn't bound
    glBindFramebuffer(GL_FRAMEBUFFER, frameBufferID);
    glViewport(0, 0, width, height);

    previousMatrixKit = Renderer.getMatrices();
    Renderer.setMatrixKit(Matrices.createMatrixKit(width, height));
}

public void unbindFrameBuffer() {
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glViewport(0, 0, previousMatrixKit.width, previousMatrixKit.height);

    Renderer.setMatrixKit(previousMatrixKit);
}

public int getWidth() {
    return this.width;
}

public int getHeight() {
    return this.height;
}

public int getID() {
    return this.frameBufferID;
}
}
</code>```

Body:
I'm currently trying to get FBOs working in my game using Android Studio.

I've already managed to set up an FBO and to draw a filled white rectangle (64x64px) to it.

But when I'm trying to render the FBO's color buffer onto the screen,
random noise and weird images appear.

Snapshot of the weird images which the FBO is producing

I neither know why my solid colored rectangle isn't showing up nor why
there is a profile picture of a Whatsapp chat, which isn't intended to be so.

This is how I initialize my FrameBuffer object:

private void initFrameBuffer() {

    int[] temp = new int[1];

    //Create a texture object and bind it. This will be the color buffer.
    glGenTextures(1, temp, 0);
    colorTexture = temp[0];

    glBindTexture(GL_TEXTURE_2D, colorTexture);

    //Set parameters. We're probably using non-power-of-two (NPOT) dimensions,
    //so some values may not be available for use!
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    //Create a texture storage:
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, null);

    //Create framebuffer object and bind it.
    glGenBuffers(1, temp, 0);
    frameBufferID = temp[0];
    glBindFramebuffer(GL_FRAMEBUFFER, frameBufferID);

    //Create a depth buffer and bind it.
    glGenRenderbuffers(1, temp, 0);
    depthBuffer = temp[0];

    glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer);

    //Allocate storage for the depth buffer.
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height);

    //Attach the depth buffer and the texture (color buffer) to the framebuffer object.
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
            GL_TEXTURE_2D, colorTexture, 0);

    //Check if GL ES is happy with all this ... :)
    int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if (status != GL_FRAMEBUFFER_COMPLETE) {
        throw new RuntimeException("Framebuffer not complete! StatusID: " + status);
    }

    //Switch back to the default framebuffer.
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

How I'm drawing the whole scenery:

@Override
public void draw() {
    GLES20.glBindFramebuffer(GL_FRAMEBUFFER, frameBufferObject.getID());
        Graphics.setColor(new Color(255, 255, 255));
        Graphics.fillRect(0, 0, 64, 64);
    GLES20.glBindFramebuffer(GL_FRAMEBUFFER, 0);

    Graphics.drawFrameBuffer(frameBufferObject, 0, 0, frameBufferObject.getWidth(), frameBufferObject.getHeight());
}

Last but not least, this is how I draw the FBO's color buffer to the screen using a simple shader program:

public static void drawFrameBuffer(FrameBufferObject frameBufferObject, int x, int y, int w, int h) {

    ImageMesh mesh = new ImageMesh(generateMesh(x, y, w, h));

    imageShader.start();

    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, frameBufferObject.getColorTexture());
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);

    //Enable generic vertex attribute array
    GLES20.glEnableVertexAttribArray(imageShader.positionHandle);

    //Prepare triangle coordinate data
    GLES20.glVertexAttribPointer(imageShader.positionHandle, 3, GLES20.GL_FLOAT, false, 0, mesh.baseMesh.vertexBuffer);

    //Enable generic vertex attribute array
    GLES20.glEnableVertexAttribArray(imageShader.texCoordLocation);

    //Prepare the textureCoordinates
    GLES20.glVertexAttribPointer(imageShader.texCoordLocation, 2, GLES20.GL_FLOAT, false, 0, mesh.uvBuffer);

    //Apply the projection and view transformation
    GLES20.glUniformMatrix4fv(imageShader.mtrxHandle, 1, false, Renderer.getUMVPMatrix(), 0);

    //Set the sampler texture unit to 0
    GLES20.glUniform1i(imageShader.samplerLoc, 0);

    //Draw the triangles
    GLES20.glDrawElements(GLES20.GL_TRIANGLES, mesh.baseMesh.indices.length, GLES20.GL_UNSIGNED_SHORT, mesh.baseMesh.drawListBuffer);

    //Disable vertex arrays
    GLES20.glDisableVertexAttribArray(imageShader.positionHandle);
    GLES20.glDisableVertexAttribArray(imageShader.texCoordLocation);

    //Unbind the texture
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);

    imageShader.stop();
}

The Android API-Level I'm using is 22.
Also, the FBO I've created fits the screen size exactly,
which is 720x1280px.

This problem wasted a whole day of mine,
and I'm have no idea what could be causing this problem!

I'm really grateful for any kind of help! <3

Body:
After a few hours I finally managed to get it working though!

The main reason for the error was, that I haven't set up my FBO correctly,
which resulted in this glitchy image.

So I watched an OpenGL tutorial by ThinMatrix tutorial on Youtube, and he was able to get me out of this bad situation. :)

Here's my updated FrameBuffer Object code:

public class FrameBufferObject {

private int width;
private int height;

private int frameBufferID;
private int texture;
private int depthTexture;
private int depthBuffer;

private Matrices.MatrixKit previousMatrixKit;

public FrameBufferObject(int width, int height) {
    this.width = width;
    this.height = height;

    initFrameBuffer();
}

private void initFrameBuffer() {

    frameBufferID = createFrameBuffer();
    texture = createTextureAttachment();
    depthTexture = createDepthTextureAttachment(width, height);
    depthBuffer = createDepthBufferAttachment();

    int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if (status != GL_FRAMEBUFFER_COMPLETE) {
        Logger.error("Framebuffer not Complete! STATUS: " + status + "\nWidth: " + width + "\nHeight: " + height);
    }

    glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

private int createFrameBuffer() {
    int[] ids = new int[1];
    glGenFramebuffers(1, ids, 0);
    int frameBufferID = ids[0];
    glBindFramebuffer(GL_FRAMEBUFFER, frameBufferID);

    int[] buffers = new int[] {GL_COLOR_ATTACHMENT0};

    GLES30.glDrawBuffers(1, buffers, 0);
    return frameBufferID;
}

private int createTextureAttachment() {
    int[] ids = new int[1];
    glGenTextures(1, ids, 0);
    int colorTexture = ids[0];

    glBindTexture(GL_TEXTURE_2D, colorTexture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, null);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture, 0);
    return colorTexture;
}

private int createDepthTextureAttachment(int width, int height) {
    int[] ids = new int[1];
    glGenTextures(1, ids, 0);
    int depthTextureID = ids[0];

    glBindTexture(GL_TEXTURE_2D, depthTextureID);
    //glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, null);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, null);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTextureID, 0);
    return depthTextureID;
}

private int createDepthBufferAttachment() {
    int[] ids = new int[1];
    glGenBuffers(1, ids, 0);
    int depthBuffer = ids[0];

    glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer);
    return depthBuffer;
}

public int getColorTexture() {
    return this.texture;
}

public void bindFrameBuffer() {
    glBindTexture(GL_TEXTURE_2D, 0); //just make sure the texture isn't bound
    glBindFramebuffer(GL_FRAMEBUFFER, frameBufferID);
    glViewport(0, 0, width, height);

    previousMatrixKit = Renderer.getMatrices();
    Renderer.setMatrixKit(Matrices.createMatrixKit(width, height));
}

public void unbindFrameBuffer() {
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glViewport(0, 0, previousMatrixKit.width, previousMatrixKit.height);

    Renderer.setMatrixKit(previousMatrixKit);
}

public int getWidth() {
    return this.width;
}

public int getHeight() {
    return this.height;
}

public int getID() {
    return this.frameBufferID;
}
}


问:
Python - Django query using auth.User model as OneToOneField
I am using the auth.User model for login info, and a custom UserProfile model for all of a user's profile data.

The auth.User.username is a random string.
and the UserProfile.user is the same string.

When attempting to query the database table "UserProfile" I get the following error:

```<code>ValueError: invalid literal for int() with base 10: '3df69698-c97d-11e7-a924-b0c0905e8512'
</code>```

models.py

```<code>from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=256, default=None)
    last_name = models.CharField(max_length=256, default=None)
    ...

    def __str__(self):
        return str(self.user)
</code>```

views.py

```<code>from .models import UserProfile
from django.contrib.auth.models import User

def get_users(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = escape(data['id'])

    # error occurs here
    user_pref = UserProfile.objects.get(user=user_id)
</code>```

The problem comes when trying to query the database, and using a string compared to an auth.User object. I do not know how to get around this?

答:
Maybe this:</p>

```<code>UserProfile.objects.get(user__user_id=user_id)
</code>```

Body:
I am using the auth.User model for login info, and a custom UserProfile model for all of a user's profile data.

The auth.User.username is a random string.
and the UserProfile.user is the same string.

When attempting to query the database table "UserProfile" I get the following error:

ValueError: invalid literal for int() with base 10: '3df69698-c97d-11e7-a924-b0c0905e8512'

models.py

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=256, default=None)
    last_name = models.CharField(max_length=256, default=None)
    ...

    def __str__(self):
        return str(self.user)

views.py

from .models import UserProfile
from django.contrib.auth.models import User

def get_users(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = escape(data['id'])

    # error occurs here
    user_pref = UserProfile.objects.get(user=user_id)

The problem comes when trying to query the database, and using a string compared to an auth.User object. I do not know how to get around this?

Body:
Maybe this:

UserProfile.objects.get(user__user_id=user_id)


问:
Amazon SSO with Microsoft Active Directory on Premises
I need to design SSO solution for different applications in an organization. The current Identity provider is AD on-premises. Here is what I have

Different Microservices are hosted on mulitple AWS EC2

Front End application implemented using Angular2

Authentication Service: which validates the users credentials against an Identity provider and generates a jwt

Authorization service: check the user rights

Here is required behavior:

The Authentication service is responsible of checking if the
credentials are valid against AD and then issue a JWT.

The Authorization service is responsible of checking if the user has the required permissions to access specific resource (another micro-service or viewing a page)

If I am using Azure I would do the following:

"Azure AD Connect" to sync the users between AD on Premises & "Azure AD"

"Azure AD" will serve as Identity Provider

When the users login to one of the applications, Azure AD will verify user's identity and sends him JWT

JWT will be used to check the user privileges and make subsequent calls to other microservices

What type of services should I use for Amazon to generate JWT?

答:
The logical choice for Amazon is Cognito Federated Identities which supports Active Directory, specifically ADFS, as an identity provider via SAML integration. After authentication, Cognito returns a JWT token which is then exchanged for Amazon credentials (authorization).

Amazon Cognito Federated Identities


问:
ngx-bootstrap - tabs Angular 4 - Router navigate
i have one problem , in my tabs with router, only clicking right on the link works. if you click below or around the link the tab switches but the route does not. and this view the tab is blank, i view that in link the router is ok , but around of tab is a event javascript.

```<code><tabset >
    <tab>
        <ng-template tabHeading>
                <a class="routing_link" [routerLink]="['/VariablesParamCrear']" >Asociar</a>
        </ng-template>
    </tab>
    <tab [active]="tabset" >
        <ng-template tabHeading>
            <a class="routing_link" [routerLink]="['/VariablesParamCrear']">Crear</a>
        </ng-template>
        <h1>Hola putitos</h1>
    </tab>
    <tab>
        <ng-template tabHeading>
                <a class="routing_link" [routerLink]="['/VariablesOrder']">Ordenar</a>
        </ng-template>
    </tab>
    <tab>
        <ng-template tabHeading>
                <a class="routing_link" [routerLink]="['/VariablesFilter']">Filtrar</a>
        </ng-template>
    </tab>
</code>```

答:
Try putting a method in the component and call it on (click) on the tab itself, like this:

import {
  Component,
  OnInit
} from '@angular/core';
import {
  Router
} from '@angular/router';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.less']
})
export class MyComponentComponent implements OnInit {

  constructor(private router: Router) {}

  ngOnInit() {}

  goToLink(link: string): void {
    this.router.navigateByUrl(link);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><tabset>
  <tab (click)="goToLink('/VariablesParamCrear')">
    <ng-template tabHeading>
      Asociar
    </ng-template>
  </tab>
  <tab [active]="tabset" (click)="goToLink('/VariablesParamCrear')">
    <ng-template tabHeading>
      Crear
    </ng-template>
    <h1>Title</h1>
  </tab>
  <tab (click)="goToLink('/VariablesOrder')">
    <ng-template tabHeading>
      Ordenar
    </ng-template>
  </tab>
  <tab (click)="goToLink('/VariablesFilter')">
    <ng-template tabHeading>
      Filtrar
    </ng-template>
  </tab>
</tabset></code>```

Body:
i have one problem , in my tabs with router, only clicking right on the link works. if you click below or around the link the tab switches but the route does not. and this view the tab is blank, i view that in link the router is ok , but around of tab is a event javascript.

<tabset >
    <tab>
        <ng-template tabHeading>
                Asociar
        </ng-template>
    </tab>
    <tab [active]="tabset" >
        <ng-template tabHeading>
            Crear
        </ng-template>

Hola putitos

    </tab>
    <tab>
        <ng-template tabHeading>
                Ordenar
        </ng-template>
    </tab>
    <tab>
        <ng-template tabHeading>
                Filtrar
        </ng-template>
    </tab>

Body:
Try putting a method in the component and call it on (click) on the tab itself, like this:

import {
  Component,
  OnInit
} from '@angular/core';
import {
  Router
} from '@angular/router';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.less']
})
export class MyComponentComponent implements OnInit {

  constructor(private router: Router) {}

  ngOnInit() {}

  goToLink(link: string): void {
    this.router.navigateByUrl(link);
  }
}

<tabset>
  <tab (click)="goToLink('/VariablesParamCrear')">
    <ng-template tabHeading>
      Asociar
    </ng-template>
  </tab>
  <tab [active]="tabset" (click)="goToLink('/VariablesParamCrear')">
    <ng-template tabHeading>
      Crear
    </ng-template>
    <h1>Title</h1>
  </tab>
  <tab (click)="goToLink('/VariablesOrder')">
    <ng-template tabHeading>
      Ordenar
    </ng-template>
  </tab>
  <tab (click)="goToLink('/VariablesFilter')">
    <ng-template tabHeading>
      Filtrar
    </ng-template>
  </tab>
</tabset>


问:
Microseconds in PHP
I'm accessing an API that requires a timestamp to be in microseconds, I can print the value and it works it prints this:

```<code>1295308800
</code>```

So I figured I can multiply this by 1000 and then print this but when I print the query before I send it (using CURL) it prints this:

```<code>1.2953088E+12
</code>```

Can I use a different variable type or something?

Thanks!

答:
If you're sending the value in a way that PHP converts it to its exponent syntax (i.e. 1.2953088E+12) there's a nifty trick you can do using printf or sprintf in order to get the full number):

```<code>php -r '$date = 12434613435134661234; echo $date;'
1.2434613435135E+19

php -r '$date = 12434613435134661234; printf("%.0f", $date);'
12434613435134660608
</code>```

You can then use sprintf to just assign that number to a variable (as a string) and pass that into the remote API.

Note the lack of accuracy from converting the floating point number, though.

Edit:

I also want to point out that PHP's unsigned decimal numbers appear to be accurate up to 19 places. So, this returns the correct value:

```<code>php -r '$date = 6243461343513466123; printf("%u", $date);'
6243461343513466123
</code>```

When expressing that same value as a float, it loses its precision:

```<code>php -r '$date = 6243461343513466123; printf("%.0f", $date);'
6243461343513465856
</code>```

Title: Microseconds in PHP

Body:
I'm accessing an API that requires a timestamp to be in microseconds, I can print the value and it works it prints this:

1295308800

So I figured I can multiply this by 1000 and then print this but when I print the query before I send it (using CURL) it prints this:

1.2953088E+12

Can I use a different variable type or something?

Thanks!

Body:
If you're sending the value in a way that PHP converts it to its exponent syntax (i.e. 1.2953088E+12) there's a nifty trick you can do using printf or sprintf in order to get the full number):

php -r '$date = 12434613435134661234; echo $date;'
1.2434613435135E+19

php -r '$date = 12434613435134661234; printf("%.0f", $date);'
12434613435134660608

You can then use sprintf to just assign that number to a variable (as a string) and pass that into the remote API.

Note the lack of accuracy from converting the floating point number, though.

Edit:

I also want to point out that PHP's unsigned decimal numbers appear to be accurate up to 19 places. So, this returns the correct value:

php -r '$date = 6243461343513466123; printf("%u", $date);'
6243461343513466123

When expressing that same value as a float, it loses its precision:

php -r '$date = 6243461343513466123; printf("%.0f", $date);'
6243461343513465856


问:
Determing if a RewardedVideoAd is paused?
There are onVideoStart, onVideoOpen, and onVideoClosed-events.
Is there some way to get if the video is paused by the "Close video"-dialog?</p>

答:
It looks like AdMob doesn't have triggers on this event (on Video Paused). But if there isn't any super specific case I would stick with this callback void onRewarded(RewardItem reward) which is returned when a user gets through the ad and deserves the reward. Means he watched the whole video and you earned something.

Take a look here googleads-mobile-android-examples and Rewarded Video Ads. There it's perfectly explained. Good luck