问:
How to join two json path query in json path extractor of jmeter?
Let's say I have this popular data sample.

```<code>{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "color": "red",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "color": "blue",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}
</code>```

What I want from here is a all the book where category == fiction and all the bicycle where color == red.

That is, I want,

```<code>   {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "color": "red",
        "title": "Sword of Honour",
        "price": 12.99
    },
    {
        "category": "fiction",
        "author": "Herman Melville",
        "color": "blue",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
    },
    {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
    },
    "bicycle": {
         "color": "red",
         "price": 19.95
    }
</code>```

I know, I can use $.store.book[?(@.category == "fiction")] to achieve the targeted books and $.store.bicycle[?(@.color == 'red')] to achieve the targeted bicycle.

But how can I achieve both at one go?

答:
You can use && and || operators.

$.store.*[?(@.color== 'red' || @.category == 'fiction')]

will fetch the results as you wanted

Body:
Let's say I have this popular data sample.

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "color": "red",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "color": "blue",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

What I want from here is a all the book where category == fiction and all the bicycle where color == red.

That is, I want,

   {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "color": "red",
        "title": "Sword of Honour",
        "price": 12.99
    },
    {
        "category": "fiction",
        "author": "Herman Melville",
        "color": "blue",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
    },
    {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
    },
    "bicycle": {
         "color": "red",
         "price": 19.95
    }

I know, I can use $.store.book[?(@.category == "fiction")] to achieve the targeted books and $.store.bicycle[?(@.color == 'red')] to achieve the targeted bicycle.

But how can I achieve both at one go?


来源: stackexchange

问:
Registering asp:button click event handler
I have multiple asp:button that I created dynamically with jQuery.

For each of them, I have OnClick="ibtn_Click" .

But on the code behind, I have to manually register each one of them on Page_Load..like.. button.Click += new EventHandler(this.ibtn_Click); .

Is there a way I can register this handler automatically? Or is it possible to register it with ajax jquery?

Thanks!

答:
Is your purpose of generating dynamic asp.net buttons to call code behind?
you can generate html "Submit" button (type=submit) and call webMethods from javascript.
The webmethods are than redirected to you c# code behind</p>

ContentLicense: CC BY-SA 2.5


问:
How to count integer values stored in a variable using php?
I am developing a web form which have a field 'marks' where user can put marks... I want to force the user to  input only marks less then 4 digits. Here is function for this purpose but it is not working...

```<code>Function validate($marks)
If(strlen($marks)<=4 && !filter_var($marks, FILTER_VALIDATE_INT)
</code>```

)

```<code>Return false;
</code>```

Else

```<code>Return true ;
</code>```

答:
This can be achieved using only HTML5 input options (PHP is unnecessary for this application).

If your input is type="number" you can use min=-9999 max=9999 to limit the number to 4 digits.

If your input is type="text" you can use maxlength=4 to limit to 4 characters.

Here is a list of input types and options that might help: https://www.w3schools.com/tags/tag_input.asp

ContentLicense: CC BY-SA 3.0

Body:
I am developing a web form which have a field 'marks' where user can put marks... I want to force the user to  input only marks less then 4 digits. Here is function for this purpose but it is not working...

Function validate($marks)
If(strlen($marks)<=4 && !filter_var($marks, FILTER_VALIDATE_INT)

)

Return false;

Else

Return true ;


问:
converting outputStream to byte array
How can I get the bytes of an outputStream, or how can I convert an outputStream to a byte array?</p>

答:
For @Obicere comment example:</p>

```<code>ByteArrayOutputStream btOs = new ByteArrayOutputStream();
btOs.write("test bytes".getBytes());
String restoredString = new String(btOs.toByteArray());
System.out.println(restoredString);
</code>```

ContentLicense: CC BY-SA 4.0

Title: converting outputStream to byte array

Body:
For @Obicere comment example:

ByteArrayOutputStream btOs = new ByteArrayOutputStream();
btOs.write("test bytes".getBytes());
String restoredString = new String(btOs.toByteArray());
System.out.println(restoredString);


问:
Instigating CSS animation with Javascript
I currently have it so my titles slide in when the link is clicked.
How do I make it so that (when the link is clicked) the current title will slide out before the new one slides in?

This is the clicked event I have been using. It might be all wonky, I have been adding different things to it to try and get it to work.

```<code>// list of sections.  the first section contains only the h1.
var sections = document.querySelectorAll("section");

function hideSections() {
  for (var i = 0; i < sections.length; i++) {
    sections[i].className = "hidden";
  }
}

// list of links in the nav.
var links = document.querySelector("nav").querySelectorAll("a");

// add listeners to those links
for (var i = 0; i < links.length; i++) {
  links[i].addEventListener("click", clicked);
}

function clicked(event) {
  var target = document.querySelector('h2');
  target.className = "slideout";

  event.preventDefault();
  hideSections();

  var current = event.target.hash;
  // "show" appropriate selection, based on id from link
  document.querySelector(current).className = "";

  // modify URL to reflect current location
  location.hash = current;

  target.addEventListener("animationend", newfile);

  function newfile() {
    target.removeEventListener("animationend", newfile);
  }
  target.addEventListener("animationstart", newfile);

}

// when page loads...
hideSections();

if (location.hash == "") {
  sections[0].className = "";
} else {
  document.querySelector(location.hash).className = "";
}
</code>```

https://jsfiddle.net/yk7w2zt2/
Here is my full code.

答:
You need you delay showing the next section until after the h2 has slid off the screen.
See JSFiddle using setTimeout():

https://jsfiddle.net/w9uypaae/

Body:
I currently have it so my titles slide in when the link is clicked.
How do I make it so that (when the link is clicked) the current title will slide out before the new one slides in?

This is the clicked event I have been using. It might be all wonky, I have been adding different things to it to try and get it to work.

// list of sections.  the first section contains only the h1.
var sections = document.querySelectorAll("section");

function hideSections() {
  for (var i = 0; i < sections.length; i++) {
    sections[i].className = "hidden";
  }
}

// list of links in the nav.
var links = document.querySelector("nav").querySelectorAll("a");

// add listeners to those links
for (var i = 0; i < links.length; i++) {
  links[i].addEventListener("click", clicked);
}

function clicked(event) {
  var target = document.querySelector('h2');
  target.className = "slideout";

  event.preventDefault();
  hideSections();

  var current = event.target.hash;
  // "show" appropriate selection, based on id from link
  document.querySelector(current).className = "";

  // modify URL to reflect current location
  location.hash = current;

  target.addEventListener("animationend", newfile);

  function newfile() {
    target.removeEventListener("animationend", newfile);
  }
  target.addEventListener("animationstart", newfile);

}

// when page loads...
hideSections();

if (location.hash == "") {
  sections[0].className = "";
} else {
  document.querySelector(location.hash).className = "";
}

https://jsfiddle.net/yk7w2zt2/
Here is my full code.


问:
Detect Document Height Change
I'm trying to detect when my document height changes.  Once it does, I need to run a few functions to help organize my page layout.

I'm not looking for window.onresize.  I need the entire document, which is larger than the window.

How do I observe this change?

答:
You can use an absolute positioned iframe with zero width inside the element you want to monitor for height changes, and listen to resize events on its contentWindow.  For example:

HTML

```<code><body>
  Your content...
  <iframe class="height-change-listener" tabindex="-1"></iframe>
</body>
</code>```

CSS

```<code>body {
  position: relative;
}
.height-change-listener {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  height: 100%;
  width: 0;
  border: 0;
  background-color: transparent;
}
</code>```

JavaScript (using jQuery but could be adapted to pure JS)

```<code>$('.height-change-listener').each(function() {
  $(this.contentWindow).resize(function() {
    // Do something more useful
    console.log('doc height is ' + $(document).height());
  });
});
</code>```

If for whatever reason you have height:100% set on body you'll need find (or add) another container element to implement this on.  If you want to add the iframe dynamically you'll probably need to use the .load event to attach the contentWindow.resize listener.  If you want this to work in IE7 as well as browsers, you'll need to add the *zoom:1 hack to the container element and also listen to the 'proprietary' resize event on the  element itself (which will duplicate contentWindow.resize in IE8-10).

Here's a fiddle...

Title: Detect Document Height Change

Body:
You can use an absolute positioned iframe with zero width inside the element you want to monitor for height changes, and listen to resize events on its contentWindow.  For example:

HTML

<body>
  Your content...
  <iframe class="height-change-listener" tabindex="-1"></iframe>
</body>

CSS

body {
  position: relative;
}
.height-change-listener {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  height: 100%;
  width: 0;
  border: 0;
  background-color: transparent;
}

JavaScript (using jQuery but could be adapted to pure JS)

$('.height-change-listener').each(function() {
  $(this.contentWindow).resize(function() {
    // Do something more useful
    console.log('doc height is ' + $(document).height());
  });
});

If for whatever reason you have height:100% set on body you'll need find (or add) another container element to implement this on.  If you want to add the iframe dynamically you'll probably need to use the <iframe>.load event to attach the contentWindow.resize listener.  If you want this to work in IE7 as well as browsers, you'll need to add the *zoom:1 hack to the container element and also listen to the 'proprietary' resize event on the <iframe> element itself (which will duplicate contentWindow.resize in IE8-10).

Here's a fiddle...


问:
Setting KeystoneJS Date format
I can't seem to set the date format in my keystone JS blog and on other pages.

If I use {{ publishedDate }} in the template (I'm using handlebars) all is fine except that it gives me something like this: Thu Mar 23 2017 00:00:00 GMT+0000 (GMT Standard Time) which is obviously not fine.

```<code>{{ post.publishedDate.format('D MMMM') }}
{{ post._.publishedDate.format('D MMMM') }}
{{ publishedDate.format('D MMMM') }}
</code>```

All return an error as follows:
Parse error on line 18:
... post.publishedDate.format('D MMMM') }}<
-----------------------^
Expecting 'ID', got 'INVALID'

I've also tried changing things in the model:

```<code>publishedDate: { type: Types.Date, index: true, format: 'YYYY', dependsOn: { state: 'published' }},
</code>```

And numerous variations thereof. I've looked at the keystone documentation at: http://keystonejs.com/docs/database/#fieldtypes-date and have tried to implement what it says there but it's still not working.

This should actually be really simple and I'm sure it is - I just don't know how to do it(!)

Any help appreciated.

答:
Thanks Shea - help above and beyond the call of duty. Much appreciated ;-) Eventual solution (for anyone else interested) was - if running in a loop -  to create a virtual in the model as follows:

```<code>Post.schema.virtual('formattedDate').get(function () {
    return this._.publishedDate.format("D MMMM");
});
</code>```

and then, in the handlebars template use the following format:

```<code>{{formattedDate}}
</code>```

If not running in a loop can be done simply with:

{{_.publishedDate.format "D MMMM"}}

Title: Setting KeystoneJS Date format

Body:
I can't seem to set the date format in my keystone JS blog and on other pages.

If I use {{ publishedDate }} in the template (I'm using handlebars) all is fine except that it gives me something like this: Thu Mar 23 2017 00:00:00 GMT+0000 (GMT Standard Time) which is obviously not fine.

{{ post.publishedDate.format('D MMMM') }}
{{ post._.publishedDate.format('D MMMM') }}
{{ publishedDate.format('D MMMM') }}

All return an error as follows:
Parse error on line 18:
... post.publishedDate.format('D MMMM') }}<
-----------------------^
Expecting 'ID', got 'INVALID'

I've also tried changing things in the model:

publishedDate: { type: Types.Date, index: true, format: 'YYYY', dependsOn: { state: 'published' }},

And numerous variations thereof. I've looked at the keystone documentation at: http://keystonejs.com/docs/database/#fieldtypes-date and have tried to implement what it says there but it's still not working.

This should actually be really simple and I'm sure it is - I just don't know how to do it(!)

Any help appreciated.

Body:
Thanks Shea - help above and beyond the call of duty. Much appreciated ;-) Eventual solution (for anyone else interested) was - if running in a loop -  to create a virtual in the model as follows:

Post.schema.virtual('formattedDate').get(function () {
    return this._.publishedDate.format("D MMMM");
});

and then, in the handlebars template use the following format:

{{formattedDate}}

If not running in a loop can be done simply with:

{{_.publishedDate.format "D MMMM"}}


问:
Testing return value of AngularJS's .then() using Jasmine
This is my AngularJS:

```<code>self.fetch = {
 things: function() {
   return $http.get("/things/")
     .then(function(response) {
         return response.data;
   });
 }
};
</code>```

And this is my test:

```<code>it('fetch.things() should GET to /things/, success', function() {
    mockBackend.expectGET("/thingss/").respond({stuffs: 'stuffs'});

    var response = BaseService.fetch.things();

    mockBackend.flush();

    expect(response).toEqual({stuffs: 'stuffs'})
});
</code>```

And this is the error I get:

```<code>Expected Object({ $$state: Object({ status: 1, value: Object({ stuffs: 'stuffs' }) }) }) to equal Object({ stuffs: 'stuffs' }).
        at Object.<anonymous> (tests/test_base.js:28:26)
Chromium 53.0.2785 (Ubuntu 0.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.102 seChromium 53.0.2785 (Ubuntu 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.119 secs / 0.102 secs)
</code>```

What's that extra status: 1, stuff and where is it coming from?

答:
Try the following in your test;</p>

```<code>it('fetch.things() should GET to /things/, success', function() {
   mockBackend.expectGET("/things/").respond({stuffs: 'stuffs'});
   var p = BaseService.fetch.things();

   mockBackend.flush();

   p.then(function(response){
      expect(response.data).toEqual({stuffs: 'stuffs'})
   });

   $rootScope.digest();

   return p;
});
</code>```

Body:
This is my AngularJS:

self.fetch = {
 things: function() {
   return $http.get("/things/")
     .then(function(response) {
         return response.data;
   });
 }
};

And this is my test:

it('fetch.things() should GET to /things/, success', function() {
    mockBackend.expectGET("/thingss/").respond({stuffs: 'stuffs'});

    var response = BaseService.fetch.things();

    mockBackend.flush();

    expect(response).toEqual({stuffs: 'stuffs'})
});

And this is the error I get:

Expected Object({ $$state: Object({ status: 1, value: Object({ stuffs: 'stuffs' }) }) }) to equal Object({ stuffs: 'stuffs' }).
        at Object.<anonymous> (tests/test_base.js:28:26)
Chromium 53.0.2785 (Ubuntu 0.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.102 seChromium 53.0.2785 (Ubuntu 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.119 secs / 0.102 secs)

What's that extra status: 1, stuff and where is it coming from?

Body:
Try the following in your test;

it('fetch.things() should GET to /things/, success', function() {
   mockBackend.expectGET("/things/").respond({stuffs: 'stuffs'});
   var p = BaseService.fetch.things();

   mockBackend.flush();

   p.then(function(response){
      expect(response.data).toEqual({stuffs: 'stuffs'})
   });

   $rootScope.digest();

   return p;
});


问:
Replacing one url base with another in php
I'm trying to figure out how to replace one url base with another within php.

So a function that takes "http://www.website1.com/test" and replaces the "http://www.website1.com" to make it "http://www.website2.com/test" .

This is probably a very easy quick function but i'm having trouble finding the right str_replace() to get this done.

```<code><?php
$pre_replace = "http://www.website1.com/test";
$post_replace = str_replace(
  'http://www.website1.com',
  'http://www.website2.com',
  $pre_replace);
echo $post_replace;
?>
</code>```

isn't quite working for some reason

答:
Try:</p>

```<code><?php

   //----------------
   // Original base
   $pre_replace = 'http://www.website1.com/test';

   //----------------
   // New base
   echo $post_replace = str_replace('website1','website2',$pre_replace);
?>
</code>```

Body:
I'm trying to figure out how to replace one url base with another within php.

So a function that takes "http://www.website1.com/test" and replaces the "http://www.website1.com" to make it "http://www.website2.com/test" .

This is probably a very easy quick function but i'm having trouble finding the right str_replace() to get this done.

<?php
$pre_replace = "http://www.website1.com/test";
$post_replace = str_replace(
  'http://www.website1.com',
  'http://www.website2.com',
  $pre_replace);
echo $post_replace;
?>

isn't quite working for some reason

Body:
Try:

<?php

   //----------------
   // Original base
   $pre_replace = 'http://www.website1.com/test';

   //----------------
   // New base
   echo $post_replace = str_replace('website1','website2',$pre_replace);
?>


问:
How to duplicate image using BitmapData
I had a situation to duplicate an image with the help of bitmap data, below is the code i used to do the same, am I wrong anywhere, please help me.. Try drawing this image
http://i.stack.imgur.com/VCSoQ.png in the bmp format

```<code>private void button1_Click(object sender, EventArgs e)
{
Bitmap mask = Image.FromFile("../../Data/mask.bmp") as Bitmap;
BitmapData data = mask.LockBits(new Rectangle(0, 0, mask.Width, mask.Height), ImageLockMode.ReadWrite, mask.PixelFormat);
int bytes = Math.Abs(data.Stride) * mask.Height;
byte[] outPut = new byte[bytes];
Marshal.Copy(data.Scan0, outPut, 0, bytes);

Bitmap test = new Bitmap(mask.Width, mask.Height, mask.PixelFormat);
BitmapData testData = test.LockBits(new Rectangle(0, 0, test.Width, test.Height),
ImageLockMode.ReadWrite, test.PixelFormat);
Marshal.Copy(outPut, 0, testData.Scan0, bytes);
test.UnlockBits(testData);
test.Save("test.jpg");
}
</code>```

Thanks,
Suresh

答:
If you're willing to use P/Invoke, this can be done with a single copy.</p>

```<code>class MyClass
{
  [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
  public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);

  Bitmap _frame = null;
  BitmapData _dest = null;

  void Reinit( int width, int height, PixelFormat format )
  {
    if ( _frame != null )
    {
      _frame.Unlock(_dest);
      _frame.Dispose();
    }

    _frame = new Bitmap( width, height, format );
    _dest = _frame.LockBits( new Rectangle( 0, 0, _frame.Width, _frame.Height ), ImageLockMode.ReadWrite, _frame.PixelFormat );
  }

  void CloneBitmapData( BitmapData src )
  {
    if ( _dest == null || _dest.Width != src.Width || _dest.Height != src.Height )
      Reinit( src.Width, src.Height, src.PixelFormat );

    CopyMemory( _dest.Scan0, src.Scan0, (uint)(src.Stride * src.Height) );
  }
</code>```

Title: How to duplicate image using BitmapData

Body:
I had a situation to duplicate an image with the help of bitmap data, below is the code i used to do the same, am I wrong anywhere, please help me.. Try drawing this image
http://i.stack.imgur.com/VCSoQ.png in the bmp format

private void button1_Click(object sender, EventArgs e)
{
Bitmap mask = Image.FromFile("../../Data/mask.bmp") as Bitmap;
BitmapData data = mask.LockBits(new Rectangle(0, 0, mask.Width, mask.Height), ImageLockMode.ReadWrite, mask.PixelFormat);
int bytes = Math.Abs(data.Stride) * mask.Height;
byte[] outPut = new byte[bytes];
Marshal.Copy(data.Scan0, outPut, 0, bytes);

Bitmap test = new Bitmap(mask.Width, mask.Height, mask.PixelFormat);
BitmapData testData = test.LockBits(new Rectangle(0, 0, test.Width, test.Height),
ImageLockMode.ReadWrite, test.PixelFormat);
Marshal.Copy(outPut, 0, testData.Scan0, bytes);
test.UnlockBits(testData);
test.Save("test.jpg");
}

Thanks,
Suresh

Body:
If you're willing to use P/Invoke, this can be done with a single copy.

class MyClass
{
  [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
  public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);

  Bitmap _frame = null;
  BitmapData _dest = null;

  void Reinit( int width, int height, PixelFormat format )
  {
    if ( _frame != null )
    {
      _frame.Unlock(_dest);
      _frame.Dispose();
    }

    _frame = new Bitmap( width, height, format );
    _dest = _frame.LockBits( new Rectangle( 0, 0, _frame.Width, _frame.Height ), ImageLockMode.ReadWrite, _frame.PixelFormat );
  }

  void CloneBitmapData( BitmapData src )
  {
    if ( _dest == null || _dest.Width != src.Width || _dest.Height != src.Height )
      Reinit( src.Width, src.Height, src.PixelFormat );

    CopyMemory( _dest.Scan0, src.Scan0, (uint)(src.Stride * src.Height) );
  }


问:
Session keeps getting Error
On my index.php page I have this:

```<code>session_start();

if($_SESSION['logged_in']==true) {
   header("Location:home.php");
} else {
   header("Location:login.php");
}
</code>```

On my login page, whenever the user correctly inputs the username and password I wrote this:

```<code>$_SESSION['username']=$username;
</code>```

I used this as a reference to the future pages. But on my home.php, no matter what I do it keeps giving me this error:

```<code> Undefined variable: _SESSION in C:\xampp\htdocs\website\home.php on line 8
</code>```

The line 8 is:

```<code>$user= $_SESSION['username'];
</code>```

答: In home.php you must call session_start(); at the very beginning of the file too.

Title: Session keeps getting Error

Body:
On my index.php page I have this:

session_start();

if($_SESSION['logged_in']==true) {
   header("Location:home.php");
} else {
   header("Location:login.php");
}

On my login page, whenever the user correctly inputs the username and password I wrote this:

$_SESSION['username']=$username;

I used this as a reference to the future pages. But on my home.php, no matter what I do it keeps giving me this error:

 Undefined variable: _SESSION in C:\xampp\htdocs\website\home.php on line 8

The line 8 is:

$user= $_SESSION['username'];


问:
execute updates inside theano scan
```<code>rng = RandomStreams()

res, updates = th.map(lambda x: rng.binomial(),
                      T.arange(10))

final_res, final_updates = th.scan(lambda x: res,
                                   sequences=T.arange(10))
</code>```

Imagine that I want to implement some similar thing. The problem is that map uses RNG, so it has it's own nonblank updates to update RNG states. How can I force updates to be executed inside scan?

答:
According to scan source code docs:

        The function is expected to return two things. One is a list of
    outputs ordered in the same order as ``outputs_info``, with the
    difference that there should be only one output variable per
    output initial state (even if no tap value is used). Secondly
    `fn` should return an update dictionary (that tells how to
    update any shared variable after each iteration step). The
    dictionary can optionally be given as a list of tuples. There is
    no constraint on the order of these two list, ``fn`` can return
    either ``(outputs_list, update_dictionary)`` or
    ``(update_dictionary, outputs_list)`` or just one of the two (in
    case the other is empty).

Title: execute updates inside theano scan

Body:
rng = RandomStreams()

res, updates = th.map(lambda x: rng.binomial(),
                      T.arange(10))

final_res, final_updates = th.scan(lambda x: res,
                                   sequences=T.arange(10))

Imagine that I want to implement some similar thing. The problem is that map uses RNG, so it has it's own nonblank updates to update RNG states. How can I force updates to be executed inside scan?


答:
You need to call session_start() on each php file that is loaded.

Since php works by parsing each php file individually, you will have to have this at every page you have.

Title: Session keeps getting Error


答:
Use the maxlength attribute of the input tag.

e.g.

```<code><input type='text' maxlength='4' name='marks' />
</code>```

Depending on how you want to implement this, you can use javascript too, which will allow you to display some dynamic warning info when it is less than 4 digits.

Title: How to count integer values stored in a variable using php?

Body:
Use the maxlength attribute of the input tag.

e.g.

<input type='text' maxlength='4' name='marks' />

Depending on how you want to implement this, you can use javascript too, which will allow you to display some dynamic warning info when it is less than 4 digits.


问:
Apache Zeppelin with Spark Interpreter
I am currently exploring Zeppelin with Spark interpreter. Have a question?

Once i query all the required data using Spark interpreter where does it store for further action like group by, drill down etc. For every action does it except the spark job.

答:
The computation and storage of data is handled by Spark itself, refer to spark execution model for more details.
Link: https://spark.apache.org/docs/latest/programming-guide.html#performance-impact </p>

Title: Apache Zeppelin with Spark Interpreter


问:
.js scope program throwing error
I've looked into it and cannot figure out why this program is throwing an error in the console.

var laundryRoom = 'Basement';
var mailRoom = 'Room 1A';

function myApartment() {
  var mailBoxNumber = 'Box 3';
  var laundryRoom = 'In-unit';
  console.log('Mail box: ' + mailBoxNumber + ', Laundry:' + laundryRoom);
}

console.log('Laundry: ' + laundryRoom + ', Mail: ' + mailRoom);
console.log(myApartment());```
</div>
</div>
</p>

<p>Output:</p>

```Laundry: Basement, Mail: Room 1A
Mail box: Box 3, Laundry:In-unit
undefined
```

Everything seems fine until this last "undefined".

Any insight would be appreciated.

答: myApartment() doesn't return anything explicitly, so it implicitly returns undefined. Just call myApartment() directly, not console.log(myApartment());.

Title: .js scope program throwing error

Body:
I've looked into it and cannot figure out why this program is throwing an error in the console.

var laundryRoom = 'Basement';
var mailRoom = 'Room 1A';

function myApartment() {
  var mailBoxNumber = 'Box 3';
  var laundryRoom = 'In-unit';
  console.log('Mail box: ' + mailBoxNumber + ', Laundry:' + laundryRoom);
}

console.log('Laundry: ' + laundryRoom + ', Mail: ' + mailRoom);
console.log(myApartment());

Output:

Laundry: Basement, Mail: Room 1A
Mail box: Box 3, Laundry:In-unit
undefined

Everything seems fine until this last "undefined".

Any insight would be appreciated.


问:
SKActions not recognizing changes in certain values
I have 3 groups of sprites (EnemyGroups) and these groups are arranged in a specific sequence (one second delay for each). Please see the code:

EnemyGroup:

```<code>struct EnemyGroup    {
    var enemies : [Enemy]
    var isVisible : Bool
    var isStatic : Bool

    func setup   ()  {
    if isStatic {
        for enemy in enemies  {
            enemy.sprite.alpha = 1.0
            enemy.sprite.isUserInteractionEnabled = false

        }
        isVisible = true
    }
        }

    mutating func switchEnemiesON   ()  {
    if !isStatic {
    for enemy in enemies  {

        enemy.sprite.alpha = 1.0
        enemy.sprite.physicsBody?.categoryBitMask = enemyCategory
        enemy.sprite.physicsBody?.collisionBitMask = bombCategory

    }
    isVisible = true
    }
}

mutating func switchEnemiesOFF   ()  {
    if !isStatic {
        for enemy in enemies  {
        enemy.sprite.alpha = 0.0
        enemy.sprite.physicsBody?.collisionBitMask = 0
        enemy.sprite.physicsBody?.categoryBitMask = 0
    }

    isVisible = false
    }
}
</code>```

in GameScene:

```<code>   func groupActionSequence (enemyGroup: EnemyGroup)  {
    for enemy in enemyGroup.enemies {
    var enemyGroupWithAction = enemyGroup
    let groupSequence = SKAction.sequence([
        SKAction.run({ enemyGroupWithAction.switchEnemiesON() }),
        SKAction.wait(forDuration: showTime),
        SKAction.run({ enemyGroupWithAction.switchEnemiesOFF() }),
        SKAction.wait(forDuration: hideTime)
        ])

    let repeatGroupAction = SKAction.repeatForever(groupSequence)
    enemy.sprite.run(repeatGroupAction)
    }
}

func groupActionSequenceWithDelay (delayTime: TimeInterval, enemyGroup: EnemyGroup, groupKey: String)   {
    for enemy in enemyGroup.enemies {

        var group = enemyGroup
    let groupSequence = SKAction.sequence([
        SKAction.run({ group.setup() }),
        SKAction.wait(forDuration: delayTime),
        SKAction.run({ self.groupActionSequence(enemyGroup: enemyGroup) })
        ])

    enemy.sprite.run(groupSequence, withKey: groupKey)
    }
}
</code>```

setting actions for enemy groups:

```<code> groupActionSequenceWithDelay(delayTime: 0, enemyGroup: enemyGroup1, groupKey: "group1")
 groupActionSequenceWithDelay(delayTime: 1, enemyGroup: enemyGroup2, groupKey: "group2")
 groupActionSequenceWithDelay(delayTime: 2, enemyGroup: enemyGroup3, groupKey: "group3")
</code>```

I set enemyGroup1 and enemyGroup2 to have isStatic = false and enemyGroup3 to isStatic = true.
I changed enemyGroup1 and enemyGroup2 isStatic to true the actions still are still running on enemyGroup1 and enemyGroup2 as ifisStatic = false. How can I getswitchEnemiesOFF()andswitchEnemiesON()to recognize changes in the value ofisStatic`?
Also, I don't want to stop the actions because I want to keep the same sequence of each group having a one second difference in their running actions, that's why I protected some of the functions with if statements instead.

答:
Make EnemyGroup a class rather than a Struct.

Because it is a Struct, the enemyGroupWithAction variable captured in the run block closure is a copy of the one you received in parameter (which is also a copy of the one passed as parameter to the function).  Each of these copies have their own separate value (Struct is a value type) and live separately.   If enemyGroup was an object (class), only the reference would be captured (classes are reference types) and any modifications to is properties would affect the original object instance.

Body:
I have 3 groups of sprites (EnemyGroups) and these groups are arranged in a specific sequence (one second delay for each). Please see the code:

EnemyGroup:

struct EnemyGroup    {
    var enemies : [Enemy]
    var isVisible : Bool
    var isStatic : Bool

    func setup   ()  {
    if isStatic {
        for enemy in enemies  {
            enemy.sprite.alpha = 1.0
            enemy.sprite.isUserInteractionEnabled = false

        }
        isVisible = true
    }
        }

    mutating func switchEnemiesON   ()  {
    if !isStatic {
    for enemy in enemies  {

        enemy.sprite.alpha = 1.0
        enemy.sprite.physicsBody?.categoryBitMask = enemyCategory
        enemy.sprite.physicsBody?.collisionBitMask = bombCategory

    }
    isVisible = true
    }
}

mutating func switchEnemiesOFF   ()  {
    if !isStatic {
        for enemy in enemies  {
        enemy.sprite.alpha = 0.0
        enemy.sprite.physicsBody?.collisionBitMask = 0
        enemy.sprite.physicsBody?.categoryBitMask = 0
    }

    isVisible = false
    }
}

in GameScene:

   func groupActionSequence (enemyGroup: EnemyGroup)  {
    for enemy in enemyGroup.enemies {
    var enemyGroupWithAction = enemyGroup
    let groupSequence = SKAction.sequence([
        SKAction.run({ enemyGroupWithAction.switchEnemiesON() }),
        SKAction.wait(forDuration: showTime),
        SKAction.run({ enemyGroupWithAction.switchEnemiesOFF() }),
        SKAction.wait(forDuration: hideTime)
        ])

    let repeatGroupAction = SKAction.repeatForever(groupSequence)
    enemy.sprite.run(repeatGroupAction)
    }
}

func groupActionSequenceWithDelay (delayTime: TimeInterval, enemyGroup: EnemyGroup, groupKey: String)   {
    for enemy in enemyGroup.enemies {

        var group = enemyGroup
    let groupSequence = SKAction.sequence([
        SKAction.run({ group.setup() }),
        SKAction.wait(forDuration: delayTime),
        SKAction.run({ self.groupActionSequence(enemyGroup: enemyGroup) })
        ])

    enemy.sprite.run(groupSequence, withKey: groupKey)
    }
}

setting actions for enemy groups:

 groupActionSequenceWithDelay(delayTime: 0, enemyGroup: enemyGroup1, groupKey: "group1")
 groupActionSequenceWithDelay(delayTime: 1, enemyGroup: enemyGroup2, groupKey: "group2")
 groupActionSequenceWithDelay(delayTime: 2, enemyGroup: enemyGroup3, groupKey: "group3")

I set enemyGroup1 and enemyGroup2 to have isStatic = false and enemyGroup3 to isStatic = true.
I changed enemyGroup1 and enemyGroup2 isStatic to true the actions still are still running on enemyGroup1 and enemyGroup2 as ifisStatic = false. How can I getswitchEnemiesOFF()andswitchEnemiesON()to recognize changes in the value ofisStatic`?
Also, I don't want to stop the actions because I want to keep the same sequence of each group having a one second difference in their running actions, that's why I protected some of the functions with if statements instead.


问:
How to get exact answers instead of the whole document using Watson Discovery?
After testing the discovery service, it seems useless to me at least or I might be missing something.

When I query, it matches the document and returns the whole document. If my document is huge, then for all queries it returns the whole document matching the query text, which is useless.

Now Do I have to create a separate document for every query?

If that's the case, API.AI or WIT.AI is a better option.

Please clear me on what I am missing in here!

答:
Watson Discovery service allows cognitive search in hundreds of documents.
You can use the Watson Document Conversion service in order to automatically create granularity of PAUs (Possible Answer Units) for each document in JSON format. Then you can load the PAUs generated by the Watson Document Conversion in the Watson Discovery Service.
This way, Watson Discovery will return exact answers for your cognitive queries.</p>


问:
Apache Rewrite for Entire Subdomain
How would I go about rewriting :

proxmox.example.com
```

<p>
to
</p>

```example.com/forward/?url=proxmox.example.com
```

I am trying to do this on Ubuntu with Apache

Please let me know what Apache plugins are used.

Will this rewrite go into my VirtualHosts file? (/etc/apache2/sites-available)

Thanks for the help!

答:
You won't need a vhost for that. It can be put in the main Apache config.
Put this in your config:

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^(proxmox.(example.com))$
RewriteRule .* http://%2/forward/?url=%1 [R,L]
</code>```

Use [P,L] instead of 'R' if you want to mask/hide the rewrite from the user. Otherwise stay with 'P'.

Also I used two nested brackets to retrieve example.com (value is stored in %2) and use that instead of a static 'example.com' in the second line. But if you prefer a 'clearer' (=easier to read) rule, use this:

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^(proxmox.example.com)$
RewriteRule .* http://example.com/forward/?url=%1 [R,L]
</code>```

Hope it helped. Let us know if it did, and even more so, if it didn't so we can help furthermore :)

Title: Apache Rewrite for Entire Subdomain

Body:
How would I go about rewriting :

proxmox.example.com

to

example.com/forward/?url=proxmox.example.com

I am trying to do this on Ubuntu with Apache

Please let me know what Apache plugins are used.

Will this rewrite go into my VirtualHosts file? (/etc/apache2/sites-available)

Thanks for the help!

Body:
You won't need a vhost for that. It can be put in the main Apache config.
Put this in your config:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(proxmox.(example.com))$
RewriteRule .* http://%2/forward/?url=%1 [R,L]

Use [P,L] instead of 'R' if you want to mask/hide the rewrite from the user. Otherwise stay with 'P'.

Also I used two nested brackets to retrieve example.com (value is stored in %2) and use that instead of a static 'example.com' in the second line. But if you prefer a 'clearer' (=easier to read) rule, use this:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(proxmox.example.com)$
RewriteRule .* http://example.com/forward/?url=%1 [R,L]

Hope it helped. Let us know if it did, and even more so, if it didn't so we can help furthermore :)


问:
Android - I can't refresh / redraw a ListView
I have a ListView that lists a set of books.

The user can add a new book and, after that, the set of books is shown again using the onActivityResult method.

I have been trying for hours to get the set of books to refresh after adding a new book but with no luck, at all.

This is the code I have tried:

```<code>public class BookActivity extends Activity {

    private ArrayList<Book> books = null;
    private BookItemAdapter bookItemAdapter;
    ListView booksSetView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        books = new ArrayList<Book>();
        booksSetView = (ListView)findViewById(R.id.booksSet);

        Cursor booksCursor = null;

        booksCursor = getBooksCursor();
        if (booksCursor.moveToFirst())
        {
            do
            {
                books.add(getBookFromCursor(booksCursor));
            } while(booksCursor.moveToNext());
        }

        bookItemAdapter = new BookItemAdapter(this, R.layout.book_item, books, 0); // BookItemAdapter is a ArrayAdapter
        booksSetView.setAdapter(bookItemAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
            Log.e("BOOKS MANAGER", "trying to refresh");

        bookItemAdapter.notifyDataSetChanged();
        booksSetView.invalidate();
        booksSetView.invalidateViews();
    }
}
</code>```

Please some help.

Thanks a lot!

答: I don't see where you are updating the books ArrayList which is the data behind the ListView. If you update that object in onActivityResult then it should work correctly.</p>

Body:
I have a ListView that lists a set of books.

The user can add a new book and, after that, the set of books is shown again using the onActivityResult method.

I have been trying for hours to get the set of books to refresh after adding a new book but with no luck, at all.

This is the code I have tried:

public class BookActivity extends Activity {

    private ArrayList<Book> books = null;
    private BookItemAdapter bookItemAdapter;
    ListView booksSetView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        books = new ArrayList<Book>();
        booksSetView = (ListView)findViewById(R.id.booksSet);

        Cursor booksCursor = null;

        booksCursor = getBooksCursor();
        if (booksCursor.moveToFirst())
        {
            do
            {
                books.add(getBookFromCursor(booksCursor));
            } while(booksCursor.moveToNext());
        }

        bookItemAdapter = new BookItemAdapter(this, R.layout.book_item, books, 0); // BookItemAdapter is a ArrayAdapter
        booksSetView.setAdapter(bookItemAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
            Log.e("BOOKS MANAGER", "trying to refresh");

        bookItemAdapter.notifyDataSetChanged();
        booksSetView.invalidate();
        booksSetView.invalidateViews();
    }
}

Please some help.

Thanks a lot!


问:
Why Doesn't My Code Work When Converting From ES5 To ES6 Syntax?
I'm new to React and working my way through how to use 'props' and 'state' in online course. Online course uses ES5, but my IDE is set up for ES6. I've gotten through converting most examples just fine. But the following is baffling. The example works fine, but my ES6 conversion doesn't--the page renders blank. I looked through "Questions that may already have your answer", but nothing reveals my omission(s)/mistake(s). I was validated on other changes syntactically though. :)

My conversion in 'App.js' file

```<code>import React, { Component } from 'react';

let green = '#39D1B4';
let yellow = '#FFD712';

class Toggle extends Component {

  getInitialState() {
    return {color: green};
  }

  changeColor(){
    let newColor = this.state.color === green ? yellow : green;
    this.setState({color: newColor});
  }

  render() {
    return (
      <div style={{background: this.state.color}}>
        <h1>
          Change My Color
        </h1>
        <button onClick={this.changeColor}>
          Change Color
        </button>
      </div>
    );
  }
}

export default Toggle;
</code>```

My conversion in 'index.js' file

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import Toggle from './App';

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);
</code>```

'index.html' file

```<code><!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Call 'this.setState' From Another Function</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
</code>```

$ npm start says:

Compiled successfully!

The app is running at:

http://localhost:3000/

Note that the development build is not optimized.
To create a production build, use npm run build.

Yes, I got the following from the Console:

```<code>Warning: getInitialState was defined on Toggle, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?
printWarning @ warning.js:36
App.js:20Uncaught TypeError: Cannot read property 'color' of null
    at Toggle.render (App.js:20)
    at ReactCompositeComponent.js:796
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:362)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
content.js:4186 Uncaught TypeError: Cannot read property 'indexOf' of null
    at content.js:4186
</code>```

Looks like everything works fine after adding a constructor, binding the method and fixing the onClick syntax. Direction is appreciated. Thanks.

答:
I don't see that this would cause no rendering, but you cannot use getInitialState() in React class components.  You need to use the constructor of the class to do it:</p>

```<code>import React, { Component } from 'react';

let green = '#39D1B4';
let yellow = '#FFD712';
class Toggle extends Component {

  constructor() {
    super();
    this.state = {
      color: green
    }
  }

  changeColor(){
    let newColor = this.state.color === green ? yellow : green;
    this.setState({color: newColor});
  }

  render() {
    return (
      <div style={{background: this.state.color}}>
        <h1>
          Change My Color
        </h1>
        <button onClick={this.changeColor}>
          Change Color
        </button>
      </div>
    );
  }
}

export default Toggle;
</code>```

Body:
I'm new to React and working my way through how to use 'props' and 'state' in online course. Online course uses ES5, but my IDE is set up for ES6. I've gotten through converting most examples just fine. But the following is baffling. The example works fine, but my ES6 conversion doesn't--the page renders blank. I looked through "Questions that may already have your answer", but nothing reveals my omission(s)/mistake(s). I was validated on other changes syntactically though. :)

My conversion in 'App.js' file

import React, { Component } from 'react';

let green = '#39D1B4';
let yellow = '#FFD712';

class Toggle extends Component {

  getInitialState() {
    return {color: green};
  }

  changeColor(){
    let newColor = this.state.color === green ? yellow : green;
    this.setState({color: newColor});
  }

  render() {
    return (

          Change My Color

        <button onClick={this.changeColor}>
          Change Color
        </button>

    );
  }
}

export default Toggle;

My conversion in 'index.js' file

import React from 'react';
import ReactDOM from 'react-dom';
import Toggle from './App';

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

'index.html' file

<!doctype html>

    <meta charset="utf-8">
    <title>Call 'this.setState' From Another Function</title>

$ npm start says:

Compiled successfully!

The app is running at:

http://localhost:3000/

Note that the development build is not optimized.
To create a production build, use npm run build.

Yes, I got the following from the Console:

Warning: getInitialState was defined on Toggle, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?
printWarning @ warning.js:36
App.js:20Uncaught TypeError: Cannot read property 'color' of null
    at Toggle.render (App.js:20)
    at ReactCompositeComponent.js:796
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:362)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
content.js:4186 Uncaught TypeError: Cannot read property 'indexOf' of null
    at content.js:4186

Looks like everything works fine after adding a constructor, binding the method and fixing the onClick syntax. Direction is appreciated. Thanks.

Body:
I don't see that this would cause no rendering, but you cannot use getInitialState() in React class components.  You need to use the constructor of the class to do it:

import React, { Component } from 'react';

let green = '#39D1B4';
let yellow = '#FFD712';
class Toggle extends Component {

  constructor() {
    super();
    this.state = {
      color: green
    }
  }

  changeColor(){
    let newColor = this.state.color === green ? yellow : green;
    this.setState({color: newColor});
  }

  render() {
    return (
      <div style={{background: this.state.color}}>
        <h1>
          Change My Color
        </h1>
        <button onClick={this.changeColor}>
          Change Color
        </button>
      </div>
    );
  }
}

export default Toggle;


问:
PHP login issue when moving to a different server
I have a very basic log in system, which I have tested on my localhost as well as a free hosting site I use to test my projects and all worked fine.

I have just moved the site to Site Ground as a subdomain and the login has stopped working. The site is still loading content from the database I have created in this location, so I know the issue is not a result from a failure to connect to the database.

There is nothing in the .htaccess file to block a user login either, if it is an issue with moving it to a new server, how would I find a way around this? The page does NOT return any error when attempting to login

login PHP:

```<code><?php

require 'includes/connect.php';

session_start();

if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5 ($_POST['password']);

$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT COUNT(user_id) FROM nathan WHERE username='$username' AND password='$password'";
$q = $pdo->prepare($sql);
$q->execute();

$count = $q->fetchColumn();

if($count == 1){
    $_SESSION['username'] = $username;

    header('Location: admin.php');
}
}

?>
</code>```

DB connection:

```<code><?php
class Database
{
private static $dbName = "some_DB" ;
private static $dbHost = "localhost" ;
private static $username = "some_user";
private static $password = "password123";

private static $cont  = null;

public function __construct() {
    die('Init function is not allowed');
}

public static function connect()
{
   // One connection through whole application
   if ( null == self::$cont )
   {
    try
    {
      self::$cont =  new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$username, self::$password);
    }
    catch(PDOException $e)
    {
      die($e->getMessage());
    }
   }
   return self::$cont;
}

public static function disconnect()
{
    self::$cont = null;
}
}
?>
</code>```

Session PHP:

```<code><?php

session_start();

if (!isset($_SESSION['username'])){
header('Location: login.php');
};
?>
</code>```

答:
You might want to inspect your cookies when viewing and verify that you indeed are getting a cookie set with session information. If this isn't working, my limited view of your environment would suggest that you're not allowing cookies from that specific subdomain.

Another thing to check is the directory where sessions data is stored. If that isn't populated, then you're not going to be able to persist a session.

Body:
I have a very basic log in system, which I have tested on my localhost as well as a free hosting site I use to test my projects and all worked fine.

I have just moved the site to Site Ground as a subdomain and the login has stopped working. The site is still loading content from the database I have created in this location, so I know the issue is not a result from a failure to connect to the database.

There is nothing in the .htaccess file to block a user login either, if it is an issue with moving it to a new server, how would I find a way around this? The page does NOT return any error when attempting to login

login PHP:

<?php

require 'includes/connect.php';

session_start();

if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5 ($_POST['password']);

$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT COUNT(user_id) FROM nathan WHERE username='$username' AND password='$password'";
$q = $pdo->prepare($sql);
$q->execute();

$count = $q->fetchColumn();

if($count == 1){
    $_SESSION['username'] = $username;

    header('Location: admin.php');
}
}

?>

DB connection:

<?php
class Database
{
private static $dbName = "some_DB" ;
private static $dbHost = "localhost" ;
private static $username = "some_user";
private static $password = "password123";

private static $cont  = null;

public function __construct() {
    die('Init function is not allowed');
}

public static function connect()
{
   // One connection through whole application
   if ( null == self::$cont )
   {
    try
    {
      self::$cont =  new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$username, self::$password);
    }
    catch(PDOException $e)
    {
      die($e->getMessage());
    }
   }
   return self::$cont;
}

public static function disconnect()
{
    self::$cont = null;
}
}
?>

Session PHP:

<?php

session_start();

if (!isset($_SESSION['username'])){
header('Location: login.php');
};
?>


问:
Session.Timeout not working correctly in ASP Classic / IIS
Recently I created a asp classic web page with which a user can insert his worked hours.

One of the requests was that the page should show a message who is logged in every 10 minutes. The user does his production on a machine and has it's computer besides him, so it is possible that a user will be inactive on the hour web page for 5 - 60 minutes (or even more), yet he will stay on the page nonetheless.

To make the pop up message every 10 minutes I used a timer created in JQuery, this all works fine. Because the total inactive time is not sure, the person wanted the session timeout to be large (24-hours) so that session state (who is logged in) remains for a long time. When a user uses the insert hour web page he is requested to select his username on a different web page and the session("user") is then set.

To accomplish the long session timeout I created a global.asa file in the root with the following code:

```<code><script language="VBScript" runat="Server">
 <!-- METADATA
        TYPE="typelib"
        UUID="00000200-0000-0010-8000-00AA006D2EA4"
-->

Sub Session_OnStart

    ' Session timeout in minutes (24 hours)
    Session.Timeout = 1420

End Sub

</SCRIPT>
</code>```

Though for some reason (I timed it) the timeout is still the default 20 minutes.. Then I tried to also set the Session.Timeout = 1420 in:

a. The web page of the hours inserting and

b. In the page where the user is selected and the session is being set.

This didn't had any effect though. So then I started researching it and found a similar question on stackoverflow: Session Timeout in Classic ASP website

So this made me look at my IIS settings on the server where I changed a few things.

In the application pool of the website I changed the Regular Time Interval to 0:

Next I also changed the Time-Out to 24 hours in the Session Properties on the Services tab of my website (under Sites):

However this all doesn't have any effect. It still ends the session after 20 minutes (at least it resets my session("user") state.

In the hour inserting web page the session is being checked as follows:

```<code>if session("user")="" then
        response.redirect("ShowPage.asp?page=SelectUserTimeout")

        response.end
end if
</code>```

So when the session is empty it will redirect to the select a user page where the session("user") will be set again. Though with my time-out settings, if it would actually work, this should only happen after 24 hours and not after 20 minutes.

Any ideas what's going wrong here?
I am using by the way IIS 8.0.

UPDATE

I found the problem! It seems that the Idle Time-Out (Minutes) in the Application Pool of my website was still on the default 20 minutes and for some reason my session.timeout in the asp code didn't override that.

So for anyone facing the same problem I suggest that you go to your Application Pools in IIS --> then go to the application Pool of the website --> go to advanced settings --> Process Model --> and change Idle Time-out

答:
In fact the answer posted by the OP is not the solution. I had the same problem and solved configuring the application pool:

Basic Configuration - DO NOT USE .NET CLR. Select No Managed Code.

Pipeline code still Integrated.

Tried on Windows 10 Pro and Windows 2008 server and worked for both.

Body:
Recently I created a asp classic web page with which a user can insert his worked hours.

One of the requests was that the page should show a message who is logged in every 10 minutes. The user does his production on a machine and has it's computer besides him, so it is possible that a user will be inactive on the hour web page for 5 - 60 minutes (or even more), yet he will stay on the page nonetheless.

To make the pop up message every 10 minutes I used a timer created in JQuery, this all works fine. Because the total inactive time is not sure, the person wanted the session timeout to be large (24-hours) so that session state (who is logged in) remains for a long time. When a user uses the insert hour web page he is requested to select his username on a different web page and the session("user") is then set.

To accomplish the long session timeout I created a global.asa file in the root with the following code:

Though for some reason (I timed it) the timeout is still the default 20 minutes.. Then I tried to also set the Session.Timeout = 1420 in:

a. The web page of the hours inserting and

b. In the page where the user is selected and the session is being set.

This didn't had any effect though. So then I started researching it and found a similar question on stackoverflow: Session Timeout in Classic ASP website

So this made me look at my IIS settings on the server where I changed a few things.

In the application pool of the website I changed the Regular Time Interval to 0:

Next I also changed the Time-Out to 24 hours in the Session Properties on the Services tab of my website (under Sites):

However this all doesn't have any effect. It still ends the session after 20 minutes (at least it resets my session("user") state.

In the hour inserting web page the session is being checked as follows:

if session("user")="" then
        response.redirect("ShowPage.asp?page=SelectUserTimeout")

        response.end
end if

So when the session is empty it will redirect to the select a user page where the session("user") will be set again. Though with my time-out settings, if it would actually work, this should only happen after 24 hours and not after 20 minutes.

Any ideas what's going wrong here?
I am using by the way IIS 8.0.

UPDATE

I found the problem! It seems that the Idle Time-Out (Minutes) in the Application Pool of my website was still on the default 20 minutes and for some reason my session.timeout in the asp code didn't override that.

So for anyone facing the same problem I suggest that you go to your Application Pools in IIS --> then go to the application Pool of the website --> go to advanced settings --> Process Model --> and change Idle Time-out


答:
myApartment is a function

The return value of a function is undefined.

Please put a return in your function.

Title: .js scope program throwing error


问:
VS2017 - Project load failed - Duplicated linked item found in the project
I'm unable to get my project to load if an included Nuget package includes files that exist in my project.

My Nuget package contains a appsettings.json file, and since my project also has an appsettings.json file, I get the following error in Visual Studio 2017:

```<code>(load failed) - Duplicated linked item found in the project: "C:\users\user\.nuget\packages\mypackage\contentFiles\any\netcoreapp1.1\appsettings.json"
</code>```

If I remove the appsettings file from my project (not the Nuget package), the project loads fine, but the file is needed for the project to work.

I can't seem to remove the appsettings file from the nuget package, but this might be my only option.
'dotnet pack' seems to include this file even though my csproj file is not referencing it in the "CopyToPublishDirectory"

So the question is:
How to exclude certain files from being packaged (via dotnet pack)?
Or how to load a project where duplicated linked items exist?

答:
My set up is different from yours, but I got a similar error message when trying to add an existing project to a solution. I tried a few things, so not sure what exactly helped solved it in the end, but here's what I did:

Cleaned the folder in which the project was located by deleting bin and obj folders

Noticed that in the csproj file of the failing to load project there were a couple of PropertyGroup and Item nodes that were not used or were empty or pointing to folders that were not on the disk anymore, so I removed those nodes.

After that I removed and re-added the project to the solution and it loaded successfully.

Body:
I'm unable to get my project to load if an included Nuget package includes files that exist in my project.

My Nuget package contains a appsettings.json file, and since my project also has an appsettings.json file, I get the following error in Visual Studio 2017:

(load failed) - Duplicated linked item found in the project: "C:\users\user\.nuget\packages\mypackage\contentFiles\any\netcoreapp1.1\appsettings.json"

If I remove the appsettings file from my project (not the Nuget package), the project loads fine, but the file is needed for the project to work.

I can't seem to remove the appsettings file from the nuget package, but this might be my only option.
'dotnet pack' seems to include this file even though my csproj file is not referencing it in the "CopyToPublishDirectory"

So the question is:
How to exclude certain files from being packaged (via dotnet pack)?
Or how to load a project where duplicated linked items exist?


问:
Could not find goal 'copy' in plugin com.heroku.sdk
I'm following this tutorial (https://devcenter.heroku.com/articles/java-webapp-runner) and I'm also trying to use Heroku Maven Plugin. However, there should be something wrong with my POM.XML file so the command mvn package gives me this:

```<code>D:\JavaProjects\Again\helloworld>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building helloworld Maven Webapp 0.1
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.466 s
[INFO] Finished at: 2017-03-28T23:45:04+03:00
[INFO] Final Memory: 8M/295M
[INFO] ------------------------------------------------------------------------
[ERROR] Could not find goal 'copy' in plugin com.heroku.sdk:heroku-maven-plugin:1.1.3 among available goals create-slug, dashboard, deploy, deploy-slug, deploy-war, deploy-war-slug, eclipse-launch-config, release-slug, run-war -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoNotFoundException
</code>```

Here is my POM.XML below:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>helloworld</artifactId>
  <packaging>war</packaging>
  <version>0.1</version>
  <name>helloworld Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>helloworld</finalName>
    <plugins>
        <plugin>
            <groupId>com.heroku.sdk</groupId>
        <artifactId>heroku-maven-plugin</artifactId>
        <version>1.1.3</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals><goal>copy</goal></goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>com.github.jsimone</groupId>
                                <artifactId>webapp-runner</artifactId>
                                <version>8.5.11.3</version>
                                <destFileName>webapp-runner.jar</destFileName>
                            </artifactItem>
                        </artifactItems>
                        <appName>sushi-dushi</appName>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
        <groupId>org.eclipse.m2e</groupId>
        <artifactId>lifecycle-mapping</artifactId>
        <version>1.0.0</version>
        <configuration>
            <lifecycleMappingMetadata>
                <pluginExecutions>
                    <!-- copy-dependency plugin -->
                    <pluginExecution>
                        <pluginExecutionFilter>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-dependency-plugin</artifactId>
                            <versionRange>[1.0.0,)</versionRange>
                            <goals>
                                <goal>copy-dependencies</goal>
                            </goals>
                        </pluginExecutionFilter>
                        <action>
                            <ignore />
                        </action>
                    </pluginExecution>
                </pluginExecutions>
            </lifecycleMappingMetadata>
        </configuration>
    </plugin>
    </plugins>
  </build>
</project>
</code>```

So, what am I doing wrong so I can't even build an app with this POM.XML?

答:
The <executions> section of the heroku-maven-plugin is invalid. It should look like this:

```<code><plugin>
  <groupId>com.heroku.sdk</groupId>
  <artifactId>heroku-maven-plugin</artifactId>
  <version>1.1.3</version>
</plugin>
</code>```

Body:
I'm following this tutorial (https://devcenter.heroku.com/articles/java-webapp-runner) and I'm also trying to use Heroku Maven Plugin. However, there should be something wrong with my POM.XML file so the command mvn package gives me this:

D:\JavaProjects\Again\helloworld>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building helloworld Maven Webapp 0.1
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.466 s
[INFO] Finished at: 2017-03-28T23:45:04+03:00
[INFO] Final Memory: 8M/295M
[INFO] ------------------------------------------------------------------------
[ERROR] Could not find goal 'copy' in plugin com.heroku.sdk:heroku-maven-plugin:1.1.3 among available goals create-slug, dashboard, deploy, deploy-slug, deploy-war, deploy-war-slug, eclipse-launch-config, release-slug, run-war -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoNotFoundException

Here is my POM.XML below:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>helloworld</artifactId>
  <packaging>war</packaging>
  <version>0.1</version>
  <name>helloworld Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>helloworld</finalName>
    <plugins>
        <plugin>
            <groupId>com.heroku.sdk</groupId>
        <artifactId>heroku-maven-plugin</artifactId>
        <version>1.1.3</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals><goal>copy</goal></goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>com.github.jsimone</groupId>
                                <artifactId>webapp-runner</artifactId>
                                <version>8.5.11.3</version>
                                <destFileName>webapp-runner.jar</destFileName>
                            </artifactItem>
                        </artifactItems>
                        <appName>sushi-dushi</appName>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
        <groupId>org.eclipse.m2e</groupId>
        <artifactId>lifecycle-mapping</artifactId>
        <version>1.0.0</version>
        <configuration>
            <lifecycleMappingMetadata>
                <pluginExecutions>

                    <pluginExecution>
                        <pluginExecutionFilter>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-dependency-plugin</artifactId>
                            <versionRange>[1.0.0,)</versionRange>
                            <goals>
                                <goal>copy-dependencies</goal>
                            </goals>
                        </pluginExecutionFilter>
                        <action>
                            <ignore />
                        </action>
                    </pluginExecution>
                </pluginExecutions>
            </lifecycleMappingMetadata>
        </configuration>
    </plugin>
    </plugins>
  </build>
</project>

So, what am I doing wrong so I can't even build an app with this POM.XML?

Body:
The <executions> section of the heroku-maven-plugin is invalid. It should look like this:

<plugin>
  <groupId>com.heroku.sdk</groupId>
  <artifactId>heroku-maven-plugin</artifactId>
  <version>1.1.3</version>
</plugin>


问:
Ionic2,Angular2 - sorting elements by date
currently I am working on app for managing workouts. I would like to sort workouts by date. My record of one workout looks like that:

```<code> "title": "Running through the park",
    "type": "Running",
    "distance": "10",
    "duration": [
        {
            "hours": "2"
        },
        {
            "minutes": "40"
        },
        {
            "seconds": "44"
        }
    ],
    "note": "Running in NY park."
</code>```

I would like to sort workouts by the day. For example:

09.10

running

basketball

07.10

push-ups

football

Currently it looks like that: workouts-main screen

My html file for that component is simple :

```<code><ion-list>
<ion-item *ngFor="let workout of workouts" (click)="workoutSelected($event,workout)">
    {{workout.title}}
</ion-item>
</code>```

What's the best way to do that?

答:
As I stumbled recently on similar issue and couldn't find fully satisfactory answer I would like to share my solution.

.ts

```<code>  objectEntries: any[];
  groupedObjectEntries: any[];

  ionViewDidLoad() {
    // put in the line below your custom function for getting data into objectEntries object
    .....
    this.groupObjectEntries(this.objectEntries);
  }

  groupObjectEntries(objectEntries){

        var currentDate: any;
        var currentObjectEntries = [];
        var output = [];

        // sort descending
        let sortedObjectEntries =objectEntries.sort(function (a, b) {
          var key1 = new Date(a.date);
          var key2 = new Date(b.date);

          if (key1 < key2) {
              return 1;
          } else if (key1 == key2) {
              return 0;
          } else {
              return -1;
          }
        });

        sortedObjectEntries.forEach((item, index) => {

            // conversion from JSON format
            var itemDate = new (item.date);
            itemDate.setHours(0,0,0,0);

            if(itemDate != currentDate){

                currentDate = itemDate;
                let newGroup = {
                    groupDate: currentDate,
                   objectEntries: []
                };

                currentObjectEntries = newGroup.objectEntries;
                output.push(newGroup);

            }

            currentObjectEntries.push(item);

        });

        this.groupedObjectEntries = output;
  }
</code>```

.html

```<code><ion-content>
<ion-item-group *ngFor="let group of groupedObjectEntries">
    <ion-item-divider sticky>
    <ion-item color="gray" ><h4>{{ group.groupDate | date:'fullDate' }} </h4> </ion-item>
    </ion-item-divider>

      <button ion-item *ngFor="let item of group.objectEntries"  (click)="itemSelected(item)">
          <h3>{{ item.field1 }} </h3>
          <p>{{ item.field2 }}</p>
      </button>
 </ion-item-group>
</ion-content>
</code>```

Body:
currently I am working on app for managing workouts. I would like to sort workouts by date. My record of one workout looks like that:

 "title": "Running through the park",
    "type": "Running",
    "distance": "10",
    "duration": [
        {
            "hours": "2"
        },
        {
            "minutes": "40"
        },
        {
            "seconds": "44"
        }
    ],
    "note": "Running in NY park."

I would like to sort workouts by the day. For example:

09.10

running

basketball

07.10

push-ups

football

Currently it looks like that: workouts-main screen

My html file for that component is simple :

<ion-list>
<ion-item *ngFor="let workout of workouts" (click)="workoutSelected($event,workout)">
    {{workout.title}}
</ion-item>

What's the best way to do that?

Body:
As I stumbled recently on similar issue and couldn't find fully satisfactory answer I would like to share my solution.

.ts

  objectEntries: any[];
  groupedObjectEntries: any[];

  ionViewDidLoad() {
    // put in the line below your custom function for getting data into objectEntries object
    .....
    this.groupObjectEntries(this.objectEntries);
  }

  groupObjectEntries(objectEntries){

        var currentDate: any;
        var currentObjectEntries = [];
        var output = [];

        // sort descending
        let sortedObjectEntries =objectEntries.sort(function (a, b) {
          var key1 = new Date(a.date);
          var key2 = new Date(b.date);

          if (key1 < key2) {
              return 1;
          } else if (key1 == key2) {
              return 0;
          } else {
              return -1;
          }
        });

        sortedObjectEntries.forEach((item, index) => {

            // conversion from JSON format
            var itemDate = new (item.date);
            itemDate.setHours(0,0,0,0);

            if(itemDate != currentDate){

                currentDate = itemDate;
                let newGroup = {
                    groupDate: currentDate,
                   objectEntries: []
                };

                currentObjectEntries = newGroup.objectEntries;
                output.push(newGroup);

            }

            currentObjectEntries.push(item);

        });

        this.groupedObjectEntries = output;
  }

.html

<ion-content>
<ion-item-group *ngFor="let group of groupedObjectEntries">
    <ion-item-divider sticky>
    <ion-item color="gray" ><h4>{{ group.groupDate | date:'fullDate' }} </h4> </ion-item>
    </ion-item-divider>

      <button ion-item *ngFor="let item of group.objectEntries"  (click)="itemSelected(item)">
          <h3>{{ item.field1 }} </h3>
          <p>{{ item.field2 }}</p>
      </button>
 </ion-item-group>
</ion-content>


问:
Navigation item added under storyboard
I have a project which uses a tab bar. All the tabs in the tab bar have the same main navigation controller. On one of the views I want to have custom buttons which the user can use.

I am having problems adding these buttons to the storyboard and having them shown:

Programatically adding them

My project is written in Objective-C so I tried adding them programatically to my viewController:

```<code>self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                                target:self
                                                                                action:@selector(myFriendsView)];
</code>```

I also tried adding them using the following:

```<code>self.navigationController.navigationItem.rightBarButton = ...
</code>```

As the initial method didn't work. I didn't know if I needed a pointer to the tab bar navigation controller to add a button. Neither of these approaches worked.

Adding the buttons in the storyboard

I added a navigation item to my viewController in the storyboard and then dragged my buttons into it. You can see a screenshot below:

The problem with this technique was that the buttons didn't appear when I loaded the code. Once again I thought that this might be to do with the UITabBar navigation controller overwriting the storyboard.

Add a navigation controller to the storyboard to load the viewController

I next tried adding a UINavigationController and then loading my viewController as the root view. The root view still containing the navigation item and the buttons.

This was the first method that seemed to have any effect on the functionality I was after. The weird thing was that the navigation item was added below the navigation bar:

As you can see it has added the navigation items below the navigation bar instead of inside it. This functionality works as hoped except for the buttons being in the wrong place.

Other things I have tried:

-Dragging the UIBarbuttonItems into the navigation controller nav bar in the storyboard

Conclusion:
To me this seems like it should be an easy thing to achieve with storyboards. I can't understand what is causing this code to not work correctly and why Apple would enable functionality that adds the navigation items under a nav bar without me adding a navigation bar into the same view in the storyboard.

If anyone can give me advice on using storyboards and how to add navigation buttons to a view controller when using a tab bar that would be very appreciated.

答:
Huge thanks to @matt for helping me think this issue through.

This was an interesting case where I needed to think slightly harder on what was actually happening to be able to find the answer - in this case needing a bit of help in the comments.

The problem was that I wasn't setting the navigation item in the correct place. The framework of my app was set up as follows:

```<code>tabBarController -> viewController -> navigationBar
</code>```

My initial approach was to try to set the navigation item on the viewController. As you can see in the framework above there is no navigation item to set. This is why self.navigationController wasn't working.

Next I attempted to add a navigationController in to remedy this:

```<code>tabBarController -> navigationController -> viewController -> navigationBar
</code>```

This didn't work either as the navigation bar is being set in the tabBarController first and so the navigationController won't override it.

This step was the hole in my logic. I was assuming something was wrong with my code/storyboard somewhere as the navigationControllers and items I was setting weren't appearing.

The issue was that I was not understanding the problem. In this case we have the tabBarController which controls the tabBar. This controls the navigation bar. This means if I want to access it I need to get the current navigation controller for our parent view. This is done easily with self.tabBarController:

The solution:

```<code>self.tabBarController.navigationItem.rightBarButtonItem = ...;
</code>```

As you can see this is very similar to my attempts in the above question. Both follow the conventions of navigation items. The difference was that in the solution I was accessing the parent navigationController of the entire view.

Title: Navigation item added under storyboard

Body:
I have a project which uses a tab bar. All the tabs in the tab bar have the same main navigation controller. On one of the views I want to have custom buttons which the user can use.

I am having problems adding these buttons to the storyboard and having them shown:

Programatically adding them

My project is written in Objective-C so I tried adding them programatically to my viewController:

self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                                target:self
                                                                                action:@selector(myFriendsView)];

I also tried adding them using the following:

self.navigationController.navigationItem.rightBarButton = ...

As the initial method didn't work. I didn't know if I needed a pointer to the tab bar navigation controller to add a button. Neither of these approaches worked.

Adding the buttons in the storyboard

I added a navigation item to my viewController in the storyboard and then dragged my buttons into it. You can see a screenshot below:

The problem with this technique was that the buttons didn't appear when I loaded the code. Once again I thought that this might be to do with the UITabBar navigation controller overwriting the storyboard.

Add a navigation controller to the storyboard to load the viewController

I next tried adding a UINavigationController and then loading my viewController as the root view. The root view still containing the navigation item and the buttons.

This was the first method that seemed to have any effect on the functionality I was after. The weird thing was that the navigation item was added below the navigation bar:

As you can see it has added the navigation items below the navigation bar instead of inside it. This functionality works as hoped except for the buttons being in the wrong place.

Other things I have tried:

-Dragging the UIBarbuttonItems into the navigation controller nav bar in the storyboard

Conclusion:
To me this seems like it should be an easy thing to achieve with storyboards. I can't understand what is causing this code to not work correctly and why Apple would enable functionality that adds the navigation items under a nav bar without me adding a navigation bar into the same view in the storyboard.

If anyone can give me advice on using storyboards and how to add navigation buttons to a view controller when using a tab bar that would be very appreciated.

Body:
Huge thanks to @matt for helping me think this issue through.

This was an interesting case where I needed to think slightly harder on what was actually happening to be able to find the answer - in this case needing a bit of help in the comments.

The problem was that I wasn't setting the navigation item in the correct place. The framework of my app was set up as follows:

tabBarController -> viewController -> navigationBar

My initial approach was to try to set the navigation item on the viewController. As you can see in the framework above there is no navigation item to set. This is why self.navigationController wasn't working.

Next I attempted to add a navigationController in to remedy this:

tabBarController -> navigationController -> viewController -> navigationBar

This didn't work either as the navigation bar is being set in the tabBarController first and so the navigationController won't override it.

This step was the hole in my logic. I was assuming something was wrong with my code/storyboard somewhere as the navigationControllers and items I was setting weren't appearing.

The issue was that I was not understanding the problem. In this case we have the tabBarController which controls the tabBar. This controls the navigation bar. This means if I want to access it I need to get the current navigation controller for our parent view. This is done easily with self.tabBarController:

The solution:

self.tabBarController.navigationItem.rightBarButtonItem = ...;

As you can see this is very similar to my attempts in the above question. Both follow the conventions of navigation items. The difference was that in the solution I was accessing the parent navigationController of the entire view.


问:
Colour Saturation/Desat in jQuery
My question is a pretty simple one:

If I code an image to display using standard HTML, is it possible to desaturate that image completely using on jQuery alone?

The idea would be to return to normal saturation once the user hovers over the image...

I know there's an experimental method using HTML5 Canvas , but for the time being I'd like to stay away from HTML5 :)

答:
Using jQuery alone? Not really. You need some method to manipulate the image data and there are only four methods I'm aware of:

HTML5 Canvas (You said you didn't want it)

Proprietary IE Filter (Internet Explorer only)

SVG Filters applied via CSS (Currently Firefox-only according to my tests)

Flash Applet (Overkill, heavy, and generally unpleasant.)

Matt Gibson's suggestion of Pixastic is a good one if your only concern is compatibility or you could roll your own using some mixture of the aforementioned approaches.

Title: Colour Saturation/Desat in jQuery


答:
There's no getInitialState() when you use a class. For that, set the initial state in the constructor:

```<code>class SomeComponent extends Component {
  constructor(props) {
    super(props);

    // Define initial state here
    this.state = {
      color: '#39D1B4'
    };
  }
  // ...
}
</code>```

Title: Why Doesn't My Code Work When Converting From ES5 To ES6 Syntax?

Body:
There's no getInitialState() when you use a class. For that, set the initial state in the constructor:

class SomeComponent extends Component {
  constructor(props) {
    super(props);

    // Define initial state here
    this.state = {
      color: '#39D1B4'
    };
  }
  // ...
}


问:
New users can't login on PHPmyadmin
I am currently having a problem with allowing multiple users to login with phpmyadmin without seeing each other's databases. I am using this method: http://alandoyle.com/tutorials/configuring-phpmyadmin-for-multiple-users/

While the method works for the most part, although when creating a New User where I check off the "Grant all privileges on wildcard name (username_%)" selection does not allow me to login with that user unless I don't specify a password and enable  "$cfg['Servers'][$i]['AllowNoPassword']".

What I've tried:

I've tried to create the same User where I don't check it off, but while I can login unfortunately I can see all the root databases. As opposed to when I choose no password and I can only see databases pertaining to that user.

答: When u select the rights on the new user, check the GRANT flag if you like enable user.</p>

Title: New users can't login on PHPmyadmin


问:
Setting data on ViewHolder
I am using a RecyclerView in my project and I am having an issue where my RecyclerView is being populated by the same values as if the values are being overwritten inside the forEach in onBindViewHolder below:

```<code>   class ProfListAdapter extends RecyclerView.Adapter<ViewHolder>{
    private LayoutInflater mLayoutInflater;
    public ProfListAdapter(Context context) {
        mLayoutInflater = LayoutInflater.from(context);
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType){
        return new ViewHolder(mLayoutInflater
        .inflate(R.layout.recycler_view, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position){
    System.out.println(position);
        final String profName;
        Integer k = 0;
        for (Integer key : mData.keySet()) {
            viewHolder.setData(mData.get(key));
        }

    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            Intent intent = ProfPager.newIntent(getActivity(), position);
            startActivity(intent);
        }
    });
    }
    @Override
    public int getItemCount() {
    return mData.size();
}
}

class ViewHolder extends RecyclerView.ViewHolder {
    private TextView mTextView;
    private ViewHolder(View itemView){
        super(itemView);
        mTextView = (TextView) itemView.findViewById(R.id._prof); // galleryimage
    }
    private void setData(String profName){
        mTextView.setText(profName);
        System.out.println("setData" + profName);
    }
}
</code>```

When I log out to the console I can see that the value in setData() is getting the correct item to display. However, what is being displayed inside the fragment is just the last profName that is comes across in the forEach. What could be causing this behaviour? Here is a link to the entire fragment: https://pastebin.com/xS7CSbbK

If I use the position, it does not always coincide with the key in the Hashmap that stores the SQLite _id.

答:
For RecyclerView , use ArrayList for simplicity

And change your onBindViewHolder like this

```<code>@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position){
    System.out.println(position);
    viewHolder.setData(mData.get(position));

viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v){
        Intent intent = ProfPager.newIntent(getActivity(), position);
        startActivity(intent);
    }
});
}
</code>```

I assume mData as ArrayList

Title: Setting data on ViewHolder

Body:
I am using a RecyclerView in my project and I am having an issue where my RecyclerView is being populated by the same values as if the values are being overwritten inside the forEach in onBindViewHolder below:

   class ProfListAdapter extends RecyclerView.Adapter<ViewHolder>{
    private LayoutInflater mLayoutInflater;
    public ProfListAdapter(Context context) {
        mLayoutInflater = LayoutInflater.from(context);
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType){
        return new ViewHolder(mLayoutInflater
        .inflate(R.layout.recycler_view, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position){
    System.out.println(position);
        final String profName;
        Integer k = 0;
        for (Integer key : mData.keySet()) {
            viewHolder.setData(mData.get(key));
        }

    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            Intent intent = ProfPager.newIntent(getActivity(), position);
            startActivity(intent);
        }
    });
    }
    @Override
    public int getItemCount() {
    return mData.size();
}
}

class ViewHolder extends RecyclerView.ViewHolder {
    private TextView mTextView;
    private ViewHolder(View itemView){
        super(itemView);
        mTextView = (TextView) itemView.findViewById(R.id._prof); // galleryimage
    }
    private void setData(String profName){
        mTextView.setText(profName);
        System.out.println("setData" + profName);
    }
}

When I log out to the console I can see that the value in setData() is getting the correct item to display. However, what is being displayed inside the fragment is just the last profName that is comes across in the forEach. What could be causing this behaviour? Here is a link to the entire fragment: https://pastebin.com/xS7CSbbK

If I use the position, it does not always coincide with the key in the Hashmap that stores the SQLite _id.

Body:
For RecyclerView , use ArrayList for simplicity

And change your onBindViewHolder like this

@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position){
    System.out.println(position);
    viewHolder.setData(mData.get(position));

viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v){
        Intent intent = ProfPager.newIntent(getActivity(), position);
        startActivity(intent);
    }
});
}

I assume mData as ArrayList


问:
loop in nested list in python
Hello I am new in Python and what I am trying to do is to make a loop in a nested list to sum the elements 10 by 10 in the code below:

1.1

```<code>for i in range (n):
            for k in range (n):
                G[i] += (F[(n*i)+k])
</code>```

and I am getting the error:

ValueError: operands could not be broadcast together with shapes (6,)
  (3,)

what I already did and worked was

1.2

```<code>for i in range (n):
    G[i]=F[n*i+0]+F[n*i+1]+F[n*i+2]+F[n*i+3]+F[n*i+4]+F[n*i+5]+F[n*i+6]+F[n*i+7]+F[n*i+8]+F[n*i+9]
</code>```

So I am trying to do the loop to get the same as in 1.2 but I know i cant use the loop in 1.1 in python. How would I do that?
Thanks a lot!

答:
I am not sure of what you want to add.
If it is a problem with the shape of the array, it should be

```<code>import numpy as np
n=10
t=[(0,0,0)]
F=np.array(t*n**2)
G=np.array(t*n)
for i in range (n):
    for k in range (n):
        G[i] += F[n*i+k]
</code>```

Of course if t=[(0,0,0)], it sums up to zero

Title: loop in nested list in python

Body:
Hello I am new in Python and what I am trying to do is to make a loop in a nested list to sum the elements 10 by 10 in the code below:

1.1

for i in range (n):
            for k in range (n):
                G[i] += (F[(n*i)+k])

and I am getting the error:

ValueError: operands could not be broadcast together with shapes (6,)
  (3,)

what I already did and worked was

1.2

for i in range (n):
    G[i]=F[n*i+0]+F[n*i+1]+F[n*i+2]+F[n*i+3]+F[n*i+4]+F[n*i+5]+F[n*i+6]+F[n*i+7]+F[n*i+8]+F[n*i+9]

So I am trying to do the loop to get the same as in 1.2 but I know i cant use the loop in 1.1 in python. How would I do that?
Thanks a lot!

Body:
I am not sure of what you want to add.
If it is a problem with the shape of the array, it should be

import numpy as np
n=10
t=[(0,0,0)]
F=np.array(t*n**2)
G=np.array(t*n)
for i in range (n):
    for k in range (n):
        G[i] += F[n*i+k]

Of course if t=[(0,0,0)], it sums up to zero