问:
javascript onclick with animation and iframes
First of all, I'm not an expert in web development !

I need some help to improve my little web application.

You can see it here : https://jsfiddle.net/s9ysfc2b/2/

My functions :

```<code>    function rollout(id) {
  var height = document.getElementById(id).height;

  if(height <= 0) {
    document.getElementById(id).height = 450;
  } else {
    document.getElementById(id).height = 0;
  }
}

  function videotitle(texte){

  document.getElementById('txt').innerHTML = texte;

  }

  function go(loc) {
    document.getElementById('music').src = loc;
  }
</code>```

The css transition :

```<code>iframe {
  transition: 0.3s height;
}
</code>```

The html

```<code><body>
  <div id="txt"></div>
  <iframe id="music" src="about:blank" width="1000" height="0" frameborder="0" scrolling="no"></iframe>

  <form method="post">
    <input name="musicSelection" id="1" type="button" value="" onclick="go('https://www.youtube.com/embed/videoseries?list=PLg46y7jCyHx57PG6pE_UZ46r8PPSDCxnK'); videotitle('<h2>Coucou!</h2>'); rollout('music');" />
    <input name="musicSelection" type="button" value="" onclick="go('https://www.youtube.com/embed/videoseries?list=PLg46y7jCyHx6TNKaZ3auFYw5fT0qWiw67'); videotitle('<h2>C\'est moi...</h2>'); rollout('music')" />
    <input name="musicSelection" type="button" value="" onclick="go('https://www.youtube.com/embed/Di78xYSR0T0?list=PLO-2Biv8vPGPkkVV7LQZUguKkbwCA6qsg'); videotitle('<h2>Tu te souviens?</h2>'); rollout('music')" />

  </form>

</body>
</code>```

When you click on emoji, a youtube video is rolling out.

If you want to click on another emoji, the video is rolling in and you have to click another time on emoji to roll the video out.

How can I roll in and out the video when I click on another emoji ? Without click one time to open it and one time to close it.

Please be free to suggest what I could do to improve whatever parts of my project

(sorry for my english..)

Thanks !

答:
I have completely started again my project in jQuery, it's easier. I don't know how to solve it in pure JS.. now it works.

https://jsfiddle.net/gf3h6a42/

```<code>    $(function () {
    $(".playlistTitle").on("click", function (e) {
        $("#genericTitle").text($(this).data("text"));
        $('p').text($(this).data("desc"));
    });
});

$(document).ready(function(){
    $("a").click(function(e) {
        e.preventDefault();

        $("#playlist").attr("src", $(this).attr("href"));
    })
});

$(document).ready(function(){
  $('.button').click(function() {
        if ($('#roll').is(':visible')) {
              $('#roll').slideUp();
            if ($("#roll").data('lastClicked') !== this) {
               $('#roll').slideDown();
            }
        }
    else {
      $('#roll').slideDown();
    }
        $("#roll").data('lastClicked', this);
  });
});

$(document).ready(function(){
    $('.button').click(function() {
        $('.button').not(this).removeClass('buttonactive');
        $(this).toggleClass('buttonactive');
    });
});
</code>```

Body:
First of all, I'm not an expert in web development !

I need some help to improve my little web application.

You can see it here : https://jsfiddle.net/s9ysfc2b/2/

My functions :

    function rollout(id) {
  var height = document.getElementById(id).height;

  if(height <= 0) {
    document.getElementById(id).height = 450;
  } else {
    document.getElementById(id).height = 0;
  }
}

  function videotitle(texte){

  document.getElementById('txt').innerHTML = texte;

  }

  function go(loc) {
    document.getElementById('music').src = loc;
  }

The css transition :

iframe {
  transition: 0.3s height;
}

The html

  <form method="post">
    <input name="musicSelection" id="1" type="button" value="" onclick="go('https://www.youtube.com/embed/videoseries?list=PLg46y7jCyHx57PG6pE_UZ46r8PPSDCxnK'); videotitle('
Coucou!
'); rollout('music');" />
    <input name="musicSelection" type="button" value="" onclick="go('https://www.youtube.com/embed/videoseries?list=PLg46y7jCyHx6TNKaZ3auFYw5fT0qWiw67'); videotitle('
C\'est moi...
'); rollout('music')" />
    <input name="musicSelection" type="button" value="" onclick="go('https://www.youtube.com/embed/Di78xYSR0T0?list=PLO-2Biv8vPGPkkVV7LQZUguKkbwCA6qsg'); videotitle('
Tu te souviens?
'); rollout('music')" />

  </form>

When you click on emoji, a youtube video is rolling out.

If you want to click on another emoji, the video is rolling in and you have to click another time on emoji to roll the video out.

How can I roll in and out the video when I click on another emoji ? Without click one time to open it and one time to close it.

Please be free to suggest what I could do to improve whatever parts of my project

(sorry for my english..)

Thanks !

Body:
I have completely started again my project in jQuery, it's easier. I don't know how to solve it in pure JS.. now it works.

https://jsfiddle.net/gf3h6a42/

    $(function () {
    $(".playlistTitle").on("click", function (e) {
        $("#genericTitle").text($(this).data("text"));
        $('p').text($(this).data("desc"));
    });
});

$(document).ready(function(){
    $("a").click(function(e) {
        e.preventDefault();

        $("#playlist").attr("src", $(this).attr("href"));
    })
});

$(document).ready(function(){
  $('.button').click(function() {
        if ($('#roll').is(':visible')) {
              $('#roll').slideUp();
            if ($("#roll").data('lastClicked') !== this) {
               $('#roll').slideDown();
            }
        }
    else {
      $('#roll').slideDown();
    }
        $("#roll").data('lastClicked', this);
  });
});

$(document).ready(function(){
    $('.button').click(function() {
        $('.button').not(this).removeClass('buttonactive');
        $(this).toggleClass('buttonactive');
    });
});


来源: stackexchange

问:
sub string replacment in PHP
I have a string like:
$string = "/physics/mechanics/vectors/P-M-C (1).doc";

I want to get like this:

"/physics/mechanics/vectors/1-P-M-C (1).doc";

Please note that "1-" is added just before P in the original string.

Is it possible in PHP?
How the function in PHP should be used?

答:
@fawad:Here's a sample to get you started --</p>

```<code>$oldstring = "/physics/mechanics/vectors/P-M-C (1).doc";
$parts = explode("/", $oldstring);
$file = $parts[count($parts) - 1];

$newstring = str_replace($file, "1-" . $file, $oldstring);
</code>```

ContentLicense: CC BY-SA 2.5

Title: sub string replacment in PHP

Body:
@fawad:Here's a sample to get you started --

$oldstring = "/physics/mechanics/vectors/P-M-C (1).doc";
$parts = explode("/", $oldstring);
$file = $parts[count($parts) - 1];

$newstring = str_replace($file, "1-" . $file, $oldstring);


问:
Change color of the last point in a graph

I created a graph in VBA

But i want to the last point i have done is in another color (red)

here is my code :

```<code>Sub Macro2()
'
' Macro2 Macro
'

'

    i = Range("G3").Select

    j = Range("D3").Select

     With ActiveChart.ChartArea.Select
            i.MarkerBackgroundColor = RGB(250, 250, 250)
            j.MarkerForegroundColor = RGB(250, 250, 250)
    End With
End Sub
</code>```

In i is the X abscisse and j is the Y abscisse of the last point !

thank you for any advice

答:
This code will set the last marker on the chart to red.  Note the the RGB value for red is (255, 0, 0)

```<code>Sub SetLastMarkerRed()

    Dim ws As Worksheet
    Dim ch As Chart
    Dim sc As SeriesCollection
    Dim s As Series
    Dim p As Point

    Set ws = ThisWorkbook.ActiveSheet
    Set ch = ws.ChartObjects(1).Chart
    Set sc = ch.SeriesCollection
    Set s = sc.Item(1)
    Set p = s.Points(s.Points.Count)
    p.MarkerBackgroundColor = RGB(255, 0, 0)
    p.MarkerForegroundColor = RGB(255, 0, 0)

    Set ws = Nothing
    Set ch = Nothing
    Set sc = Nothing
    Set s = Nothing
    Set p = Nothing

End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I created a graph in VBA

But i want to the last point i have done is in another color (red)

here is my code :

Sub Macro2()
'
' Macro2 Macro
'

'

    i = Range("G3").Select

    j = Range("D3").Select

     With ActiveChart.ChartArea.Select
            i.MarkerBackgroundColor = RGB(250, 250, 250)
            j.MarkerForegroundColor = RGB(250, 250, 250)
    End With
End Sub

In i is the X abscisse and j is the Y abscisse of the last point !

thank you for any advice

Body:
This code will set the last marker on the chart to red.  Note the the RGB value for red is (255, 0, 0)

Sub SetLastMarkerRed()

    Dim ws As Worksheet
    Dim ch As Chart
    Dim sc As SeriesCollection
    Dim s As Series
    Dim p As Point

    Set ws = ThisWorkbook.ActiveSheet
    Set ch = ws.ChartObjects(1).Chart
    Set sc = ch.SeriesCollection
    Set s = sc.Item(1)
    Set p = s.Points(s.Points.Count)
    p.MarkerBackgroundColor = RGB(255, 0, 0)
    p.MarkerForegroundColor = RGB(255, 0, 0)

    Set ws = Nothing
    Set ch = Nothing
    Set sc = Nothing
    Set s = Nothing
    Set p = Nothing

End Sub


问:
Angular routing is not working properly
While i am trying to click on first and second page its not showing any thing, i have wasted lot of time on this but no output is coming, Files script.js index.html first.html and second.html

script.js

angular.module('RoutingApp', ['ngRoute'])
.config( ['$routeProvider', function($routeProvider) {

        $routeProvider

            .when('/first', {

                templateUrl: 'first.html'

            })

            .when('/second', {

                templateUrl: 'second.html'

            })

            .otherwise({

                redirectTo: '/'

            });

    }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.min.js"></script>
 <script src="script.js"></script>
</head>

<body ng-app="RoutingApp">
 <h2>AngularJS Routing Example</h2>
 <p>Jump to the first or second page</p>
 <div ng-view>
 </div>
</body>
</html></code>```

first.html

```<code><h2>This is the first page.</h2>
</code>```

second.html

```<code><h2>This is the second page.</h2>
</code>```

答:
Anchor(a) tag needs to be changed to match them with route URL. Those should have / in them.

```<code><a href="#/first">first</a>
or
<a href="#/second">second page</a>
</code>```

Title: Angular routing is not working properly

Body:
While i am trying to click on first and second page its not showing any thing, i have wasted lot of time on this but no output is coming, Files script.js index.html first.html and second.html

script.js

angular.module('RoutingApp', ['ngRoute'])
.config( ['$routeProvider', function($routeProvider) {

        $routeProvider

            .when('/first', {

                templateUrl: 'first.html'

            })

            .when('/second', {

                templateUrl: 'second.html'

            })

            .otherwise({

                redirectTo: '/'

            });

    }]);

<!DOCTYPE html>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

AngularJS Routing Example

Jump to the first or second page

first.html

This is the first page.

second.html

This is the second page.

Body:
Anchor(a) tag needs to be changed to match them with route URL. Those should have / in them.

<a href="#/first">first</a>
or
<a href="#/second">second page</a>


问:
Trying to copy TD element formSharePoint and getting weird error
Here is my non-working code:

```<code>        SnapShotDate = SnapShot & M
        'Wait for site to fully load

        URL = SnapShotDate

        'Wait for site to fully load
        IE.Navigate2 URL
        Do While IE.Busy = True
           DoEvents
        Loop

        With ActiveSheet.Name
            x = IE.document.body.innertext
            StartDate = InStr(1, x, "In-Market Start Date ")
            EndDate = InStr(1, x, "In-Market End Date ")
            ActualDate = Mid(x, StartDate + 10, EndDate - StartDate - 10)
                .Range(y, 35) = ActualDate
        End With
</code>```

I'm concatenating two variables together to come up with the URL; this works fine.  I'm searching the URL for a date, which is between 'In-Market Start Date' and 'In-Market End Date'.  I can find the value, and fit it into the string named 'ActualDate'.  Now, when I try to write it into a cell, I get this error: 'run-time error 424 object required'

This line always throws an error.
.Range(y, 35) = ActualDate

I'm not sure what's wrong here.  Also, I'm thinking there may be a better approach, since this seems kind of difficult, and I've learned, over time, if something seems difficult in Excel, it's probably because you are doing it wrong.  Can someone here give me a little guidance on what is wrong here?  Also, can I possibly do this in a more efficient fashion?

Thanks!

答:
Remove the .Name from With ActiveSheet.Name as it's not needed.

Also,  change the .Range(y, 35) to .Cells(y, 35).

Body:
Here is my non-working code:

        SnapShotDate = SnapShot & M
        'Wait for site to fully load

        URL = SnapShotDate

        'Wait for site to fully load
        IE.Navigate2 URL
        Do While IE.Busy = True
           DoEvents
        Loop

        With ActiveSheet.Name
            x = IE.document.body.innertext
            StartDate = InStr(1, x, "In-Market Start Date ")
            EndDate = InStr(1, x, "In-Market End Date ")
            ActualDate = Mid(x, StartDate + 10, EndDate - StartDate - 10)
                .Range(y, 35) = ActualDate
        End With

I'm concatenating two variables together to come up with the URL; this works fine.  I'm searching the URL for a date, which is between 'In-Market Start Date' and 'In-Market End Date'.  I can find the value, and fit it into the string named 'ActualDate'.  Now, when I try to write it into a cell, I get this error: 'run-time error 424 object required'

This line always throws an error.
.Range(y, 35) = ActualDate

I'm not sure what's wrong here.  Also, I'm thinking there may be a better approach, since this seems kind of difficult, and I've learned, over time, if something seems difficult in Excel, it's probably because you are doing it wrong.  Can someone here give me a little guidance on what is wrong here?  Also, can I possibly do this in a more efficient fashion?

Thanks!


问:
Print the contents of the file
I am trying to print the contents of my file byte by byte. However, I do get the compiler error "invalid type argument of unary *(have int)

my code is :

```<code> void print_the_file ()
    {
       void *file_hndl;
       UINT32 file_size = 2048;
       UINT8 *hndl;
       file_hndl = fopen("my_bin_file.bin", "r") ;
       if ( file_hndl == NULL )
       {
          printf("file open failed");
       }
       hndl = (UINT8*)file_hndl;
     /* print the contents */
      for ( UINT32 i = 0; i< 2048; i++ )
    {
        printf ("%02x", *hndl[i] );
    }
   }
</code>```

Please advise me where i am going wrong and right way to print the contents of the file.

答:
the error was fired because of * in front of the variable hndl

```<code>for ( UINT32 i = 0; i< 2048; i++ )
    {
       // printf ("%02x", *hndl[i] );
       printf ("%02x", fgetc(hndl) );
       // remove * if you are using [] or write like this *(hndl+i)
    }
</code>```

make sure that you are compiling it with C99 or higher standard. for this

```<code>for ( UINT32 i = 0; i< 2048; i++ )
</code>```

Title: Print the contents of the file

Body:
I am trying to print the contents of my file byte by byte. However, I do get the compiler error "invalid type argument of unary *(have int)

my code is :

 void print_the_file ()
    {
       void *file_hndl;
       UINT32 file_size = 2048;
       UINT8 *hndl;
       file_hndl = fopen("my_bin_file.bin", "r") ;
       if ( file_hndl == NULL )
       {
          printf("file open failed");
       }
       hndl = (UINT8*)file_hndl;
     /* print the contents */
      for ( UINT32 i = 0; i< 2048; i++ )
    {
        printf ("%02x", *hndl[i] );
    }
   }

Please advise me where i am going wrong and right way to print the contents of the file.

Body:
the error was fired because of * in front of the variable hndl

for ( UINT32 i = 0; i< 2048; i++ )
    {
       // printf ("%02x", *hndl[i] );
       printf ("%02x", fgetc(hndl) );
       // remove * if you are using [] or write like this *(hndl+i)
    }

make sure that you are compiling it with C99 or higher standard. for this

for ( UINT32 i = 0; i< 2048; i++ )


问:
Brace placement after init list in C++
For anyone who places braces thus:

```<code>void f() {
    stuff();
}
</code>```

How do you prefer to place braces after long initializer lists?

The same way?

```<code>Object::Object()
    : foo(1)
    , bar(2) {
    stuff();
}
</code>```

Or make an exception so you actually see where the init list ends?

```<code>Object::Object()
    : foo(1)
    , bar(2)
{
    stuff();
}
</code>```

Or leave a blank line?

```<code>Object::Object()
    : foo(1)
    , bar(2) {

    stuff();
}
</code>```

Or maybe make a weird hybrid?

```<code>Object::Object()
    : foo(1)
    , bar(2)
    {
    stuff();
}
</code>```

Or abuse indentation

```<code>Object::Object()
: foo(1)
, bar(2) {
    stuff();
}

Object::Object() : foo(1)
                            , bar(2) {
    stuff();
}
</code>```

In this small example all are pretty but crank a dozen initializers and a moderately long function body and this quickly changes.

答:
It seems important to be able to detect where the ctor-initializer list begins/ends, and where the code block begins/ends.</p>

```<code>Object::Object ()
  : foo (1)
  , bar (2)
{
  ...
}
</code>```

OwnerDisplayName: Iraimbilanja

LastEditorDisplayName: Iraimbilanja

Title: Brace placement after init list in C++

Body:
For anyone who places braces thus:

void f() {
    stuff();
}

How do you prefer to place braces after long initializer lists?

The same way?

Object::Object()
    : foo(1)
    , bar(2) {
    stuff();
}

Or make an exception so you actually see where the init list ends?

Object::Object()
    : foo(1)
    , bar(2)
{
    stuff();
}

Or leave a blank line?

Object::Object()
    : foo(1)
    , bar(2) {

    stuff();
}

Or maybe make a weird hybrid?

Object::Object()
    : foo(1)
    , bar(2)
    {
    stuff();
}

Or abuse indentation

Object::Object()
: foo(1)
, bar(2) {
    stuff();
}

Object::Object() : foo(1)
                            , bar(2) {
    stuff();
}

In this small example all are pretty but crank a dozen initializers and a moderately long function body and this quickly changes.

Body:
It seems important to be able to detect where the ctor-initializer list begins/ends, and where the code block begins/ends.

Object::Object ()
  : foo (1)
  , bar (2)
{
  ...
}


问:
How to find a javascript function using selenium/python/chrome
Im struggling to find and click javascript element which inspected looks like this:

```<code>"<a href="javascript:setTopicMode('PAAdvanced-search','300')">Patch advisories</a>"
</code>```

I tried to find by name, partial name and a href but I am a beginner so I did not managed to make it work.

driver.find_element_by_css_selector("a[onlick*=PAAdvanced-search','300]").click(); does not work either

Can someone advise?

Thank you

答:
You should be able to do something simple like

```<code>driver.find_element_by_link_text("Patch advisories").click()
</code>```

An alternative using the href would be to do something like

```<code>driver.find_element_by_css_selector("a[href*='PAAdvanced-search']").click()
</code>```

If those aren't working, something else is going on in the page. You either need a wait to wait for them to be available or you may have an IFRAME on the page.

Body:
Im struggling to find and click javascript element which inspected looks like this:

"Patch advisories"

I tried to find by name, partial name and a href but I am a beginner so I did not managed to make it work.

driver.find_element_by_css_selector("a[onlick*=PAAdvanced-search','300]").click(); does not work either

Can someone advise?

Thank you

Body:
You should be able to do something simple like

driver.find_element_by_link_text("Patch advisories").click()

An alternative using the href would be to do something like

driver.find_element_by_css_selector("a[href*='PAAdvanced-search']").click()

If those aren't working, something else is going on in the page. You either need a wait to wait for them to be available or you may have an IFRAME on the page.


问:
iOS get CGPoint from openCV cv::Point

In the above image ,we can see point which are drawn on image ,by some openCV algorithm.

I want to draw a UIView point on those points ,so that user can crop it.

I am not getting how will I access those points so that i can add uiview points.

I tried to read the cv::Point ,but value are just different(more) to the co-ordinate height and width.

```<code>static cv::Mat drawSquares( cv::Mat& image, const std::vector<std::vector<cv::Point> >& squares )
{

    int max_X=0,max_Y=0;
    int min_X=999,min_Y=999;
    for( size_t i = 0; i < squares.size(); i++ )
    {
        const cv::Point* p = &squares[i][0];
        int n = (int)squares[i].size();

        NSLog(@"Squares%d %d %d",n,p->x,p->y);

        polylines(image, &p, &n, 1, true, cv::Scalar(0,255,0), 3, cv::LINE_AA);

    }

    return image;
}
</code>```

In above code ,drawsquare method draw the squares .I have NSLog the point x, y co-ordinates but these values are not w.r.t to device co-ordinate system.

Can someone help me how it can be achieved Or an alternative to my requirement.

Thanks

答:
This is in Swift 3. In the Swift class that you're returning the cv::Points to:

Get the x and y dimensions of the image you're recording from your camera AV Capture Session

Divide the x and y dimension of the UIview you're using to visualize the image by the capture session's image dimensions in the X and Y

Multiply the point's x and y coordinates by the scaled x and y dimensions

```<code>{
    let imageScaleX = imgView.bounds.width/(newCameraHelper?.dimensionX)!
    let imageScaleY = imgView.bounds.height/(newCameraHelper?.dimensionY)!
    for point in Squares {
       let x = point.x * imageScaleX
       let y = point.y * imageScaleY
    }
}
</code>```

Title: iOS get CGPoint from openCV cv::Point

Body:
In the above image ,we can see point which are drawn on image ,by some openCV algorithm.

I want to draw a UIView point on those points ,so that user can crop it.

I am not getting how will I access those points so that i can add uiview points.

I tried to read the cv::Point ,but value are just different(more) to the co-ordinate height and width.

static cv::Mat drawSquares( cv::Mat& image, const std::vector<std::vector<cv::Point> >& squares )
{

    int max_X=0,max_Y=0;
    int min_X=999,min_Y=999;
    for( size_t i = 0; i < squares.size(); i++ )
    {
        const cv::Point* p = &squares[i][0];
        int n = (int)squares[i].size();

        NSLog(@"Squares%d %d %d",n,p->x,p->y);

        polylines(image, &p, &n, 1, true, cv::Scalar(0,255,0), 3, cv::LINE_AA);

    }

    return image;
}

In above code ,drawsquare method draw the squares .I have NSLog the point x, y co-ordinates but these values are not w.r.t to device co-ordinate system.

Can someone help me how it can be achieved Or an alternative to my requirement.

Thanks

Body:
This is in Swift 3. In the Swift class that you're returning the cv::Points to:

Get the x and y dimensions of the image you're recording from your camera AV Capture Session

Divide the x and y dimension of the UIview you're using to visualize the image by the capture session's image dimensions in the X and Y

Multiply the point's x and y coordinates by the scaled x and y dimensions

{
    let imageScaleX = imgView.bounds.width/(newCameraHelper?.dimensionX)!
    let imageScaleY = imgView.bounds.height/(newCameraHelper?.dimensionY)!
    for point in Squares {
       let x = point.x * imageScaleX
       let y = point.y * imageScaleY
    }
}


问:
ps -ax shows me a "rack" process. Is this normal?
I run a webpage using the Ruby web-framework Sinatra on my Ubuntu server. Today I looked to my processes and found these two lines:

```<code>30129 ?        S      0:00 Passenger ApplicationSpawner: /var/www/bla.com
30139 ?        S      0:00 Rack: /var/www/bla.com
</code>```

I never noticed these before. Are these normal, or should I be concerned?

答: It should be normal. Check out what Rack is. Killing that process could risk your webpage functionality, so don't do it.</p>

Body:
I run a webpage using the Ruby web-framework Sinatra on my Ubuntu server. Today I looked to my processes and found these two lines:

30129 ?        S      0:00 Passenger ApplicationSpawner: /var/www/bla.com
30139 ?        S      0:00 Rack: /var/www/bla.com

I never noticed these before. Are these normal, or should I be concerned?


问:
Thread.sleep( ) with Espresso
Espresso claims that there is no need for Thread.sleep() but my code doesn't work unless I include it. I am connecting to an IP and, while connecting, a progress dialog is shown. I need a Thread.sleep() call to wait for the dialog to dismiss. This is my test code where I use it:

```<code>    IP.enterIP(); // fills out an IP dialog (this is done with espresso)

    //progress dialog is now shown
    Thread.sleep(1500);

    onView(withId(R.id.button).perform(click());
</code>```

I have tried this code without the Thread.sleep() call but it says R.id.Button doesn't exist. The only way I can get it to work is with the Thread.sleep() call.

Also, I have tried replacing Thread.sleep() with things like getInstrumentation().waitForIdleSync() and still no luck.

Is this the only way to do this? Or am I missing something?

答:
You can just use Barista methods:

BaristaSleepActions.sleep(2000);

BaristaSleepActions.sleep(2, SECONDS);

Barista is a library that wraps Espresso to avoid adding all the code needed by the accepted answer. And here's a link!  https://github.com/SchibstedSpain/Barista

ContentLicense: CC BY-SA 4.0

Title: Thread.sleep( ) with Espresso

Body:
Espresso claims that there is no need for Thread.sleep() but my code doesn't work unless I include it. I am connecting to an IP and, while connecting, a progress dialog is shown. I need a Thread.sleep() call to wait for the dialog to dismiss. This is my test code where I use it:

    IP.enterIP(); // fills out an IP dialog (this is done with espresso)

    //progress dialog is now shown
    Thread.sleep(1500);

    onView(withId(R.id.button).perform(click());

I have tried this code without the Thread.sleep() call but it says R.id.Button doesn't exist. The only way I can get it to work is with the Thread.sleep() call.

Also, I have tried replacing Thread.sleep() with things like getInstrumentation().waitForIdleSync() and still no luck.

Is this the only way to do this? Or am I missing something?


问:
Facebook Logon not working properly with Azure Mobile Client in Xamarin.Forms
I'm implementing Facebook Logon with Azure Mobile Client in Xamarin.Forms. In iOS, after entering login name and password, it directed to the confirmation page but I couldn't click anything on the screen. The loading icon kept running and should represent that the loading hadn't completed yet. Anyone encountered similar situation and anything I could do to fix it?

答: There are/were issues with Facebook auth on Azure App Service due to a deprecation in the Facebook side of the OAuth dance.  See https://social.msdn.microsoft.com/Forums/en-US/397f6952-57bf-4c28-b383-6bba08d28f9a/facebook-login-failures-with-app-service-authentication-authorization?forum=windowsazurewebsitespreview for more details.</p>


问:
How to set position from StreamReader file
Okay here's the thing. I tired to try make position from StreamReader file. I also already try using Console.SetCursorPosition with function but it only change on first row in file text. My question is, how to make position for all rows in file. Here's my file:

```<code> N01    Chicken Nugget  20000   0
 N02    Tempe Nugget    15000   0
 N03    Tofu Nugget     15000   0
</code>```

and here's the output, which is not display N word causing hide on left frame.Click to see it and my expectation here

Here's my code

```<code>namespace Nugget
{
    class case1
    {
        public void cs1()
        {
            Console.Clear();
            Console.WriteLine("╔═══════════════════════════════════════════════════════════════════════════════════════╗");
            Console.WriteLine("║ProID\tProduct Name\tPrice\tStock\t\t\t\t\t\t\t║");
            Console.WriteLine("╠═══════════════════════════════════════════════════════════════════════════════════════╣");
            StreamReader objReader = new StreamReader(@"E:\CCIT\Semester 2\Q1\Project 1\AbsolutlyRealGetNugget\Nugget.txt");
            string sLine = "";
            ArrayList arrText = new ArrayList();
            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                    arrText.Add(sLine);
            }
            objReader.Close();
            foreach (string sOutput in arrText)
            Console.WriteLine(sOutput);
            Console.SetCursorPosition(0, 4);
            Console.WriteLine("║");
            Console.SetCursorPosition(0, 5);
            Console.WriteLine("║");
            Console.SetCursorPosition(0, 6);
            Console.WriteLine("║");
            Console.SetCursorPosition(88, 4);
            Console.WriteLine("║");
            Console.SetCursorPosition(88, 5);
            Console.WriteLine("║");
            Console.SetCursorPosition(88, 6);
            Console.WriteLine("║");
            Console.WriteLine("╚═══════════════════════════════════════════════════════════════════════════════════════╝\n");
        }
    }
}
</code>```

答:
I also already try using Console.SetCursorPosition with function but
  it only change on first row in file text.

Your current foreach loop code of:

```<code>foreach (string sOutput in arrText)
Console.WriteLine(sOutput);
Console.SetCursorPosition(0, 4);
... more code ...
</code>```

does not have any brackets { and }, which means only the line directly below the foreach line gets repeated.  To make the whole block get repeated for each iteration, insert brackets like this:

```<code>foreach (string sOutput in arrText)
{
    Console.WriteLine(sOutput);
    Console.SetCursorPosition(0, 4);
    ... more code ...
}
</code>```

With that said, I would approach it this way instead:

```<code>    static void Main(string[] args)
    {
        string nugget = @"C:\Users\mikes\Documents\Nugget.txt";
        string[] arrText = File.ReadAllLines(nugget);

        int menuWidth = 89;
        string bar = new string('═', menuWidth - 2);

        Console.Clear();
        Console.WriteLine("╔" + bar + "╗");
        Console.Write("║ProID\tProduct Name\tPrice\tStock");
        Console.SetCursorPosition(menuWidth - 1, Console.CursorTop);
        Console.WriteLine("║");
        Console.WriteLine("╠" + bar + "╣");

        foreach (string sOutput in arrText)
        {
            Console.Write(sOutput);
            Console.SetCursorPosition(0, Console.CursorTop);
            Console.Write("║");
            Console.SetCursorPosition(menuWidth - 1, Console.CursorTop);
            Console.WriteLine("║");
        }

        Console.WriteLine("╚" + bar + "╝");
        Console.WriteLine("");
        Console.ReadLine();
    }
</code>```

Note that I'm using both Console.WriteLine() and Console.Write().  The latter method will output to the console without a line terminator, thus leaving the cursor on the same line.  Afterwards, we can move the cursor to the right edge of the menu, on the same line via Console.CursorTop, and draw the vertical bar with:

```<code>Console.SetCursorPosition(menuWidth - 1, Console.CursorTop);
Console.WriteLine("║");
</code>```

This produced the following output:

```<code>╔═══════════════════════════════════════════════════════════════════════════════════════╗
║ProID  Product Name    Price   Stock                                                   ║
╠═══════════════════════════════════════════════════════════════════════════════════════╣
║N01    Chicken Nugget  20000   0                                                       ║
║N02    Tempe Nugget    15000   0                                                       ║
║N03    Tofu Nugget     15000   0                                                       ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝
</code>```

Body:
Okay here's the thing. I tired to try make position from StreamReader file. I also already try using Console.SetCursorPosition with function but it only change on first row in file text. My question is, how to make position for all rows in file. Here's my file:

 N01    Chicken Nugget  20000   0
 N02    Tempe Nugget    15000   0
 N03    Tofu Nugget     15000   0

and here's the output, which is not display N word causing hide on left frame.Click to see it and my expectation here

Here's my code

namespace Nugget
{
    class case1
    {
        public void cs1()
        {
            Console.Clear();
            Console.WriteLine("╔═══════════════════════════════════════════════════════════════════════════════════════╗");
            Console.WriteLine("║ProID\tProduct Name\tPrice\tStock\t\t\t\t\t\t\t║");
            Console.WriteLine("╠═══════════════════════════════════════════════════════════════════════════════════════╣");
            StreamReader objReader = new StreamReader(@"E:\CCIT\Semester 2\Q1\Project 1\AbsolutlyRealGetNugget\Nugget.txt");
            string sLine = "";
            ArrayList arrText = new ArrayList();
            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                    arrText.Add(sLine);
            }
            objReader.Close();
            foreach (string sOutput in arrText)
            Console.WriteLine(sOutput);
            Console.SetCursorPosition(0, 4);
            Console.WriteLine("║");
            Console.SetCursorPosition(0, 5);
            Console.WriteLine("║");
            Console.SetCursorPosition(0, 6);
            Console.WriteLine("║");
            Console.SetCursorPosition(88, 4);
            Console.WriteLine("║");
            Console.SetCursorPosition(88, 5);
            Console.WriteLine("║");
            Console.SetCursorPosition(88, 6);
            Console.WriteLine("║");
            Console.WriteLine("╚═══════════════════════════════════════════════════════════════════════════════════════╝\n");
        }
    }
}

Body:
I also already try using Console.SetCursorPosition with function but
  it only change on first row in file text.

Your current foreach loop code of:

foreach (string sOutput in arrText)
Console.WriteLine(sOutput);
Console.SetCursorPosition(0, 4);
... more code ...

does not have any brackets { and }, which means only the line directly below the foreach line gets repeated.  To make the whole block get repeated for each iteration, insert brackets like this:

foreach (string sOutput in arrText)
{
    Console.WriteLine(sOutput);
    Console.SetCursorPosition(0, 4);
    ... more code ...
}

With that said, I would approach it this way instead:

    static void Main(string[] args)
    {
        string nugget = @"C:\Users\mikes\Documents\Nugget.txt";
        string[] arrText = File.ReadAllLines(nugget);

        int menuWidth = 89;
        string bar = new string('═', menuWidth - 2);

        Console.Clear();
        Console.WriteLine("╔" + bar + "╗");
        Console.Write("║ProID\tProduct Name\tPrice\tStock");
        Console.SetCursorPosition(menuWidth - 1, Console.CursorTop);
        Console.WriteLine("║");
        Console.WriteLine("╠" + bar + "╣");

        foreach (string sOutput in arrText)
        {
            Console.Write(sOutput);
            Console.SetCursorPosition(0, Console.CursorTop);
            Console.Write("║");
            Console.SetCursorPosition(menuWidth - 1, Console.CursorTop);
            Console.WriteLine("║");
        }

        Console.WriteLine("╚" + bar + "╝");
        Console.WriteLine("");
        Console.ReadLine();
    }

Note that I'm using both Console.WriteLine() and Console.Write().  The latter method will output to the console without a line terminator, thus leaving the cursor on the same line.  Afterwards, we can move the cursor to the right edge of the menu, on the same line via Console.CursorTop, and draw the vertical bar with:

Console.SetCursorPosition(menuWidth - 1, Console.CursorTop);
Console.WriteLine("║");

This produced the following output:

╔═══════════════════════════════════════════════════════════════════════════════════════╗
║ProID  Product Name    Price   Stock                                                   ║
╠═══════════════════════════════════════════════════════════════════════════════════════╣
║N01    Chicken Nugget  20000   0                                                       ║
║N02    Tempe Nugget    15000   0                                                       ║
║N03    Tofu Nugget     15000   0                                                       ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝


问:
Error with Tuple in C# 2008
I have made a program in C# 2010 and my code contains a Tuple, but when I put my program into C# 2008 it does not recognise it, and comes up with the error of:

"The type of namespace name 'Tuple' could not be found"

So I don't know how to make this work, this is the line of code in which the error occurs:

```<code>private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
</code>```

Please help.

EDIT

Basically this is my code at the moment which doesn't compile due to the error:

```<code>public partial class Form1 : Form
{
    private bool isMoving = false;
    private Point mouseDownPosition = Point.Empty;
    private Point mouseMovePosition = Point.Empty;
    private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        var g = e.Graphics;
        if (isMoving)
        {
            g.Clear(pictureBox1.BackColor);
            g.DrawLine(Pens.Black, mouseDownPosition, mouseMovePosition);
            foreach (var line in lines)
            {
                g.DrawLine(Pens.Black, line.Item1, line.Item2);
            }
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        isMoving = true;
        mouseDownPosition = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            mouseMovePosition = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            lines.Add(Tuple.Create(mouseDownPosition, mouseMovePosition));
        }
        isMoving = false;
    }
}
</code>```

So I need a way of changing or making the Tuple work in VS C# 2008 as well as 2010,

Thanks

答: Update to framework 4.0 (find any patch for VS 2008) else, visual studio 2010 is recommended for Tuple, </p>

Title: Error with Tuple in C# 2008

Body:
I have made a program in C# 2010 and my code contains a Tuple, but when I put my program into C# 2008 it does not recognise it, and comes up with the error of:

"The type of namespace name 'Tuple' could not be found"

So I don't know how to make this work, this is the line of code in which the error occurs:

private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();

Please help.

EDIT

Basically this is my code at the moment which doesn't compile due to the error:

public partial class Form1 : Form
{
    private bool isMoving = false;
    private Point mouseDownPosition = Point.Empty;
    private Point mouseMovePosition = Point.Empty;
    private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        var g = e.Graphics;
        if (isMoving)
        {
            g.Clear(pictureBox1.BackColor);
            g.DrawLine(Pens.Black, mouseDownPosition, mouseMovePosition);
            foreach (var line in lines)
            {
                g.DrawLine(Pens.Black, line.Item1, line.Item2);
            }
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        isMoving = true;
        mouseDownPosition = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            mouseMovePosition = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            lines.Add(Tuple.Create(mouseDownPosition, mouseMovePosition));
        }
        isMoving = false;
    }
}

So I need a way of changing or making the Tuple work in VS C# 2008 as well as 2010,

Thanks


问:
UIImageOrientation documentation is incorrect
Looking through Apple's documentation for UIImageOrientation I notice that the images that go with the descriptions are incorrect.

https://developer.apple.com/reference/uikit/uiimageorientation

This has been painful for me, so I'm going to leave this here, with the correct images in the answer in case others find the same.

If people think this shouldn't be here, please comment / vote down and I'll remove.

答:
Here's how I got the correct images:

```<code>extension UIImage {

    var normalised: UIImage {

        if imageOrientation == .up {
            return self
        }

        var normalisedImage: UIImage

        let format = UIGraphicsImageRendererFormat.default()
        format.scale = scale
        format.opaque = true
        format.prefersExtendedRange = false
        normalisedImage = UIGraphicsImageRenderer(size: size, format: format).image { _ in
            draw(in: CGRect(origin: .zero, size: size))
        }

        return normalisedImage
    }

    func translated(to orientation: UIImageOrientation) -> UIImage {
        guard let cgImage = cgImage else {

            return self
        }

        return UIImage(cgImage: cgImage, scale: 1, orientation: orientation).normalised
    }
}
</code>```

Then using this image as the "base"

Body:
Here's how I got the correct images:

extension UIImage {

    var normalised: UIImage {

        if imageOrientation == .up {
            return self
        }

        var normalisedImage: UIImage

        let format = UIGraphicsImageRendererFormat.default()
        format.scale = scale
        format.opaque = true
        format.prefersExtendedRange = false
        normalisedImage = UIGraphicsImageRenderer(size: size, format: format).image { _ in
            draw(in: CGRect(origin: .zero, size: size))
        }

        return normalisedImage
    }

    func translated(to orientation: UIImageOrientation) -> UIImage {
        guard let cgImage = cgImage else {

            return self
        }

        return UIImage(cgImage: cgImage, scale: 1, orientation: orientation).normalised
    }
}

Then using this image as the "base"


问:
Laravel Auth::attempt always return false?
Here is myscreen shot of database and my login input

```<code>public function action(Request $request){
         $username = $request->username;
         $pass = bcrypt($request->password);
         $credentials = [
                         'id' => $username,
                         'password' => $pass
                        ];

    dd(Auth::attempt($credentials));
         if (Auth::attempt(['id' => $username, 'password' => $pass])) {
            echo 'Ok';
         }else{
            echo 'Not ok';
         }
</code>```

I'm trying to make a login action using laravel auth::attemptbut it always return false.

答:
```<code>$pass = bcrypt($request->password);
</code>```

should be

```<code>$pass = $request->password;
</code>```

The attempt method will automatically handle the encryption and comparison. You are in effect bcrypting it twice, so a match isn't found

Body:
Here is myscreen shot of database and my login input

public function action(Request $request){
         $username = $request->username;
         $pass = bcrypt($request->password);
         $credentials = [
                         'id' => $username,
                         'password' => $pass
                        ];

    dd(Auth::attempt($credentials));
         if (Auth::attempt(['id' => $username, 'password' => $pass])) {
            echo 'Ok';
         }else{
            echo 'Not ok';
         }

I'm trying to make a login action using laravel auth::attemptbut it always return false.

Body:
$pass = bcrypt($request->password);

should be

$pass = $request->password;

The attempt method will automatically handle the encryption and comparison. You are in effect bcrypting it twice, so a match isn't found


问:
Renaming Child Nodes where there are two of the same
I am trying to rename one of the child nodes where two exist within a parent node and create a new XML file with the updated information.There may be a parent node <Accounts> with one child node, but where there exist a 2nd child node with the same name, I'd like to rename it, to something like <Account2></Account2>. I have some code where I read the entire XML file and renames the node, but I know this is not the right approach.

For example XML data looks similar to the below:

<Accounts>
    <Account>Value</Account>
    <Account>Value</Account>
</Accounts>
```

<p>VBScript: </p>

<pre class="lang-vb prettyprint-override"><code>Dim objFSO, objTextFile, strText, strNewText, objNewFile
Dim strOriginalFile, strTempFile

strOriginalFile = "c:\XML_File.xml"

strTempFile = "c:\temp.xml"

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objNewFile = objFSO.CreateTextFile(strTempFile)

Set objTextFile = objFSO.OpenTextFile (strOriginalFile, 1)
strText = objTextFile.ReadAll

strNewText = Replace(strText, "<Account>", "<Account2>", vbTextCompare)

objNewFile.Write strNewText

objTextFile.Close
objNewFile.Close
</code>```

答:
Using XPath notation, you can access child nodes based off context.  Loops through each <Account> child node, replaces it with an enumerated node that's a deep copy of the old one.

Set xml = CreateObject("Microsoft.XMLDOM")

xml.async = False
count_var = 1

If xml.Load("C:\file.xml") Then
    For Each accountCollection In xml.SelectNodes("//Accounts")
        For Each account In accountCollection.SelectNodes("./Account")
            If count_var > 1 Then

                Set accountEnum = xml.createNode(1, "Account" & count_var, "")
                For Each child In account.childNodes
                    accountEnum.appendChild(child.cloneNode(TRUE))
                Next
                accountCollection.replaceChild accountEnum, account

                xml.save("C:\file.xml")
            End If
            count_var = count_var + 1
        Next
        count_var = 1
    Next
End If
```

<p><strong>Input:</strong></p>

<pre class="lang-xml prettyprint-override"><code><Accounts>
    <Account>test</Account>
    <Account>
        <ID>000</ID>
        <CONFIG type="binary" name="test"/>
    </Account>
    <Account>test1</Account>
</Accounts>
</code>```

Output

```<code><Accounts>
    <Account>test</Account>
    <Account2>
        <ID>000</ID>
        <CONFIG type="binary" name="test"/>
    </Account2>
    <Account3>test1</Account3>
</Accounts>
</code>```

Body:
I am trying to rename one of the child nodes where two exist within a parent node and create a new XML file with the updated information.There may be a parent node <Accounts> with one child node, but where there exist a 2nd child node with the same name, I'd like to rename it, to something like <Account2></Account2>. I have some code where I read the entire XML file and renames the node, but I know this is not the right approach.

For example XML data looks similar to the below:

<Accounts>
    <Account>Value</Account>
    <Account>Value</Account>
</Accounts>

VBScript:

Dim objFSO, objTextFile, strText, strNewText, objNewFile
Dim strOriginalFile, strTempFile

strOriginalFile = "c:\XML_File.xml"

strTempFile = "c:\temp.xml"

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objNewFile = objFSO.CreateTextFile(strTempFile)

Set objTextFile = objFSO.OpenTextFile (strOriginalFile, 1)
strText = objTextFile.ReadAll

strNewText = Replace(strText, "<Account>", "<Account2>", vbTextCompare)

objNewFile.Write strNewText

objTextFile.Close
objNewFile.Close

Body:
Using XPath notation, you can access child nodes based off context.  Loops through each <Account> child node, replaces it with an enumerated node that's a deep copy of the old one.

Set xml = CreateObject("Microsoft.XMLDOM")

xml.async = False
count_var = 1

If xml.Load("C:\file.xml") Then
    For Each accountCollection In xml.SelectNodes("//Accounts")
        For Each account In accountCollection.SelectNodes("./Account")
            If count_var > 1 Then

                Set accountEnum = xml.createNode(1, "Account" & count_var, "")
                For Each child In account.childNodes
                    accountEnum.appendChild(child.cloneNode(TRUE))
                Next
                accountCollection.replaceChild accountEnum, account

                xml.save("C:\file.xml")
            End If
            count_var = count_var + 1
        Next
        count_var = 1
    Next
End If

Input:

<Accounts>
    <Account>test</Account>
    <Account>
        <ID>000</ID>
        <CONFIG type="binary" name="test"/>
    </Account>
    <Account>test1</Account>
</Accounts>

Output

<Accounts>
    <Account>test</Account>
    <Account2>
        <ID>000</ID>
        <CONFIG type="binary" name="test"/>
    </Account2>
    <Account3>test1</Account3>
</Accounts>


问:
Using shared memory in Dynamic Parallelism CUDA
Question 1:
Do I have to specify the amount of dynamic shared memory to be allocated at the launch of parent kernel if shared memory is only used by child kernel.

Question 2:
The following is my child kernel and parent kernel

Parent kernel

```<code>__global__ void ColumnFractionalShift(DataIn DataInput,float* __restrict__ DeviceInput, float ShiftAmount, float* __restrict__ LightFieldDevice)
{
    cudaError_t status;
    float ImageShift = threadIdx.x*ShiftAmount;
    float ImageIntegerShift = nearbyintf(ImageShift);
    float Delay = ImageShift - ImageIntegerShift;
    int InputImageOffset = +DataInput.X*DataInput.Y*DataInput.U*(threadIdx.y) + DataInput.X*DataInput.Y*(threadIdx.x);
    dim3 dimBlock(32, 24);
    dim3 dimGrid(16, 14);
    //if (threadIdx.x > 5)
    {
        ConvolutionColumn << <dimGrid, dimBlock, ((sizeof(float)* 24 * 32 * 3)) >> >(DataInput, DeviceInput + InputImageOffset, Delay, LightFieldDevice + InputImageOffset);
    }
    status = cudaGetLastError();
    if (status != cudaSuccess) {
        printf("failed %s\n", cudaGetErrorString(status));
    }
    cudaDeviceSynchronize();

    if (threadIdx.x == 5)
    {
        printf("The values at beginig of %d  %d are %f\n", threadIdx.x, threadIdx.y, *(LightFieldDevice + InputImageOffset));
    }
}
</code>```

Child Kernel

```<code>__global__ void ConvolutionColumn(DataIn DataInput,float* __restrict__ DeviceInput, float Delay, float* __restrict__ DeviceResult)
{
    extern __shared__ float ConvolutionBlockLeft[];
    int BlockStart = blockDim.y*blockIdx.y*DataInput.V + blockIdx.x*blockDim.x;
    //int BlockEnd = BlockStart+(blockDim.x*blockDim.y)-1;
    int PixelId = blockDim.x*threadIdx.y + threadIdx.x; //32 by 24 kernal
    int LoadPixelId = DataInput.V*threadIdx.y + threadIdx.x;
    int LoadLeft,LoadRght,LoadCentre;
    float KernalSum;
    float DelayPower = Delay;
    //load upper values
    if (blockIdx.y == 0)
    {
        LoadLeft = DataInput.V*(blockDim.y - threadIdx.y-1) + threadIdx.x;
    }
    else
    {
        LoadLeft =  LoadPixelId - (DataInput.V*blockDim.y);
    }
    *(ConvolutionBlockLeft + (threadIdx.y*blockDim.x) + threadIdx.x) = *(DeviceInput + BlockStart + LoadLeft);
    if (blockIdx.y*blockDim.y + threadIdx.y >= DataInput.U)
    {
        LoadCentre = ((DataInput.U - 1)*DataInput.V) + (blockDim.x*blockIdx.x) + threadIdx.x - ((blockIdx.y*blockDim.y + threadIdx.y) - DataInput.U)*DataInput.V;
    }
    else
    {
        LoadCentre = BlockStart+LoadPixelId;
    }
    *(ConvolutionBlockLeft + (blockDim.x*blockDim.y) + (threadIdx.y*blockDim.x) + threadIdx.x) = *(DeviceInput + LoadCentre);
    if (blockIdx.y*blockDim.y + threadIdx.y + blockDim.y >= DataInput.U)
    {
        LoadRght = ((DataInput.U - 1)*DataInput.V) + (blockDim.x*blockIdx.x) + threadIdx.x - ((((blockIdx.y*blockDim.y) + threadIdx.y + blockDim.y) - DataInput.U)*DataInput.V);
    }
    else
    {
        LoadRght = BlockStart+LoadPixelId + (DataInput.V*blockDim.y);
    }
    //float tempfil, tempdata;
    //int t;
    *(ConvolutionBlockLeft + (2 * blockDim.x*blockDim.y) + (threadIdx.y*blockDim.x) + threadIdx.x) = *(DeviceInput + LoadRght);
    __syncthreads();
    float FilterSum = *(ConvolutionBlockLeft + ((blockDim.x*blockDim.y) + PixelId));
    for (int k = 1; k < DataInput.KernalNoOfFilters; k++)
    {
        KernalSum = 0;
        //printf("The value of filter size is %d\n", (DeviceFilterSize[k]));
        for (int l = -((*(DeviceFilterSize + k) - 1) / 2); l < ((*(DeviceFilterSize + k) + 1) / 2); l++)
        {
            //tempfil = *(DeviceFilterKernal + k*DataInput.KernalFilterLength + ((*(DeviceFilterSize + k) - 1) / 2) + l);
            //t = (blockDim.x*blockDim.y) + PixelId + (l*blockDim.x);
            //tempdata = *(ConvolutionBlockLeft + ((blockDim.x*blockDim.y) + PixelId - (l*blockDim.x)));
            KernalSum += *(DeviceFilterKernal + k*DataInput.KernalFilterLength + ((*(DeviceFilterSize + k) - 1) / 2) + l)**(ConvolutionBlockLeft + ((blockDim.x*blockDim.y) + PixelId - (l*blockDim.x)));
        }
        KernalSum *= DelayPower;
        DelayPower *= Delay;
        FilterSum += KernalSum;
    }
    if (blockIdx.y*blockDim.y + threadIdx.y < DataInput.U)
    {
        *(DeviceResult + LoadPixelId + BlockStart) = FilterSum;
    }
}
</code>```

Here child kernel alone works fine. However when its launched from another kernel, after parent kernel launch from host at cudaDeviceSynchronize() unspecified launch failure error is given(The error isn't printed from printf within the kernel).

The launch configuration of parent kernel is <<<1,(17 17)>>>. If only one thread from parent is allowed to launch the child grid then the code works fine. Is there a limit on how many grids that can be launched from one block?

答:
Do I have to specify the amount of dynamic shared memory to be allocated at the launch of parent kernel if shared memory is only used by child kernel.

No, you only specify dynamic shared memory allocation on the actual kernel invocations that will need/use it.  You do not have to take into account child kernel needs on parent kernel launches.

Is there a limit on how many grids that can be launched from one block?

There isn't any such limit.  There is a cudaLimitDevRuntimePendingLaunchCount, but by default it is set to 2048, which would appear to exceed your request of 17*17 = 289, and furthermore you don't appear to be receiving this particular error.  (And this is a dynamic limit, so the simple fact that a parent kernel appears to be launching more than this limit does not guarantee that this limit/error will be hit. It depends on the actual dynamic launch behavior.)

If the question you'd like to ask is "why isn't this code working?", then you should provide a MCVE.

Body:
Question 1:
Do I have to specify the amount of dynamic shared memory to be allocated at the launch of parent kernel if shared memory is only used by child kernel.

Question 2:
The following is my child kernel and parent kernel

Parent kernel

__global__ void ColumnFractionalShift(DataIn DataInput,float* __restrict__ DeviceInput, float ShiftAmount, float* __restrict__ LightFieldDevice)
{
    cudaError_t status;
    float ImageShift = threadIdx.x*ShiftAmount;
    float ImageIntegerShift = nearbyintf(ImageShift);
    float Delay = ImageShift - ImageIntegerShift;
    int InputImageOffset = +DataInput.X*DataInput.Y*DataInput.U*(threadIdx.y) + DataInput.X*DataInput.Y*(threadIdx.x);
    dim3 dimBlock(32, 24);
    dim3 dimGrid(16, 14);
    //if (threadIdx.x > 5)
    {
        ConvolutionColumn << <dimGrid, dimBlock, ((sizeof(float)* 24 * 32 * 3)) >> >(DataInput, DeviceInput + InputImageOffset, Delay, LightFieldDevice + InputImageOffset);
    }
    status = cudaGetLastError();
    if (status != cudaSuccess) {
        printf("failed %s\n", cudaGetErrorString(status));
    }
    cudaDeviceSynchronize();

    if (threadIdx.x == 5)
    {
        printf("The values at beginig of %d  %d are %f\n", threadIdx.x, threadIdx.y, *(LightFieldDevice + InputImageOffset));
    }
}

Child Kernel

__global__ void ConvolutionColumn(DataIn DataInput,float* __restrict__ DeviceInput, float Delay, float* __restrict__ DeviceResult)
{
    extern __shared__ float ConvolutionBlockLeft[];
    int BlockStart = blockDim.y*blockIdx.y*DataInput.V + blockIdx.x*blockDim.x;
    //int BlockEnd = BlockStart+(blockDim.x*blockDim.y)-1;
    int PixelId = blockDim.x*threadIdx.y + threadIdx.x; //32 by 24 kernal
    int LoadPixelId = DataInput.V*threadIdx.y + threadIdx.x;
    int LoadLeft,LoadRght,LoadCentre;
    float KernalSum;
    float DelayPower = Delay;
    //load upper values
    if (blockIdx.y == 0)
    {
        LoadLeft = DataInput.V*(blockDim.y - threadIdx.y-1) + threadIdx.x;
    }
    else
    {
        LoadLeft =  LoadPixelId - (DataInput.V*blockDim.y);
    }
    *(ConvolutionBlockLeft + (threadIdx.y*blockDim.x) + threadIdx.x) = *(DeviceInput + BlockStart + LoadLeft);
    if (blockIdx.y*blockDim.y + threadIdx.y >= DataInput.U)
    {
        LoadCentre = ((DataInput.U - 1)*DataInput.V) + (blockDim.x*blockIdx.x) + threadIdx.x - ((blockIdx.y*blockDim.y + threadIdx.y) - DataInput.U)*DataInput.V;
    }
    else
    {
        LoadCentre = BlockStart+LoadPixelId;
    }
    *(ConvolutionBlockLeft + (blockDim.x*blockDim.y) + (threadIdx.y*blockDim.x) + threadIdx.x) = *(DeviceInput + LoadCentre);
    if (blockIdx.y*blockDim.y + threadIdx.y + blockDim.y >= DataInput.U)
    {
        LoadRght = ((DataInput.U - 1)*DataInput.V) + (blockDim.x*blockIdx.x) + threadIdx.x - ((((blockIdx.y*blockDim.y) + threadIdx.y + blockDim.y) - DataInput.U)*DataInput.V);
    }
    else
    {
        LoadRght = BlockStart+LoadPixelId + (DataInput.V*blockDim.y);
    }
    //float tempfil, tempdata;
    //int t;
    *(ConvolutionBlockLeft + (2 * blockDim.x*blockDim.y) + (threadIdx.y*blockDim.x) + threadIdx.x) = *(DeviceInput + LoadRght);
    __syncthreads();
    float FilterSum = *(ConvolutionBlockLeft + ((blockDim.x*blockDim.y) + PixelId));
    for (int k = 1; k < DataInput.KernalNoOfFilters; k++)
    {
        KernalSum = 0;
        //printf("The value of filter size is %d\n", (DeviceFilterSize[k]));
        for (int l = -((*(DeviceFilterSize + k) - 1) / 2); l < ((*(DeviceFilterSize + k) + 1) / 2); l++)
        {
            //tempfil = *(DeviceFilterKernal + k*DataInput.KernalFilterLength + ((*(DeviceFilterSize + k) - 1) / 2) + l);
            //t = (blockDim.x*blockDim.y) + PixelId + (l*blockDim.x);
            //tempdata = *(ConvolutionBlockLeft + ((blockDim.x*blockDim.y) + PixelId - (l*blockDim.x)));
            KernalSum += *(DeviceFilterKernal + k*DataInput.KernalFilterLength + ((*(DeviceFilterSize + k) - 1) / 2) + l)**(ConvolutionBlockLeft + ((blockDim.x*blockDim.y) + PixelId - (l*blockDim.x)));
        }
        KernalSum *= DelayPower;
        DelayPower *= Delay;
        FilterSum += KernalSum;
    }
    if (blockIdx.y*blockDim.y + threadIdx.y < DataInput.U)
    {
        *(DeviceResult + LoadPixelId + BlockStart) = FilterSum;
    }
}

Here child kernel alone works fine. However when its launched from another kernel, after parent kernel launch from host at cudaDeviceSynchronize() unspecified launch failure error is given(The error isn't printed from printf within the kernel).

The launch configuration of parent kernel is <<<1,(17 17)>>>. If only one thread from parent is allowed to launch the child grid then the code works fine. Is there a limit on how many grids that can be launched from one block?


问:
Use CSS :not Selector for inner link
I use a plugin on a Wordpress blog. It marks alle links to amazon with an asterix in source code (no css). I mark my custom link also with an asterix via css. So the plugin links have two asterix ** instead of one *.
I tried to fix it with the not selector but is does not work (broweser: firefox).
I want to know if its possible with :not() selector

Plugin Code:

```<code><div class="plugin"><a href="amazon.com">LINK*</a></div>
</code>```

My Code:

```<code><a href="amazon.com">Link</a>
</code>```

CSS

```<code>a[href*="amazon.com"]:not(.plugin a):after {content: "*"; }
</code>```

答:
You can add a new CSS rule.

```<code>a[href*="amazon.com"]:after {
  content: "*";
}
.plugin a:after{
  content: "";
}
</code>```

EDIT: Here is a solution that uses :not

```<code>:not(.plugin) > a[href*="amazon.com"]:after {
  content: "*";
}
</code>```

https://jsfiddle.net/zcktfbad/

Title: Use CSS :not Selector for inner link

Body:
I use a plugin on a Wordpress blog. It marks alle links to amazon with an asterix in source code (no css). I mark my custom link also with an asterix via css. So the plugin links have two asterix ** instead of one *.
I tried to fix it with the not selector but is does not work (broweser: firefox).
I want to know if its possible with :not() selector

Plugin Code:

LINK*

My Code:

Link

CSS

a[href*="amazon.com"]:not(.plugin a):after {content: "*"; }

Body:
You can add a new CSS rule.

a[href*="amazon.com"]:after {
  content: "*";
}
.plugin a:after{
  content: "";
}

EDIT: Here is a solution that uses :not

:not(.plugin) > a[href*="amazon.com"]:after {
  content: "*";
}

https://jsfiddle.net/zcktfbad/


问:
The fastest way to work with a large array of data in node
I have some db with 4 000 000 numbers and I need to check if some number is exist in db

Database exapmle: [177,219,245,309,348,436,...]

I tried use mysql table but it takes 1300ms for check if some 1 number is exist

It very long time and I`ve check some another ways:

1) Push all numbers to array and check it with indexOf

2) Push all numbers to string and check it with indexOf

3) Push all numbers to object and check it with hasOwnProperty

4) Push all numbers to object and check value

I`ve made 100 checks in all of this ways and measured the time:

```<code>try [...].indexOf(...) === 0
Total: 726ms

try String(...).indexOf(...) === 0
Total: 1915ms

try {...}.hasOwnProperty(...) === true
Total: 4ms

try {...}[...] === true === true
Total: 4ms
</code>```

The code of tests:

```<code>// Reads db json with ~4 000 000 elements
var arr = utils.readJSON('members.json');
// Converts db to string type
var arr_string = arr.toString();
// Makes empty object
var arr_obj = {};
// Converts db to object type
for(var i in arr){
    arr_obj[arr[i]] = true;
}
// Makes empty array
var checkList = [];
// Gets 100 different values from different places of db
for(var i = 0; i < 100; i++){
    checkList.push(arr[Math.floor(arr.length / 100 * i)]);
}
// Main time variable
var time;

// test
time = new Date().getTime();
for (var i in checkList) {
    console.log('try [...].indexOf('+ checkList[i]+') === ' + arr.indexOf(checkList[i]));
}
console.log('Total: ' + (new Date().getTime() - time) + 'ms');

// test
time = new Date().getTime();
for (var i in checkList) {
    console.log('try String(...).indexOf(' + checkList[i] + ') === ' + arr_string.indexOf(checkList[i]));
}
console.log('Total: ' + (new Date().getTime() - time) + 'ms');

// test
time = new Date().getTime();
for (var i in checkList) {
    console.log('try {...}.hasOwnProperty(' + checkList[i] + ') === ' + arr_obj.hasOwnProperty(checkList[i]));
}
console.log('Total: ' + (new Date().getTime() - time) + 'ms');

// test
time = new Date().getTime();
for (var i in checkList) {
    console.log('try {...}[' + checkList[i] + '] === true === ' + (arr_obj[checkList[i]] === true));
}
console.log('Total: ' + (new Date().getTime() - time) + 'ms');
</code>```

I believe that the best way to perform this task is Object with hasOwnProperty, but what different ways do you know?

Maybe I should try using other databases?

答:
It started out as a comments but it didn't fit so I post it as an answer. As other has already pointed out, use an index on the column that you want to search or sort anything by. Always. Not only in this example.

If it isn't enough then consider using some other data store like Redis that may be more efficient to handle your particular use case.

Body:
I have some db with 4 000 000 numbers and I need to check if some number is exist in db

Database exapmle: [177,219,245,309,348,436,...]

I tried use mysql table but it takes 1300ms for check if some 1 number is exist

It very long time and I`ve check some another ways:

1) Push all numbers to array and check it with indexOf

2) Push all numbers to string and check it with indexOf

3) Push all numbers to object and check it with hasOwnProperty

4) Push all numbers to object and check value

I`ve made 100 checks in all of this ways and measured the time:

try [...].indexOf(...) === 0
Total: 726ms

try String(...).indexOf(...) === 0
Total: 1915ms

try {...}.hasOwnProperty(...) === true
Total: 4ms

try {...}[...] === true === true
Total: 4ms

The code of tests:

// Reads db json with ~4 000 000 elements
var arr = utils.readJSON('members.json');
// Converts db to string type
var arr_string = arr.toString();
// Makes empty object
var arr_obj = {};
// Converts db to object type
for(var i in arr){
    arr_obj[arr[i]] = true;
}
// Makes empty array
var checkList = [];
// Gets 100 different values from different places of db
for(var i = 0; i < 100; i++){
    checkList.push(arr[Math.floor(arr.length / 100 * i)]);
}
// Main time variable
var time;

// test
time = new Date().getTime();
for (var i in checkList) {
    console.log('try [...].indexOf('+ checkList[i]+') === ' + arr.indexOf(checkList[i]));
}
console.log('Total: ' + (new Date().getTime() - time) + 'ms');

// test
time = new Date().getTime();
for (var i in checkList) {
    console.log('try String(...).indexOf(' + checkList[i] + ') === ' + arr_string.indexOf(checkList[i]));
}
console.log('Total: ' + (new Date().getTime() - time) + 'ms');

// test
time = new Date().getTime();
for (var i in checkList) {
    console.log('try {...}.hasOwnProperty(' + checkList[i] + ') === ' + arr_obj.hasOwnProperty(checkList[i]));
}
console.log('Total: ' + (new Date().getTime() - time) + 'ms');

// test
time = new Date().getTime();
for (var i in checkList) {
    console.log('try {...}[' + checkList[i] + '] === true === ' + (arr_obj[checkList[i]] === true));
}
console.log('Total: ' + (new Date().getTime() - time) + 'ms');

I believe that the best way to perform this task is Object with hasOwnProperty, but what different ways do you know?

Maybe I should try using other databases?


问:
Only one row echoed
I have following code. I  only get one one row echoed the first one.

What do ido wrong?

```<code><?php
include("/connectdb.php");
$link2=Connection();
$rt = mysql_query("SELECT motion FROM tempLog WHERE Id='13007423' AND DATE(`timeStamp`) = CURDATE() ORDER BY timeStamp DESC LIMIT 2", $link2);
$result = mysql_fetch_row($rt);
if($result)
echo $result[0];
echo $result[1];
?>
</code>```

Thanks for help!

答:
mysql is deprecated  and you should migrate to mysqli or PDO  </p>

<p>anyway  you shot iterate over the result </p>

```<code>while($row = mysql_fetch_row($rt)) {

    echo $result[0];

    echo '<br />';
}
</code>```

Title: Only one row echoed

Body:
I have following code. I  only get one one row echoed the first one.

What do ido wrong?

<?php
include("/connectdb.php");
$link2=Connection();
$rt = mysql_query("SELECT motion FROM tempLog WHERE Id='13007423' AND DATE(`timeStamp`) = CURDATE() ORDER BY timeStamp DESC LIMIT 2", $link2);
$result = mysql_fetch_row($rt);
if($result)
echo $result[0];
echo $result[1];
?>

Thanks for help!

Body:
mysql is deprecated  and you should migrate to mysqli or PDO

anyway  you shot iterate over the result

while($row = mysql_fetch_row($rt)) {

    echo $result[0];

    echo '<br />';
}


问:
CSS: How can I select all ul tags contained within ol tags
My HTML looks like

```<code><ol class='enlarge'>
<li>Larger
<ul>
<li>Normal
</li>
</ul>
</li>
</ol>
</code>```

Where you see Larger I want the font size to be larger. And where you see Normal, I want the font size to be normal.

I've tried

```<code>  ol.enlarge {
    font-size: 130%;
  }
  ul.enlarge {
    font-size: 70%;
  }
</code>```

And

```<code>  ol {
    font-size: 130%;
  }
  ul > ol {
    font-size: 70%;
  }
</code>```

And

```<code>  ol {
    font-size: 130%;
  }
  ol > ul {
    font-size: 70%;
  }
</code>```

All are setting the font size bigger for everything in my

Thanks!

-Tom

答:
You are looking for a descendant combinator. Select any ul element within ol element.

ol {
  font-size: 130%;
}

ol ul {
  font-size: 70%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>Larger
    <ul>
      <li>Normal
      </li>
    </ul>
  </li>
</ol></code>```

Why did your attempts failed?

Case 1:

You were missing the class enlarge in your markup:

ol.enlarge {
  font-size: 130%;
}

ul.enlarge {
  font-size: 70%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol class="enlarge">
  <li>Larger
    <ul class="enlarge">
      <li>Normal
      </li>
    </ul>
  </li>
</ol></code>```

Case 2:

There is no ordered list element (ol) as a direct child, that's why the child combinator does not work. Notice that an ol element cannot be a direct child of an ul element according to semantic HTML.

ol {
  font-size: 130%;
}

ul>ol {
  font-size: 70%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>Larger
    <ul>
      <ol>Invalid</ol>
      <li>Normal
      </li>
    </ul>
  </li>
</ol></code>```

Case 3:

Similar to the case above, there is no ul element as a  direct child of an ol element. Which again, it is not a valid markup.

ol {
  font-size: 130%;
}

ol>ul {
  font-size: 70%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <ul>Invalid</ul>
  <li>Larger
    <ul>
      <li>Normal
      </li>
    </ul>
  </li>
</ol></code>```

Body:
My HTML looks like

Larger

Normal

Where you see Larger I want the font size to be larger. And where you see Normal, I want the font size to be normal.

I've tried

  ol.enlarge {
    font-size: 130%;
  }
  ul.enlarge {
    font-size: 70%;
  }

And

  ol {
    font-size: 130%;
  }
  ul > ol {
    font-size: 70%;
  }

And

  ol {
    font-size: 130%;
  }
  ol > ul {
    font-size: 70%;
  }

All are setting the font size bigger for everything in my

Thanks!

-Tom

Body:
You are looking for a descendant combinator. Select any ul element within ol element.

ol {
  font-size: 130%;
}

ol ul {
  font-size: 70%;
}

<ol>
  <li>Larger
    <ul>
      <li>Normal
      </li>
    </ul>
  </li>
</ol>

Why did your attempts failed?

Case 1:

You were missing the class enlarge in your markup:

ol.enlarge {
  font-size: 130%;
}

ul.enlarge {
  font-size: 70%;
}

<ol class="enlarge">
  <li>Larger
    <ul class="enlarge">
      <li>Normal
      </li>
    </ul>
  </li>
</ol>

Case 2:

There is no ordered list element (ol) as a direct child, that's why the child combinator does not work. Notice that an ol element cannot be a direct child of an ul element according to semantic HTML.

ol {
  font-size: 130%;
}

ul>ol {
  font-size: 70%;
}

<ol>
  <li>Larger
    <ul>
      <ol>Invalid</ol>
      <li>Normal
      </li>
    </ul>
  </li>
</ol>

Case 3:

Similar to the case above, there is no ul element as a  direct child of an ol element. Which again, it is not a valid markup.

ol {
  font-size: 130%;
}

ol>ul {
  font-size: 70%;
}

<ol>
  <ul>Invalid</ul>
  <li>Larger
    <ul>
      <li>Normal
      </li>
    </ul>
  </li>
</ol>


问:
objective c parse json from url request
I am trying to parse a json string requested from an api located at:
http://www.physics.leidenuniv.nl/json/news.php

However, i am having trouble parsing this json.
I get the following error:
Unexpected end of file during string parse

I have looked for hours, but I can not find an answer to this problem.

My code snippet:

In my viewDidLoad:

```<code>NSURLRequest *request = [NSURLRequest requestWithURL:
                         [NSURL URLWithString:@"http://www.physics.leidenuniv.nl/json/news.php"]];

[[NSURLConnection alloc] initWithRequest:request delegate:self];
</code>```

The delegate:

```<code>- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableData *responseData = [[NSMutableData alloc] init];
[responseData appendData:data];

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSError *e = nil;
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];
}
</code>```

Anybody know an answer to this problem so i can parse the json data?

答:
```<code>-(void)getWebServic{
NSURL *url = [NSURL URLWithString:@"----URL----"];

// 2
NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession]
                                      dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
    NSDictionary *jsonObject=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    [self loadDataFromDictionary:(NSArray*)jsonObject];
    NSLog(@"data: %@",jsonObject);

}];

// 3
[downloadTask resume]; }
</code>```

Title: objective c parse json from url request

Body:
I am trying to parse a json string requested from an api located at:
http://www.physics.leidenuniv.nl/json/news.php

However, i am having trouble parsing this json.
I get the following error:
Unexpected end of file during string parse

I have looked for hours, but I can not find an answer to this problem.

My code snippet:

In my viewDidLoad:

NSURLRequest *request = [NSURLRequest requestWithURL:
                         [NSURL URLWithString:@"http://www.physics.leidenuniv.nl/json/news.php"]];

[[NSURLConnection alloc] initWithRequest:request delegate:self];

The delegate:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableData *responseData = [[NSMutableData alloc] init];
[responseData appendData:data];

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSError *e = nil;
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];
}

Anybody know an answer to this problem so i can parse the json data?


问:
Looping Dictionary with unexpected returns
It has been a long night and day. I could use some help why this is not working can not think straight. This script opens a .csv file checks if a certain word is contained in a the title which is at row[4] and then it will loop through a dictionary that contains list and if the word is in the title then it will return the dictionary key to be written to a new csv file.

What I am getting is uncategorized for every row which should not be correct because the title does contain words in the list.

Thanks for the help in advance.

Example CSV in BrandsMart USA,http://www.BrandsMartUSA.com,BrandsMart Product Catalog,01:30.8,Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2Boom BX320K,2Boom BX320K Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2BOOMBX320K,2Boom,BX320K,7.08192E+11,,USD,,19.88,19.88,,http://www.example.com,http://www.ftjcfx.com/image-8299186-11133500,https://www.brandsmartusa.com/images/product/large/20225377.jpg,Bluetooth & Docking Speakers,,,,,,,,,,,,,,,,yes,,,
BrandsMart USA,http://www.BrandsMartUSA.com,BrandsMart Product Catalog,01:30.8,Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2Boom BX320R,2Boom BX320R Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2BOOMBX320R,2Boom,BX320R,7.08192E+11,,USD,,19.88,19.88,,http://www.example.com,http://www.ftjcfx.com/image-8299186-11133500,https://www.brandsmartusa.com/images/product/large/20225393.jpg,Bluetooth & Docking Speakers,,,,,,,,,,,,,,,,yes,,,
BrandsMart USA,http://www.BrandsMartUSA.com,BrandsMart Product Catalog,01:30.8,Bluetooth Noise-Cancelling Earbud Headphones,2Boom EPBT690B,2Boom EPBT690B Bluetooth Noise-Cancelling Earbud Headphones,2BOOMEPBT690B,2Boom,EPBT690B,7.44751E+11,,USD,,9.88,9.88,,http://www.example.com,http://www.ftjcfx.com/image-8299186-11133500,https://www.brandsmartusa.com/images/product/large/20225398.jpg,Earbuds,,,,,,,,,,,,,,,,yes,,,

Using Python 3

```<code>import os, csv, time

csv_path = os.path.dirname(os.path.abspath(__file__))

row_list = []

# Appliances
category_list = {"Appliance Accessories": ['Air Conditioner Accessories', 'Air Purifier Accessories', "Coffee Maker Accessories",
                           'Dishwasher Accessories', 'Food Processor Accessories', 'Heater Accessories',
                           'Humidifier Accessories', 'Humidifier Accessories', 'Mixer Accessories',
                           'Range & Oven Accessories', 'Range Hood Accessories', 'Refrigerator Accessories',
                           'Vacuum Accessories', 'Washer & Dryer Accessories'],
 "Electronics Accessories": ['cables & adapters', 'audio accessories', 'video accessories', 'camcorder accessories',
                             'cell phone accessories', 'clock radios', 'Digital Book Reader Accessories',
                             'Digital Picture Frames', 'Electronics Cases & Bags', 'GPS Accessories',
                             'Projector Accessories', 'Telephone Accessories', 'batteries', 'battery'],
 "Photography": ['Camcorders', 'Cameras', 'Digital Camera Accessories', 'Digital Cameras', 'Camera', 'Digital Camera',
                 'Photography', 'Darkroom']}

category = ""

with open(csv_path + "/pre.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        for k, val in category_list.items():
            for v in val:
                if v.lower() in row[4].lower():
                    category = k
                else:
                    category = "Uncategorized"

        new_row = [str(row[0]),  # company
                   str(row[1]),  # company url
                   str(row[4]),  # product name
                   str(row[5]),  # keywords
                   str(row[6]),  # descripition
                   str(row[7]),  # sku
                   str(row[8]),  # manufacturer
                   str(row[13]),  # saleprice
                   str(row[14]),  # price
                   str(row[15]),  # retailprice
                   str(row[17]),  # buy_link
                   str(row[19]),  # product_image_url
                   str(row[31]),  # promotional_text
                   str(row[36]),  # stock
                   str(row[37]),  # condition
                   str(row[38]),  # warrenty
                   str(row[39]),  # shipping_cost
                   category,
                   ]
        row_list.append(new_row)

    f.close()

with open(csv_path + "/final.csv", 'w') as ff:
    writer = csv.writer(ff)
    writer.writerows(row_list)
    ff.close()
</code>```

答:
Well, this block will only store the result of the last value in val:

```<code>for v in val:
    if v.lower() in row[4].lower():
        category = k
    else:
        category = "Uncategorized"
</code>```

It's only comparing val[-1] in the end, since you're overwriting category.

You probably want to break the loop once you find a category, or do something with this value on each iteration?

Body:
It has been a long night and day. I could use some help why this is not working can not think straight. This script opens a .csv file checks if a certain word is contained in a the title which is at row[4] and then it will loop through a dictionary that contains list and if the word is in the title then it will return the dictionary key to be written to a new csv file.

What I am getting is uncategorized for every row which should not be correct because the title does contain words in the list.

Thanks for the help in advance.

Example CSV in BrandsMart USA,http://www.BrandsMartUSA.com,BrandsMart Product Catalog,01:30.8,Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2Boom BX320K,2Boom BX320K Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2BOOMBX320K,2Boom,BX320K,7.08192E+11,,USD,,19.88,19.88,,http://www.example.com,http://www.ftjcfx.com/image-8299186-11133500,https://www.brandsmartusa.com/images/product/large/20225377.jpg,Bluetooth & Docking Speakers,,,,,,,,,,,,,,,,yes,,,
BrandsMart USA,http://www.BrandsMartUSA.com,BrandsMart Product Catalog,01:30.8,Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2Boom BX320R,2Boom BX320R Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2BOOMBX320R,2Boom,BX320R,7.08192E+11,,USD,,19.88,19.88,,http://www.example.com,http://www.ftjcfx.com/image-8299186-11133500,https://www.brandsmartusa.com/images/product/large/20225393.jpg,Bluetooth & Docking Speakers,,,,,,,,,,,,,,,,yes,,,
BrandsMart USA,http://www.BrandsMartUSA.com,BrandsMart Product Catalog,01:30.8,Bluetooth Noise-Cancelling Earbud Headphones,2Boom EPBT690B,2Boom EPBT690B Bluetooth Noise-Cancelling Earbud Headphones,2BOOMEPBT690B,2Boom,EPBT690B,7.44751E+11,,USD,,9.88,9.88,,http://www.example.com,http://www.ftjcfx.com/image-8299186-11133500,https://www.brandsmartusa.com/images/product/large/20225398.jpg,Earbuds,,,,,,,,,,,,,,,,yes,,,

Using Python 3

import os, csv, time

csv_path = os.path.dirname(os.path.abspath(__file__))

row_list = []

# Appliances
category_list = {"Appliance Accessories": ['Air Conditioner Accessories', 'Air Purifier Accessories', "Coffee Maker Accessories",
                           'Dishwasher Accessories', 'Food Processor Accessories', 'Heater Accessories',
                           'Humidifier Accessories', 'Humidifier Accessories', 'Mixer Accessories',
                           'Range & Oven Accessories', 'Range Hood Accessories', 'Refrigerator Accessories',
                           'Vacuum Accessories', 'Washer & Dryer Accessories'],
 "Electronics Accessories": ['cables & adapters', 'audio accessories', 'video accessories', 'camcorder accessories',
                             'cell phone accessories', 'clock radios', 'Digital Book Reader Accessories',
                             'Digital Picture Frames', 'Electronics Cases & Bags', 'GPS Accessories',
                             'Projector Accessories', 'Telephone Accessories', 'batteries', 'battery'],
 "Photography": ['Camcorders', 'Cameras', 'Digital Camera Accessories', 'Digital Cameras', 'Camera', 'Digital Camera',
                 'Photography', 'Darkroom']}

category = ""

with open(csv_path + "/pre.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        for k, val in category_list.items():
            for v in val:
                if v.lower() in row[4].lower():
                    category = k
                else:
                    category = "Uncategorized"

        new_row = [str(row[0]),  # company
                   str(row[1]),  # company url
                   str(row[4]),  # product name
                   str(row[5]),  # keywords
                   str(row[6]),  # descripition
                   str(row[7]),  # sku
                   str(row[8]),  # manufacturer
                   str(row[13]),  # saleprice
                   str(row[14]),  # price
                   str(row[15]),  # retailprice
                   str(row[17]),  # buy_link
                   str(row[19]),  # product_image_url
                   str(row[31]),  # promotional_text
                   str(row[36]),  # stock
                   str(row[37]),  # condition
                   str(row[38]),  # warrenty
                   str(row[39]),  # shipping_cost
                   category,
                   ]
        row_list.append(new_row)

    f.close()

with open(csv_path + "/final.csv", 'w') as ff:
    writer = csv.writer(ff)
    writer.writerows(row_list)
    ff.close()

Body:
Well, this block will only store the result of the last value in val:

for v in val:
    if v.lower() in row[4].lower():
        category = k
    else:
        category = "Uncategorized"

It's only comparing val[-1] in the end, since you're overwriting category.

You probably want to break the loop once you find a category, or do something with this value on each iteration?


问:
Find the median of an array
I wrote some code that returns the median of an unsorted odd numbered array, but it does not return the median of an even numbered array.

I know that in order to find the median of an even numbered array, you have to take the middle two numbers of the array, average them, and that's the median. I can't translate that into usable code. Aside from the obvious verbosity of this code, the issue seems to be with lines 7-8 and I don't see why.

I prefer hints to answers, but if you rather post some fixed code, I can accept that too.

```<code>def media(array)
  sorted = array.sort
  list = sorted.length
  if list %2 != 0
    (list + 1) / 2.0
  else
    even = ((list.to_f + 2) / 2) + ((list.to_f / 2)
    return (even/2)
  end
end
</code>```

答:
Here is the answer:</p>

```<code>def get_median(sub_a)
    result = -1
    size = sub_a.size
    if size == 0
        result = 0
    elsif size == 1
        result = sub_a[0]
    elsif size == 2
        result = get_average(sub_a[0], sub_a[1])
    else
        sorted_a = sub_a.sort
        index = size / 2
        if size % 2 == 0
            result = get_average(sorted_a[index - 1], sorted_a[index]);
        else
            result = sorted_a[index];
        end
    end

    '%0.01f' % result
end
</code>```

Title: Find the median of an array

Body:
I wrote some code that returns the median of an unsorted odd numbered array, but it does not return the median of an even numbered array.

I know that in order to find the median of an even numbered array, you have to take the middle two numbers of the array, average them, and that's the median. I can't translate that into usable code. Aside from the obvious verbosity of this code, the issue seems to be with lines 7-8 and I don't see why.

I prefer hints to answers, but if you rather post some fixed code, I can accept that too.

def media(array)
  sorted = array.sort
  list = sorted.length
  if list %2 != 0
    (list + 1) / 2.0
  else
    even = ((list.to_f + 2) / 2) + ((list.to_f / 2)
    return (even/2)
  end
end

Body:
Here is the answer:

def get_median(sub_a)
    result = -1
    size = sub_a.size
    if size == 0
        result = 0
    elsif size == 1
        result = sub_a[0]
    elsif size == 2
        result = get_average(sub_a[0], sub_a[1])
    else
        sorted_a = sub_a.sort
        index = size / 2
        if size % 2 == 0
            result = get_average(sorted_a[index - 1], sorted_a[index]);
        else
            result = sorted_a[index];
        end
    end

    '%0.01f' % result
end


问:
errno: 150 "Foreign key constraint is incorrectly formed" Nothing helps
sorry for maybe stupid question, but I stack with my sql query. Tried out many methods to avid it but still have error 150. I've created 3 tables and one with foreighn keys:

Table users

```<code>create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   cname varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
);
</code>```

Table behaviours

```<code>CREATE TABLE behaviours (
   id int(2) AUTO_INCREMENT PRIMARY KEY,
   bName varchar(100) NOT NULL
);
</code>```

Table severytys

```<code>CREATE TABLE severitys (
   id int(2) AUTO_INCREMENT PRIMARY KEY,
   severity varchar(10) NOT NULL
);
</code>```

And here it shows errors:

```<code>CREATE TABLE child_behaviours(
   id int(11) primary key auto_increment,
   name varchar(50) not null,
   cname varchar(50) not null,
   bName varchar(100) NOT NULL,
   severity varchar(10) NOT NULL,
   start_at datetime,
   stop_at datetime null,
   FOREIGN KEY (id) REFERENCES users(id),
   FOREIGN KEY (bName) REFERENCES behaviours(bName),
   FOREIGN KEY (severity) REFERENCES severitys(severity)
);
</code>```

Will be really pleasent to have an answer to this issue

答:
You have to refer to a primary key, when building a foreign key</p>

```<code>CREATE TABLE child_behaviours(
   userId int not null,
   behaviourId int NOT NULL,
   severityId int NOT NULL,
   start_at datetime not null,
   stop_at datetime,
   FOREIGN KEY (userId) REFERENCES users(id),
   FOREIGN KEY (behaviourId) REFERENCES behaviours(id),
   FOREIGN KEY (severityId) REFERENCES severitys(id)
);
</code>```

Body:
sorry for maybe stupid question, but I stack with my sql query. Tried out many methods to avid it but still have error 150. I've created 3 tables and one with foreighn keys:

Table users

create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   cname varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
);

Table behaviours

CREATE TABLE behaviours (
   id int(2) AUTO_INCREMENT PRIMARY KEY,
   bName varchar(100) NOT NULL
);

Table severytys

CREATE TABLE severitys (
   id int(2) AUTO_INCREMENT PRIMARY KEY,
   severity varchar(10) NOT NULL
);

And here it shows errors:

CREATE TABLE child_behaviours(
   id int(11) primary key auto_increment,
   name varchar(50) not null,
   cname varchar(50) not null,
   bName varchar(100) NOT NULL,
   severity varchar(10) NOT NULL,
   start_at datetime,
   stop_at datetime null,
   FOREIGN KEY (id) REFERENCES users(id),
   FOREIGN KEY (bName) REFERENCES behaviours(bName),
   FOREIGN KEY (severity) REFERENCES severitys(severity)
);

Will be really pleasent to have an answer to this issue

Body:
You have to refer to a primary key, when building a foreign key

CREATE TABLE child_behaviours(
   userId int not null,
   behaviourId int NOT NULL,
   severityId int NOT NULL,
   start_at datetime not null,
   stop_at datetime,
   FOREIGN KEY (userId) REFERENCES users(id),
   FOREIGN KEY (behaviourId) REFERENCES behaviours(id),
   FOREIGN KEY (severityId) REFERENCES severitys(id)
);


问:
Regex not accepting numbers
I can't figure out why this regex pattern isn't accepting numbers? It used to but then I added [()#'/- part and it stopped.</p>

```<code>^[()#'/-0-9A-Za-z ]+$
</code>```

答:
The /-0 created a valid range that only matches / or 0:

So, your regex could match a string with 0 and 9 in it (like ()#'/0-9ABCZab c), but not the whole digit range.

Replace with

```<code>^[-()#'/0-9A-Za-z ]+$
</code>```

See the regex demo

Title: Regex not accepting numbers

Body:
I can't figure out why this regex pattern isn't accepting numbers? It used to but then I added [()#'/- part and it stopped.

^[()#'/-0-9A-Za-z ]+$

Body:
The /-0 created a valid range that only matches / or 0:

So, your regex could match a string with 0 and 9 in it (like ()#'/0-9ABCZab c), but not the whole digit range.

Replace with

^[-()#'/0-9A-Za-z ]+$

See the regex demo


答:
You can only create a FK on a column that is both UNIQUE and NOT NULL. This is usually, but not always, the primary key of the referenced table.

If you reference anything other than the PK, you need a really really good reason.

(I'd even add to that, that you need a really really good reason to use anything other than an INT or a couple INTs as a PK...)

Now, child_behaviours has several errors:

Duplication of columns already present in users. If you reference users by its id, there is no need to duplicate the columns.

Reference to behaviors(bName) instead of using its id

same thing for reference to severity

Also, there is the generic mistake of using "id" columns. Please call them "user_id", "severity_id", etc, and then call them the same in your references. This will make your life much easier, and avoid stuff like:

```<code>SELECT foo.id AD foo_id, bar.id AS bar_id FROM foo JOIN bar ON ...
</code>```

Title: errno: 150 "Foreign key constraint is incorrectly formed" Nothing helps

Body:
You can only create a FK on a column that is both UNIQUE and NOT NULL. This is usually, but not always, the primary key of the referenced table.

If you reference anything other than the PK, you need a really really good reason.

(I'd even add to that, that you need a really really good reason to use anything other than an INT or a couple INTs as a PK...)

Now, child_behaviours has several errors:

Duplication of columns already present in users. If you reference users by its id, there is no need to duplicate the columns.

Reference to behaviors(bName) instead of using its id

same thing for reference to severity

Also, there is the generic mistake of using "id" columns. Please call them "user_id", "severity_id", etc, and then call them the same in your references. This will make your life much easier, and avoid stuff like:

SELECT foo.id AD foo_id, bar.id AS bar_id FROM foo JOIN bar ON ...


答:
ol ul should be sufficient to target elements needed for reduced font-sizes.

ol {
  font-size: 130%;
}

ol ul {
  font-size: 70%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>Larger
    <ul>
      <li>Normal</li>
    </ul>
  </li>
</ol></code>```

Title: CSS: How can I select all ul tags contained within ol tags

Body:
ol ul should be sufficient to target elements needed for reduced font-sizes.

ol {
  font-size: 130%;
}

ol ul {
  font-size: 70%;
}

<ol>
  <li>Larger
    <ul>
      <li>Normal</li>
    </ul>
  </li>
</ol>


答:
The Tuple class isn't in pre-v4 framework, but here is a simplified version that should match most of your needs:

```<code>public class Tuple<T,U>
{
    public T Item1 { get; private set; }
    public U Item2 { get; private set; }

    public Tuple(T item1, U item2)
    {
        Item1 = item1;
        Item2 = item2;
    }
}

public static class Tuple
{
    public static Tuple<T, U> Create<T, U>(T item1, U item2)
    {
        return new Tuple<T, U>(item1, item2);
    }
}
</code>```

you could easily add classes to have Tuples with more than 2 parameters

Title: Error with Tuple in C# 2008

Body:
I have made a program in C# 2010 and my code contains a Tuple, but when I put my program into C# 2008 it does not recognise it, and comes up with the error of:

"The type of namespace name 'Tuple' could not be found"

So I don't know how to make this work, this is the line of code in which the error occurs:

private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();

Please help.

EDIT

Basically this is my code at the moment which doesn't compile due to the error:

public partial class Form1 : Form
{
    private bool isMoving = false;
    private Point mouseDownPosition = Point.Empty;
    private Point mouseMovePosition = Point.Empty;
    private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        var g = e.Graphics;
        if (isMoving)
        {
            g.Clear(pictureBox1.BackColor);
            g.DrawLine(Pens.Black, mouseDownPosition, mouseMovePosition);
            foreach (var line in lines)
            {
                g.DrawLine(Pens.Black, line.Item1, line.Item2);
            }
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        isMoving = true;
        mouseDownPosition = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            mouseMovePosition = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            lines.Add(Tuple.Create(mouseDownPosition, mouseMovePosition));
        }
        isMoving = false;
    }
}

So I need a way of changing or making the Tuple work in VS C# 2008 as well as 2010,

Thanks

Body:
The Tuple class isn't in pre-v4 framework, but here is a simplified version that should match most of your needs:

public class Tuple<T,U>
{
    public T Item1 { get; private set; }
    public U Item2 { get; private set; }

    public Tuple(T item1, U item2)
    {
        Item1 = item1;
        Item2 = item2;
    }
}

public static class Tuple
{
    public static Tuple<T, U> Create<T, U>(T item1, U item2)
    {
        return new Tuple<T, U>(item1, item2);
    }
}

you could easily add classes to have Tuples with more than 2 parameters