问:
Hide login/register button when logged in and hide logout button when logged out
i'm kinda new in PHP and I have some issues. When I'm logged in on my website I want to hide the 'Login' and 'Register' button, and when I'm logged out I want to hide the 'logout' button.

This is my login.php page:

```<code><?php
    include "navbar.php";
?>
<?php
    include_once "check.php";

    $error = ""; //Variable for storing our errors.
    if(isset($_POST["submit"]))
    {
        if(empty($_POST["username"]) || empty($_POST["password"]))
        {
            $error = "Both fields are required.";
        }else
        {
            // Define $username and $password
            $username=$_POST['username'];
            $password=$_POST['password'];

            // To protect from MySQL injection
            $username = stripslashes($username);
            $password = stripslashes($password);
            $username = mysqli_real_escape_string($db, $username);
            $password = mysqli_real_escape_string($db, $password);
            $password = md5($password);

            //Check username and password from database
            $sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
            $result=mysqli_query($db,$sql);
            $row=mysqli_fetch_array($result,MYSQLI_ASSOC);

            //If username and password exist in our database then create a session.
            //Otherwise echo error.

            if(mysqli_num_rows($result) == 1)
            {
                $_SESSION['username'] = $username;
                header("location: index.php");
            }else
            {
                $error = "Incorrect username or password.";
            }

        }
    }

?>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="assets/css/acc.css">
        <link rel="stylesheet" type="text/css" href="assets/css/acc2.css">
        <link rel="stylesheet" type="text/css" href="assets/css/navbar.css">
        <title>Login | Peerbolte-ICT</title>
    </head>
    </body>
        <section>
        <p style="color:red;"><?php echo $error; ?> </p>
            <form method="POST" action="">
                <div class="accPanel">
                <h1 style="color: black; padding-bottom: 5%;">Login</h1>
                <form method="POST" action="">
                    <div class="login-input">
                        <label class="accLabel"><b>Username<span style="color:red;">*</span></b></label>
                        <input type="text" placeholder="Enter Username" name="username" required>

                        <label class="accLabel"><b>Password<span style="color:red;">*</span></b></label>
                        <input type="password" placeholder="Enter Password" name="password" required>

                        <button class="submitButton" type="submit" name="submit">Login</button>
                    </div>
                </form>
            </div>
        </section>
    </body>
</html>
</code>```

And this is my navbar.php where the buttons are:

```<code><ul>
  <li><a href="index.php">Home</a></li>
  <li><a href="#bannerTwo">Services</a></li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Our Work</a>
    <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Account</a>
    <div class="dropdown-content">
      <a href="login.php">Login</a>
      <a href="register.php">Register</a>
      <a href="logout.php">Logout</a>
    </div>
  </li>
</ul>
</code>```

Thanks

答:
you can display your link based on condition. check session for that if user login you get session value on base of that logic you can put condition like below:

```<code><?php if( isset($_SESSION['username']) && !empty($_SESSION['username']) )
{
?>
      <a href="logout.php">Logout</a>
<?php }else{ ?>
     <a href="login.php">Login</a>
     <a href="register.php">Register</a>
<?php } ?>
</code>```

Note: make your you start session in file.

Body:
i'm kinda new in PHP and I have some issues. When I'm logged in on my website I want to hide the 'Login' and 'Register' button, and when I'm logged out I want to hide the 'logout' button.

This is my login.php page:

<?php
    include "navbar.php";
?>
<?php
    include_once "check.php";

    $error = ""; //Variable for storing our errors.
    if(isset($_POST["submit"]))
    {
        if(empty($_POST["username"]) || empty($_POST["password"]))
        {
            $error = "Both fields are required.";
        }else
        {
            // Define $username and $password
            $username=$_POST['username'];
            $password=$_POST['password'];

            // To protect from MySQL injection
            $username = stripslashes($username);
            $password = stripslashes($password);
            $username = mysqli_real_escape_string($db, $username);
            $password = mysqli_real_escape_string($db, $password);
            $password = md5($password);

            //Check username and password from database
            $sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
            $result=mysqli_query($db,$sql);
            $row=mysqli_fetch_array($result,MYSQLI_ASSOC);

            //If username and password exist in our database then create a session.
            //Otherwise echo error.

            if(mysqli_num_rows($result) == 1)
            {
                $_SESSION['username'] = $username;
                header("location: index.php");
            }else
            {
                $error = "Incorrect username or password.";
            }

        }
    }

?>

        <link rel="stylesheet" type="text/css" href="assets/css/acc.css">
        <link rel="stylesheet" type="text/css" href="assets/css/acc2.css">
        <link rel="stylesheet" type="text/css" href="assets/css/navbar.css">
        <title>Login | Peerbolte-ICT</title>

<?php echo $error; ?>

            <form method="POST" action="">

Login

                <form method="POST" action="">

                        Username*
                        <input type="text" placeholder="Enter Username" name="username" required>

                        Password*
                        <input type="password" placeholder="Enter Password" name="password" required>

                        <button class="submitButton" type="submit" name="submit">Login</button>

                </form>

And this is my navbar.php where the buttons are:

Home

Services

    Our Work

      Link 1
      Link 2
      Link 3

    Account

      Login
      Register
      Logout

Thanks

Body:
you can display your link based on condition. check session for that if user login you get session value on base of that logic you can put condition like below:

<?php if( isset($_SESSION['username']) && !empty($_SESSION['username']) )
{
?>
      <a href="logout.php">Logout</a>
<?php }else{ ?>
     <a href="login.php">Login</a>
     <a href="register.php">Register</a>
<?php } ?>

Note: make your you start session in file.


来源: stackexchange

问:
Remove particular string from url Jquery
I need to remove size i.e. resolution of image path from url. Take following example:

```<code>http://raudevlocal.com/wp/wp-content/uploads/2017/05/0000362_chocolate-layer-cake-1024x682.jpeg
</code>```

I need to remove -1024x682

```<code>http://raudevlocal.com/wp/wp-content/uploads/2017/05/rohit-300x118.jpg
</code>```

Need to remove -300x118

答:
You can use replace function

```<code>window.location.href.replace('-1024x682', '');
</code>```

If you want to use the new one as your current url then try

```<code>window.location.href = window.location.href.replace('-1024x682', '');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to remove size i.e. resolution of image path from url. Take following example:

http://raudevlocal.com/wp/wp-content/uploads/2017/05/0000362_chocolate-layer-cake-1024x682.jpeg

I need to remove -1024x682

http://raudevlocal.com/wp/wp-content/uploads/2017/05/rohit-300x118.jpg

Need to remove -300x118

Body:
You can use replace function

window.location.href.replace('-1024x682', '');

If you want to use the new one as your current url then try

window.location.href = window.location.href.replace('-1024x682', '');


问:
Remove Specific LineGeometry in a Path
My application consists of a canvas with some user drag-droppable UIelements which can be further connected using lines.

To connect two UIelements I have used a Path consisting a GeometryGroup, which further contains LineGeometry as its childs. Check this screenshot.

So as in the picture, the three items are connected via a Path which consists of 2 LineGeometry. I'm trying to implement 'Remove Link' option but all i can do is remove the whole Path, which would remove both the LineGeometry. How can i specifically select that particular line segment and remove it?

答:
You need the distances to the click point.</p>

```<code>public void RemoveLink(Point point)
{
    // ...

    // point - 2D click point
    // lineList - list of links (lines)
    setDistance(lineList, point)

    lineList.Sort(compare);
    lineList[0].remove();
    // ...
}

private static Comparison<GeomObject> compare = new Comparison<GeomObject>(GeomObject.CompareByDistance);

public static int CompareByDistance(GeomObject go1, GeomObject go2)
{
    return go1.mDistance.CompareTo(go2.mDistance);
}

private void setDistance(List<Line> lineList, Point point) {
    // set mDistance for each Line
    // mDistance - distance to point
}
</code>```

Title: Remove Specific LineGeometry in a Path

Body:
You need the distances to the click point.

public void RemoveLink(Point point)
{
    // ...

    // point - 2D click point
    // lineList - list of links (lines)
    setDistance(lineList, point)

    lineList.Sort(compare);
    lineList[0].remove();
    // ...
}

private static Comparison<GeomObject> compare = new Comparison<GeomObject>(GeomObject.CompareByDistance);

public static int CompareByDistance(GeomObject go1, GeomObject go2)
{
    return go1.mDistance.CompareTo(go2.mDistance);
}

private void setDistance(List<Line> lineList, Point point) {
    // set mDistance for each Line
    // mDistance - distance to point
}


问:
Doctrine LifecycleEventArgs return Gedmo\Loggable\Entity\LogEntry
I'm trying to work with doctrine event in a symfony project,
following the symfony doc I have this code

```<code>public function postPersist(LifecycleEventArgs $args)
{
    $entity = $args->getEntity();

    if (!$entity instanceof Rubrique) {
        return;
    }

    $entityManager = $args->getEntityManager();
    // do some stuff
}
</code>```

The problem is that $entity is not the expected object Rubrique but an instance of Gedmo\Loggable\Entity\LogEntry maybe because Rubrique is Loggable. How can I access to my entity for manipulate it as I want ?
Thanks

答:
This event listener is a "generic" one and not an doctrine entity listener

This means that the event is raised for each entity persisted: if you have a relation between Rubrique and LogEntry, than is possible that you're checking only for the "first" of them being "postPersisted".

If you need a specific listener only for that kind of entity, think about using doctrine entity listener (linked above).

Moreover remember that "generic" listener will listen (or will be subscribed) for events of every entity (so, basically, it could be invoked a lot of times) wheres doctrine entity listener not.

Body:
I'm trying to work with doctrine event in a symfony project,
following the symfony doc I have this code

public function postPersist(LifecycleEventArgs $args)
{
    $entity = $args->getEntity();

    if (!$entity instanceof Rubrique) {
        return;
    }

    $entityManager = $args->getEntityManager();
    // do some stuff
}

The problem is that $entity is not the expected object Rubrique but an instance of Gedmo\Loggable\Entity\LogEntry maybe because Rubrique is Loggable. How can I access to my entity for manipulate it as I want ?
Thanks


问:
Excel and IE11 VBA Automation
I'm new in VBA and i'm trying to automate a web Explorer navigation but with many difficolties. I've composed a script that navigate into a web page and search for a code. the result is a table ("table") with one row that contains the searched item ("TCKNodanSorgula.aspx?tckno=27497556158") displayed as a link to another page. Here the code of that table:

T.C. Kimlik No

B.S. No

Yakınlık

Adı

Doğum Tarihi

Durumu

27461077396

34

Kendisi

SEVGİ

25/10/1960

Açık

27497076158

19

Babası

ŞEKİ

01/12/1932

Ölüm

27470077004

30

Annesi

YÜKEL

11/09/1937

Açık

  ```
</div>
</div>
</p>

<p>Here my code:</p>

```For Each tık In ob.document.getElementsByTagName("a")
    If tık.innertext = href Then
        tık.Click
        Exit For
    End If
Next tık
```

I can find but I can't execute the code in order to press the second href button. I'm using IE 11.

Thanks for your patience!.

答:
Solution:</p>

```<code>y = 0
For Each ele In ob.document.getElementById("MainContent_lbl_YakinBilgi").getElementsByTagName("a")
    y = y + 1
    If y = 2 Then
    Cells(i, 34).Value = ele.outerHTML
    End If

Next ele
</code>```

Title: Excel and IE11 VBA Automation

Body:
I'm new in VBA and i'm trying to automate a web Explorer navigation but with many difficolties. I've composed a script that navigate into a web page and search for a code. the result is a table ("table") with one row that contains the searched item ("TCKNodanSorgula.aspx?tckno=27497556158") displayed as a link to another page. Here the code of that table:

T.C. Kimlik No

B.S. No

Yakınlık

Adı

Doğum Tarihi

Durumu

27461077396

34

Kendisi

SEVGİ

25/10/1960

Açık

27497076158

19

Babası

ŞEKİ

01/12/1932

Ölüm

27470077004

30

Annesi

YÜKEL

11/09/1937

Açık

Here my code:

For Each tık In ob.document.getElementsByTagName("a")
    If tık.innertext = href Then
        tık.Click
        Exit For
    End If
Next tık

I can find but I can't execute the code in order to press the second href button. I'm using IE 11.

Thanks for your patience!.

Body:
Solution:

y = 0
For Each ele In ob.document.getElementById("MainContent_lbl_YakinBilgi").getElementsByTagName("a")
    y = y + 1
    If y = 2 Then
    Cells(i, 34).Value = ele.outerHTML
    End If

Next ele


问:
Get Bitmap image details (such as width and height)
How to get the image detail (name, width, height, size, etc) which is selected in image view

I Generate ImageViewXML

```<code><ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent"/>
</code>```

and get a function to put selected image from folder to that ImageView

```<code>Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

            //Log.d(TAG, String.valueOf(bitmap));

            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            imageView.setImageBitmap(bitmap);

        } catch (IOException e) {
            e.printStackTrace();
        }
</code>```

Its all working correctly without bug, when i want to get the image detail, such as name by using String.valueOf(bitmap) but it return with : android.graphics.Bitmap@5280fcb4

How to get that image detail ?

答:
Try this

```<code>Bitmap bitmap = ((BitmapDrawable)imageView.getBackground()).getBitmap();
int width = bitmap .getWidth();
int height = bitmap .getHeight();
</code>```

Size of Image

```<code> Bitmap bitmap = ((BitmapDrawable)imageView.getBackground()).getBitmap();
 ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytestream );
 byte[] imageByte = bytestream .toByteArray();
 long lengthbmp = imageByte .length;
</code>```

Body:
How to get the image detail (name, width, height, size, etc) which is selected in image view

I Generate ImageViewXML

<ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent"/>

and get a function to put selected image from folder to that ImageView

Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

            //Log.d(TAG, String.valueOf(bitmap));

            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            imageView.setImageBitmap(bitmap);

        } catch (IOException e) {
            e.printStackTrace();
        }

Its all working correctly without bug, when i want to get the image detail, such as name by using String.valueOf(bitmap) but it return with : android.graphics.Bitmap@5280fcb4

How to get that image detail ?

Body:
Try this

Bitmap bitmap = ((BitmapDrawable)imageView.getBackground()).getBitmap();
int width = bitmap .getWidth();
int height = bitmap .getHeight();

Size of Image

 Bitmap bitmap = ((BitmapDrawable)imageView.getBackground()).getBitmap();
 ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytestream );
 byte[] imageByte = bytestream .toByteArray();
 long lengthbmp = imageByte .length;


问:
How to handle `UnhandledPromiseRejectionWarning` when using Observable.from(<Promise>) and catching error in the Observable
I am using redux-observable together with isomorphic-fetch to handle http requests in my React app. I am favouring this combination over using rxjs' ajax because I am testing with Jest - which runs tests in Node.js- and want to intercept http requests with nock. See this related question: Use fetch instead of ajax with redux-observable.

So here is the problem: I get an UnhandledPromiseRejectionWarning together with a scary: DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. because I am not catching my promise rejections directly but rather leave that to the Observable:

```<code>// apiModule.js
import fetch from 'isomorphic-fetch'

const api = {
  getSomething: () => {
    const request = fetch('http://some-api/')
      .then(res => catchError(res)) // throwing an Error here if not response.ok
      .then(res => res.json())

    return Observable.from(request)
  }
}
</code>```

Then in the epic:

```<code>// myReduxModule.js
import {api} from './apiModule.js'

const getSomethingEpic = action$ =>
  action$
    .ofType(GET_SOMETHING)
    .mergeMap(action =>
      api
        .getSomething()
        .map(response => getSomethingSucceeded(response))
        .catch(error => logError(error)) // error is handled here!
    )
</code>```

So the promise rejection is handled in the Observable but not directly!

Any suggestions how to avoid the warning (and a possible future terminate with non-zero exit code) in this scenario?

答:
From now on, every time you have a promise and you call the then, you must also implement the catch. Also in your tests.

```<code> const request = fetch('http://some-api/')
      .then(res => catchError(res))
      .then(res => res.json())
      .catch(err => catchError(res)) // <= here you should implement the catch
</code>```

Body:
I am using redux-observable together with isomorphic-fetch to handle http requests in my React app. I am favouring this combination over using rxjs' ajax because I am testing with Jest - which runs tests in Node.js- and want to intercept http requests with nock. See this related question: Use fetch instead of ajax with redux-observable.

So here is the problem: I get an UnhandledPromiseRejectionWarning together with a scary: DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. because I am not catching my promise rejections directly but rather leave that to the Observable:

// apiModule.js
import fetch from 'isomorphic-fetch'

const api = {
  getSomething: () => {
    const request = fetch('http://some-api/')
      .then(res => catchError(res)) // throwing an Error here if not response.ok
      .then(res => res.json())

    return Observable.from(request)
  }
}

Then in the epic:

// myReduxModule.js
import {api} from './apiModule.js'

const getSomethingEpic = action$ =>
  action$
    .ofType(GET_SOMETHING)
    .mergeMap(action =>
      api
        .getSomething()
        .map(response => getSomethingSucceeded(response))
        .catch(error => logError(error)) // error is handled here!
    )

So the promise rejection is handled in the Observable but not directly!

Any suggestions how to avoid the warning (and a possible future terminate with non-zero exit code) in this scenario?

Body:
From now on, every time you have a promise and you call the then, you must also implement the catch. Also in your tests.

 const request = fetch('http://some-api/')
      .then(res => catchError(res))
      .then(res => res.json())
      .catch(err => catchError(res)) // <= here you should implement the catch


问:
Given an associative array of Date strings, find the next closest date
Given an associative array of Date strings, how do I find the next closest date on or after today?

UPDATE: What if this were an associative array? How do I return the key for the closest date?

```<code>var matchdays = {};

7386: "09/14/2010"
7387: "09/29/2010"
7388: "10/20/2010"
7389: "11/02/2010"
7390: "11/24/2010"
7391: "12/07/2010"
7392: "12/18/2010"
</code>```

For example, I'd expect it to return 7392 because 12/18 is on or after today (12/14).

答:
Sort your array, and then search until you find a date later than today.  You could also do a binary search, or other fancy things depending on the size of your array and your performance requirements.

```<code>var today = new Date();

dateList.sort();

var nextLater = null;

for (var i = 0; i < dateList.length; i++) {
  if (dateList[i] > today) {
    nextLater = dateList[i];
    break;
  }
}
</code>```

Update

Associative arrays are a bit trickier.  You can sort the keys by the dates, and then do the same as above, or you could simply go through one at a time tracking the smallest positive offset from today.  The former is like this:

```<code>// Function to get the keys
function keys(obj) {
    var keys = [];
    for (var key in obj) {
        keys.push(key);
    }
    return keys;
}

// Get the keys, then sort the keys by there associated date
var keys = keys(matchdays).sort(function(a, b) {
    var d1 = new Date(matchdays[a]);
    var d2 = new Date(matchdays[b]);

    return d1 - d2;
});

// Iterate through the keys, finding the key associated with the next date after today
var today = new Date();
var nextLater = null;

for (var i = 0; i < keys.length; i++) {
    var date = new Date(matchdays[keys[i]]);

    if (date > today) {
        nextLater = keys[i];
        break;
    }
}

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

Sorting adds some redundancy as a brute force search is going to be O(n) and a best-case sort is going to be O(n) as well.  So to brute force search, just:

```<code>// Function to get the keys
function keys(obj) {
    var keys = [];
    for (var key in obj) {
        keys.push(key);
    }
    return keys;
}

// Get the keys
var keys = keys(matchdays);

// Iterate through the keys, finding the key associated with the next date after today
var today = new Date();
var nextLater = null;
var min;

for (var i = 0; i < keys.length; i++) {
    var date = new Date(matchdays[keys[i]]);

    var diff = date - today;

    if (diff > 0 && (min == undefined || diff < min ) {
        min = diff
        nextLater = keys[i];
    }
}

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

ContentLicense: CC BY-SA 2.5

Body:
Given an associative array of Date strings, how do I find the next closest date on or after today?

UPDATE: What if this were an associative array? How do I return the key for the closest date?

var matchdays = {};

7386: "09/14/2010"
7387: "09/29/2010"
7388: "10/20/2010"
7389: "11/02/2010"
7390: "11/24/2010"
7391: "12/07/2010"
7392: "12/18/2010"

For example, I'd expect it to return 7392 because 12/18 is on or after today (12/14).

Body:
Sort your array, and then search until you find a date later than today.  You could also do a binary search, or other fancy things depending on the size of your array and your performance requirements.

var today = new Date();

dateList.sort();

var nextLater = null;

for (var i = 0; i < dateList.length; i++) {
  if (dateList[i] > today) {
    nextLater = dateList[i];
    break;
  }
}

Update

Associative arrays are a bit trickier.  You can sort the keys by the dates, and then do the same as above, or you could simply go through one at a time tracking the smallest positive offset from today.  The former is like this:

// Function to get the keys
function keys(obj) {
    var keys = [];
    for (var key in obj) {
        keys.push(key);
    }
    return keys;
}

// Get the keys, then sort the keys by there associated date
var keys = keys(matchdays).sort(function(a, b) {
    var d1 = new Date(matchdays[a]);
    var d2 = new Date(matchdays[b]);

    return d1 - d2;
});

// Iterate through the keys, finding the key associated with the next date after today
var today = new Date();
var nextLater = null;

for (var i = 0; i < keys.length; i++) {
    var date = new Date(matchdays[keys[i]]);

    if (date > today) {
        nextLater = keys[i];
        break;
    }
}

alert(nextLater);

Sorting adds some redundancy as a brute force search is going to be O(n) and a best-case sort is going to be O(n) as well.  So to brute force search, just:

// Function to get the keys
function keys(obj) {
    var keys = [];
    for (var key in obj) {
        keys.push(key);
    }
    return keys;
}

// Get the keys
var keys = keys(matchdays);

// Iterate through the keys, finding the key associated with the next date after today
var today = new Date();
var nextLater = null;
var min;

for (var i = 0; i < keys.length; i++) {
    var date = new Date(matchdays[keys[i]]);

    var diff = date - today;

    if (diff > 0 && (min == undefined || diff < min ) {
        min = diff
        nextLater = keys[i];
    }
}

alert(nextLater);


问:
Stopping reference variables changing the value of the original variable
I am assigning the value of a custom class to another variable. Updating the value of the new variable is affecting the value of the original variable. However, I need to stop the reference variable from updating the original variable.

Here's a basic representation of what's happening:

```<code>var originalVariable = CustomClass()

originalVariable.myProperty = originalValue

var referenceVariable = originalVariable

referenceVariable.myProperty = updatedValue

print("\(originalVariable.myProperty)") //this prints the ->updatedValue<- and not the ->originalValue<-
</code>```

I've tried wrapping the referenceVariable in a struct to make it a value type but it hasn't solved the problem.

I've found information regarding value and reference types but I haven't been able to find a solution.

My question in a nutshell: How do I stop an update to a reference variable from updating the original variable that it got its value assigned from?

Thanks in advance.

答:
The whole point of reference semantics (as used by classes) is that all variables point to the same (i.e., they reference the same) object in memory. If you don't want that behaviour, you should use value types (Struct, Enum, Array...) or create copies of your object.

If CustomClass implements the NSCopying protocol you can do:

```<code>var referenceVariable = originalVariable.copy()
</code>```

If it doesn't, you'll have to find some other way to copy it or implement the protocol yourself.

Wrapping the class in a struct will just make two different structs each containing a different reference to the same object.

Body:
I am assigning the value of a custom class to another variable. Updating the value of the new variable is affecting the value of the original variable. However, I need to stop the reference variable from updating the original variable.

Here's a basic representation of what's happening:

var originalVariable = CustomClass()

originalVariable.myProperty = originalValue

var referenceVariable = originalVariable

referenceVariable.myProperty = updatedValue

print("\(originalVariable.myProperty)") //this prints the ->updatedValue<- and not the ->originalValue<-

I've tried wrapping the referenceVariable in a struct to make it a value type but it hasn't solved the problem.

I've found information regarding value and reference types but I haven't been able to find a solution.

My question in a nutshell: How do I stop an update to a reference variable from updating the original variable that it got its value assigned from?

Thanks in advance.

Body:
The whole point of reference semantics (as used by classes) is that all variables point to the same (i.e., they reference the same) object in memory. If you don't want that behaviour, you should use value types (Struct, Enum, Array...) or create copies of your object.

If CustomClass implements the NSCopying protocol you can do:

var referenceVariable = originalVariable.copy()

If it doesn't, you'll have to find some other way to copy it or implement the protocol yourself.

Wrapping the class in a struct will just make two different structs each containing a different reference to the same object.


问:
How to get value from JSON Array
May I know how to get respond value from JSON in below code format? Currently I'm using this way, but it won't work for me

What I use to get JSON value:

```<code>NSError * err2 = nil;
NSArray* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                options:0
                                                  error:&err2];

NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
</code>```

The JSON value that I wanted to get:

```<code> [
          {
            "Status": 1,
            "NearuCode": "17060521957",
            "ParcelBox": "Thursday"
          },
          {
            "Status": 1,
            "NearuCode": "17060521957",
            "ParcelBox": "Thursday"
          }
        ]
</code>```

答:
I give you the solution which explains you the description of error as you get empty results.</p>

```<code>NSError * err2 = nil;
NSArray* json = [NSJSONSerialization JSONObjectWithData:responseData
                                            options:0
                                              error:&err2];
if (err2)
{
     NSLog(@"The reason for the error is - %@",[err2 description]);
}
</code>```

Title: How to get value from JSON Array

Body:
May I know how to get respond value from JSON in below code format? Currently I'm using this way, but it won't work for me

What I use to get JSON value:

NSError * err2 = nil;
NSArray* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                options:0
                                                  error:&err2];

NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];

The JSON value that I wanted to get:

 [
          {
            "Status": 1,
            "NearuCode": "17060521957",
            "ParcelBox": "Thursday"
          },
          {
            "Status": 1,
            "NearuCode": "17060521957",
            "ParcelBox": "Thursday"
          }
        ]

Body:
I give you the solution which explains you the description of error as you get empty results.

NSError * err2 = nil;
NSArray* json = [NSJSONSerialization JSONObjectWithData:responseData
                                            options:0
                                              error:&err2];
if (err2)
{
     NSLog(@"The reason for the error is - %@",[err2 description]);
}


问:
gradle - execution order issue
I have a project that looks like this.

```<code>root
    build.gradle
    settings.gradle
    project1
         build.gradle

    project2
         build.gradle

    project3
         build.gradle

    project4
         build.gradle
</code>```

settings.gradle looks like this.

```<code>include ':project1', ':project2', ':project3', ':project4'
</code>```

build.gradle (from root)

```<code>apply plugin: 'java'
apply plugin: 'eclipse'

repositories {
    mavenCentral()
}
dependencies {
    compile project(':project1')
    compile project(':project2')
    compile project(':project3')
    compile project(':project4')
}
</code>```

So basically, I want 'project1' to be built first before project2, 3, 4, because it needs to download our internal dependency(jar and some schema files) so that project2, 3 and 4 will be able to extract artifacts from the schema files(from project1).

But when I run it, i see standard output from project2 and 3 printed first before project1 runs.

Especially project2 contains many tasks(type: JavaExec) which run this type of arguments.

```<code>  main = 'org.apache.xmlbeans.impl.tool.SchemaCompiler'
  classpath "${BUILDROOT}/project1/${COMMON_DENEPDENCY_FILE}"
  args "-src", "${projectDir}/src/main/java", "-d", "build/generated", "-srconly", "${projectDir}/xml/schema/example1.xsd", "${projectDir}/xml/schema/example1.xsdconfig"
</code>```

One of the tasks looks like this. I have several tasks that look like this in project2. So project1 has to be fully built before project2 and project3 run.

build.gradle from project2

```<code>task xmlbeansExample2(dependsOn: xmlbeansExample1, type: JavaExec) {
  println "Example2 is running"
  main = 'org.apache.xmlbeans.impl.tool.SchemaCompiler'
  classpath "${BUILDROOT}/common/${COMMON_DENEPDENCY_FILE}"
  args "-src", "${projectDir}/src/main/java", "-d", "build/generated", "-srconly", "${projectDir}/xml/schema/example2.xsd", "${projectDir}/xml/schema/example2.xsdconfig"
  println "Example2 is done"
}
task handleSchema(dependsOn: ['xmlbeansExample1', 'xmlbeansExample2'])

build.dependsOn handleSchema, jar
</code>```

When I run 'gradle build' from the root or project2, I see the printout from project2 first.

Is there something wrong with my layout?

My team is migrating from Ant to Gradle, but gradle seems a little different from Ant execution. Maybe I am little misunderstood about the gradle.

答:
Well, for root project it's unnecessary to specify child modules as a dependencies.

If your modules are dependant from another one you should clearly defined this dependency.

```<code>// project2/build.gradle
dependencies {
    compile project(':project1')
}
</code>```

Title: gradle - execution order issue

Body:
I have a project that looks like this.

root
    build.gradle
    settings.gradle
    project1
         build.gradle

    project2
         build.gradle

    project3
         build.gradle

    project4
         build.gradle

settings.gradle looks like this.

include ':project1', ':project2', ':project3', ':project4'

build.gradle (from root)

apply plugin: 'java'
apply plugin: 'eclipse'

repositories {
    mavenCentral()
}
dependencies {
    compile project(':project1')
    compile project(':project2')
    compile project(':project3')
    compile project(':project4')
}

So basically, I want 'project1' to be built first before project2, 3, 4, because it needs to download our internal dependency(jar and some schema files) so that project2, 3 and 4 will be able to extract artifacts from the schema files(from project1).

But when I run it, i see standard output from project2 and 3 printed first before project1 runs.

Especially project2 contains many tasks(type: JavaExec) which run this type of arguments.

  main = 'org.apache.xmlbeans.impl.tool.SchemaCompiler'
  classpath "${BUILDROOT}/project1/${COMMON_DENEPDENCY_FILE}"
  args "-src", "${projectDir}/src/main/java", "-d", "build/generated", "-srconly", "${projectDir}/xml/schema/example1.xsd", "${projectDir}/xml/schema/example1.xsdconfig"

One of the tasks looks like this. I have several tasks that look like this in project2. So project1 has to be fully built before project2 and project3 run.

build.gradle from project2

task xmlbeansExample2(dependsOn: xmlbeansExample1, type: JavaExec) {
  println "Example2 is running"
  main = 'org.apache.xmlbeans.impl.tool.SchemaCompiler'
  classpath "${BUILDROOT}/common/${COMMON_DENEPDENCY_FILE}"
  args "-src", "${projectDir}/src/main/java", "-d", "build/generated", "-srconly", "${projectDir}/xml/schema/example2.xsd", "${projectDir}/xml/schema/example2.xsdconfig"
  println "Example2 is done"
}
task handleSchema(dependsOn: ['xmlbeansExample1', 'xmlbeansExample2'])

build.dependsOn handleSchema, jar

When I run 'gradle build' from the root or project2, I see the printout from project2 first.

Is there something wrong with my layout?

My team is migrating from Ant to Gradle, but gradle seems a little different from Ant execution. Maybe I am little misunderstood about the gradle.

Body:
Well, for root project it's unnecessary to specify child modules as a dependencies.

If your modules are dependant from another one you should clearly defined this dependency.

// project2/build.gradle
dependencies {
    compile project(':project1')
}


问:
Exact Search Term in Elastic Search in Kibana Dev Tools (with ES 5.x)
I have setup Elastic Search 5.x & Kibana on my local development environment, and have setup the indices I want to have results return exact search term (so only return results where that exact search term/string is found.

How can I adjust this to perform an exact search so "facebook advice" would be valid, but "advice facebook" would not be found

My existing Kibana query is as follows :

```<code>{
  "query": {
     "bool": {
        "should": [
         {
           "match": {
           "text": "facebook advice"
         }
       },
      {
      "match": {
        "profile": "facebook advice"
      }
    }
  ],
  "minimum_should_match": 1,
  "filter": {
    "term": {
      "accountid": "15"
    }
   }
  }
 }
}
</code>```

答:
You would need to form your query within double quotes for exact match in Kibana.

E.g. "facebook advice"

Kibana would of course escape the quotes correctly under the hood.

Body:
I have setup Elastic Search 5.x & Kibana on my local development environment, and have setup the indices I want to have results return exact search term (so only return results where that exact search term/string is found.

How can I adjust this to perform an exact search so "facebook advice" would be valid, but "advice facebook" would not be found

My existing Kibana query is as follows :

{
  "query": {
     "bool": {
        "should": [
         {
           "match": {
           "text": "facebook advice"
         }
       },
      {
      "match": {
        "profile": "facebook advice"
      }
    }
  ],
  "minimum_should_match": 1,
  "filter": {
    "term": {
      "accountid": "15"
    }
   }
  }
 }
}


问:
list out paired bluetooth devices in listview created in layout
I want to list out all the paired devices in a list that i created in layouts.. what wrong in this code? i just created this function to display all the bonded devices</p>

```<code>void tooth_scan() {
    ListView listView = (ListView) findViewById(R.id.pairList);
    Set<BluetoothDevice> pairedDevices = bAdapter.getBondedDevices();
    devicesPaired = new String[pairedDevices.size()];
    int count = 0;
    if (pairedDevices.size() > 0) {
        for (BluetoothDevice device : pairedDevices) {
            devicesPaired[count] = device.getName();
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,
                devicesPaired);
        listView.setAdapter(adapter);
    }
}
</code>```

答:
```<code>public void showPairedDevices()
    {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            ArrayList<String> bluetoothDevices = new ArrayList<String>();
            for (BluetoothDevice device : pairedDevices) {

                String deviceName = device.getName(); // Get BT name
                String deviceAddress = device.getAddress(); // Get MAC
                ListView listView = (ListView)findViewById(R.id.paired_list);

                bluetoothDevices.add(deviceName);

                final ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,bluetoothDevices);
                listView.setAdapter(adapter);

            }

        }
    }
</code>```

Body:
I want to list out all the paired devices in a list that i created in layouts.. what wrong in this code? i just created this function to display all the bonded devices

void tooth_scan() {
    ListView listView = (ListView) findViewById(R.id.pairList);
    Set<BluetoothDevice> pairedDevices = bAdapter.getBondedDevices();
    devicesPaired = new String[pairedDevices.size()];
    int count = 0;
    if (pairedDevices.size() > 0) {
        for (BluetoothDevice device : pairedDevices) {
            devicesPaired[count] = device.getName();
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,
                devicesPaired);
        listView.setAdapter(adapter);
    }
}


问:
How to delete a data in a many to many relationship table
For example, i have 3 table which is supplier, supplier_product, and product.
1 supplier has many product and 1 product may supplied by many supplier, data stored in supplier_product table.

```<code>supplier1 - product2
supplier1 - product 1
</code>```

i want to delete supplier 1 with product 1, how can i do it?

Table:

Supplier | supplier_id, name.....

Supplier_Product | supplier_id, product_id........

Product | product_id, name.....

答:
You can use Eloquents detach() or sync() methods which explanation you can find here

Below are some examples

```<code>// detaching
$supplier = App\Supplier::find(1);
$supplier->products()->detach([1]);

// syncing
$supplier = App\Supplier::find(1);
$supplier->products()->sync([2]);
</code>```

Body:
For example, i have 3 table which is supplier, supplier_product, and product.
1 supplier has many product and 1 product may supplied by many supplier, data stored in supplier_product table.

supplier1 - product2
supplier1 - product 1

i want to delete supplier 1 with product 1, how can i do it?

Table:

Supplier | supplier_id, name.....

Supplier_Product | supplier_id, product_id........

Product | product_id, name.....

Body:
You can use Eloquents detach() or sync() methods which explanation you can find here

Below are some examples

// detaching
$supplier = App\Supplier::find(1);
$supplier->products()->detach([1]);

// syncing
$supplier = App\Supplier::find(1);
$supplier->products()->sync([2]);


问:
Split Java String by New Line
I'm trying to split text in a JTextArea using a regex to split the String by \n However, this does not work and I also tried by \r\n|\r|n and many other combination of regexes.
Code:

```<code>public void insertUpdate(DocumentEvent e) {
    String split[], docStr = null;
    Document textAreaDoc = (Document)e.getDocument();

    try {
        docStr = textAreaDoc.getText(textAreaDoc.getStartPosition().getOffset(), textAreaDoc.getEndPosition().getOffset());
    } catch (BadLocationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    split = docStr.split("\\n");
}
</code>```

答:
As an alternative to the previous answers, guava's Splitter API can be used if other operations are to be applied to the resulting lines, like trimming lines or filtering empty lines :

```<code>import com.google.common.base.Splitter;

Iterable<String> split = Splitter.onPattern("\r?\n").trimResults().omitEmptyStrings().split(docStr);
</code>```

Note that the result is an Iterable and not an array.

Title: Split Java String by New Line

Body:
I'm trying to split text in a JTextArea using a regex to split the String by \n However, this does not work and I also tried by \r\n|\r|n and many other combination of regexes.
Code:

public void insertUpdate(DocumentEvent e) {
    String split[], docStr = null;
    Document textAreaDoc = (Document)e.getDocument();

    try {
        docStr = textAreaDoc.getText(textAreaDoc.getStartPosition().getOffset(), textAreaDoc.getEndPosition().getOffset());
    } catch (BadLocationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    split = docStr.split("\\n");
}

Body:
As an alternative to the previous answers, guava's Splitter API can be used if other operations are to be applied to the resulting lines, like trimming lines or filtering empty lines :

import com.google.common.base.Splitter;

Iterable<String> split = Splitter.onPattern("\r?\n").trimResults().omitEmptyStrings().split(docStr);

Note that the result is an Iterable and not an array.


问:
What would be the fastest way to concatenate three files in C#?
I need to concatenate 3 files using C#. A header file, content, and a footer file, but I want to do this as cool as it can be done.

Cool = really small code or really fast (non-assembly code).

答:
```<code>void CopyStream(Stream destination, Stream source) {
   int count;
   byte[] buffer = new byte[BUFFER_SIZE];
   while( (count = source.Read(buffer, 0, buffer.Length)) > 0)
       destination.Write(buffer, 0, count);
}

CopyStream(outputFileStream, fileStream1);
CopyStream(outputFileStream, fileStream2);
CopyStream(outputFileStream, fileStream3);
</code>```

OwnerDisplayName: Bobby Bruckovnic

LastEditorDisplayName: bdukes

OwnerDisplayName: Mehrdad Afshari


问:
How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?
It's a sad fact of life on Scala that if you instantiate a List[Int], you can verify that your instance is a List, and you can verify that any individual element of it is an Int, but not that it is a List[Int], as can be easily verified:

```<code>scala> List(1,2,3) match {
     | case l : List[String] => println("A list of strings?!")
     | case _ => println("Ok")
     | }
warning: there were unchecked warnings; re-run with -unchecked for details
A list of strings?!
</code>```

The -unchecked option puts the blame squarely on type erasure:

```<code>scala>  List(1,2,3) match {
     |  case l : List[String] => println("A list of strings?!")
     |  case _ => println("Ok")
     |  }
<console>:6: warning: non variable type-argument String in type pattern is unchecked since it is eliminated by erasure
        case l : List[String] => println("A list of strings?!")
                 ^
A list of strings?!
</code>```

Why is that, and how do I get around it?

答:
I found a slightly better workaround for this limitation of the otherwise awesome language.

In Scala, the issue of type erasure does not occur with arrays. I think it is easier to demonstrate this with an example.

Let us say we have a list of (Int, String), then the following gives a type erasure warning

```<code>x match {
  case l:List[(Int, String)] =>
  ...
}
</code>```

To work around this, first create a case class:

```<code>case class IntString(i:Int, s:String)
</code>```

then in the pattern matching do something like:

```<code>x match {
  case a:Array[IntString] =>
  ...
}
</code>```

which seems to work perfectly.

This will require minor changes in your code to work with arrays instead of lists, but should not be a major problem.

Note that using case a:Array[(Int, String)] will still give a type erasure warning, so it is necessary to use a new container class (in this example, IntString).

Body:
It's a sad fact of life on Scala that if you instantiate a List[Int], you can verify that your instance is a List, and you can verify that any individual element of it is an Int, but not that it is a List[Int], as can be easily verified:

scala> List(1,2,3) match {
     | case l : List[String] => println("A list of strings?!")
     | case _ => println("Ok")
     | }
warning: there were unchecked warnings; re-run with -unchecked for details
A list of strings?!

The -unchecked option puts the blame squarely on type erasure:

scala>  List(1,2,3) match {
     |  case l : List[String] => println("A list of strings?!")
     |  case _ => println("Ok")
     |  }
<console>:6: warning: non variable type-argument String in type pattern is unchecked since it is eliminated by erasure
        case l : List[String] => println("A list of strings?!")
                 ^
A list of strings?!

Why is that, and how do I get around it?

Body:
I found a slightly better workaround for this limitation of the otherwise awesome language.

In Scala, the issue of type erasure does not occur with arrays. I think it is easier to demonstrate this with an example.

Let us say we have a list of (Int, String), then the following gives a type erasure warning

x match {
  case l:List[(Int, String)] =>
  ...
}

To work around this, first create a case class:

case class IntString(i:Int, s:String)

then in the pattern matching do something like:

x match {
  case a:Array[IntString] =>
  ...
}

which seems to work perfectly.

This will require minor changes in your code to work with arrays instead of lists, but should not be a major problem.

Note that using case a:Array[(Int, String)] will still give a type erasure warning, so it is necessary to use a new container class (in this example, IntString).


问:
multiple clicks on custom tableViewCell
I have a custom tableView cell, When I click on the cell the height of the cell increases (the cell expands):

```<code> var selectedIndex:IndexPath?
    var isExpanded = false

    func didExpandCell(){

        self.isExpanded = !isExpanded
        self.TableView.reloadRows(at: [selectedIndex!], with: .automatic)
    }

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       self.selectedIndex = indexPath
        self.didExpandCell()
    }
</code>```

I would like to click the cell a second time and segue to another view controller; is this possible?

```<code>self.performSegue(withIdentifier: "details", sender: tableView)
</code>```

答: In the func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) method you have to check whether the cell is expanded or not. If it is expanded try calling self.performSegue(withIdentifier: "details", sender: tableView). If it is not then implement the code to expand the cell.

Title: multiple clicks on custom tableViewCell

Body:
I have a custom tableView cell, When I click on the cell the height of the cell increases (the cell expands):

 var selectedIndex:IndexPath?
    var isExpanded = false

    func didExpandCell(){

        self.isExpanded = !isExpanded
        self.TableView.reloadRows(at: [selectedIndex!], with: .automatic)
    }

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       self.selectedIndex = indexPath
        self.didExpandCell()
    }

I would like to click the cell a second time and segue to another view controller; is this possible?

self.performSegue(withIdentifier: "details", sender: tableView)


问:
Extract field list from reStructuredText
Say I have the following reST input:

```<code>Some text ...

:foo: bar

Some text ...
</code>```

What I would like to end up with is a dict like this:

```<code>{"foo": "bar"}
</code>```

I tried to use this:

```<code>tree = docutils.core.publish_parts(text)
</code>```

It does parse the field list, but I end up with some pseudo XML in tree["whole"]?:

```<code><document source="<string>">
    <docinfo>
        <field>
            <field_name>
                foo
            <field_body>
                <paragraph>
                    bar
</code>```

Since the tree dict does not contain any other useful information and that is just a string, I am not sure how to parse the field list out of the reST document. How would I do that?

答:
Here's my ElementTree implementation:

```<code>from docutils.core import publish_doctree
from xml.etree.ElementTree import fromstring

source = """Some text ...

:foo: bar

Some text ...
"""

def gen_fields(source):
    dom = publish_doctree(source).asdom()
    tree = fromstring(dom.toxml())

    for field in tree.iter(tag='field'):
        name = next(field.iter(tag='field_name'))
        body = next(field.iter(tag='field_body'))
        yield {name.text: ''.join(body.itertext())}
</code>```

Usage

```<code>>>> next(gen_fields(source))
{'foo': 'bar'}
</code>```

Body:
Say I have the following reST input:

Some text ...

:foo: bar

Some text ...

What I would like to end up with is a dict like this:

{"foo": "bar"}

I tried to use this:

tree = docutils.core.publish_parts(text)

It does parse the field list, but I end up with some pseudo XML in tree["whole"]?:

<document source="<string>">
    <docinfo>
        <field>
            <field_name>
                foo
            <field_body>
                <paragraph>
                    bar

Since the tree dict does not contain any other useful information and that is just a string, I am not sure how to parse the field list out of the reST document. How would I do that?

Body:
Here's my ElementTree implementation:

from docutils.core import publish_doctree
from xml.etree.ElementTree import fromstring

source = """Some text ...

:foo: bar

Some text ...
"""

def gen_fields(source):
    dom = publish_doctree(source).asdom()
    tree = fromstring(dom.toxml())

    for field in tree.iter(tag='field'):
        name = next(field.iter(tag='field_name'))
        body = next(field.iter(tag='field_body'))
        yield {name.text: ''.join(body.itertext())}

Usage

>>> next(gen_fields(source))
{'foo': 'bar'}


问:
Keep columns when using do
Code

Suppose I have the following code (I know, instead of the second do, I could use a simple mutate in this case (and skip the rowwise()), but that is not the point, as in my real code the second do is a bit more complicated and calculates a model):

```<code>library(dplyr)
set.seed(1)
d <- data_frame(n = c(5, 1, 3))
e <- d %>% group_by(n) %>%
    do(data_frame(y = rnorm(.$n), dat = list(data.frame(a = 1))))
e %>% rowwise() %>% do(data_frame(sum = .$y + .$n))

# Source: local data frame [9 x 1]
# Groups: <by row>

# # A tibble: 9 x 1
#         sum
# *     <dbl>
# 1 0.3735462
# 2 3.1836433
# 3 2.1643714
# 4 4.5952808
# 5 5.3295078
# 6 4.1795316
# 7 5.4874291
# 8 5.7383247
# 9 5.5757814
</code>```

Problem

As you can see, the result contains only the column sum.

Question

Is there a way to keep the original columns from e without needing to specify them explicitly (like in e %>% do(data_frame(n = .$n, y = .$y, dat = .$dat, sum = .$y + .$n)) in dplyr or do I have to use purrrlyr::by_row? (not that I do not like purrrlyr*, I was just wondering whether there is a straight forward dplyr way of doing it which I may have overloooked):

```<code>e %>% purrrlyr::by_row(function(x) x$y + x$n, .collate = "cols", .to = "sum")
</code>```

*) Well, there is in fact a catch with purrrlyr::by_row:

```<code>e %>% purrrlyr::by_row(function(x) data_frame(sum = x$y + x$n, diff = x$y - x$n),
                       .collate ="cols")
</code>```

Will produce columns sum1 and diff1 which I would need to rename again to get sum and diff, which adds another line of code.

答:
I almost never use do, but rather do a combination of nest, mutate and map.

It's a bit hard to tell how that would look in your case, as your example doesn't seem to fully specify your needs.

In the simplest case, you could specify the variables that you do need (if they would be lists of S3 objects, for example):

```<code>mutate(e, sum = map2_dbl(y, n, `+`))
</code>```

Or, you could nest the required data then map the whole data. E.g.:

```<code>f <- e
f$r <- 1:nrow(e) # i.e. add some other variable, not necessarily row indices

f %>%
  ungroup() %>%                               # e was still grouped
  nest(n:dat) %>%                               # specify what you variables you need
  mutate(sum = map_dbl(data, ~.$y + .$n)) %>% # map to data, use the same formula as in do
  unnest()                                    # unnest to get original columns back
</code>```

Both leave the original columns untouched.

For a modeling example, e.g.:

```<code>mtcars %>%
  group_by(cyl) %>%
  nest() %>%
  mutate(model = map(data, ~lm(qsec ~ hp, .)),
         coef  = map_dbl(model, ~coef(.)[2])) %>%
  unnest(data)
</code>```

This will give you all your original data, but with added regression coefficents per group. Before unnesting, the whole models are in your data.frame as a list column.

Title: Keep columns when using do

Body:
Code

Suppose I have the following code (I know, instead of the second do, I could use a simple mutate in this case (and skip the rowwise()), but that is not the point, as in my real code the second do is a bit more complicated and calculates a model):

library(dplyr)
set.seed(1)
d <- data_frame(n = c(5, 1, 3))
e <- d %>% group_by(n) %>%
    do(data_frame(y = rnorm(.$n), dat = list(data.frame(a = 1))))
e %>% rowwise() %>% do(data_frame(sum = .$y + .$n))

# Source: local data frame [9 x 1]
# Groups: <by row>

# # A tibble: 9 x 1
#         sum
# *     <dbl>
# 1 0.3735462
# 2 3.1836433
# 3 2.1643714
# 4 4.5952808
# 5 5.3295078
# 6 4.1795316
# 7 5.4874291
# 8 5.7383247
# 9 5.5757814

Problem

As you can see, the result contains only the column sum.

Question

Is there a way to keep the original columns from e without needing to specify them explicitly (like in e %>% do(data_frame(n = .$n, y = .$y, dat = .$dat, sum = .$y + .$n)) in dplyr or do I have to use purrrlyr::by_row? (not that I do not like purrrlyr*, I was just wondering whether there is a straight forward dplyr way of doing it which I may have overloooked):

e %>% purrrlyr::by_row(function(x) x$y + x$n, .collate = "cols", .to = "sum")

*) Well, there is in fact a catch with purrrlyr::by_row:

e %>% purrrlyr::by_row(function(x) data_frame(sum = x$y + x$n, diff = x$y - x$n),
                       .collate ="cols")

Will produce columns sum1 and diff1 which I would need to rename again to get sum and diff, which adds another line of code.

Body:
I almost never use do, but rather do a combination of nest, mutate and map.

It's a bit hard to tell how that would look in your case, as your example doesn't seem to fully specify your needs.

In the simplest case, you could specify the variables that you do need (if they would be lists of S3 objects, for example):

mutate(e, sum = map2_dbl(y, n, `+`))

Or, you could nest the required data then map the whole data. E.g.:

f <- e
f$r <- 1:nrow(e) # i.e. add some other variable, not necessarily row indices

f %>%
  ungroup() %>%                               # e was still grouped
  nest(n:dat) %>%                               # specify what you variables you need
  mutate(sum = map_dbl(data, ~.$y + .$n)) %>% # map to data, use the same formula as in do
  unnest()                                    # unnest to get original columns back

Both leave the original columns untouched.

For a modeling example, e.g.:

mtcars %>%
  group_by(cyl) %>%
  nest() %>%
  mutate(model = map(data, ~lm(qsec ~ hp, .)),
         coef  = map_dbl(model, ~coef(.)[2])) %>%
  unnest(data)

This will give you all your original data, but with added regression coefficents per group. Before unnesting, the whole models are in your data.frame as a list column.


问:
AutoHotKey: catching & manipulating windows without human interaction
Something sounding very basic has taken a lot of time: how can an AutoHotKey script be programmed to wait for a specific window and then accept it, Send {enter}, to close it down? In this case it’s an annoying settings confirmation dialogue which comes up every time certain file types are opened for a programme. A minor complication is also that the windows title changes every time, while its ahn_class is shared with the mother programme – things which i’ve tried to tackle by catching the window by its pixel size instead:

```<code>#IfWinActive ahk_class SALFRAME
    ~LButton::
    WinGetActiveStats, , width, , ,
    if (width = "681") {
        Send {enter}
    }
return
</code>```

This works, but forces to click somewhere on the dialogue when it comes up, which is faster then before, but still not really automated. I also tried with WinWaitActive among other things, but it doesn’t seem to catch the window (at some point some of the scripts i’ve tried to write actually killed the window when the script was executed, but only once, without touching subsequent windows coming after the script first ran). What is the correct way to wait for and terminate certain windows without human input with AutoHotKey?

答:
```<code>#Persistent
SetTimer, Send_Enter_to_specific_window, 50
return

    Send_Enter_to_specific_window:
IfWinActive ahk_class SALFRAME
{
    WinGetPos,,, width,, A
    if (width = "681")
         Send {enter}
}
return
</code>```

https://autohotkey.com/docs/commands/SetTimer.htm#Examples

Body:
Something sounding very basic has taken a lot of time: how can an AutoHotKey script be programmed to wait for a specific window and then accept it, Send {enter}, to close it down? In this case it’s an annoying settings confirmation dialogue which comes up every time certain file types are opened for a programme. A minor complication is also that the windows title changes every time, while its ahn_class is shared with the mother programme – things which i’ve tried to tackle by catching the window by its pixel size instead:

#IfWinActive ahk_class SALFRAME
    ~LButton::
    WinGetActiveStats, , width, , ,
    if (width = "681") {
        Send {enter}
    }
return

This works, but forces to click somewhere on the dialogue when it comes up, which is faster then before, but still not really automated. I also tried with WinWaitActive among other things, but it doesn’t seem to catch the window (at some point some of the scripts i’ve tried to write actually killed the window when the script was executed, but only once, without touching subsequent windows coming after the script first ran). What is the correct way to wait for and terminate certain windows without human input with AutoHotKey?

Body:
#Persistent
SetTimer, Send_Enter_to_specific_window, 50
return

    Send_Enter_to_specific_window:
IfWinActive ahk_class SALFRAME
{
    WinGetPos,,, width,, A
    if (width = "681")
         Send {enter}
}
return

https://autohotkey.com/docs/commands/SetTimer.htm#Examples


问:
teradata covalent td-menu-header
I had been looking thru all the documentation available at https://teradata.github.io/covalent/ but I didn't found any documentation about the "td-menu-header" found in the Teradata Covalent Quickstart.

This css framework seems interesting but the lack of documentation -it would be great a "API" documentation or developper guide- is putting us in a difficult choice.

答:
I have used it this way. The code sample is present in Teradata Quickstart Project.</p>

```<code><button md-icon-button mdTooltip="Profile" [mdMenuTriggerFor]="profileMenu"><md-icon class="md-24">person</md-icon></button>
    <md-menu #profileMenu="mdMenu">
        <td-menu>
            <div td-menu-header class="md-subhead">Profile</div>
            <div flex>
                <md-list dense>
                    <!--<h3 md-subheader>Metadata</h3>-->
                    <md-list-item>
                        <md-icon md-list-avatar>location_on</md-icon>
                        <h2 md-line *ngIf='client.address!==""'><span class="text-wrap">{{client.address}}</span></h2>
                        <h2 md-line *ngIf='client.address===""'>--</h2>
                        <p md-line>Address</p>
                    </md-list-item>
                    <md-divider md-inset></md-divider>
                    <md-list-item>
                        <md-icon md-list-avatar>location_city</md-icon>
                        <h2 md-line>{{client.city}}, {{client.state}}-{{client.zip}}</h2>
                        <p md-line>City,State-Zip</p>
                    </md-list-item>
                    <md-divider md-inset></md-divider>
                    <md-list-item>
                        <md-icon md-list-avatar>flag</md-icon>
                        <h2 md-line>{{client.country}}</h2>
                        <p md-line>Country</p>
                    </md-list-item>
                    <md-list-item>
                        <md-icon md-list-avatar>call</md-icon>
                        <h2 md-line>{{client.phone}}</h2>
                        <p md-line>Primary Phone</p>
                    </md-list-item>
                    <md-divider md-inset></md-divider>
                    <md-list-item *ngIf='client.phone2!==""'>
                        <md-icon md-list-avatar>call</md-icon>
                        <h2 md-line>{{client.phone2}}</h2>
                        <p md-line>Secondary Phone</p>
                    </md-list-item>
                    <md-divider md-inset *ngIf='client.phone2!==""'></md-divider>
                    <md-list-item>
                        <md-icon md-list-avatar>email</md-icon>
                        <h1 md-line><span class="text-wrap">{{client.email}}</span></h1>
                        <!--<h1 md-line></h1>-->
                        <p md-line>Primary Email {{client.email2}}
                        </p>
                    </md-list-item>
                    <md-divider md-inset></md-divider>
                    <md-list-item *ngIf='client.email2!==""'>
                        <md-icon md-list-avatar>email</md-icon>
                        <h1 md-line><span class="text-wrap">{{client.email2}}</span></h1>
                        <!--<h1 md-line></h1>-->
                        <p md-line>Secondary Email
                        </p>
                    </md-list-item>
                    <md-divider md-inset *ngIf='client.email2!==""'></md-divider>
                    <md-list-item>
                        <md-icon md-list-avatar>print</md-icon>
                        <h2 md-line *ngIf='client.fax!==""'>{{client.fax}}</h2>
                        <h2 md-line *ngIf='client.fax===""'>--</h2>
                        <p md-line>Fax</p>
                    </md-list-item>
                </md-list>
            </div>
        </td-menu>
    </md-menu>
</code>```

Title: teradata covalent td-menu-header

Body:
I have used it this way. The code sample is present in Teradata Quickstart Project.

<button md-icon-button mdTooltip="Profile" [mdMenuTriggerFor]="profileMenu"><md-icon class="md-24">person</md-icon></button>
    <md-menu #profileMenu="mdMenu">
        <td-menu>
            <div td-menu-header class="md-subhead">Profile</div>
            <div flex>
                <md-list dense>
                    <!--<h3 md-subheader>Metadata</h3>-->
                    <md-list-item>
                        <md-icon md-list-avatar>location_on</md-icon>
                        <h2 md-line *ngIf='client.address!==""'><span class="text-wrap">{{client.address}}</span></h2>
                        <h2 md-line *ngIf='client.address===""'>--</h2>
                        <p md-line>Address</p>
                    </md-list-item>
                    <md-divider md-inset></md-divider>
                    <md-list-item>
                        <md-icon md-list-avatar>location_city</md-icon>
                        <h2 md-line>{{client.city}}, {{client.state}}-{{client.zip}}</h2>
                        <p md-line>City,State-Zip</p>
                    </md-list-item>
                    <md-divider md-inset></md-divider>
                    <md-list-item>
                        <md-icon md-list-avatar>flag</md-icon>
                        <h2 md-line>{{client.country}}</h2>
                        <p md-line>Country</p>
                    </md-list-item>
                    <md-list-item>
                        <md-icon md-list-avatar>call</md-icon>
                        <h2 md-line>{{client.phone}}</h2>
                        <p md-line>Primary Phone</p>
                    </md-list-item>
                    <md-divider md-inset></md-divider>
                    <md-list-item *ngIf='client.phone2!==""'>
                        <md-icon md-list-avatar>call</md-icon>
                        <h2 md-line>{{client.phone2}}</h2>
                        <p md-line>Secondary Phone</p>
                    </md-list-item>
                    <md-divider md-inset *ngIf='client.phone2!==""'></md-divider>
                    <md-list-item>
                        <md-icon md-list-avatar>email</md-icon>
                        <h1 md-line><span class="text-wrap">{{client.email}}</span></h1>
                        <!--<h1 md-line></h1>-->
                        <p md-line>Primary Email {{client.email2}}
                        </p>
                    </md-list-item>
                    <md-divider md-inset></md-divider>
                    <md-list-item *ngIf='client.email2!==""'>
                        <md-icon md-list-avatar>email</md-icon>
                        <h1 md-line><span class="text-wrap">{{client.email2}}</span></h1>
                        <!--<h1 md-line></h1>-->
                        <p md-line>Secondary Email
                        </p>
                    </md-list-item>
                    <md-divider md-inset *ngIf='client.email2!==""'></md-divider>
                    <md-list-item>
                        <md-icon md-list-avatar>print</md-icon>
                        <h2 md-line *ngIf='client.fax!==""'>{{client.fax}}</h2>
                        <h2 md-line *ngIf='client.fax===""'>--</h2>
                        <p md-line>Fax</p>
                    </md-list-item>
                </md-list>
            </div>
        </td-menu>
    </md-menu>


问:
Dsum with Null Value
I am having abit of a situation and hope you can point me at the right direction.

1st DSUM (Text2):

=DSum("[quantity_ya7]","Stock","[part_number]= '" & [part_number] & "'")

2nd DSUM (Text2): (This can be Null at times as there are no withdrawals or records)

=DSum("[amt_ya7]","Withdrawal","[part_number]= '" & [part_number] & "' ")

After setting the 2 DSUM above, I will carry the subtract out.

=Text1-Text2

If there are values for to calculate for 2nd DSUM, the result will display in order. Else, it will be empty. (No values displayed)

How do I calculate as -0 (deduct 0) so I can get the right value displayed?

Thank you, much appreciated.

答:
You can use the Nz function to return zero, a zero-length string ("
  "), or another specified value when a Variant is Null. For example,
  you can use this function to convert a Null value to another value and
  prevent it from propagating through an expression.

  https://support.office.com/en-gb/article/Nz-Function-8ef85549-cc9c-438b-860a-7fd9f4c69b6c

In  your case you want the DSUM to return 0 rather than Null when there's no value so you can use it in a calculation.

=NZ(DSum("[amt_ya7]","Withdrawal","[part_number]= '" & [part_number] & "' "),0)

Title: Dsum with Null Value


问:
how to use psliwa/image-optimizer?
Has someone use this php image optimizer (psliwa/image-optimizer) before? What do I need to use this library? Do I need to be able to access the SSH command prompt ? How to install optipng, pngquant, jpegoptim?

I have so many questions. Its documentation is not clear at all.

It uses optipng, pngquant, jpegoptim and few more libraries, so before use it you should install proper libraries on your server.

Help appreciated !

答: optipng, pngquant and jpegoptim can be installed via apt-get install command.

Title: how to use psliwa/image-optimizer?


问:
What is the most elegant way to insert objects between array elements?
I'm sure there are many ways to achieve that but I'm looking for something "elegant".

```<code>a = [
  'a',
  'b',
  'c'
];

magicArrayJoin(a, {value: 255} ); // insert the same object between each item

result ==  [
  'a',
  {value: 255},
  'b',
  {value: 255}
  'c'
];
</code>```

All proposals are welcome. :)

答:
You can achieve this using reduce (it is also immutable).

const insertBetween = (insertion, array) =>
    array.reduce(
        (newArray, member, i, array) =>
            i < array.length - 1
                ? newArray.concat(member, insertion)
                : newArray.concat(member),
        []
    );

const result = insertBetween('and', [1, 2, 3]);

console.log(result);

// outputs;
// [
//   1,
//   'and',
//   2,
//   'and',
//   3
// ]```
</div>
</div>
</p>

<p>Or in older JS syntax;</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function insertBetween(insertion, array) {
    const indexOfLastItem = array.length - 1;
    return array.reduce(withInsertion, []);

    function withInsertion(newArray, item, index, array) {
        return index < indexOfLastItem
            ? newArray.concat(item, insertion)
            : newArray.concat(item);
    }
}

const result = insertBetween('and', [1, 2, 3]);

console.log(result);

// outputs;
// [
//   1,
//   'and',
//   2,
//   'and',
//   3
// ]</code>```

Body:
I'm sure there are many ways to achieve that but I'm looking for something "elegant".

a = [
  'a',
  'b',
  'c'
];

magicArrayJoin(a, {value: 255} ); // insert the same object between each item

result ==  [
  'a',
  {value: 255},
  'b',
  {value: 255}
  'c'
];

All proposals are welcome. :)

Body:
You can achieve this using reduce (it is also immutable).

const insertBetween = (insertion, array) =>
    array.reduce(
        (newArray, member, i, array) =>
            i < array.length - 1
                ? newArray.concat(member, insertion)
                : newArray.concat(member),
        []
    );

const result = insertBetween('and', [1, 2, 3]);

console.log(result);

// outputs;
// [
//   1,
//   'and',
//   2,
//   'and',
//   3
// ]

Or in older JS syntax;

function insertBetween(insertion, array) {
    const indexOfLastItem = array.length - 1;
    return array.reduce(withInsertion, []);

    function withInsertion(newArray, item, index, array) {
        return index < indexOfLastItem
            ? newArray.concat(item, insertion)
            : newArray.concat(item);
    }
}

const result = insertBetween('and', [1, 2, 3]);

console.log(result);

// outputs;
// [
//   1,
//   'and',
//   2,
//   'and',
//   3
// ]


问:
string in xpath
I have a string and I want to use  it as a selector in xpath to select a node with name as value of the string.

```<code>declare variable $get_count := <count><comedy>1</comedy></count>;
(: $string = "comedy" :)
 let $value =  $get_count/$string (: but this doesn't return anything)
</code>```

How shall i do it?

答:
```<code>let $value =  $get_count/$string (: but this doesn't return anything)
</code>```

Use:

```<code>declare variable $get_count := <count><comedy>1</comedy></count>;
declare variable $string := "comedy";

 let $value :=  $get_count/*[name()=$string]
  return
    $value
</code>```

When this is applied on any XML document (not used), the wanted, correct result is produced:

```<code><comedy>1</comedy>
</code>```

Title: string in xpath

Body:
I have a string and I want to use  it as a selector in xpath to select a node with name as value of the string.

declare variable $get_count := <count><comedy>1</comedy></count>;
(: $string = "comedy" :)
 let $value =  $get_count/$string (: but this doesn't return anything)

How shall i do it?

Body:
let $value =  $get_count/$string (: but this doesn't return anything)

Use:

declare variable $get_count := <count><comedy>1</comedy></count>;
declare variable $string := "comedy";

 let $value :=  $get_count/*[name()=$string]
  return
    $value

When this is applied on any XML document (not used), the wanted, correct result is produced:

<comedy>1</comedy>


问:
Attaching a property to a javsacript function - Where does the property gets linked?
Please take a look at this following nsnippet of simple code:-

```<code>function Fis(){
}

Fis.num =20;//no errors
console.log(Fis.num);//prints  20
</code>```

Now, I know that the Fis function is implicitly(from the very beginning) linked to  an object through "Fis.prototype" link.

In the code Fis.num = 20 is getting executed without any errors. Where is this num property getting linked ?

答:
In JavaScript, every function is an object:

var fn = function () {};
fn.foo = 'bar'; // add property to object
for (var index in fn) {
  // read properties from object
  if (fn.hasOwnProperty(index)) {
    console.log(fn[index]);
  }
}```
</div>
</div>
</p>

<p>In addition to that, every function object has a <code>prototype</code> property, which is an object itself. When you call a function the normal way, this <code>prototype</code> property has no effect. But when you call the function using <code>new</code>, JS creates a new object, whose prototype is the function's <code>prototype</code> property. Then it calls the function with the newly created object and returns it:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var Func = function (baz) {
  console.log(this.foo + baz); // "barabc"
}

Func.prototype.foo = "bar";

var object = new Func("abc");</code>```

In this case, the function is also called the constructor of a class, an the new object is called an instance of this class.

Read more about the prototype chain on MDN.

Body:
Please take a look at this following nsnippet of simple code:-

function Fis(){
}

Fis.num =20;//no errors
console.log(Fis.num);//prints  20

Now, I know that the Fis function is implicitly(from the very beginning) linked to  an object through "Fis.prototype" link.

In the code Fis.num = 20 is getting executed without any errors. Where is this num property getting linked ?

Body:
In JavaScript, every function is an object:

var fn = function () {};
fn.foo = 'bar'; // add property to object
for (var index in fn) {
  // read properties from object
  if (fn.hasOwnProperty(index)) {
    console.log(fn[index]);
  }
}

In addition to that, every function object has a prototype property, which is an object itself. When you call a function the normal way, this prototype property has no effect. But when you call the function using new, JS creates a new object, whose prototype is the function's prototype property. Then it calls the function with the newly created object and returns it:

var Func = function (baz) {
  console.log(this.foo + baz); // "barabc"
}

Func.prototype.foo = "bar";

var object = new Func("abc");

In this case, the function is also called the constructor of a class, an the new object is called an instance of this class.

Read more about the prototype chain on MDN.


问:
Laravel display image from path which is in database
So use is uploading a logo and it's path is stored in a database like this:

C:\xampp\htdocs\laravel\public\logo\1496912432.jpg

I am displaying the image like this:

```<code><img class="images" id="image" src="{{$business->image}}" />
</code>```

However I get this error:

```<code>Not allowed to load local resource: file:///C:/xampp/htdocs/laravel/public/logo/1496912432.jpg
</code>```

How can this problem be solved?

//edit

Controller:

```<code>public function image(Request $request) {
    if($request->hasFile('img'))
    {
        $image = Input::file('img');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $path = public_path('logo/' . $filename);
        Image::make($image->getRealPath())->fit(303, 200)->save($path);
        $file = $request->file('img');
        $session = session()->get('key');
        $update_image = Business::find($session);
        $update_image->image = $path;
        $update_image->save();
        return ['url' => url('logo/' . $filename)];
    }
</code>```

答:
You can do in two ways

Best way is update url path when image saving save url path to db

```<code>$path = $request->photo->store('logo'); // in 5.4
</code>```

The other way if you can't changes db url you can do some hack like this

```<code>$file = explode('/public/', $business->image);
echo asset($file[1]);
</code>```

Body:
So use is uploading a logo and it's path is stored in a database like this:

C:\xampp\htdocs\laravel\public\logo\1496912432.jpg

I am displaying the image like this:

image}}" />

However I get this error:

Not allowed to load local resource: file:///C:/xampp/htdocs/laravel/public/logo/1496912432.jpg

How can this problem be solved?

//edit

Controller:

public function image(Request $request) {
    if($request->hasFile('img'))
    {
        $image = Input::file('img');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $path = public_path('logo/' . $filename);
        Image::make($image->getRealPath())->fit(303, 200)->save($path);
        $file = $request->file('img');
        $session = session()->get('key');
        $update_image = Business::find($session);
        $update_image->image = $path;
        $update_image->save();
        return ['url' => url('logo/' . $filename)];
    }

Body:
You can do in two ways

Best way is update url path when image saving save url path to db

$path = $request->photo->store('logo'); // in 5.4

The other way if you can't changes db url you can do some hack like this

$file = explode('/public/', $business->image);
echo asset($file[1]);


问:
Azure Functions host.json settings per function or global?
Do the settings in host.json apply to each function individually, or apply to all of the functions as a whole?

For example, I've two functions in the same Project that both get messages from Azure ServiceBus Queues.

If I set maxConcurrentCalls to 10 in host.json, does that mean that as a whole only 10 concurrent calls to ServiceBus will be made, or that it is 10 per function, so there will be 20 concurrent calls?

Thanks in advance.

答:
host.json file is shared for all functions of a FunctionApp. That's to say that maxConcurrentCalls value will apply to all functions of the app, as any other setting will.

The effect of maxConcurrentCalls will be independent for each function. In your example, each function will have up to 10 messages processed concurrently. If you set it to 1, there will be 1 thread working per function.

Note that maxConcurrentCalls applies per instance. If you have multiple instances running, the max concurrency increases proportionally.


问:
Minimum value on a 2d array python
I have an array of the following structure which is simplified for this question:

```<code>8 2 3 4 5 6
3 6 6 7 2 6
3 8 5 1 2 9
6 4 2 7 8 3
</code>```

I wish to find the minimum value in this 2D array however using the inbuilt min function returns a value error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have looked into the alternative of using np.argmin:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html

However it only evaluates along a single axis and returns the index of the minimum value along a single row/column whereas I wish to evaluate the whole array and return the lowest value not the indices.

If it is possible to return the index values of the lowest item in the array then that would be preferable also as from that the lowest value can easily be found.

EDIT: Thanks to the comments below np.min is the solution I was looking for and I was not aware of it existing so my answer is solved.

答:
However it only evaluates along a single axis and returns the index of the minimum value along a single row/column whereas I wish to evaluate the whole array and return the lowest value not the indices.

numpy.argmin does not by default evaluate along a single axis, the default is to evaluate along the flattened matrix and it returns the linear index in the flattened array; from the numpy docs that you linked:

By default, the index is into the flattened array, otherwise along the specified axis.

Either way, use numpy.amin or numpy.min to return the minimum value, or equivalently for an array arrname use arrname.min(). As you mentioned, numpy.argmin returns the index of the minimum value (of course, you can then use this index to return the minimum value by indexing your array with it). You could also flatten into a single dimension array with arrname.flatten() and pass that into the built-in min function.

The four following methods produce what you want.

```<code>import numpy as np

values = np.array([
    [8,2,3,4,5,6],
    [3,6,6,7,2,6],
    [3,8,5,1,2,9],
    [6,4,2,7,8,3]])

values.min()          # = 1
np.min(values)        # = 1
np.amin(values)       # = 1
min(values.flatten()) # = 1
</code>```

Title: Minimum value on a 2d array python

Body:
I have an array of the following structure which is simplified for this question:

8 2 3 4 5 6
3 6 6 7 2 6
3 8 5 1 2 9
6 4 2 7 8 3

I wish to find the minimum value in this 2D array however using the inbuilt min function returns a value error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have looked into the alternative of using np.argmin:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html

However it only evaluates along a single axis and returns the index of the minimum value along a single row/column whereas I wish to evaluate the whole array and return the lowest value not the indices.

If it is possible to return the index values of the lowest item in the array then that would be preferable also as from that the lowest value can easily be found.

EDIT: Thanks to the comments below np.min is the solution I was looking for and I was not aware of it existing so my answer is solved.

Body:
However it only evaluates along a single axis and returns the index of the minimum value along a single row/column whereas I wish to evaluate the whole array and return the lowest value not the indices.

numpy.argmin does not by default evaluate along a single axis, the default is to evaluate along the flattened matrix and it returns the linear index in the flattened array; from the numpy docs that you linked:

By default, the index is into the flattened array, otherwise along the specified axis.

Either way, use numpy.amin or numpy.min to return the minimum value, or equivalently for an array arrname use arrname.min(). As you mentioned, numpy.argmin returns the index of the minimum value (of course, you can then use this index to return the minimum value by indexing your array with it). You could also flatten into a single dimension array with arrname.flatten() and pass that into the built-in min function.

The four following methods produce what you want.

import numpy as np

values = np.array([
    [8,2,3,4,5,6],
    [3,6,6,7,2,6],
    [3,8,5,1,2,9],
    [6,4,2,7,8,3]])

values.min()          # = 1
np.min(values)        # = 1
np.amin(values)       # = 1
min(values.flatten()) # = 1


问:
PHP converting hours and minutes into a decimal
I am calculating hours and minutes into variables but i would like to convert this into a decimal number

For example, 1 hour 30 minutes should display as 1.5 and 2 hours 15 minutes would display as 2.25

答:
```<code>function time_to_float($time) {
    $timeArr = explode(":", $time);
    return $timeArr[0] + ($timeArr[1] / 60);
}

$time_str = "1:30";

$formatted = sprintf("%0.2f", time_to_float($time_str));

echo $formatted; // 1.50
</code>```


问:
Integrating Devise with Mongoid
I am developing a Ruby on Rails 3 application and this is the first time I use MongoDB.

I have been thinking for couple of days on this problem, and I don't find a good solution. There are two problems I want to discuss.

The model

How to integrate this with Devise

The application is a School Courses manager. It manages many schools, which contains many students, courses, professors and tasks.

The structure of one school – there a many– is:

School

Director

Students

Professors

Courses

Tasks

The Director is the admin of the school. He is the only one who can create professors, students and courses.

There is exactly 1 Director.

There can be (0 – many) courses.

There can be (0 – many) students

There can be (0 – many) professors

Students may be in (0 – many) courses.

Professors may be in (0 – many) courses.

For every course, there can be (0–many) tasks associated with (0 – many) students. Yes, professor can send specific tasks to specific students.

I though for a couple of days on how to architecture this collection of models on MongoDB using Mongoid, and I reach a possible solution.  Yet I come from a Relational Database world and maybe this is an awful solution and I am abusing of 'embed' :)

Collection Schools

School 1

embed Director

embed Users

embed Courses

embed Tasks

School 2

embed Director

embed Users

embed Courses

embed Task

Models:

```<code>class User
   include Mongoid::Document

   field :first_name
   field :last_name
   field :email

   embedded_in :school, :inverse_of => :director
   embedded_in :school, :inverse_of => :students
   embedded_in :school, :inverse_of => :professors
end

class School
   include Mongoid::Document

   field :name
   key :name

   embeds_one :director, :class_name => "User"
   embeds_many :students, :class_name => "User"
   embeds_many :professors, :class_name => "User"

   validates :name, :presence => true
end

class Task
   include Mongoid::Document

   field :name

   references_one :student, :class => "User"
   references_one :course
end
</code>```

Also, I think I will use this class of wrap a collection a tasks. A professor creates a TaskCollection and assign students to it.

```<code> class TaskCollection

     include Mongoid::Document

     field :name

     references_many :students, :stored_as => array, :class => "User"
     references_one :task

 end
</code>```

So this is my first question. I need feedback.  Is it the right way to use a document oriented database?  Performance?   Improvements? Errors?

And the second question. How can we integrate this in Devise?

My first try is this:

Routes.rb

devise_for :users, :path => 'schools/:school_id/users'

resources :schools do
     resources :documents, :only => [:index]
     resources :tasks, :only => [:index]

  end

But when I do try do register and user I get an error.

```<code>http://localhost:3000/schools/pablo-de-olavide/users

 Mongoid::Errors::InvalidCollection in Devise/registrationsController#create

 Access to the collection for User is not allowed since it is an embedded document, please access a collection from the root document.
</code>```

Thank you very much for your help.

答:
I just started playing with Devise and Mongoid myself.

Your immediate need is to make User a root document (i.e. not embedded) this is how Devise is expecting to interact with the User model. I don't know if it can be overridden easily to do what you want it to. Personally, I don't think it would make a lot of sense even if you could.

As to your document design question you should take a look at this from Mongdb http://www.mongodb.org/display/DOCS/Schema+Design#SchemaDesign-Embedvs.Reference

From your example I would consider the User object to be a "First Class" object which would warrant its own collection.

Title: Integrating Devise with Mongoid

Body:
I am developing a Ruby on Rails 3 application and this is the first time I use MongoDB.

I have been thinking for couple of days on this problem, and I don't find a good solution. There are two problems I want to discuss.

The model

How to integrate this with Devise

The application is a School Courses manager. It manages many schools, which contains many students, courses, professors and tasks.

The structure of one school – there a many– is:

School

Director

Students

Professors

Courses

Tasks

The Director is the admin of the school. He is the only one who can create professors, students and courses.

There is exactly 1 Director.

There can be (0 – many) courses.

There can be (0 – many) students

There can be (0 – many) professors

Students may be in (0 – many) courses.

Professors may be in (0 – many) courses.

For every course, there can be (0–many) tasks associated with (0 – many) students. Yes, professor can send specific tasks to specific students.

I though for a couple of days on how to architecture this collection of models on MongoDB using Mongoid, and I reach a possible solution.  Yet I come from a Relational Database world and maybe this is an awful solution and I am abusing of 'embed' :)

Collection Schools

School 1

embed Director

embed Users

embed Courses

embed Tasks

School 2

embed Director

embed Users

embed Courses

embed Task

Models:

class User
   include Mongoid::Document

   field :first_name
   field :last_name
   field :email

   embedded_in :school, :inverse_of => :director
   embedded_in :school, :inverse_of => :students
   embedded_in :school, :inverse_of => :professors
end

class School
   include Mongoid::Document

   field :name
   key :name

   embeds_one :director, :class_name => "User"
   embeds_many :students, :class_name => "User"
   embeds_many :professors, :class_name => "User"

   validates :name, :presence => true
end

class Task
   include Mongoid::Document

   field :name

   references_one :student, :class => "User"
   references_one :course
end

Also, I think I will use this class of wrap a collection a tasks. A professor creates a TaskCollection and assign students to it.

 class TaskCollection

     include Mongoid::Document

     field :name

     references_many :students, :stored_as => array, :class => "User"
     references_one :task

 end

So this is my first question. I need feedback.  Is it the right way to use a document oriented database?  Performance?   Improvements? Errors?

And the second question. How can we integrate this in Devise?

My first try is this:

Routes.rb

devise_for :users, :path => 'schools/:school_id/users'

resources :schools do
     resources :documents, :only => [:index]
     resources :tasks, :only => [:index]

  end

But when I do try do register and user I get an error.

http://localhost:3000/schools/pablo-de-olavide/users

 Mongoid::Errors::InvalidCollection in Devise/registrationsController#create

 Access to the collection for User is not allowed since it is an embedded document, please access a collection from the root document.

Thank you very much for your help.


问:
Spring boot: Jersey ResourceConfig needs annotating?
I am just getting started with Spring Boot and I wanted to implement a ResourceConfig and I finding some conflicting ideas.

Take the following

```<code>@Component
public class JerseyExampleConfig extends ResourceConfig {
</code>```

The above is annotated with COMPONENT

```<code>@Configuration
public class JerseyExampleConfig extends ResourceConfig {
</code>```

Which one is correct?

I thought annotating with Configuration would be the correct way but it appears that the Component is used in examples.

Any ideas ?

Whats the difference?

答:
They both make the ResourceConfig a Spring Bean, which is all that's really required to make the Spring Boot-Jersey integration work. You could even just do

```<code>@SpringBootApplication
class MyApplication {
    public static void main(String... args) {}

    @Bean
    public ResourceConfig jerseyConfig() {
        return new MyResourceConfig();
    }
}
</code>```

With this, you wouldn't need @Component or @Configuration. It simply makes the ResourceConfig a Spring Bean, which like I said, is all that is required.

That being said, between the two annotations, @Configuration is really meant for Spring configuration. You could place your Spring configuration in the ResourceConfig subclass, but I would just put it in a separate configuration class, just to keep things separate. Note that configuration classes are also Spring Beans, so that's why the @Configuration works.

@Component on the other hand, is a general purpose annotation that will make the class a Spring Bean. This is the reason all the the examples show using the annotation, as the ResourceConfig is generally not meant to be a Spring configuration class, and it is less verbose then the example above, not using any annotations.

Body:
I am just getting started with Spring Boot and I wanted to implement a ResourceConfig and I finding some conflicting ideas.

Take the following

@Component
public class JerseyExampleConfig extends ResourceConfig {

The above is annotated with COMPONENT

@Configuration
public class JerseyExampleConfig extends ResourceConfig {

Which one is correct?

I thought annotating with Configuration would be the correct way but it appears that the Component is used in examples.

Any ideas ?

Whats the difference?

Body:
They both make the ResourceConfig a Spring Bean, which is all that's really required to make the Spring Boot-Jersey integration work. You could even just do

@SpringBootApplication
class MyApplication {
    public static void main(String... args) {}

    @Bean
    public ResourceConfig jerseyConfig() {
        return new MyResourceConfig();
    }
}

With this, you wouldn't need @Component or @Configuration. It simply makes the ResourceConfig a Spring Bean, which like I said, is all that is required.

That being said, between the two annotations, @Configuration is really meant for Spring configuration. You could place your Spring configuration in the ResourceConfig subclass, but I would just put it in a separate configuration class, just to keep things separate. Note that configuration classes are also Spring Beans, so that's why the @Configuration works.

@Component on the other hand, is a general purpose annotation that will make the class a Spring Bean. This is the reason all the the examples show using the annotation, as the ResourceConfig is generally not meant to be a Spring configuration class, and it is less verbose then the example above, not using any annotations.