问:
How to get out of nested selectAll in D3JS?
Getting reacquainted with hos D3JS works and, in particular .selectAll/.data/.enter; learning how to nest data.

I have this working demo:

svg = d3.select('body')
  .append('svg')
  .attr('width',  640)
  .attr('height', 480);
svg.selectAll('text')
  .data( [ 'hello', 'world' ] )
  .enter()
    .append('text')
    .attr('x', 10)
    .attr('y', function( d, i ) {
      return 20 + i * 20;
    })
    .selectAll('tspan')
    .data( function( d, i ) { // d is from the first data
      return Array.from(d); // if needed, could return an array or object that includes the initial value, too.
    })
    .enter()
      .append('tspan')
      .attr('class', function( d, i ) {
        console.log( 'tspan class:', d, i );
        if ( ['a', 'e', 'i', 'o', 'u', 'y'].includes(d) ) {
          return 'vowel';
        }
      })
      .text( function( d, i, foo ) { // d is from the second data
        console.log( 'tspan text:', d, i, /*foo*/ );
        return d;
      })
    .exit()
    .attr('class', 'strong') // this will set strong on <tspan>, but I wanted it on <text>
    ;
```

(See it on on Codepen: D3JS selectAll SVG nested.)

Notice how we have two data(), with the second (for <tspan>s) nested inside the first one (for <text>s).

What I'm trying to do:

I want to set the strong class attribute on <text>.

I thought exit() would get me out of the "scope"/nest of working with the tspans… but I'm wrong.

If I comment out exit(), then the strong class attribute is set on the <tspan>s… while I want it on the parent <text>!

How can I achieve that, besides:

Moving the line up (before the second data()).

Using a separate statement (svg.selectAll('text').attr('class', 'strong');)

I could use one of these two options and in this example it would be trivial…

But I want to know if it's possible to get out of nested selections and, if so, how?

I hope this was clear enough; if not please comment and I'll clarify :)

答:
You could think about modifying your original data and that way you could just use one data binding and one update pattern. Within that pattern, you could check/use the word but also check each letter of the word (you could also just do this on the fly later):

```<code>const test_data = [ 'hello', 'world', 'wthtvwls' ];

const modified_data = test_data.map((item,index) => {
  return {
    word: item,
    array: Array.from(item)
  }
});

console.log(modified_data);
</code>```

Then using this data (demo - https://codepen.io/Alexander9111/pen/qBdZrLv):

```<code>svg = d3.select('body')
  .append('svg')
  .attr('width',  640)
  .attr('height', 480);
svg.selectAll('text')
  .data( modified_data )
  .enter()
    .append('text')
    .attr('x', 10)
    .attr('y', function( d, i ) {
      return 20 + i * 20;
    })
    .html(function(d) {
      return d.letters.map((letter,index) => {
        if (['a', 'e', 'i', 'o', 'u', 'y'].includes(letter)){
          return '<tspan class="vowel">' + letter + '</tspan>';
        } else{
          return '<tspan>' + letter + '</tspan>';
        }
      }).join("");
    })
    .attr('class', function( d, i ) {
        for (letter of d.letters){
          console.log('letter', letter);
          if (['a', 'e', 'i', 'o', 'u', 'y'].includes(letter)) {
            return 'strong';
          }
        }
      })
    .exit();
</code>```

Note the use of the .html() function and then .map() within that using our current data.letters in the normal update pattern to add either '<tspan class="vowel">' or '<tspan>' (no class vowel).

https://codepen.io/Alexander9111/pen/qBdZrLv

But I am not sure if you want such a specific use case or a more general answer to the nested update pattern? If so then maybe this block helps? - https://bl.ocks.org/mpbastos/bd1d6763d34ac5d3ce533a581b291364

UPDATE - I realize I misread the question the first time

So it is now clear to me that my one-time solution is no more helpful than the other two solutions suggested by @Fabien (OP) (Moving the line up (before the second data()) or Using a separate statement svg.selectAll('text').attr('class', 'strong');)

I tried patterns such as:

```<code>svg.selectAll('text')
    .data( test_data )
    .enter()
    .append('text')
    .attr('x', 10)
    ...
    .selectAll('tspan')
    .data( ...)
    .enter()
      .append('tspan')
      .attr('class', 'example')
    .exit()
    .select(this.ParentNode)
    .attr('class', 'example')
</code>```

And also with the .select(this.ParentNode) before the .exit() but neither worked.

The only thing that works but it is also a workaround and probably an anti-pattern is this - hijack the attr function to "grab" parent outside nested update :

```<code>svg = d3.select('body')
  .append('svg')
  .attr('width',  640)
  .attr('height', 480);
text = svg.selectAll('text')
    .data( test_data )
    .enter()
    .append('text')
    .attr('x', 10)
    .attr('y', function( d, i ) {
      return 20 + i * 20;
    })
    .selectAll('tspan')
    .data( function( d, i ) { // d is from the first data
      return Array.from(d); // if needed, could return an array or object that includes the initial value, too.
    })
    .enter()
      .append('tspan')
      .attr('class', function( d, i ) {
        console.log(1, i, this.parentNode);
         //hijack the attr function to "grab" parent outside nested update pattern
        if (i == 0) {
          d3.select(this.parentNode).attr('class', 'strong');
        }
        //console.log( 'tspan class:', d, i );
        if ( ['a', 'e', 'i', 'o', 'u', 'y'].includes(d) ) {
          return 'vowel';
        }
      })
      .text( function( d, i, foo ) { // d is from the second data
        //console.log( 'tspan text:', d, i, /*foo*/ );
        return d;
      })
    .exit();
</code>```

This is also not a beautiful solution.

I think because once the .data() function is called on a selection, it is now longer a normal node list object, and the .exit() function is only designed to be used one layer deep.

I think the two solutions the OP outlined are the best, but I would love to be proven wrong!

Body:
Getting reacquainted with hos D3JS works and, in particular .selectAll/.data/.enter; learning how to nest data.

I have this working demo:

svg = d3.select('body')
  .append('svg')
  .attr('width',  640)
  .attr('height', 480);
svg.selectAll('text')
  .data( [ 'hello', 'world' ] )
  .enter()
    .append('text')
    .attr('x', 10)
    .attr('y', function( d, i ) {
      return 20 + i * 20;
    })
    .selectAll('tspan')
    .data( function( d, i ) { // d is from the first data
      return Array.from(d); // if needed, could return an array or object that includes the initial value, too.
    })
    .enter()
      .append('tspan')
      .attr('class', function( d, i ) {
        console.log( 'tspan class:', d, i );
        if ( ['a', 'e', 'i', 'o', 'u', 'y'].includes(d) ) {
          return 'vowel';
        }
      })
      .text( function( d, i, foo ) { // d is from the second data
        console.log( 'tspan text:', d, i, /*foo*/ );
        return d;
      })
    .exit()
    .attr('class', 'strong') // this will set strong on <tspan>, but I wanted it on <text>
    ;

(See it on on Codepen: D3JS selectAll SVG nested.)

Notice how we have two data(), with the second (for <tspan>s) nested inside the first one (for <text>s).

What I'm trying to do:

I want to set the strong class attribute on <text>.

I thought exit() would get me out of the "scope"/nest of working with the tspans… but I'm wrong.

If I comment out exit(), then the strong class attribute is set on the <tspan>s… while I want it on the parent <text>!

How can I achieve that, besides:

Moving the line up (before the second data()).

Using a separate statement (svg.selectAll('text').attr('class', 'strong');)

I could use one of these two options and in this example it would be trivial…

But I want to know if it's possible to get out of nested selections and, if so, how?

I hope this was clear enough; if not please comment and I'll clarify :)

Body:
You could think about modifying your original data and that way you could just use one data binding and one update pattern. Within that pattern, you could check/use the word but also check each letter of the word (you could also just do this on the fly later):

const test_data = [ 'hello', 'world', 'wthtvwls' ];

const modified_data = test_data.map((item,index) => {
  return {
    word: item,
    array: Array.from(item)
  }
});

console.log(modified_data);

Then using this data (demo - https://codepen.io/Alexander9111/pen/qBdZrLv):

svg = d3.select('body')
  .append('svg')
  .attr('width',  640)
  .attr('height', 480);
svg.selectAll('text')
  .data( modified_data )
  .enter()
    .append('text')
    .attr('x', 10)
    .attr('y', function( d, i ) {
      return 20 + i * 20;
    })
    .html(function(d) {
      return d.letters.map((letter,index) => {
        if (['a', 'e', 'i', 'o', 'u', 'y'].includes(letter)){
          return '<tspan class="vowel">' + letter + '</tspan>';
        } else{
          return '<tspan>' + letter + '</tspan>';
        }
      }).join("");
    })
    .attr('class', function( d, i ) {
        for (letter of d.letters){
          console.log('letter', letter);
          if (['a', 'e', 'i', 'o', 'u', 'y'].includes(letter)) {
            return 'strong';
          }
        }
      })
    .exit();

Note the use of the .html() function and then .map() within that using our current data.letters in the normal update pattern to add either '<tspan class="vowel">' or '<tspan>' (no class vowel).

https://codepen.io/Alexander9111/pen/qBdZrLv

But I am not sure if you want such a specific use case or a more general answer to the nested update pattern? If so then maybe this block helps? - https://bl.ocks.org/mpbastos/bd1d6763d34ac5d3ce533a581b291364

UPDATE - I realize I misread the question the first time

So it is now clear to me that my one-time solution is no more helpful than the other two solutions suggested by @Fabien (OP) (Moving the line up (before the second data()) or Using a separate statement svg.selectAll('text').attr('class', 'strong');)

I tried patterns such as:

svg.selectAll('text')
    .data( test_data )
    .enter()
    .append('text')
    .attr('x', 10)
    ...
    .selectAll('tspan')
    .data( ...)
    .enter()
      .append('tspan')
      .attr('class', 'example')
    .exit()
    .select(this.ParentNode)
    .attr('class', 'example')

And also with the .select(this.ParentNode) before the .exit() but neither worked.

The only thing that works but it is also a workaround and probably an anti-pattern is this - hijack the attr function to "grab" parent outside nested update :

svg = d3.select('body')
  .append('svg')
  .attr('width',  640)
  .attr('height', 480);
text = svg.selectAll('text')
    .data( test_data )
    .enter()
    .append('text')
    .attr('x', 10)
    .attr('y', function( d, i ) {
      return 20 + i * 20;
    })
    .selectAll('tspan')
    .data( function( d, i ) { // d is from the first data
      return Array.from(d); // if needed, could return an array or object that includes the initial value, too.
    })
    .enter()
      .append('tspan')
      .attr('class', function( d, i ) {
        console.log(1, i, this.parentNode);
         //hijack the attr function to "grab" parent outside nested update pattern
        if (i == 0) {
          d3.select(this.parentNode).attr('class', 'strong');
        }
        //console.log( 'tspan class:', d, i );
        if ( ['a', 'e', 'i', 'o', 'u', 'y'].includes(d) ) {
          return 'vowel';
        }
      })
      .text( function( d, i, foo ) { // d is from the second data
        //console.log( 'tspan text:', d, i, /*foo*/ );
        return d;
      })
    .exit();

This is also not a beautiful solution.

I think because once the .data() function is called on a selection, it is now longer a normal node list object, and the .exit() function is only designed to be used one layer deep.

I think the two solutions the OP outlined are the best, but I would love to be proven wrong!


来源: stackexchange

问:
How to use UISwitch
I am new in Xcode, trying to build an app, and I am studying a lot; it seems not enough. Anyway, I need a step by step of 2 things:

my 1st Vc has 10 switch buttons and I need to limit to only 4 can be "On";

when my switch button is on, it changes a label in the 2nd Vc.

I am really struggling with the segues codes. Any light will be highly appreciated.

答:
Step 1

i. You need to have a data model of an array of Bool to store the state of the UISwitch

ii. When the value of the UISwitch changes, you have to update the value of the corresponding index of the Bool array

iii. To limit the number of On, you may disable all Off switch if the limit exceeds so that the user can only switch On to Off but not adding another On switch. Or you may listen to the valueChanged event, if the 5th switch is On, immediately set it back to Off

Step 2

You need to learn how to pass data/objects between ViewControllers.

i. the most simple one would be having a Singleton object that can be accessed anywhere.

ii. but it may be better to have a property in the 2nd VC, just pass the data model before 2nd VC is pushed

ContentLicense: CC BY-SA 4.0

Title: How to use UISwitch


问:
Integrating Cloudflare player into angular 7 for Cloudflare stream
I am trying to get cloudflare stream to work in angular. I have tried the solution given here: Angular attribute for HTML stream.

However, it is always a hit or a miss:

Out of 10 reloads, one loads the player.

But anytime I make a
    change to the <stream> tag, and angular re-compiles, the player is
    loaded. After this if I refresh the browser, it is a blank screen
    again.

The component which shows the video is deep in the tree and the component belongs to a module that is lazy loaded:

In the index.html file:

```<code><!doctype html>
<html lang="en">

<head>
...............

</head>

<body>
  <app-root></app-root>

</body>
<script src="https://embed.cloudflarestream.com/embed/r4xu.fla9.latest.js" id="video_embed" defer="" async=""></script>

</html>
</code>```

In the videoFile.component.ts:

```<code><stream src="5d5bc37ffcf54c9b82e996823bffbb81" height="480px" width="240px" controls></stream>
</code>```

答:
Found a solution here: https://github.com/angular/angular/issues/13965

So everytime the component loads, the script is removed and reattached using ngOninit, like so:

```<code>document.getElementById("video_embed").remove();
      let testScript = document.createElement("script");
      testScript.setAttribute("id", "video_embed");
      testScript.setAttribute("src", "https://embed.cloudflarestream.com/embed/r4xu.fla9.latest.js");
      document.body.appendChild(testScript);
</code>```

If anyone has any other solutions, please do let me know.

Body:
I am trying to get cloudflare stream to work in angular. I have tried the solution given here: Angular attribute for HTML stream.

However, it is always a hit or a miss:

Out of 10 reloads, one loads the player.

But anytime I make a
    change to the <stream> tag, and angular re-compiles, the player is
    loaded. After this if I refresh the browser, it is a blank screen
    again.

The component which shows the video is deep in the tree and the component belongs to a module that is lazy loaded:

In the index.html file:

<!doctype html>

...............

  <app-root></app-root>

In the videoFile.component.ts:

<stream src="5d5bc37ffcf54c9b82e996823bffbb81" height="480px" width="240px" controls></stream>

Body:
Found a solution here: https://github.com/angular/angular/issues/13965

So everytime the component loads, the script is removed and reattached using ngOninit, like so:

document.getElementById("video_embed").remove();
      let testScript = document.createElement("script");
      testScript.setAttribute("id", "video_embed");
      testScript.setAttribute("src", "https://embed.cloudflarestream.com/embed/r4xu.fla9.latest.js");
      document.body.appendChild(testScript);

If anyone has any other solutions, please do let me know.


问:
Save login form data using php
html webpage screenshotphp code shown on button clickmySql database tableI need to store user login data. i am using phpMyAdmin. When I click on submit button, data is not stored. Instead the php code is shown. Both code files are given below. What I am doing wrong. Help me. I
am unable to store user data using phpmyadmin in xampp.

my html code

```<code>
    <html>
    <head>
    <title>Yahoo Signin And Signup Form</title>
    </head>
    <body>
     <h2 style="color: midnightblue">yahoo!</h2>
     <hr color="magenta">
    <form method="post" action="connect.php" >
    <fieldset style="background:#6495ED;">
    <legend style="padding:20px 0; font-size:20px;">Signup:</legend>
    <label for ="firstName">Enter First Name</label><br>
    <input type="text" placeholder="First name" id="firstName" name ="firstName">
    <br>
    <label for ="lastName">Enter Last Name</label><br>
    <input type="text" placeholder="Last name" id="lastName" name ="lastName">
    <br>
    <label for ="email">Enter Email</label><br>
    <input type="text" placeholder="Email" id="email" name ="email"><br>
    <label for ="password">Enter Password</label><br>
    <input type="password" placeholder="Password" id="password" name ="password">
    <br>
    <label for ="number">Enter Mobile Number</label><br>
    <input placeholder="03---" id="number" name ="number"><br>
    <label for ="date">Enter Date of Birth</label><br>
    <input type="text" placeholder="DD/MM/YY" id="date" name ="date"><br>
    <label for ="gender">Enter Gender</label><br>
    <input type="text" placeholder="Male/Female/Other" id="gender" name
    ="gender"><br>
    <br><button style="background-color:orangered;border-
    color:dodgerblue;color:lightyellow">Signup</button>
    </fielsdet>
    </form>
    </body>
    </html>
</code>```

my connect.php

```<code>    <?php
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $number = $_POST['number'];
    $date = $_POST['date'];
    $gender = $_POST['gender'];

    // Making Connection with database

    $con = new mysqli('localhost','root','','phpdata');
    if ($con -> connect_error) {
    die('Connection failed :'.$conn -> connect_error);
    }
    else{
    $stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password,
    number, date, gender)
        values(?,?,?,?,?,?,?)");
    $stmt->bind_param("ssssiss",$firstName, $lastName, $email, $password,
    $number, $date, $gender);
    $stmt->execute();
    echo "Sign up successful";
    $stmt->close();
    $con->close();
     }?>
</code>```

答:
Add type in your submit button.

```<code><button type='submit' style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
</code>```

and also your question marks and params ara not matching. it should be match. otherwise data won't store your db

correct that line also

Title: Save login form data using php

Body:
html webpage screenshotphp code shown on button clickmySql database tableI need to store user login data. i am using phpMyAdmin. When I click on submit button, data is not stored. Instead the php code is shown. Both code files are given below. What I am doing wrong. Help me. I
am unable to store user data using phpmyadmin in xampp.

my html code

    <title>Yahoo Signin And Signup Form</title>

yahoo!

    <form method="post" action="connect.php" >
    <fieldset style="background:#6495ED;">
    <legend style="padding:20px 0; font-size:20px;">Signup:</legend>
    Enter First Name

    <input type="text" placeholder="First name" id="firstName" name ="firstName">

    Enter Last Name

    <input type="text" placeholder="Last name" id="lastName" name ="lastName">

    Enter Email

    <input type="text" placeholder="Email" id="email" name ="email">

    Enter Password

    <input type="password" placeholder="Password" id="password" name ="password">

    Enter Mobile Number

    <input placeholder="03---" id="number" name ="number">

    Enter Date of Birth

    <input type="text" placeholder="DD/MM/YY" id="date" name ="date">

    Enter Gender

    <input type="text" placeholder="Male/Female/Other" id="gender" name
    ="gender">

<button style="background-color:orangered;border-
    color:dodgerblue;color:lightyellow">Signup</button>
    </fielsdet>
    </form>

my connect.php

    <?php
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $number = $_POST['number'];
    $date = $_POST['date'];
    $gender = $_POST['gender'];

    // Making Connection with database

    $con = new mysqli('localhost','root','','phpdata');
    if ($con -> connect_error) {
    die('Connection failed :'.$conn -> connect_error);
    }
    else{
    $stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password,
    number, date, gender)
        values(?,?,?,?,?,?,?)");
    $stmt->bind_param("ssssiss",$firstName, $lastName, $email, $password,
    $number, $date, $gender);
    $stmt->execute();
    echo "Sign up successful";
    $stmt->close();
    $con->close();
     }?>

Body:
Add type in your submit button.

<button type='submit' style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>

and also your question marks and params ara not matching. it should be match. otherwise data won't store your db

correct that line also


问:
How do I use the toast feature?
I just started learning Android Studio. I want to display a toast notification by pressing a button on the widget. However, there is an error when using the getApplicationContext() function. Can you tell me how to fix it? Other things, including getBaseContext(), were the same..... The error message was "Cannot resolve method" getApplicationContext () ""  I didn't speak English, so I used Google Translator.... I'm so sorry if you can't understand...

```<code>package com.jhjsapp.widget;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

/**
 * Implementation of App Widget functionality.
 */
public class TestWidget extends AppWidgetProvider {

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        CharSequence widgetText = context.getString(R.string.appwidget_text);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.test_widget);
        views.setTextViewText(R.id.appwidget_text, widgetText);

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }

    public void butcli(View view){
        Toast.makeText(getApplicationContext(),"버튼 눌림", Toast.LENGTH_SHORT).show();
    }
}
</code>```

This is JAVA code

enter image description here

答:
create a global variable first

```<code>private Context context;
</code>```

then initialize context by adding this line to updateAppWidget() and onUpdate() and onEnabled() and onDisabled();

```<code>this.context=context;
</code>```

then use toast like :

```<code>Toast.makeText(context,"버튼 눌림", Toast.LENGTH_SHORT).show();
</code>```

Title: How do I use the toast feature?

Body:
I just started learning Android Studio. I want to display a toast notification by pressing a button on the widget. However, there is an error when using the getApplicationContext() function. Can you tell me how to fix it? Other things, including getBaseContext(), were the same..... The error message was "Cannot resolve method" getApplicationContext () ""  I didn't speak English, so I used Google Translator.... I'm so sorry if you can't understand...

package com.jhjsapp.widget;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

/**
 * Implementation of App Widget functionality.
 */
public class TestWidget extends AppWidgetProvider {

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        CharSequence widgetText = context.getString(R.string.appwidget_text);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.test_widget);
        views.setTextViewText(R.id.appwidget_text, widgetText);

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }

    public void butcli(View view){
        Toast.makeText(getApplicationContext(),"버튼 눌림", Toast.LENGTH_SHORT).show();
    }
}

This is JAVA code

enter image description here

Body:
create a global variable first

private Context context;

then initialize context by adding this line to updateAppWidget() and onUpdate() and onEnabled() and onDisabled();

this.context=context;

then use toast like :

Toast.makeText(context,"버튼 눌림", Toast.LENGTH_SHORT).show();


问:
Need to disable (or hide) a bar button in UIWebView depending on the page that's loaded
Part of my iOS app has a UIWebView that has a button bar on the bottom and loads a local index.html file. The 2 buttons on the bar are 'back' and 'done'. The index.html file is a list of downloaded (hence also local) html mini-apps which are loaded into that same webview. Because of some required navigation issues with those mini-apps the webview's 'back' button is not a goBack connected to the webView, it's really a link button back to the index.html.

I need that 'back' button to be hidden or disabled if index.html is the active page in the webview. I know how to disable it entirely, but I need it enabled when mini-apps are loaded to get back to the list. Any suggestions? Many thanks!

答:
You can implement one UIWebView's delegate protocols:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

Then you could do something like this:

```<code>- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *currentURL = [[request URL] absoluteString];
if ([currentURL isEqualToString:@"index.html"]) {
//hide the bar button item
//something like: [button setHidden:YES];
}

else {
//something like: [button setHidden:NO];

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

ContentLicense: CC BY-SA 3.0

Body:
You can implement one UIWebView's delegate protocols:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

Then you could do something like this:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *currentURL = [[request URL] absoluteString];
if ([currentURL isEqualToString:@"index.html"]) {
//hide the bar button item
//something like: [button setHidden:YES];
}

else {
//something like: [button setHidden:NO];

}
return YES;
}


问:
Swapping user integer input for a variable so that it incrementally increases and decreases
As the title says, I'm trying to replace the "i" variable listed with what a user inputs so that it'll incrementally increase and decrease based off of whatever they put in for the base integer when prompted. Basically I want my "for" loops to base the increment off of whatever the speed integer entered is.

I've tried inputting various things but clearly I don't know what I'm doing or clearly what those particular are. Also I have no idea what the standards are for writing Java so I apologize for the sloppy code.

Here is my actual objective:

2. Car Class

Write a class named car that has the following fields:

yearModal. The yearModel field is an int that holds the car's year model.

maka. The make field references a String object that holds the make of the car.

speed. The speed field is an int that holds the car's current speed.

In addition, the class should have the following constructor and other methods.

Constructor. The constructor should accept the car's year model and make as arguments. These values should be assigned to the object's yearModel and make fields. The constructor should also assign 0 to the speed field.

Accessor. Appropriate accessor methods should get the values stored in an object's yearModel, make, and speed fields.

accelerate. The accelerate method should add 5 to the speed field each time it is called.

brake. The brake method should subtract 5 from the speed field each time it is called.

Demonstrate the class in a program that creates a Car object, and then calls the accelerate method five times. After each call to the accelerate method, get the current speed of the car and display it. Then call the brake method five times. After each call to the brake method, get the current speed of the car and display it.

```<code>import java.util.Scanner;

public class CarProgramAssignment {
    int yearModel;
    String make;
    int speed;

    CarProgramAssignment(int yearModel, String make) {
        this.yearModel = yearModel;
        this.make = make;
        this.speed = 0;
    }

    int getYearModel()
    {
      return yearModel;
    }

    String getMake() {
      return make;
    }

    int getSpeed() {
      return speed;
    }

    void Accelerate() {
       this.speed = this.speed + 5;
    }

    void Brake() {
    this.speed = this.speed - 5;
    }

     public static void main(String[] args)
    {

     Scanner input = new Scanner( System.in );

      // This displays the current status
      System.out.println("Current status of the car:");
      System.out.println("Car Year: ");

      int carMakeYear = input.nextInt();

      input.nextLine();

      System.out.println("Car Make: ");
      String carModel = input.nextLine();

      System.out.println("Speed: ");

      int speed = input.nextInt();

     CarProgramAssignment car = new CarProgramAssignment(1, "Audi R8");
     for(int i=0;i<5;i++) {
     car.Accelerate();
     }

     System.out.printf("After accelerating 5 times, the speed is = %d km/h\n", car.getSpeed());
     for(int i=0;i<5;i++) {
        car.Brake();
     }

     System.out.println("After braking 5 times, the speed is = "+car.getSpeed());

    }
}
</code>```

Edit: I cleaned up some things and tried to clarify it a bit more.

答:
I've modified your code slightly and added some explanations inside it.

The nextLine() will scan a line including the linefeed. If you use next(), or nextInt() the scanner will not read the linefeed. This seems to be a general source of confusion for beginners.

I changed your constuctor in the Car class, so it doesn't halt and wait for the user input. Instead I placed scanning for "speed" input where the other information is scanned as well. I also changed the Car to have two constructors. One that will work if there's no speed provided and another that will take a speed as well as the year and model of the car.

```<code>import java.util.Scanner;

class Car { // Class names start with uppercase

    private int yearModel; //an int that holds the car's year model
    private String make; //references a string object that holds the make of the car
    private int speed; //an int that holds the car's speed.

    public int getYearModel() {
        return yearModel;
    }

    public String getMake(){
        return make; //This is the field of the particular object
    }

    public int getSpeed(){
        return speed;
    }

    public void accelerate() {
        speed = speed + 5;
    }

    public void brake() {
        speed = speed - 5;
    }

//    Scanner input = new Scanner(System.in); // Avoid IO-dependency in constuctor

    public Car(int yearModelGiven, String makeGiven){
        this.yearModel = yearModelGiven;
        this.make = makeGiven;
        this.speed = 0;
//        System.out.println("Please enter in the initial speed of the car:");
//        speed = input.nextInt();
    }

    // Overloaded constructor
    public Car(int yearModelGiven, String makeGiven, int speed){ // extra parameter
        this.yearModel = yearModelGiven;
        this.make = makeGiven;
        this.speed = speed;
    }

}

public class Application{

    public static void main(String [] args ) { //this is a main method

        Scanner input = new Scanner( System.in );

        System.out.println("What is the vehicle year: ");
        int carYear;
        carYear = input.nextInt();
        input.nextLine(); // This line will scan the rest of the line after the number: The linefeed.
        System.out.println("The vehicle year is " + carYear);

        System.out.println("What is the vehicle make: ");
        String carMake;
//        carMake = input.nextLine(); // nextLine() scans the rest of the line including the linefeed
// The above line will do the same as the below two:
        carMake = input.next();
        input.nextLine();
        System.out.println("The vehicle make is "+ carMake);

        System.out.println("Please enter in the initial speed of the car:");
        int speed = input.nextInt();
        input.nextLine(); // This line will scan the rest of the line after the number: The linefeed.

//        Car car1 = new Car(carYear, carMake);  // will give it default speed 0
        Car car1 = new Car(carYear, carMake, speed); // will give it the speed entered by user.

        System.out.println( "Accelerating the vehicle now:" );
        for( int seconds = 1; seconds <= 5; seconds++ ) {
            car1.accelerate();
            System.out.println( "The current speed of the" + " " + car1.getYearModel() + " " + car1.getMake() + " is " +
                      car1.getSpeed() + " km/h" );
        }

        // This is now the braking method
        System.out.println( "Braking the vehicle now:" );
        for (int seconds = 1; seconds <= 5; seconds++ ) {
             car1.brake();
             System.out.println( "The current speed of the" + " " + car1.getYearModel() + " " + car1.getMake() + " is " +
                      car1.getSpeed() + " km/h" );
        }
    }
}
</code>```

Body:
As the title says, I'm trying to replace the "i" variable listed with what a user inputs so that it'll incrementally increase and decrease based off of whatever they put in for the base integer when prompted. Basically I want my "for" loops to base the increment off of whatever the speed integer entered is.

I've tried inputting various things but clearly I don't know what I'm doing or clearly what those particular are. Also I have no idea what the standards are for writing Java so I apologize for the sloppy code.

Here is my actual objective:

2. Car Class

Write a class named car that has the following fields:

yearModal. The yearModel field is an int that holds the car's year model.

maka. The make field references a String object that holds the make of the car.

speed. The speed field is an int that holds the car's current speed.

In addition, the class should have the following constructor and other methods.

Constructor. The constructor should accept the car's year model and make as arguments. These values should be assigned to the object's yearModel and make fields. The constructor should also assign 0 to the speed field.

Accessor. Appropriate accessor methods should get the values stored in an object's yearModel, make, and speed fields.

accelerate. The accelerate method should add 5 to the speed field each time it is called.

brake. The brake method should subtract 5 from the speed field each time it is called.

Demonstrate the class in a program that creates a Car object, and then calls the accelerate method five times. After each call to the accelerate method, get the current speed of the car and display it. Then call the brake method five times. After each call to the brake method, get the current speed of the car and display it.

import java.util.Scanner;

public class CarProgramAssignment {
    int yearModel;
    String make;
    int speed;

    CarProgramAssignment(int yearModel, String make) {
        this.yearModel = yearModel;
        this.make = make;
        this.speed = 0;
    }

    int getYearModel()
    {
      return yearModel;
    }

    String getMake() {
      return make;
    }

    int getSpeed() {
      return speed;
    }

    void Accelerate() {
       this.speed = this.speed + 5;
    }

    void Brake() {
    this.speed = this.speed - 5;
    }

     public static void main(String[] args)
    {

     Scanner input = new Scanner( System.in );

      // This displays the current status
      System.out.println("Current status of the car:");
      System.out.println("Car Year: ");

      int carMakeYear = input.nextInt();

      input.nextLine();

      System.out.println("Car Make: ");
      String carModel = input.nextLine();

      System.out.println("Speed: ");

      int speed = input.nextInt();

     CarProgramAssignment car = new CarProgramAssignment(1, "Audi R8");
     for(int i=0;i<5;i++) {
     car.Accelerate();
     }

     System.out.printf("After accelerating 5 times, the speed is = %d km/h\n", car.getSpeed());
     for(int i=0;i<5;i++) {
        car.Brake();
     }

     System.out.println("After braking 5 times, the speed is = "+car.getSpeed());

    }
}

Edit: I cleaned up some things and tried to clarify it a bit more.

Body:
I've modified your code slightly and added some explanations inside it.

The nextLine() will scan a line including the linefeed. If you use next(), or nextInt() the scanner will not read the linefeed. This seems to be a general source of confusion for beginners.

I changed your constuctor in the Car class, so it doesn't halt and wait for the user input. Instead I placed scanning for "speed" input where the other information is scanned as well. I also changed the Car to have two constructors. One that will work if there's no speed provided and another that will take a speed as well as the year and model of the car.

import java.util.Scanner;

class Car { // Class names start with uppercase

    private int yearModel; //an int that holds the car's year model
    private String make; //references a string object that holds the make of the car
    private int speed; //an int that holds the car's speed.

    public int getYearModel() {
        return yearModel;
    }

    public String getMake(){
        return make; //This is the field of the particular object
    }

    public int getSpeed(){
        return speed;
    }

    public void accelerate() {
        speed = speed + 5;
    }

    public void brake() {
        speed = speed - 5;
    }

//    Scanner input = new Scanner(System.in); // Avoid IO-dependency in constuctor

    public Car(int yearModelGiven, String makeGiven){
        this.yearModel = yearModelGiven;
        this.make = makeGiven;
        this.speed = 0;
//        System.out.println("Please enter in the initial speed of the car:");
//        speed = input.nextInt();
    }

    // Overloaded constructor
    public Car(int yearModelGiven, String makeGiven, int speed){ // extra parameter
        this.yearModel = yearModelGiven;
        this.make = makeGiven;
        this.speed = speed;
    }

}

public class Application{

    public static void main(String [] args ) { //this is a main method

        Scanner input = new Scanner( System.in );

        System.out.println("What is the vehicle year: ");
        int carYear;
        carYear = input.nextInt();
        input.nextLine(); // This line will scan the rest of the line after the number: The linefeed.
        System.out.println("The vehicle year is " + carYear);

        System.out.println("What is the vehicle make: ");
        String carMake;
//        carMake = input.nextLine(); // nextLine() scans the rest of the line including the linefeed
// The above line will do the same as the below two:
        carMake = input.next();
        input.nextLine();
        System.out.println("The vehicle make is "+ carMake);

        System.out.println("Please enter in the initial speed of the car:");
        int speed = input.nextInt();
        input.nextLine(); // This line will scan the rest of the line after the number: The linefeed.

//        Car car1 = new Car(carYear, carMake);  // will give it default speed 0
        Car car1 = new Car(carYear, carMake, speed); // will give it the speed entered by user.

        System.out.println( "Accelerating the vehicle now:" );
        for( int seconds = 1; seconds <= 5; seconds++ ) {
            car1.accelerate();
            System.out.println( "The current speed of the" + " " + car1.getYearModel() + " " + car1.getMake() + " is " +
                      car1.getSpeed() + " km/h" );
        }

        // This is now the braking method
        System.out.println( "Braking the vehicle now:" );
        for (int seconds = 1; seconds <= 5; seconds++ ) {
             car1.brake();
             System.out.println( "The current speed of the" + " " + car1.getYearModel() + " " + car1.getMake() + " is " +
                      car1.getSpeed() + " km/h" );
        }
    }
}


问:
Series divided by scalar results in NaN/0
I have a series grouped on districts -> crime types -> count of crimes:

```<code>PdDistrict  Category
BAYVIEW     ASSAULT                        8976
            BURGLARY                       2891
            DISORDERLY CONDUCT              207
            DRIVING UNDER THE INFLUENCE     188
            DRUG/NARCOTIC                  2061
                                           ...
TENDERLOIN  STOLEN PROPERTY                 299
            TRESPASS                        665
            VANDALISM                      1710
            VEHICLE THEFT                   661
            WEAPON LAWS                     791
Name: IncidntNum, Length: 140, dtype: int64
</code>```

My goal is to divide every value with a scalar.

I tried to do this using a loop going over the "PdDistricts" and run the following line:

```<code>series[district] = series[district] / sum(series[district])
</code>```

If i run just series[district] / sum(series[district]) the output is as intended:

```<code> Category
ASSAULT                        0.11434063
BURGLARY                       0.09323762
DISORDERLY CONDUCT             0.00427552
DRIVING UNDER THE INFLUENCE    0.00478544
DRUG/NARCOTIC                  0.05691535
DRUNKENNESS                    0.00596219
LARCENY/THEFT                  0.46712952
PROSTITUTION                   0.00027457
ROBBERY                        0.02753589
STOLEN PROPERTY                0.00917863
TRESPASS                       0.01247352
VANDALISM                      0.09335530
VEHICLE THEFT                  0.09884679
WEAPON LAWS                    0.01168902
Name: IncidntNum, dtype: float64
</code>```

But when I try to update the existing part of the series running series[district] = series[district] / sum(series[district]) i get:

```<code> Category
ASSAULT                        0
BURGLARY                       0
DISORDERLY CONDUCT             0
DRIVING UNDER THE INFLUENCE    0
DRUG/NARCOTIC                  0
DRUNKENNESS                    0
LARCENY/THEFT                  0
PROSTITUTION                   0
ROBBERY                        0
STOLEN PROPERTY                0
TRESPASS                       0
VANDALISM                      0
VEHICLE THEFT                  0
WEAPON LAWS                    0
Name: IncidntNum, dtype: int64
</code>```

Which is not as intended. If I use .loc I simply get NaN's instead of 0's.

I simply can't wrap my head around what's going wrong, all solutions I have tried have failed, and I think the key issue is that I do not fully understand how to work with Series in Pandas.

I hope you can help me understand the issue.

/Mikkel

答:
I believe you need Series.sum per first level PdDistrict - for sum values per first level of MultiIndex:

```<code>s1 = s.sum(level=0)
print (s1)
PdDistrict
BAYVIEW       14323
TENDERLOIN     4126
Name: IncidntNum, dtype: int64
</code>```

And then divide by Series.div by first level, so division is by sums of PdDistricts :

```<code>s2 = s.div(s1, level=0)
print (s2)
PdDistrict  Category
BAYVIEW     ASSAULT                        0.626684
            BURGLARY                       0.201843
            DISORDERLY CONDUCT             0.014452
            DRIVING UNDER THE INFLUENCE    0.013126
            DRUG/NARCOTIC                  0.143894
TENDERLOIN  STOLEN PROPERTY                0.072467
            TRESPASS                       0.161173
            VANDALISM                      0.414445
            VEHICLE THEFT                  0.160204
            WEAPON LAWS                    0.191711
Name: IncidntNum, dtype: float64
</code>```

Body:
I have a series grouped on districts -> crime types -> count of crimes:

PdDistrict  Category
BAYVIEW     ASSAULT                        8976
            BURGLARY                       2891
            DISORDERLY CONDUCT              207
            DRIVING UNDER THE INFLUENCE     188
            DRUG/NARCOTIC                  2061
                                           ...
TENDERLOIN  STOLEN PROPERTY                 299
            TRESPASS                        665
            VANDALISM                      1710
            VEHICLE THEFT                   661
            WEAPON LAWS                     791
Name: IncidntNum, Length: 140, dtype: int64

My goal is to divide every value with a scalar.

I tried to do this using a loop going over the "PdDistricts" and run the following line:

series[district] = series[district] / sum(series[district])

If i run just series[district] / sum(series[district]) the output is as intended:

 Category
ASSAULT                        0.11434063
BURGLARY                       0.09323762
DISORDERLY CONDUCT             0.00427552
DRIVING UNDER THE INFLUENCE    0.00478544
DRUG/NARCOTIC                  0.05691535
DRUNKENNESS                    0.00596219
LARCENY/THEFT                  0.46712952
PROSTITUTION                   0.00027457
ROBBERY                        0.02753589
STOLEN PROPERTY                0.00917863
TRESPASS                       0.01247352
VANDALISM                      0.09335530
VEHICLE THEFT                  0.09884679
WEAPON LAWS                    0.01168902
Name: IncidntNum, dtype: float64

But when I try to update the existing part of the series running series[district] = series[district] / sum(series[district]) i get:

 Category
ASSAULT                        0
BURGLARY                       0
DISORDERLY CONDUCT             0
DRIVING UNDER THE INFLUENCE    0
DRUG/NARCOTIC                  0
DRUNKENNESS                    0
LARCENY/THEFT                  0
PROSTITUTION                   0
ROBBERY                        0
STOLEN PROPERTY                0
TRESPASS                       0
VANDALISM                      0
VEHICLE THEFT                  0
WEAPON LAWS                    0
Name: IncidntNum, dtype: int64

Which is not as intended. If I use .loc I simply get NaN's instead of 0's.

I simply can't wrap my head around what's going wrong, all solutions I have tried have failed, and I think the key issue is that I do not fully understand how to work with Series in Pandas.

I hope you can help me understand the issue.

/Mikkel

Body:
I believe you need Series.sum per first level PdDistrict - for sum values per first level of MultiIndex:

s1 = s.sum(level=0)
print (s1)
PdDistrict
BAYVIEW       14323
TENDERLOIN     4126
Name: IncidntNum, dtype: int64

And then divide by Series.div by first level, so division is by sums of PdDistricts :

s2 = s.div(s1, level=0)
print (s2)
PdDistrict  Category
BAYVIEW     ASSAULT                        0.626684
            BURGLARY                       0.201843
            DISORDERLY CONDUCT             0.014452
            DRIVING UNDER THE INFLUENCE    0.013126
            DRUG/NARCOTIC                  0.143894
TENDERLOIN  STOLEN PROPERTY                0.072467
            TRESPASS                       0.161173
            VANDALISM                      0.414445
            VEHICLE THEFT                  0.160204
            WEAPON LAWS                    0.191711
Name: IncidntNum, dtype: float64


问:
Upgrade python packages from requirements.txt using pip command
How do I upgrade all my python packages from requirements.txt file using pip command?

tried with below command

```<code>$ pip install --upgrade -r requirements.txt
</code>```

Since, the python packages are suffixed with the version number (Django==1.5.1) they don't seem to upgrade. Is there any better approach than manually editing requirements.txt file?

EDIT

As Andy mentioned in his answer packages are pinned to a specific version, hence it is not possible to upgrade packages through pip command.

But, we can achieve this with pip-tools using the following command.

```<code>$ pip-review --auto
</code>```

this will automatically upgrade all packages from requirements.txt (make sure to install pip-tools using pip install command).

答:
Another solution is to use the upgrade-requirements package

```<code>pip install upgrade-requirements
</code>```

And then run :

```<code>upgrade-requirements
</code>```

It will upgrade all the packages that are not at their latest versions, and also create an updated requirements.txt at the end.

Body:
How do I upgrade all my python packages from requirements.txt file using pip command?

tried with below command

$ pip install --upgrade -r requirements.txt

Since, the python packages are suffixed with the version number (Django==1.5.1) they don't seem to upgrade. Is there any better approach than manually editing requirements.txt file?

EDIT

As Andy mentioned in his answer packages are pinned to a specific version, hence it is not possible to upgrade packages through pip command.

But, we can achieve this with pip-tools using the following command.

$ pip-review --auto

this will automatically upgrade all packages from requirements.txt (make sure to install pip-tools using pip install command).

Body:
Another solution is to use the upgrade-requirements package

pip install upgrade-requirements

And then run :

upgrade-requirements

It will upgrade all the packages that are not at their latest versions, and also create an updated requirements.txt at the end.


答:
Use prepare instead of query. All everything is ok.:

```<code>$stmt = $con->prepare("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
        values(?,?,?,?,?,?,?)");
</code>```

And make button type as submit:

```<code><br><button type="submit" style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
</code>```

Title: Save login form data using php

Body:
Use prepare instead of query. All everything is ok.:

$stmt = $con->prepare("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
        values(?,?,?,?,?,?,?)");

And make button type as submit:

<br><button type="submit" style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>


答:
The main problem is you are not loading code via apache server try to open http://localhost/signup.html instead of C:/xmapp/htdocs/connect.php

It seems you want to user PDO but your connection string not correct

```<code><?php
    $firstName = trim($_POST['firstName']);
    $lastName = trim($_POST['lastName']);
    $email = trim($_POST['email']);
    $password = md5(trim($_POST['password']));
    $number = trim($_POST['number']);
    $date = trim($_POST['date']);
    $gender = trim($_POST['gender']);

    $con= new PDO("mysql:host=127.0.0.1;dbname=phpdata", 'root', 'root');
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sqli = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
        values(?,?,?,?,?,?,?)";
try {
    $stmt= $con->prepare($sqli);
    $stmt->bindParam(1,$firstName);
    $stmt->bindParam(2,$lastName);
    $stmt->bindParam(3,$email);
    $stmt->bindParam(4,$password);
    $stmt->bindParam(5,$number);
    $stmt->bindParam(6,$date);
    $stmt->bindParam(7,$gender);
    $status = $stmt->execute();
    echo "Sign up successful";
    $stmt->close();
    $con->close();
} catch(PDOException $e) {
  echo "Error ".$e->getMessage();
}
?>
</code>```

another problem is with your html form button type is missing

```<code><button type="submit".... />
</code>```

Title: Save login form data using php

Body:
The main problem is you are not loading code via apache server try to open http://localhost/signup.html instead of C:/xmapp/htdocs/connect.php

It seems you want to user PDO but your connection string not correct

<?php
    $firstName = trim($_POST['firstName']);
    $lastName = trim($_POST['lastName']);
    $email = trim($_POST['email']);
    $password = md5(trim($_POST['password']));
    $number = trim($_POST['number']);
    $date = trim($_POST['date']);
    $gender = trim($_POST['gender']);

    $con= new PDO("mysql:host=127.0.0.1;dbname=phpdata", 'root', 'root');
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sqli = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
        values(?,?,?,?,?,?,?)";
try {
    $stmt= $con->prepare($sqli);
    $stmt->bindParam(1,$firstName);
    $stmt->bindParam(2,$lastName);
    $stmt->bindParam(3,$email);
    $stmt->bindParam(4,$password);
    $stmt->bindParam(5,$number);
    $stmt->bindParam(6,$date);
    $stmt->bindParam(7,$gender);
    $status = $stmt->execute();
    echo "Sign up successful";
    $stmt->close();
    $con->close();
} catch(PDOException $e) {
  echo "Error ".$e->getMessage();
}
?>

another problem is with your html form button type is missing

<button type="submit".... />


问:
How to get the color of a pixel in a UIImage in Swift?
How do I get the color of a pixel in a UIImage in Swift?

The existing answers on SO are either outdated or don't work for me.

答:
Swift 5

To come up with a reliable solution, we need to take into account the following:

The pixel size of the image can differ from its point size that is returned by image.size.width/image.size.height.

There can be various layouts used by pixel components in the image, such as BGRA, ABGR, ARGB etc. or pixels may not have the alpha component at all, such as BGR and RGB. UIView.drawHierarchy(in:afterScreenUpdates:) method can produce BGRA images.

Color components can be premultiplied by the alpha for all pixels in the image and need to be divided by alpha in order to restore the original color. Again, UIView.drawHierarchy(in:afterScreenUpdates:) method can produce BGRA images with color components premultiplied by alpha.

For memory optimization used by CGImage, the size of a pixel row in bytes can be greater than the mere multiplication of the pixel width by 4.

The code below is to provide a comprehensive solution to get the UIColor of a pixel for all such special cases in Swift 5. The code is optimized for usability and clarity, not for performance.

public extension UIImage {

    var pixelWidth: Int {
        return cgImage?.width ?? 0
    }

    var pixelHeight: Int {
        return cgImage?.height ?? 0
    }

    func pixelColor(x: Int, y: Int) -> UIColor {
        assert(
            0..<pixelWidth ~= x && 0..<pixelHeight ~= y,
            "Pixel coordinates are out of bounds")

        guard
            let cgImage = cgImage,
            let data = cgImage.dataProvider?.data,
            let dataPtr = CFDataGetBytePtr(data),
            let colorSpaceModel = cgImage.colorSpace?.model,
            let componentLayout = cgImage.bitmapInfo.componentLayout
        else {
            assertionFailure("Could not get the color of a pixel in an image")
            return .clear
        }

        assert(
            colorSpaceModel == .rgb,
            "The only supported color space model is RGB")
        assert(
            cgImage.bitsPerPixel == 32 || cgImage.bitsPerPixel == 24,
            "A pixel is expected to be either 4 or 3 bytes in size")

        let bytesPerRow = cgImage.bytesPerRow
        let bytesPerPixel = cgImage.bitsPerPixel/8
        let pixelOffset = y*bytesPerRow + x*bytesPerPixel

        if componentLayout.count == 4 {
            let components = (
                dataPtr[pixelOffset + 0],
                dataPtr[pixelOffset + 1],
                dataPtr[pixelOffset + 2],
                dataPtr[pixelOffset + 3]
            )

            var alpha: UInt8 = 0
            var red: UInt8 = 0
            var green: UInt8 = 0
            var blue: UInt8 = 0

            switch componentLayout {
            case .bgra:
                alpha = components.3
                red = components.2
                green = components.1
                blue = components.0
            case .abgr:
                alpha = components.0
                red = components.3
                green = components.2
                blue = components.1
            case .argb:
                alpha = components.0
                red = components.1
                green = components.2
                blue = components.3
            case .rgba:
                alpha = components.3
                red = components.0
                green = components.1
                blue = components.2
            default:
                return .clear
            }

            // If chroma components are premultiplied by alpha and the alpha is `0`,
            // keep the chroma components to their current values.
            if cgImage.bitmapInfo.chromaIsPremultipliedByAlpha && alpha != 0 {
                let invUnitAlpha = 255/CGFloat(alpha)
                red = UInt8((CGFloat(red)*invUnitAlpha).rounded())
                green = UInt8((CGFloat(green)*invUnitAlpha).rounded())
                blue = UInt8((CGFloat(blue)*invUnitAlpha).rounded())
            }

            return .init(red: red, green: green, blue: blue, alpha: alpha)

        } else if componentLayout.count == 3 {
            let components = (
                dataPtr[pixelOffset + 0],
                dataPtr[pixelOffset + 1],
                dataPtr[pixelOffset + 2]
            )

            var red: UInt8 = 0
            var green: UInt8 = 0
            var blue: UInt8 = 0

            switch componentLayout {
            case .bgr:
                red = components.2
                green = components.1
                blue = components.0
            case .rgb:
                red = components.0
                green = components.1
                blue = components.2
            default:
                return .clear
            }

            return .init(red: red, green: green, blue: blue, alpha: UInt8(255))

        } else {
            assertionFailure("Unsupported number of pixel components")
            return .clear
        }
    }

}

public extension UIColor {

    convenience init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {
        self.init(
            red: CGFloat(red)/255,
            green: CGFloat(green)/255,
            blue: CGFloat(blue)/255,
            alpha: CGFloat(alpha)/255)
    }

}

public extension CGBitmapInfo {

    enum ComponentLayout {

        case bgra
        case abgr
        case argb
        case rgba
        case bgr
        case rgb

        var count: Int {
            switch self {
            case .bgr, .rgb: return 3
            default: return 4
            }
        }

    }

    var componentLayout: ComponentLayout? {
        guard let alphaInfo = CGImageAlphaInfo(rawValue: rawValue & Self.alphaInfoMask.rawValue) else { return nil }
        let isLittleEndian = contains(.byteOrder32Little)

        if alphaInfo == .none {
            return isLittleEndian ? .bgr : .rgb
        }
        let alphaIsFirst = alphaInfo == .premultipliedFirst || alphaInfo == .first || alphaInfo == .noneSkipFirst

        if isLittleEndian {
            return alphaIsFirst ? .bgra : .abgr
        } else {
            return alphaIsFirst ? .argb : .rgba
        }
    }

    var chromaIsPremultipliedByAlpha: Bool {
        let alphaInfo = CGImageAlphaInfo(rawValue: rawValue & Self.alphaInfoMask.rawValue)
        return alphaInfo == .premultipliedFirst || alphaInfo == .premultipliedLast
    }

}
```


问:
Why my ActiveMQ doesn't start
Ive been searching a lot and i couldn't figure out why, my java is properly installed. And the environment property is correct too.

Trying to install the ActiveMQ in Windows 7 64bit.
This is the ActiveMQ 5.8.0.

So with Administrator Cmd i run the bat inside Win64 "InstallService.bat", installs it.
But when i try to start it using "net start activemq" it throws an error related to the java.command in the wrapper.conf.

```<code>STATUS | wrapper  | 2013/07/29 13:00:10 | Launching a JVM...
FATAL  | wrapper  | 2013/07/29 13:00:10 | Unable to execute Java command.  The system cannot find the file specified. (0x2)
FATAL  | wrapper  | 2013/07/29 13:00:10 |     "%JAVA_HOME%\bin\java.exe" -Dactivemq.home="C:\apache-activemq-5.8.0\bin\win64\..\.." -Dactivemq.base="C:\apache-activemq-5.8.0\bin\win64\..\.." -Djavax.net.ssl.keyStorePassword=password -Djavax.net.ssl.trustStorePassword=password -Djavax.net.ssl.keyStore="C:\apache-activemq-5.8.0\bin\win64\..\../conf/broker.ks" -Djavax.net.ssl.trustStore="C:\apache-activemq-5.8.0\bin\win64\..\../conf/broker.ts" -Dcom.sun.management.jmxremote -Dorg.apache.activemq.UseDedicatedTaskRunner=true -Djava.util.logging.config.file=logging.properties -Dactivemq.conf="C:\apache-activemq-5.8.0\bin\win64\..\../conf" -Dactivemq.data="C:\apache-activemq-5.8.0\bin\win64\..\../data" -Xmx1024m -Djava.library.path="C:\apache-activemq-5.8.0\bin\win64\..\../bin/win64" -classpath "C:\apache-activemq-5.8.0\bin\win64\..\../bin/wrapper.jar;C:\apache-activemq-5.8.0\bin\win64\..\../bin/activemq.jar" -Dwrapper.key="b0Z3zqiLBNs16vNL" -Dwrapper.port=32000 -Dwrapper.jvm.port.min=31000 -Dwrapper.jvm.port.max=31999 -Dwrapper.pid=8120 -Dwrapper.version="3.2.3" -Dwrapper.native_library="wrapper" -Dwrapper.service="TRUE" -Dwrapper.cpu.timeout="10" -Dwrapper.jvmid=1 org.tanukisoftware.wrapper.WrapperSimpleApp org.apache.activemq.console.Main start
FATAL  | wrapper  | 2013/07/29 13:00:10 | Critical error: wait for JVM process failed
</code>```

Do you know what's wrong? :/

These are the wrapper properties in the wrapper.conf file

```<code>#********************************************************************
# Wrapper Properties
#********************************************************************

# wrapper.debug=TRUE
set.default.ACTIVEMQ_HOME=%ACTIVEMQ_HOME%
set.default.ACTIVEMQ_BASE=%ACTIVEMQ_BASE%
set.default.ACTIVEMQ_CONF=%ACTIVEMQ_BASE%/conf
set.default.ACTIVEMQ_DATA=%ACTIVEMQ_BASE%/data
wrapper.working.dir=.

# Java Application
wrapper.java.command=%JAVA_HOME%/bin/java.exe
</code>```

Thanks.

答: The same issue was solved by adding the location of JDK bin folder into PATH variable. </p>

Title: Why my ActiveMQ doesn't start

Body:
Ive been searching a lot and i couldn't figure out why, my java is properly installed. And the environment property is correct too.

Trying to install the ActiveMQ in Windows 7 64bit.
This is the ActiveMQ 5.8.0.

So with Administrator Cmd i run the bat inside Win64 "InstallService.bat", installs it.
But when i try to start it using "net start activemq" it throws an error related to the java.command in the wrapper.conf.

STATUS | wrapper  | 2013/07/29 13:00:10 | Launching a JVM...
FATAL  | wrapper  | 2013/07/29 13:00:10 | Unable to execute Java command.  The system cannot find the file specified. (0x2)
FATAL  | wrapper  | 2013/07/29 13:00:10 |     "%JAVA_HOME%\bin\java.exe" -Dactivemq.home="C:\apache-activemq-5.8.0\bin\win64\..\.." -Dactivemq.base="C:\apache-activemq-5.8.0\bin\win64\..\.." -Djavax.net.ssl.keyStorePassword=password -Djavax.net.ssl.trustStorePassword=password -Djavax.net.ssl.keyStore="C:\apache-activemq-5.8.0\bin\win64\..\../conf/broker.ks" -Djavax.net.ssl.trustStore="C:\apache-activemq-5.8.0\bin\win64\..\../conf/broker.ts" -Dcom.sun.management.jmxremote -Dorg.apache.activemq.UseDedicatedTaskRunner=true -Djava.util.logging.config.file=logging.properties -Dactivemq.conf="C:\apache-activemq-5.8.0\bin\win64\..\../conf" -Dactivemq.data="C:\apache-activemq-5.8.0\bin\win64\..\../data" -Xmx1024m -Djava.library.path="C:\apache-activemq-5.8.0\bin\win64\..\../bin/win64" -classpath "C:\apache-activemq-5.8.0\bin\win64\..\../bin/wrapper.jar;C:\apache-activemq-5.8.0\bin\win64\..\../bin/activemq.jar" -Dwrapper.key="b0Z3zqiLBNs16vNL" -Dwrapper.port=32000 -Dwrapper.jvm.port.min=31000 -Dwrapper.jvm.port.max=31999 -Dwrapper.pid=8120 -Dwrapper.version="3.2.3" -Dwrapper.native_library="wrapper" -Dwrapper.service="TRUE" -Dwrapper.cpu.timeout="10" -Dwrapper.jvmid=1 org.tanukisoftware.wrapper.WrapperSimpleApp org.apache.activemq.console.Main start
FATAL  | wrapper  | 2013/07/29 13:00:10 | Critical error: wait for JVM process failed

Do you know what's wrong? :/

These are the wrapper properties in the wrapper.conf file

#********************************************************************
# Wrapper Properties
#********************************************************************

# wrapper.debug=TRUE
set.default.ACTIVEMQ_HOME=%ACTIVEMQ_HOME%
set.default.ACTIVEMQ_BASE=%ACTIVEMQ_BASE%
set.default.ACTIVEMQ_CONF=%ACTIVEMQ_BASE%/conf
set.default.ACTIVEMQ_DATA=%ACTIVEMQ_BASE%/data
wrapper.working.dir=.

# Java Application
wrapper.java.command=%JAVA_HOME%/bin/java.exe

Thanks.


问:
How to finish an activity from an Adapter..?
I tried with passing context of activity into the adapter and then i tried context.finish(); But its giving me one error like The method finish() is undefined for the type Context

答:
For Kotlin code:</p>

```<code>(context as Activity).finish()
</code>```

Body:
For Kotlin code:

(context as Activity).finish()


问:
Include statement not working in PHP/Yii2
I have two files, the first one being in the main directory, console_output.php:

```<code><?php
class console_output
{
  function write_to_logfile($text) {
    file_put_contents("log.txt", $text);
  }
}
?>
</code>```

and the second one in a subdirectory, xController.php

```<code><?php
...import stuff...
include ("../console_output.php");

class xController extends Controller{
  ...do_stuff..

  function doMoreStuff(){
  ...

    $console_output = new console_output();
    $console_output->write_to_logfile("did Stuff");
  }
}
?>
</code>```

This is all in Yii2 framework, in case that matters. I have tried with apps/console_output.php and ../console_output.php, but it fails either way.
When I use apps/console_output.php, the error is

include(app/console_output.php) [https://secure.php.net/manual/en/function.include.php'>function.include.php]: failed to open stream: No such file or directory

The error is shown right at the include statement.

Using ../console_output.php in the include statement gives me an error at

```<code>$console_output->write_to_logfile("did Stuff");
</code>```

with the message

Class 'app\controllers\console_output' not found

I have no idea what I'm doing wrong here. Can you help me out please?

答: You relative path Def nation is wrong. You are using .. that mean you moving a director up from current script. You need to use "subdirectory/script.php"</p>

Body:
I have two files, the first one being in the main directory, console_output.php:

<?php
class console_output
{
  function write_to_logfile($text) {
    file_put_contents("log.txt", $text);
  }
}
?>

and the second one in a subdirectory, xController.php

<?php
...import stuff...
include ("../console_output.php");

class xController extends Controller{
  ...do_stuff..

  function doMoreStuff(){
  ...

    $console_output = new console_output();
    $console_output->write_to_logfile("did Stuff");
  }
}
?>

This is all in Yii2 framework, in case that matters. I have tried with apps/console_output.php and ../console_output.php, but it fails either way.
When I use apps/console_output.php, the error is

include(app/console_output.php) [https://secure.php.net/manual/en/function.include.php'>function.include.php]: failed to open stream: No such file or directory

The error is shown right at the include statement.

Using ../console_output.php in the include statement gives me an error at

$console_output->write_to_logfile("did Stuff");

with the message

Class 'app\controllers\console_output' not found

I have no idea what I'm doing wrong here. Can you help me out please?


问:
Silent APK installation by the device owner doesn't work on MIUI 11
I have a "device owner" Android app which silently installs APK using PackageInstaller (see the code, for example, here).

This code works perfectly on all Android 7+ devices except Xiaomi Redmi 7A (running MIUI 11). The installation fails, here's the related logcat output:

```<code>01-16 00:43:21.494  1488  2892 I InstallationStatistic: beginInstallSession: 417086238
01-16 00:43:21.600  1488  1658 D com.android.server.pm.PackageManagerServiceInjector: Package verify start
01-16 00:43:21.601  1488  1538 D CompatibilityInfo: mCompatibilityFlags - 0
01-16 00:43:21.601  1488  1538 D CompatibilityInfo: applicationDensity - 320
01-16 00:43:21.601  1488  1538 D CompatibilityInfo: applicationScale - 1.0
01-16 00:43:21.611 24382 24395 D  GuardProvider: start parse apk : /data/app/vmdl417086238.tmp
01-16 00:43:21.618 24382 24395 E i.guardprovide: Invalid ID 0x00000000.
01-16 00:43:21.638  4434 24418 D PackageVerifyedRecevier: verify package /data/app/vmdl417086238.tmp info:  PackageInfo{45d0d6b com.hmdm.sendphoto}
01-16 00:43:21.638  4434 24418 D PackageVerifyedRecevier: verify package /data/app/vmdl417086238.tmp finish true
01-16 00:43:21.639  1488  1658 I com.android.server.pm.PackageManagerServiceInjector: MIUILOG- Install Reject uid: 10161 pkg : com.hmdm.launcher
01-16 00:43:21.639  1488  1658 E PackageInstaller: Commit of session 417086238 failed: Permission Denied
</code>```

Package ID of the installer (device owner) is com.hmdm.launcher. Package ID of the app being installed is com.hmdm.sendphoto.

I tried to add the "Install unknown apps" permission but this didn't help.

Looks like the app must request MIUI OS for some special (undocumented) permissions?

The device owner rights were granted to the application by QR code based enrollment.

答:
Also with MIUI 10.3 some apps are refused to install/update.
For instance, I cannot install a Threema update the usual way (and just get a silly error 'not installed'). logcat shows that com.miui.global.packageinstaller.action.verifypackage called by com.android.server.pm.PackageManagerServiceInjector fails:

```<code>02-16 11:29:05.809  1271  1853 D com.android.server.pm.PackageManagerServiceInjector: Package verify start
02-16 11:29:05.810  1271  1317 D CompatibilityInfo: mCompatibilityFlags - 0
02-16 11:29:05.810  1271  1317 D CompatibilityInfo: applicationDensity - 440
02-16 11:29:05.810  1271  1317 D CompatibilityInfo: applicationScale - 1.0
02-16 11:29:05.812  1271  6228 W ActivityManager: Sending non-protected broadcast com.miui.global.packageinstaller.action.verifypackage from system 3440:com.miui.securitycenter.remote/1000 pkg com.miui.securitycenter. Callers=
02-16 11:29:05.816  3440 25765 E ActivityThread: Failed to find provider info for guard
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier: parseApk
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier: java.lang.IllegalArgumentException: Unknown URI content://guard
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at android.content.ContentResolver.call(Unknown Source:63)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at com.miui.permcenter.install.q.doInBackground(Unknown Source:17)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at com.miui.permcenter.install.q.doInBackground(Unknown Source:2)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at android.os.AsyncTask$2.call(Unknown Source:20)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at java.util.concurrent.FutureTask.run(FutureTask.java:266)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at java.lang.Thread.run(Thread.java:764)
02-16 11:29:05.817  3440 25765 D PackageVerifyedRecevier: verify package /data/app/vmdl216836998.tmp info:  null
02-16 11:29:05.818  3440 25765 D PackageVerifyedRecevier: verify package /data/app/vmdl216836998.tmp finish false
02-16 11:29:05.818  1271  1853 I com.android.server.pm.PackageManagerServiceInjector: MIUILOG- INSTALL_FAILED_VERIFICATION_FAILURE  uid: 10026 pkg : com.google.android.packageinstaller
</code>```

What worked for me was to move the apk file to /data/local/tmp/
and then call as root

```<code>pm install -r file.apk
</code>```

Body:
I have a "device owner" Android app which silently installs APK using PackageInstaller (see the code, for example, here).

This code works perfectly on all Android 7+ devices except Xiaomi Redmi 7A (running MIUI 11). The installation fails, here's the related logcat output:

01-16 00:43:21.494  1488  2892 I InstallationStatistic: beginInstallSession: 417086238
01-16 00:43:21.600  1488  1658 D com.android.server.pm.PackageManagerServiceInjector: Package verify start
01-16 00:43:21.601  1488  1538 D CompatibilityInfo: mCompatibilityFlags - 0
01-16 00:43:21.601  1488  1538 D CompatibilityInfo: applicationDensity - 320
01-16 00:43:21.601  1488  1538 D CompatibilityInfo: applicationScale - 1.0
01-16 00:43:21.611 24382 24395 D  GuardProvider: start parse apk : /data/app/vmdl417086238.tmp
01-16 00:43:21.618 24382 24395 E i.guardprovide: Invalid ID 0x00000000.
01-16 00:43:21.638  4434 24418 D PackageVerifyedRecevier: verify package /data/app/vmdl417086238.tmp info:  PackageInfo{45d0d6b com.hmdm.sendphoto}
01-16 00:43:21.638  4434 24418 D PackageVerifyedRecevier: verify package /data/app/vmdl417086238.tmp finish true
01-16 00:43:21.639  1488  1658 I com.android.server.pm.PackageManagerServiceInjector: MIUILOG- Install Reject uid: 10161 pkg : com.hmdm.launcher
01-16 00:43:21.639  1488  1658 E PackageInstaller: Commit of session 417086238 failed: Permission Denied

Package ID of the installer (device owner) is com.hmdm.launcher. Package ID of the app being installed is com.hmdm.sendphoto.

I tried to add the "Install unknown apps" permission but this didn't help.

Looks like the app must request MIUI OS for some special (undocumented) permissions?

The device owner rights were granted to the application by QR code based enrollment.

Body:
Also with MIUI 10.3 some apps are refused to install/update.
For instance, I cannot install a Threema update the usual way (and just get a silly error 'not installed'). logcat shows that com.miui.global.packageinstaller.action.verifypackage called by com.android.server.pm.PackageManagerServiceInjector fails:

02-16 11:29:05.809  1271  1853 D com.android.server.pm.PackageManagerServiceInjector: Package verify start
02-16 11:29:05.810  1271  1317 D CompatibilityInfo: mCompatibilityFlags - 0
02-16 11:29:05.810  1271  1317 D CompatibilityInfo: applicationDensity - 440
02-16 11:29:05.810  1271  1317 D CompatibilityInfo: applicationScale - 1.0
02-16 11:29:05.812  1271  6228 W ActivityManager: Sending non-protected broadcast com.miui.global.packageinstaller.action.verifypackage from system 3440:com.miui.securitycenter.remote/1000 pkg com.miui.securitycenter. Callers=
02-16 11:29:05.816  3440 25765 E ActivityThread: Failed to find provider info for guard
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier: parseApk
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier: java.lang.IllegalArgumentException: Unknown URI content://guard
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at android.content.ContentResolver.call(Unknown Source:63)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at com.miui.permcenter.install.q.doInBackground(Unknown Source:17)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at com.miui.permcenter.install.q.doInBackground(Unknown Source:2)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at android.os.AsyncTask$2.call(Unknown Source:20)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at java.util.concurrent.FutureTask.run(FutureTask.java:266)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
02-16 11:29:05.817  3440 25765 E PackageVerifyedRecevier:   at java.lang.Thread.run(Thread.java:764)
02-16 11:29:05.817  3440 25765 D PackageVerifyedRecevier: verify package /data/app/vmdl216836998.tmp info:  null
02-16 11:29:05.818  3440 25765 D PackageVerifyedRecevier: verify package /data/app/vmdl216836998.tmp finish false
02-16 11:29:05.818  1271  1853 I com.android.server.pm.PackageManagerServiceInjector: MIUILOG- INSTALL_FAILED_VERIFICATION_FAILURE  uid: 10026 pkg : com.google.android.packageinstaller

What worked for me was to move the apk file to /data/local/tmp/
and then call as root

pm install -r file.apk


问:
Using Interface Builder for UITableViews
I'm very early in the iPhone development learning process.  I'm trying to get my head around various pieces.  Right now I've just taken the basic NavigationController template and I'm trying to create a simple grouped table view with a couple of text fields.  What I can't seem to do is to get Interface Builder to allow me to drop a UITableViewCell into a UITableView so that I can then add a text field to the Cell.  Is this even possible (it would seem that its supposed to be given the fact that UITableViewCell is a draggable control)?

If not, does that mean all of that is code I will need to just write myself?

答: This is a good tutorial on using the UI builder for UITableView's</p>

OwnerDisplayName: flxkid

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ryan Townshend

OwnerDisplayName: William Denniss


问:
Azure Blob and Queue Thread Safety
I need some help in understanding the thread safety in azure CloudBlobClient, CloudQueueClient and CloudBlob classes.

I am developing a worker role which includes multiple independent job processors where each of these job processors read from a specific queue and write/update to some blob containers which may be the same.

I want to make sure that these job processors are not stepping on each other toe.

1> How can I make sure that this is the case without using any kind of lock? If I assign a separate CloudBlobClient and CloudQueueClient to each of my job processors (who all live within same process), is it enough to say that they are independent from each other and because every job processors uses a separate client instance, they will not run into each other at all?

2> Within same job processor, if I try to have parallelism on CloudBlobClient using Parallel.ForEach to say call  GetBlobReference or UploadText in parallel, do I need to incorporate some sort of synchronization or are these methods thread safe? Azure documentation says they are not but most examples that I have seen online do not seem to apply any kind of synchronization mechanism on these methods. What is the best way to achieve this? I mean the best way to use one CloudBlobClient and call GetBlobReference or UploadText in Parallel?

答:
I had a look at the CloudBlobClient documentation on MSDN and what it says is:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

As this is not a static member, it is not guaranteed to be thread safe.  If you want to be sure that you're not going to get caught out by any threading issues the MS may have missed in the storage client library, then yes you should ensure that each thread has it's own client (maybe create a ThreadStatic variable).

Having said that, I have used the CloudBlobClient to upload multiple items in a Parallel.ForEach without it causing any problems.

Title: Azure Blob and Queue Thread Safety


问:
Rename all files in a user specified directory
So I want to be able to automatically rename all files in a user specified directory (I am aware that c++ is not the optimum language/tool for doing this).

For example, a directory currently contains hundreds of files with random character names, and I wish to change them all to

August 1, August 2, August 3 etc.

The code

User specifies directory like this

```<code>std::string directory;

std::cout << "Enter directory: ";
std::cin >> directory;
</code>```

Directory is opened like this (using dirent.h)

```<code>DIR* pdir = NULL;
struct dirent* pent = NULL;
const char* DIRECTORY;

// convert directory string to const char
DIRECTORY = directory.c_str();

pdir = opendir(DIRECTORY);
</code>```

Rename all files within the specified directory here

```<code>int i = 1;
std::string s, oldname, newname;
const char* OLDNAME, * NEWNAME;

while (pent = readdir(pdir))
{
    // convert int i to str s
    std::stringstream out;
    out << i;
    s = out.str();

    oldname = pent->d_name;
    newname = "August " + s;

    OLDNAME = oldname.c_str();
    NEWNAME = newname.c_str();

    rename(OLDNAME, NEWNAME);

    i++;
}
</code>```

Everything works up until the while loop, which appears to do absolutely nothing, that is the part that I am stuck on.

However, the strange part is, that this while loop designed to display the contents of the directory (using same logic and syntax as nonworking loop) works perfectly

```<code>while (pent = readdir (pdir))
{
    std::cout << pent->d_name << "\n";
}
</code>```

Using MSVS2012 on Win7.

Another issue that I think I am going to run into is, within the directory, different files have different extensions (this may be able to be solved by saving the last 4 characters of the original name and appending it to the new name, but not sure, help would be greatly appreciated).

答:
Using c++17's <filesystem>, one can do nowadays, something like the followings. I hope that might be helpful for the future readers:

```<code>#include <iostream>
#include <string>
#include <filesystem>  //std::filesystem::path, std::filesystem::recursive_directory_iterator

std::string changeFileName(const std::string& currentFileName, const std::string& extension, int number)
{
   std::cout << "Current file name: " << currentFileName << "\n";

   // ....other logics regarding current filename

   const std::string newFileName{ "August - " + std::to_string(number) + extension};
   std::cout << "File name after renaming: " << newFileName << "\n";
   return newFileName; // new file name
}

int main()
{
   const std::filesystem::path myPath = ".....full path....";
   const std::string extension{ ".txt" };
   int number{ 0 };
   // iterate through all the files in the directory
   for (const auto& dirEntry : std::filesystem::directory_iterator(myPath))
   {
      // if the file is meant for changing name!
      if (std::filesystem::is_regular_file(dirEntry) && dirEntry.path().extension() == extension)
      {
         const std::string currentFileName{ dirEntry.path().filename().string() };
         // following function is meant for the logic to provide the new file names in the directory
         // in your case it cout have been simply: "August - " + std::to_string(number++) + "extension"
         const std::string newFileName{ changeFileName(currentFileName, extension, number++) };
         try
         {
            std::filesystem::rename(myPath / currentFileName, myPath / newFileName);
         }
         catch (std::filesystem::filesystem_error const& error)  // catch the errors(if any)!
         {
            std::cout << error.code() << "\n" << error.what() << "\n";
         }
      }

   }
}
</code>```

Body:
So I want to be able to automatically rename all files in a user specified directory (I am aware that c++ is not the optimum language/tool for doing this).

For example, a directory currently contains hundreds of files with random character names, and I wish to change them all to

August 1, August 2, August 3 etc.

The code

User specifies directory like this

std::string directory;

std::cout << "Enter directory: ";
std::cin >> directory;

Directory is opened like this (using dirent.h)

DIR* pdir = NULL;
struct dirent* pent = NULL;
const char* DIRECTORY;

// convert directory string to const char
DIRECTORY = directory.c_str();

pdir = opendir(DIRECTORY);

Rename all files within the specified directory here

int i = 1;
std::string s, oldname, newname;
const char* OLDNAME, * NEWNAME;

while (pent = readdir(pdir))
{
    // convert int i to str s
    std::stringstream out;
    out <d_name;
    newname = "August " + s;

    OLDNAME = oldname.c_str();
    NEWNAME = newname.c_str();

    rename(OLDNAME, NEWNAME);

    i++;
}

Everything works up until the while loop, which appears to do absolutely nothing, that is the part that I am stuck on.

However, the strange part is, that this while loop designed to display the contents of the directory (using same logic and syntax as nonworking loop) works perfectly

while (pent = readdir (pdir))
{
    std::cout << pent->d_name << "\n";
}

Using MSVS2012 on Win7.

Another issue that I think I am going to run into is, within the directory, different files have different extensions (this may be able to be solved by saving the last 4 characters of the original name and appending it to the new name, but not sure, help would be greatly appreciated).

Body:
Using c++17's <filesystem>, one can do nowadays, something like the followings. I hope that might be helpful for the future readers:

#include <iostream>
#include <string>
#include <filesystem>  //std::filesystem::path, std::filesystem::recursive_directory_iterator

std::string changeFileName(const std::string& currentFileName, const std::string& extension, int number)
{
   std::cout << "Current file name: " << currentFileName << "\n";

   // ....other logics regarding current filename

   const std::string newFileName{ "August - " + std::to_string(number) + extension};
   std::cout << "File name after renaming: " << newFileName << "\n";
   return newFileName; // new file name
}

int main()
{
   const std::filesystem::path myPath = ".....full path....";
   const std::string extension{ ".txt" };
   int number{ 0 };
   // iterate through all the files in the directory
   for (const auto& dirEntry : std::filesystem::directory_iterator(myPath))
   {
      // if the file is meant for changing name!
      if (std::filesystem::is_regular_file(dirEntry) && dirEntry.path().extension() == extension)
      {
         const std::string currentFileName{ dirEntry.path().filename().string() };
         // following function is meant for the logic to provide the new file names in the directory
         // in your case it cout have been simply: "August - " + std::to_string(number++) + "extension"
         const std::string newFileName{ changeFileName(currentFileName, extension, number++) };
         try
         {
            std::filesystem::rename(myPath / currentFileName, myPath / newFileName);
         }
         catch (std::filesystem::filesystem_error const& error)  // catch the errors(if any)!
         {
            std::cout << error.code() << "\n" << error.what() << "\n";
         }
      }

   }
}


问:
How to know variables from different..."namespaces"?
How can I reach some variable declared in another place from within an external javascript file ?

Suppose in an html file I have the following

```<code><head>
 <script>
   var a = 'something';
 </script>
<head>
<body>
<iframe src="otherfile.html"/>
</body>
</code>```

and inside otherfile.html, in the  section, I have

```<code>alert(a);
</code>```

How can I make sure I get an alert message saying "something" ?

I think Google Adsense does this, their code is:

```<code><script type="text/javascript"><!--
google_ad_client = "youdontneedtoknowthis";
google_ad_slot = "5404192644";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</code>```

How can the script in http://pagead2.googlesyndication.com/pagead/show_ads.js know those variables (e.g. google_ad_client) ?

答: The script can just assume that those variables will be set. They must be because they are needed. The script can check if they are undefined and fail gracefully (do nothing) when they are not. The variables are not in another namespace.</p>

Body:
How can I reach some variable declared in another place from within an external javascript file ?

Suppose in an html file I have the following

and inside otherfile.html, in the  section, I have

alert(a);

How can I make sure I get an alert message saying "something" ?

I think Google Adsense does this, their code is:

How can the script in http://pagead2.googlesyndication.com/pagead/show_ads.js know those variables (e.g. google_ad_client) ?