问:
How to detect edge and crop an image in Python
I'm new to Image Processing in Python and I'm trying to solve a common problem. I have an image having a signature of a person. I want to find the edges and crop it to fit the signature in the image.

Input Image

Expected Output

I tried Canny Edge Detection and cropping the image using a list of existing solutions (articles & answers) using PIL, CV2, but none seem to work. I'm looking for a working solution.

Some solutions I tried:

https://www.quora.com/How-can-I-detect-an-object-from-static-image-and-crop-it-from-the-image-using-openCV

Crop Image from all sides after edge detection

How to crop biggest rectangle out of an image

and many more... None worked although seems very simple. I encountered either errors or not expected output using any of the existing solutions.

答:
What you need is thresholding. In OpenCV you can accomplish this using cv2.threshold().

I took a shot at it. My approach was the following:

Convert to grayscale

Threshold the image to only get the signature and nothing else

Find where those pixels are that show up in the thresholded image

Crop around that region in the original grayscale

Create a new thresholded image from the crop that isn't as strict for display

Here was my attempt, I think it worked pretty well.

```<code>import cv2
import numpy as np

# load image
img = cv2.imread('image.jpg')
rsz_img = cv2.resize(img, None, fx=0.25, fy=0.25) # resize since image is huge
gray = cv2.cvtColor(rsz_img, cv2.COLOR_BGR2GRAY) # convert to grayscale

# threshold to get just the signature
retval, thresh_gray = cv2.threshold(gray, thresh=100, maxval=255, type=cv2.THRESH_BINARY)

# find where the signature is and make a cropped region
points = np.argwhere(thresh_gray==0) # find where the black pixels are
points = np.fliplr(points) # store them in x,y coordinates instead of row,col indices
x, y, w, h = cv2.boundingRect(points) # create a rectangle around those points
x, y, w, h = x-10, y-10, w+20, h+20 # make the box a little bigger
crop = gray[y:y+h, x:x+w] # create a cropped region of the gray image

# get the thresholded crop
retval, thresh_crop = cv2.threshold(crop, thresh=200, maxval=255, type=cv2.THRESH_BINARY)

# display
cv2.imshow("Cropped and thresholded image", thresh_crop)
cv2.waitKey(0)
</code>```

And here's the result:

Body:
What you need is thresholding. In OpenCV you can accomplish this using cv2.threshold().

I took a shot at it. My approach was the following:

Convert to grayscale

Threshold the image to only get the signature and nothing else

Find where those pixels are that show up in the thresholded image

Crop around that region in the original grayscale

Create a new thresholded image from the crop that isn't as strict for display

Here was my attempt, I think it worked pretty well.

import cv2
import numpy as np

# load image
img = cv2.imread('image.jpg')
rsz_img = cv2.resize(img, None, fx=0.25, fy=0.25) # resize since image is huge
gray = cv2.cvtColor(rsz_img, cv2.COLOR_BGR2GRAY) # convert to grayscale

# threshold to get just the signature
retval, thresh_gray = cv2.threshold(gray, thresh=100, maxval=255, type=cv2.THRESH_BINARY)

# find where the signature is and make a cropped region
points = np.argwhere(thresh_gray==0) # find where the black pixels are
points = np.fliplr(points) # store them in x,y coordinates instead of row,col indices
x, y, w, h = cv2.boundingRect(points) # create a rectangle around those points
x, y, w, h = x-10, y-10, w+20, h+20 # make the box a little bigger
crop = gray[y:y+h, x:x+w] # create a cropped region of the gray image

# get the thresholded crop
retval, thresh_crop = cv2.threshold(crop, thresh=200, maxval=255, type=cv2.THRESH_BINARY)

# display
cv2.imshow("Cropped and thresholded image", thresh_crop)
cv2.waitKey(0)

And here's the result:


来源: stackexchange

问:
Save image to device
Hi i cant seem to get his code to work

```<code>    //Save Image To Device
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[self.ImageURLS objectAtIndex:0]]]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(@"saving jpg");
NSString *jpgFilePath = [NSString stringWithFormat:@"%@/%@.jpg",docDir,[self.NameArray objectAtIndex:0]];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:jpgFilePath atomically:YES];
</code>```

and i am getting the image via

```<code>    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *jpgFilePath = [NSString stringWithFormat:@"%@/%@.jpg",docDir,[self.NameArray objectAtIndex:[indexPath row]]];
    UIImage *image = [UIImage imageNamed:jpgFilePath];
</code>```

Any help ?

Thanks

答:
Change the last line of your code to

```<code>UIImage *image = [UIImage imageWithContentsOfFile:jpgFilePath];
</code>```

UIImage's +imageNamed: searches the app bundle for a file with a given name, which is not what you need.

ContentLicense: CC BY-SA 2.5

Title: Save image to device

Body:
Hi i cant seem to get his code to work

    //Save Image To Device
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[self.ImageURLS objectAtIndex:0]]]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(@"saving jpg");
NSString *jpgFilePath = [NSString stringWithFormat:@"%@/%@.jpg",docDir,[self.NameArray objectAtIndex:0]];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:jpgFilePath atomically:YES];

and i am getting the image via

    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *jpgFilePath = [NSString stringWithFormat:@"%@/%@.jpg",docDir,[self.NameArray objectAtIndex:[indexPath row]]];
    UIImage *image = [UIImage imageNamed:jpgFilePath];

Any help ?

Thanks

Body:
Change the last line of your code to

UIImage *image = [UIImage imageWithContentsOfFile:jpgFilePath];

UIImage's +imageNamed: searches the app bundle for a file with a given name, which is not what you need.


问:
iTunes (TestFlight) - Uploaded and Visible in Activity but not available in TestFlight

I am extremely confused on trying to fix this different kind of Issue faced in iTunes. Actually I am Using Appcelerator to develop and build the Application. I had successfully get the .ipa file from the Appcelerator and by using the Application Loader I am uploading the App to the iTunes. Once my Upload is completed in iTunes my App gets visible in Activity tab that Which I had mentioned in the first Image as well as I had received the mail that "The App has been successfully moved to the iTunes and Ready for move to Testflight". In TestFlight Initially under the version number build is available with the tabular column showing the alert of Missing Compliances, then for the first question I gave "NO" and then gave start Internal testing, after this my build is no longer available in Testflight and then seems to be the second Image that I had Attached. I had a cross check with my distribution profile , Certificate and App ID that's all fine. I had been searching in many forums to fix this Issue. Can anyone faced this Issue? Please assist me on this Issue, I had been struggling for a week.

答: Yeah I had fixed the Issue by changing my provisioning profile from Adhoc Distribution profile to AppStore Distribution Profile and then take a build and upload it via Organiser of xCode. Then the App details are visible in Test flight.</p>

ContentLicense: CC BY-SA 3.0


问:
How to use declared variable for SQL statement by using "IN" condition
I am trying to write some code but it doesn't work. It only those TypeT description. How can I display the TypeT and TypeS condition for below case?

```<code>DECLARE @PaymentType VARCHAR(20) = '';

SELECT @PaymentType = LISTID
FROM LIST
WHERE LISTCONFIG IN ('TypeT', 'TypeS')

SELECT *
FROM LIST
WHERE LISTID IN  (@PaymentType)
</code>```

答:
Try the below

```<code>SELECT * FROM LIST
WHERE LISTID IN  (select LISTID FROM LIST WHERE LISTCONFIG IN 'TypeT','TypeS'))
</code>```

Or you can use the below in only sql server 2016

```<code>DECLARE @PaymentType VARCHAR(20)
SELECT @PaymentType= isnull(@PaymentType+',','')+LISTID FROM list WHERE LISTID IN ('TypeT','TypeS')
SELECT * FROM LIST WHERE LISTID IN  (select value from STRING_SPLIT(@PaymentType, ',')  )
</code>```

Body:
I am trying to write some code but it doesn't work. It only those TypeT description. How can I display the TypeT and TypeS condition for below case?

DECLARE @PaymentType VARCHAR(20) = '';

SELECT @PaymentType = LISTID
FROM LIST
WHERE LISTCONFIG IN ('TypeT', 'TypeS')

SELECT *
FROM LIST
WHERE LISTID IN  (@PaymentType)

Body:
Try the below

SELECT * FROM LIST
WHERE LISTID IN  (select LISTID FROM LIST WHERE LISTCONFIG IN 'TypeT','TypeS'))

Or you can use the below in only sql server 2016

DECLARE @PaymentType VARCHAR(20)
SELECT @PaymentType= isnull(@PaymentType+',','')+LISTID FROM list WHERE LISTID IN ('TypeT','TypeS')
SELECT * FROM LIST WHERE LISTID IN  (select value from STRING_SPLIT(@PaymentType, ',')  )


问:
What does this 'static' mean and why is it like that
```<code>public class tt {
static{
    System.out.println("class tt");
    }
}
</code>```

It the first time ive come across it and im wondering what it is and what it's used for

答:
It's a static initializer block. It will be executed once when the class is first loaded, along with static field initializers like this:

```<code>private static int staticField = someMethod();
</code>```

The difference is that an initializer block can contain control flow structures like try/catch blocks.

Body:
public class tt {
static{
    System.out.println("class tt");
    }
}

It the first time ive come across it and im wondering what it is and what it's used for

Body:
It's a static initializer block. It will be executed once when the class is first loaded, along with static field initializers like this:

private static int staticField = someMethod();

The difference is that an initializer block can contain control flow structures like try/catch blocks.


问:
Java: Printing trailing spaces
I'm a beginner in Java and working on a code that first requires user to enter total number of integers and next the integers themselves. Example input is:

```<code>4
1 4 3 2
</code>```

The code will need to reverse the second input to the following:

```<code>2 3 4 1
</code>```

My solution is as follow:

```<code>public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];
    for(int arr_i=0; arr_i < n; arr_i++){
        arr[arr_i] = in.nextInt();
    }
    for(int reverse_i=n-1; reverse_i>=0; reverse_i--){
        System.out.print(arr[reverse_i]);
            if(reverse_i != 0){System.out.print(" ");}
    }
}
</code>```

My question is related to the code to add a blank space " " in between the printed numbers. I wonder what other way I can use to get this done? Any suggestion is appreciated, thank you.

答:
It is all about output formatting. You may use this examples and become familiar with all possible approaches.

Your code can be improved in next two ways :

1) Use \t instead of Empty Space (\t is a tabulation)

2) Create a constant with output format like this private static final String output = "%d " and use it in output line like this : String.format(output, number) where number is your number that should be printed.

Title: Java: Printing trailing spaces

Body:
I'm a beginner in Java and working on a code that first requires user to enter total number of integers and next the integers themselves. Example input is:

4
1 4 3 2

The code will need to reverse the second input to the following:

2 3 4 1

My solution is as follow:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];
    for(int arr_i=0; arr_i < n; arr_i++){
        arr[arr_i] = in.nextInt();
    }
    for(int reverse_i=n-1; reverse_i>=0; reverse_i--){
        System.out.print(arr[reverse_i]);
            if(reverse_i != 0){System.out.print(" ");}
    }
}

My question is related to the code to add a blank space " " in between the printed numbers. I wonder what other way I can use to get this done? Any suggestion is appreciated, thank you.


问:
Bootstrap Dropdown menu is not working (Does not show a dropdown list)
I have this code snippet extracted from Bootstrap website. Everything works fine except when I click See Product, it won't show anything.

```<code>    <!DOCTYPE html>
<html>
<head>
    <title>Omicron.com</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
    <style>
/*#MostUpperGreyLine img{
    width: 100%;
    min-width: 10px;
    height:auto;
}*/
#Header-New img{
    width: 100%;
    min-width: 10px;
    height: auto;
    position: relative;
    top:10px;
}

</style>
</head>
<body>

    <!--<div id="MostUpperGreyLine">
        <img src="MostUpperGreyLine.png" alt="No Green Header Found!">
    </div>-->

    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">Omicron.Inc</a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">Our Applications<span class="sr-only">(current)</span></a></li>
                    <li><a href="#">Link</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">See Products <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Action</a></li>
                            <li><a href="#">Another action</a></li>
                            <li><a href="#">Something else here</a></li>
                            <li role="separator" class="divider"></li>
                            <li><a href="#">Separated link</a></li>
                            <li role="separator" class="divider"></li>
                            <li><a href="#">One more separated link</a></li>
                        </ul>
                    </li>
                </ul>
                <form class="navbar-form navbar-left">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Search">
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#">Link</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Action</a></li>
                            <li><a href="#">Another action</a></li>
                            <li><a href="#">Something else here</a></li>
                            <li role="separator" class="divider"></li>
                            <li><a href="#">Separated link</a></li>
                        </ul>
                    </li>
                </ul>
            </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
    </nav>

    <div id="Header-New">
        <img src="Header-New.png" alt="Header not Found!">
    </div>

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

答:
 <!DOCTYPE html>

    <title>Omicron.com</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    Toggle navigation

                </button>
                Omicron.Inc

Our Applications(current)

Link

                        See Products

Action

Another action

Something else here

Separated link

One more separated link

                <form class="navbar-form navbar-left">

                        <input type="text" class="form-control" placeholder="Search">

                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

Link

                        Dropdown

Action

Another action

Something else here

Separated link

```

Body:
I have this code snippet extracted from Bootstrap website. Everything works fine except when I click See Product, it won't show anything.

    <!DOCTYPE html>

    <title>Omicron.com</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    Toggle navigation

                </button>
                Omicron.Inc

Our Applications(current)

Link

                        See Products

Action

Another action

Something else here

Separated link

One more separated link

                <form class="navbar-form navbar-left">

                        <input type="text" class="form-control" placeholder="Search">

                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

Link

                        Dropdown

Action

Another action

Something else here

Separated link

Body:
 <!DOCTYPE html>
<html>
<head>
    <title>Omicron.com</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style>
/*#MostUpperGreyLine img{
    width: 100%;
    min-width: 10px;
    height:auto;
}*/
#Header-New img{
    width: 100%;
    min-width: 10px;
    height: auto;
    position: relative;
    top:10px;
}

</style>
</head>
<body>

    <!--<div id="MostUpperGreyLine">
        <img src="MostUpperGreyLine.png" alt="No Green Header Found!">
    </div>-->

    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">Omicron.Inc</a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">Our Applications<span class="sr-only">(current)</span></a></li>
                    <li><a href="#">Link</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">See Products <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Action</a></li>
                            <li><a href="#">Another action</a></li>
                            <li><a href="#">Something else here</a></li>
                            <li role="separator" class="divider"></li>
                            <li><a href="#">Separated link</a></li>
                            <li role="separator" class="divider"></li>
                            <li><a href="#">One more separated link</a></li>
                        </ul>
                    </li>
                </ul>
                <form class="navbar-form navbar-left">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Search">
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#">Link</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Action</a></li>
                            <li><a href="#">Another action</a></li>
                            <li><a href="#">Something else here</a></li>
                            <li role="separator" class="divider"></li>
                            <li><a href="#">Separated link</a></li>
                        </ul>
                    </li>
                </ul>
            </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
    </nav>

    <div id="Header-New">
        <img src="Header-New.png" alt="Header not Found!">
    </div>

</body>
</html>


问:
Send uploaded Image in Express
Have an Express application that uploads an image using Multer. What I would like to be able to do is serve that image. The challenge though is when the file is uploaded it does not save the file extension which is by designed from what I've read for security purposes. What I need to be able to do is add the correct extensions to the corresponding mime type.

Technology

Express: 4.15.0

Multer: 1.3.0

mmmagic: 0.4.5

File Structure

```<code>root
  server.js
  /uploads
    /images
      ad58c400e67362118ac1b11f6c4b6c44
      ...
  /routes
    drinks.routes.js
    uploads.routes.js
</code>```

Running this all through Postman. Have form elements name, tagline, image. If I upload "IMG_111.jpg" That image will get uploaded through Multer, validated that it's an image type, and placed in /images/uploads with a new name, default behavior for Multer to create uniqueness. The problem is I have the filename but it is not saved with an extension.

drinks.routes.js

```<code>var upload = multer({
  dest: 'uploads/images',
  fileFilter: function (req, file, callback) {
    console.log('running upload file filter');
      var fileType = file.mimetype;
      if(fileType !== 'image/png' && fileType !== 'image/jpeg' && fileType !== 'image/gif' && fileType !== 'image/jpg') {
          return callback(new Error('Only images are allowed'))
      }
      callback(null, true)
  },
}).single('image');

router.route('/').post(passport.authenticate('jwt', { session: false }), upload, function(req, res, next){
var drink = req.body;
var drinkImage = req.file;
console.log('DRINK IMAGE', drinkImage);

Drink.createDrink(drink, drinkImage, function(err, drink, drinkImage){
  console.log('creating drink');
  if(err){
    res.send(err);
  }
    res.json(drink)
  });
});
</code>```

So I can upload a file, validate the file, save the file with a unique name and no extension. Where I'm have difficulties is then checking the mime type of the requested image, attaching an extension and sending that back in a response.

My original thought is to create a route with the image name requested, use mmmagic to detect the mime type, add the extension and serve that file. But, all attempts at this have failed.

uploads.routes.js

```<code>var express = require('express');
var router = express.Router();
var path = require('path');

var mmm = require('mmmagic');
var Magic = mmm.Magic;
var magic = new Magic(mmm.MAGIC_MIME_TYPE);

router.use(function(req, res, next){
  next();
});

router.route('/images/:filename')
  .get(function(req,res){
    var fileName = req.params.filename;
    var constructFile = function(res){
      magic.detectFile(__dirname + '/../uploads/images/' + fileName, function(err, result) {
        if (err) throw err;
        console.log(result);
        if (result == 'image/jpeg'){
      // return res.sendFile(__dirname + '/../uploads/images/' + fileName + '.jpg');
      res.send(express.static(path.join(__dirname, '/../uploads/images'), {index: false, extensions:['jpg']}));
    }
  });
}

constructFile(res);
  })

module.exports = router;
</code>```

Tried following this SO Which lead me to express.static. But can't figure out at this point if I'm on the right track and just missing something or if I should be looking at this from a different angle.

答:
You have to configure your multer uploader first. Try this:

```<code>var multer = require('multer');
//This is for preventing multer from giving name without extention
var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'public/files/')
},
filename: function(req, file, cb) {
    cb(null, file.originalname);
}
});
</code>```

However if you want to still have unique name then try this:

```<code>var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/files/')
  },
  filename: function (req, file, cb) {
    crypto.pseudoRandomBytes(16, function (err, raw) {
      cb(null, raw.toString('hex') + Date.now() + '.' +
         mime.extension(file.mimetype));
    });
  }
});
var upload = multer({ storage: storage });
</code>```

Title: Send uploaded Image in Express

Body:
Have an Express application that uploads an image using Multer. What I would like to be able to do is serve that image. The challenge though is when the file is uploaded it does not save the file extension which is by designed from what I've read for security purposes. What I need to be able to do is add the correct extensions to the corresponding mime type.

Technology

Express: 4.15.0

Multer: 1.3.0

mmmagic: 0.4.5

File Structure

root
  server.js
  /uploads
    /images
      ad58c400e67362118ac1b11f6c4b6c44
      ...
  /routes
    drinks.routes.js
    uploads.routes.js

Running this all through Postman. Have form elements name, tagline, image. If I upload "IMG_111.jpg" That image will get uploaded through Multer, validated that it's an image type, and placed in /images/uploads with a new name, default behavior for Multer to create uniqueness. The problem is I have the filename but it is not saved with an extension.

drinks.routes.js

var upload = multer({
  dest: 'uploads/images',
  fileFilter: function (req, file, callback) {
    console.log('running upload file filter');
      var fileType = file.mimetype;
      if(fileType !== 'image/png' && fileType !== 'image/jpeg' && fileType !== 'image/gif' && fileType !== 'image/jpg') {
          return callback(new Error('Only images are allowed'))
      }
      callback(null, true)
  },
}).single('image');

router.route('/').post(passport.authenticate('jwt', { session: false }), upload, function(req, res, next){
var drink = req.body;
var drinkImage = req.file;
console.log('DRINK IMAGE', drinkImage);

Drink.createDrink(drink, drinkImage, function(err, drink, drinkImage){
  console.log('creating drink');
  if(err){
    res.send(err);
  }
    res.json(drink)
  });
});

So I can upload a file, validate the file, save the file with a unique name and no extension. Where I'm have difficulties is then checking the mime type of the requested image, attaching an extension and sending that back in a response.

My original thought is to create a route with the image name requested, use mmmagic to detect the mime type, add the extension and serve that file. But, all attempts at this have failed.

uploads.routes.js

var express = require('express');
var router = express.Router();
var path = require('path');

var mmm = require('mmmagic');
var Magic = mmm.Magic;
var magic = new Magic(mmm.MAGIC_MIME_TYPE);

router.use(function(req, res, next){
  next();
});

router.route('/images/:filename')
  .get(function(req,res){
    var fileName = req.params.filename;
    var constructFile = function(res){
      magic.detectFile(__dirname + '/../uploads/images/' + fileName, function(err, result) {
        if (err) throw err;
        console.log(result);
        if (result == 'image/jpeg'){
      // return res.sendFile(__dirname + '/../uploads/images/' + fileName + '.jpg');
      res.send(express.static(path.join(__dirname, '/../uploads/images'), {index: false, extensions:['jpg']}));
    }
  });
}

constructFile(res);
  })

module.exports = router;

Tried following this SO Which lead me to express.static. But can't figure out at this point if I'm on the right track and just missing something or if I should be looking at this from a different angle.

Body:
You have to configure your multer uploader first. Try this:

var multer = require('multer');
//This is for preventing multer from giving name without extention
var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'public/files/')
},
filename: function(req, file, cb) {
    cb(null, file.originalname);
}
});

However if you want to still have unique name then try this:

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/files/')
  },
  filename: function (req, file, cb) {
    crypto.pseudoRandomBytes(16, function (err, raw) {
      cb(null, raw.toString('hex') + Date.now() + '.' +
         mime.extension(file.mimetype));
    });
  }
});
var upload = multer({ storage: storage });


问:
download and split large file into 100 MB chunks in blob storage
I have a 2GB file in blob storage and am building a console application that will download this file into a desktop. Requirement is to split into 100MB chunks and append a number into the filename. I do not need to re-combine those files again. What I need is only the chunks of files.

I currently have this code from Azure download blob part

But I cannot figure out how to stop downloading when the file size is already 100MB and create a new one.

Any help will be appreciated.

Update: Here is my code

```<code>CloudStorageAccount account = CloudStorageAccount.Parse(connectionString);
            var blobClient = account.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference(containerName);
            var file = uri;
            var blob = container.GetBlockBlobReference(file);
            //First fetch the size of the blob. We use this to create an empty file with size = blob's size
            blob.FetchAttributes();
            var blobSize = blob.Properties.Length;
            long blockSize = (1 * 1024 * 1024);//1 MB chunk;
            blockSize = Math.Min(blobSize, blockSize);
            //Create an empty file of blob size
            using (FileStream fs = new FileStream(file, FileMode.Create))//Create empty file.
            {
                fs.SetLength(blobSize);//Set its size
            }
            var blobRequestOptions = new BlobRequestOptions
            {
                RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(5), 3),
                MaximumExecutionTime = TimeSpan.FromMinutes(60),
                ServerTimeout = TimeSpan.FromMinutes(60)
            };
            long startPosition = 0;
            long currentPointer = 0;
            long bytesRemaining = blobSize;
            do
            {
                var bytesToFetch = Math.Min(blockSize, bytesRemaining);
                using (MemoryStream ms = new MemoryStream())
                {
                    //Download range (by default 1 MB)
                    blob.DownloadRangeToStream(ms, currentPointer, bytesToFetch, null, blobRequestOptions);
                    ms.Position = 0;
                    var contents = ms.ToArray();
                    using (var fs = new FileStream(file, FileMode.Open))//Open that file
                    {
                        fs.Position = currentPointer;//Move the cursor to the end of file.
                        fs.Write(contents, 0, contents.Length);//Write the contents to the end of file.
                    }
                    startPosition += blockSize;
                    currentPointer += contents.Length;//Update pointer
                    bytesRemaining -= contents.Length;//Update bytes to fetch

                    Console.WriteLine(fileName + dateTimeStamp + ".csv " + (startPosition / 1024 / 1024) + "/" + (blob.Properties.Length / 1024 / 1024) + " MB downloaded...");
                }
            }
            while (bytesRemaining > 0);
</code>```

答:
Per my understanding, you could break your blob file into your expected pieces (100MB), then leverage CloudBlockBlob.DownloadRangeToStream to download each of your chunks of files. Here is my code snippet, you could refer to it:

ParallelDownloadBlob

```<code>private static void ParallelDownloadBlob(Stream outPutStream, CloudBlockBlob blob,long startRange,long endRange)
{
    blob.FetchAttributes();
    int bufferLength = 1 * 1024 * 1024;//1 MB chunk for download
    long blobRemainingLength = endRange-startRange;
    Queue<KeyValuePair<long, long>> queues = new Queue<KeyValuePair<long, long>>();
    long offset = startRange;
    while (blobRemainingLength > 0)
    {
        long chunkLength = (long)Math.Min(bufferLength, blobRemainingLength);
        queues.Enqueue(new KeyValuePair<long, long>(offset, chunkLength));
        offset += chunkLength;
        blobRemainingLength -= chunkLength;
    }
    Parallel.ForEach(queues,
        new ParallelOptions()
        {
            MaxDegreeOfParallelism = 5
        }, (queue) =>
        {
            using (var ms = new MemoryStream())
            {
                blob.DownloadRangeToStream(ms, queue.Key, queue.Value);
                lock (outPutStream)
                {
                    outPutStream.Position = queue.Key- startRange;
                    var bytes = ms.ToArray();
                    outPutStream.Write(bytes, 0, bytes.Length);
                }
            }
        });
}
</code>```

Program Main

```<code>var container = storageAccount.CreateCloudBlobClient().GetContainerReference(defaultContainerName);
var blob = container.GetBlockBlobReference("code.txt");
blob.FetchAttributes();
long blobTotalLength = blob.Properties.Length;
long chunkLength = 10 * 1024; //divide blob file into each file with 10KB in size
for (long i = 0; i <= blobTotalLength; i += chunkLength)
{

    long startRange = i;
    long endRange = (i + chunkLength) > blobTotalLength ? blobTotalLength : (i + chunkLength);

    using (var fs = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"resources\\code_[{startRange}]_[{endRange}].txt"), FileMode.Create))
    {
        Console.WriteLine($"\nParallelDownloadBlob from range [{startRange}] to [{endRange}] start...");
        Stopwatch sp = new Stopwatch();
        sp.Start();

        ParallelDownloadBlob(fs, blob, startRange, endRange);
        sp.Stop();
        Console.WriteLine($"download done, time cost:{sp.ElapsedMilliseconds / 1000.0}s");
    }
}
</code>```

RESULT

UPDATE:

Based on your requirement, I recommend that you could download your blob into a single file, then leverage LumenWorks.Framework.IO to read your large file records line by line, then check the byte size you have read and save into a new csv file with the size up to 100MB. Here is a code snippet, you could refer to it:

```<code>using (CsvReader csv = new CsvReader(new StreamReader("data.csv"), true))
{
    int fieldCount = csv.FieldCount;
    string[] headers = csv.GetFieldHeaders();
    while (csv.ReadNextRecord())
    {
        for (int i = 0; i < fieldCount; i++)
            Console.Write(string.Format("{0} = {1};",
                          headers[i],
                          csv[i] == null ? "MISSING" : csv[i]));
        //TODO:
        //1.Read the current record, check the total bytes you have read;
        //2.Create a new csv file if the current total bytes up to 100MB, then save the current record to the current CSV file.
    }
}
</code>```

Additionally, you could refer to A Fast CSV Reader and CsvHelper for more details.

UPDATE2

Code sample for breaking large CSV file into small CSV file with the fixed bytes, I used CsvHelper 2.16.3 for the following code snippet, you could refer to it:

```<code>string[] headers = new string[0];
using (var sr = new StreamReader(@"C:\Users\v-brucch\Desktop\BlobHourMetrics.csv")) //83.9KB
{
    using (CsvHelper.CsvReader csvReader = new CsvHelper.CsvReader(sr,
        new CsvHelper.Configuration.CsvConfiguration()
        {
            Delimiter = ",",
            Encoding = Encoding.UTF8
        }))
    {
        //check header
        if (csvReader.ReadHeader())
        {
            headers = csvReader.FieldHeaders;
        }

        TextWriter writer = null;
        CsvWriter csvWriter = null;
        long readBytesCount = 0;
        long chunkSize = 30 * 1024; //divide CSV file into each CSV file with byte size up to 30KB

        while (csvReader.Read())
        {
            var curRecord = csvReader.CurrentRecord;
            var curRecordByteCount = curRecord.Sum(r => Encoding.UTF8.GetByteCount(r)) + headers.Count() + 1;
            readBytesCount += curRecordByteCount;

            //check bytes you have read
            if (writer == null || readBytesCount > chunkSize)
            {
                readBytesCount = curRecordByteCount + headers.Sum(h => Encoding.UTF8.GetByteCount(h)) + headers.Count() + 1;
                if (writer != null)
                {
                    writer.Flush();
                    writer.Close();
                }
                string fileName = $"BlobHourMetrics_{Guid.NewGuid()}.csv";
                writer = new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName), true);
                csvWriter = new CsvWriter(writer);
                csvWriter.Configuration.Encoding = Encoding.UTF8;
                //output header field
                foreach (var header in headers)
                {
                    csvWriter.WriteField(header);
                }
                csvWriter.NextRecord();
            }
            //output record field
            foreach (var field in curRecord)
            {
                csvWriter.WriteField(field);
            }
            csvWriter.NextRecord();
        }
        if (writer != null)
        {
            writer.Flush();
            writer.Close();
        }
    }
}
</code>```

RESULT

Body:
I have a 2GB file in blob storage and am building a console application that will download this file into a desktop. Requirement is to split into 100MB chunks and append a number into the filename. I do not need to re-combine those files again. What I need is only the chunks of files.

I currently have this code from Azure download blob part

But I cannot figure out how to stop downloading when the file size is already 100MB and create a new one.

Any help will be appreciated.

Update: Here is my code

CloudStorageAccount account = CloudStorageAccount.Parse(connectionString);
            var blobClient = account.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference(containerName);
            var file = uri;
            var blob = container.GetBlockBlobReference(file);
            //First fetch the size of the blob. We use this to create an empty file with size = blob's size
            blob.FetchAttributes();
            var blobSize = blob.Properties.Length;
            long blockSize = (1 * 1024 * 1024);//1 MB chunk;
            blockSize = Math.Min(blobSize, blockSize);
            //Create an empty file of blob size
            using (FileStream fs = new FileStream(file, FileMode.Create))//Create empty file.
            {
                fs.SetLength(blobSize);//Set its size
            }
            var blobRequestOptions = new BlobRequestOptions
            {
                RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(5), 3),
                MaximumExecutionTime = TimeSpan.FromMinutes(60),
                ServerTimeout = TimeSpan.FromMinutes(60)
            };
            long startPosition = 0;
            long currentPointer = 0;
            long bytesRemaining = blobSize;
            do
            {
                var bytesToFetch = Math.Min(blockSize, bytesRemaining);
                using (MemoryStream ms = new MemoryStream())
                {
                    //Download range (by default 1 MB)
                    blob.DownloadRangeToStream(ms, currentPointer, bytesToFetch, null, blobRequestOptions);
                    ms.Position = 0;
                    var contents = ms.ToArray();
                    using (var fs = new FileStream(file, FileMode.Open))//Open that file
                    {
                        fs.Position = currentPointer;//Move the cursor to the end of file.
                        fs.Write(contents, 0, contents.Length);//Write the contents to the end of file.
                    }
                    startPosition += blockSize;
                    currentPointer += contents.Length;//Update pointer
                    bytesRemaining -= contents.Length;//Update bytes to fetch

                    Console.WriteLine(fileName + dateTimeStamp + ".csv " + (startPosition / 1024 / 1024) + "/" + (blob.Properties.Length / 1024 / 1024) + " MB downloaded...");
                }
            }
            while (bytesRemaining > 0);

Body:
Per my understanding, you could break your blob file into your expected pieces (100MB), then leverage CloudBlockBlob.DownloadRangeToStream to download each of your chunks of files. Here is my code snippet, you could refer to it:

ParallelDownloadBlob

private static void ParallelDownloadBlob(Stream outPutStream, CloudBlockBlob blob,long startRange,long endRange)
{
    blob.FetchAttributes();
    int bufferLength = 1 * 1024 * 1024;//1 MB chunk for download
    long blobRemainingLength = endRange-startRange;
    Queue<KeyValuePair<long, long>> queues = new Queue<KeyValuePair<long, long>>();
    long offset = startRange;
    while (blobRemainingLength > 0)
    {
        long chunkLength = (long)Math.Min(bufferLength, blobRemainingLength);
        queues.Enqueue(new KeyValuePair<long, long>(offset, chunkLength));
        offset += chunkLength;
        blobRemainingLength -= chunkLength;
    }
    Parallel.ForEach(queues,
        new ParallelOptions()
        {
            MaxDegreeOfParallelism = 5
        }, (queue) =>
        {
            using (var ms = new MemoryStream())
            {
                blob.DownloadRangeToStream(ms, queue.Key, queue.Value);
                lock (outPutStream)
                {
                    outPutStream.Position = queue.Key- startRange;
                    var bytes = ms.ToArray();
                    outPutStream.Write(bytes, 0, bytes.Length);
                }
            }
        });
}

Program Main

var container = storageAccount.CreateCloudBlobClient().GetContainerReference(defaultContainerName);
var blob = container.GetBlockBlobReference("code.txt");
blob.FetchAttributes();
long blobTotalLength = blob.Properties.Length;
long chunkLength = 10 * 1024; //divide blob file into each file with 10KB in size
for (long i = 0; i <= blobTotalLength; i += chunkLength)
{

    long startRange = i;
    long endRange = (i + chunkLength) > blobTotalLength ? blobTotalLength : (i + chunkLength);

    using (var fs = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"resources\\code_[{startRange}]_[{endRange}].txt"), FileMode.Create))
    {
        Console.WriteLine($"\nParallelDownloadBlob from range [{startRange}] to [{endRange}] start...");
        Stopwatch sp = new Stopwatch();
        sp.Start();

        ParallelDownloadBlob(fs, blob, startRange, endRange);
        sp.Stop();
        Console.WriteLine($"download done, time cost:{sp.ElapsedMilliseconds / 1000.0}s");
    }
}

RESULT

UPDATE:

Based on your requirement, I recommend that you could download your blob into a single file, then leverage LumenWorks.Framework.IO to read your large file records line by line, then check the byte size you have read and save into a new csv file with the size up to 100MB. Here is a code snippet, you could refer to it:

using (CsvReader csv = new CsvReader(new StreamReader("data.csv"), true))
{
    int fieldCount = csv.FieldCount;
    string[] headers = csv.GetFieldHeaders();
    while (csv.ReadNextRecord())
    {
        for (int i = 0; i < fieldCount; i++)
            Console.Write(string.Format("{0} = {1};",
                          headers[i],
                          csv[i] == null ? "MISSING" : csv[i]));
        //TODO:
        //1.Read the current record, check the total bytes you have read;
        //2.Create a new csv file if the current total bytes up to 100MB, then save the current record to the current CSV file.
    }
}

Additionally, you could refer to A Fast CSV Reader and CsvHelper for more details.

UPDATE2

Code sample for breaking large CSV file into small CSV file with the fixed bytes, I used CsvHelper 2.16.3 for the following code snippet, you could refer to it:

string[] headers = new string[0];
using (var sr = new StreamReader(@"C:\Users\v-brucch\Desktop\BlobHourMetrics.csv")) //83.9KB
{
    using (CsvHelper.CsvReader csvReader = new CsvHelper.CsvReader(sr,
        new CsvHelper.Configuration.CsvConfiguration()
        {
            Delimiter = ",",
            Encoding = Encoding.UTF8
        }))
    {
        //check header
        if (csvReader.ReadHeader())
        {
            headers = csvReader.FieldHeaders;
        }

        TextWriter writer = null;
        CsvWriter csvWriter = null;
        long readBytesCount = 0;
        long chunkSize = 30 * 1024; //divide CSV file into each CSV file with byte size up to 30KB

        while (csvReader.Read())
        {
            var curRecord = csvReader.CurrentRecord;
            var curRecordByteCount = curRecord.Sum(r => Encoding.UTF8.GetByteCount(r)) + headers.Count() + 1;
            readBytesCount += curRecordByteCount;

            //check bytes you have read
            if (writer == null || readBytesCount > chunkSize)
            {
                readBytesCount = curRecordByteCount + headers.Sum(h => Encoding.UTF8.GetByteCount(h)) + headers.Count() + 1;
                if (writer != null)
                {
                    writer.Flush();
                    writer.Close();
                }
                string fileName = $"BlobHourMetrics_{Guid.NewGuid()}.csv";
                writer = new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName), true);
                csvWriter = new CsvWriter(writer);
                csvWriter.Configuration.Encoding = Encoding.UTF8;
                //output header field
                foreach (var header in headers)
                {
                    csvWriter.WriteField(header);
                }
                csvWriter.NextRecord();
            }
            //output record field
            foreach (var field in curRecord)
            {
                csvWriter.WriteField(field);
            }
            csvWriter.NextRecord();
        }
        if (writer != null)
        {
            writer.Flush();
            writer.Close();
        }
    }
}

RESULT


问:
Background Uploading Task
I have been stucked in this from last week. But I did not get the solution.

I want to access all photos from camera roll and want to save all photos on remote server with the help of NSURLSessionUploadTask. For this I am using following code:

```<code> NSString *boundary = @"----WebKitFormBoundarycC4YiaUFwM44F6rT";
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.jpeg\"\r\n", @"upload",self.pictureName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:self.imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPMaximumConnectionsPerHost = 1;
config.HTTPAdditionalHeaders = @{
                                 @"api-key"       : @"55e76dc4bbae25b066cb",
                                 @"Accept"        : @"application/json",
                                 @"Content-Type"  : [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]
                                 };
NSURLSession *upLoadSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURL *url = self.uploadURL;
NSLog(@"URL=%@",url);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"PUT"];
[request setHTTPBody:body];

// 3

self.uploadTask = [upLoadSession uploadTaskWithRequest:request fromData:nil];
// self.uploadTask = [upLoadSession uploadTaskWithRequest:request fromFile:tmpFileUrl];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

// 5
[_uploadTask resume];
</code>```

All thing is working fine in foreground. But as I enter in background, It stop working. Where is the problem?
What I will have to do for uploading images in background using NSURLSessionUploadTask?

答:
For upload task to work in background, you have to use uploadTaskWithRequest:fromFile: instead of uploadTaskWithRequest:fromData:

If you use NSData to supply the files, it will work while the app is active and will stop once the app is in background.

Title: Background Uploading Task

Body:
I have been stucked in this from last week. But I did not get the solution.

I want to access all photos from camera roll and want to save all photos on remote server with the help of NSURLSessionUploadTask. For this I am using following code:

 NSString *boundary = @"----WebKitFormBoundarycC4YiaUFwM44F6rT";
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.jpeg\"\r\n", @"upload",self.pictureName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:self.imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPMaximumConnectionsPerHost = 1;
config.HTTPAdditionalHeaders = @{
                                 @"api-key"       : @"55e76dc4bbae25b066cb",
                                 @"Accept"        : @"application/json",
                                 @"Content-Type"  : [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]
                                 };
NSURLSession *upLoadSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURL *url = self.uploadURL;
NSLog(@"URL=%@",url);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"PUT"];
[request setHTTPBody:body];

// 3

self.uploadTask = [upLoadSession uploadTaskWithRequest:request fromData:nil];
// self.uploadTask = [upLoadSession uploadTaskWithRequest:request fromFile:tmpFileUrl];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

// 5
[_uploadTask resume];

All thing is working fine in foreground. But as I enter in background, It stop working. Where is the problem?
What I will have to do for uploading images in background using NSURLSessionUploadTask?


问:
Force sorting json in PHP
How can I sort label in order:

```<code>1080p
720p
480p
360p
</code>```

I've tried all Sorting Arrays in PHP documentation and some another "User Defined" sorting functions, but no luck, it shows completely random, not in order.

My original json:

```<code>[{"file":"***","label":"360p","default":"true","type":"video\/mp4"},
{"file":"***","label":"720p","type":"video\/mp4"},
{"file":"***","label":"1080p","type":"video\/mp4"},
{"file":"***","label":"480p","type":"video\/mp4"}]
</code>```

答:
First you must decode the JSON string using json_decode.

Second sort the decoded array using usort.

```<code><?php
$array = json_decode($json);
usort($array, function ($a, $b) {
    $valueA = (int) $a->label;
    $valueB = (int) $b->label;
    if ($valueA == $valueB) {
        return 0;
    }
    return ($valueA < $valueB) ? -1 : 1;
});
</code>```

Title: Force sorting json in PHP

Body:
How can I sort label in order:

1080p
720p
480p
360p

I've tried all Sorting Arrays in PHP documentation and some another "User Defined" sorting functions, but no luck, it shows completely random, not in order.

My original json:

[{"file":"***","label":"360p","default":"true","type":"video\/mp4"},
{"file":"***","label":"720p","type":"video\/mp4"},
{"file":"***","label":"1080p","type":"video\/mp4"},
{"file":"***","label":"480p","type":"video\/mp4"}]

Body:
First you must decode the JSON string using json_decode.

Second sort the decoded array using usort.

<?php
$array = json_decode($json);
usort($array, function ($a, $b) {
    $valueA = (int) $a->label;
    $valueB = (int) $b->label;
    if ($valueA == $valueB) {
        return 0;
    }
    return ($valueA < $valueB) ? -1 : 1;
});


问:
Using Spark and R for trending detection in time series
I am new to both R and to Spark, but I am trying to create a scalable R application to detect increasing/decreasing query executed by users.

I have a Spark DataFrame containing data in the following format:

```<code>+-------+------------------------+-------------------------+
| user  |         query          |       query_time        |
+-------+------------------------+-------------------------+
| user1 | Hp tablet              | 2011-08-21T11:07:57.346 |
| user2 | Hp tablet              | 2011-08-21T22:22:32.599 |
| user3 | Hp tablet              | 2011-08-22T19:08:57.412 |
| user4 | hp laptop              | 2011-09-05T15:33:31.489 |
| user5 | Samsung LCD 550        | 2011-09-01T10:28:33.547 |
| user6 | memory stick           | 2011-09-06T17:15:42.852 |
| user7 | Castle                 | 2011-08-28T22:06:37.618 |
+-------+------------------------+-------------------------+
</code>```

This dataset has hundreds of thousand of rows. I need to be able to visualise somehow that, for example, "hp tablet" is trending up.

I have looked at some libraries (e.g. Breakout Detection, Anomaly Detection and this question) that could help me achieve this, but I do not know if they play well with Spark. And if they do, I couldn't find any examples on how to go about the programming.

I'm using R version 3.4.0 and SparkR version 2.1.0, running on a Zeppelin Notebook.

Does anyone have any ideas? I am also open to any other approaches.
Thank you!

Body:
I am new to both R and to Spark, but I am trying to create a scalable R application to detect increasing/decreasing query executed by users.

I have a Spark DataFrame containing data in the following format:

+-------+------------------------+-------------------------+
| user  |         query          |       query_time        |
+-------+------------------------+-------------------------+
| user1 | Hp tablet              | 2011-08-21T11:07:57.346 |
| user2 | Hp tablet              | 2011-08-21T22:22:32.599 |
| user3 | Hp tablet              | 2011-08-22T19:08:57.412 |
| user4 | hp laptop              | 2011-09-05T15:33:31.489 |
| user5 | Samsung LCD 550        | 2011-09-01T10:28:33.547 |
| user6 | memory stick           | 2011-09-06T17:15:42.852 |
| user7 | Castle                 | 2011-08-28T22:06:37.618 |
+-------+------------------------+-------------------------+

This dataset has hundreds of thousand of rows. I need to be able to visualise somehow that, for example, "hp tablet" is trending up.

I have looked at some libraries (e.g. Breakout Detection, Anomaly Detection and this question) that could help me achieve this, but I do not know if they play well with Spark. And if they do, I couldn't find any examples on how to go about the programming.

I'm using R version 3.4.0 and SparkR version 2.1.0, running on a Zeppelin Notebook.

Does anyone have any ideas? I am also open to any other approaches.
Thank you!

Body:
%r
#created a sparkR dataframe
df_query <- createDataFrame(sqlContext, data.frame(query = c("Hp tablet","Hp tablet","Hp tablet","hp laptop", "Samsung LCD 550 "),
query_time = c("2011-08-21T11:07:57.346","2011-08-21T22:22:32.599","2011-08-22T19:08:57.412","2011-09-05T15:33:31.489","2011-09-01T10:28:33.547")))

#remove T as its not a timestamp format = "yyyy-MM-dd HH:mm:ss"
df_query_1 <- select(df_query, df_query$query, regexp_replace(df_query$query_time, '(T)', ' '))
+----------------+--------------------------------+
|           query|regexp_replace(query_time,(T), )|
+----------------+--------------------------------+
|       Hp tablet|            2011-08-21 11:07:...|
|       Hp tablet|            2011-08-21 22:22:...|
|       Hp tablet|            2011-08-22 19:08:...|
|       hp laptop|            2011-09-05 15:33:...|
|Samsung LCD 550 |            2011-09-01 10:28:...|
+----------------+--------------------------------+

df_query_1 <-  rename(df_query_1, query_time=df_query_1[[2]])

#registering temp table:
registerTempTable(df_query_1, "temp_query")

Visualizing from temp table created above:

%sql
select * from temp_query

screen 1

screen 2: visualize as bar graph


问:
Is there a way to dump a stream from the debugger in VS
I'm using VS 2010 and am working with a lot of streams in C# in my current project. I've written some stream dump utilities for writing out certain types of streams for debugging purposes, but I seem to keep stumbling across times when I am debugging and need to look into the stream I am debugging over, but I didn't put my dump calls in there. It seems like I should be able to dump the stream somehow just using VS or maybe tell it to call one of my dump methods on a stream in the debugger. Is there a wy to do this?

The streams I am working with have some text describing a blob of data and then the bytes of the blob, so looking at the description is useful. My dump methods typically just dump that information out and then skip the blobs.

答:
If you have binary data in the stream you can try dumping it into a file using the following lines in the immediate window:

```<code>var lastPos = stream.Position;
stream.Seek(0, SeekOrigin.Begin)
File.WriteAllBytes("filepath.bin", new BinaryReader(stream).ReadBytes((int)stream.Length))
stream.Seek(lastPos, SeekOrigin.Begin)
</code>```

The stream obviously has to be seekable to prevent the side effects of changing the position of the stream when dumping it (reverted in the last line).

If the stream doesn't have the Length property you can use a similar solution to the one done here:

```<code>var lastPos = stream.Position;
var ms = new MemoryStream();
stream.Seek(0, SeekOrigin.Begin)
stream.CopyTo(ms)
File.WriteAllBytes("filepath.bin", ms.ToArray())
stream.Seek(lastPos, SeekOrigin.Begin)
</code>```

Body:
If you have binary data in the stream you can try dumping it into a file using the following lines in the immediate window:

var lastPos = stream.Position;
stream.Seek(0, SeekOrigin.Begin)
File.WriteAllBytes("filepath.bin", new BinaryReader(stream).ReadBytes((int)stream.Length))
stream.Seek(lastPos, SeekOrigin.Begin)

The stream obviously has to be seekable to prevent the side effects of changing the position of the stream when dumping it (reverted in the last line).

If the stream doesn't have the Length property you can use a similar solution to the one done here:

var lastPos = stream.Position;
var ms = new MemoryStream();
stream.Seek(0, SeekOrigin.Begin)
stream.CopyTo(ms)
File.WriteAllBytes("filepath.bin", ms.ToArray())
stream.Seek(lastPos, SeekOrigin.Begin)


问:
My Scannerclass doesn't scan the String - but why?
We received an exercise at college about unicode and ASCII and chars and so on. One part of the exercise is to find a way to read the users input in console that have to be a char and give back the ASCII and Unicode.

Quite easy I think, but my scanner won't scan. Because there's no .nextChar method for the scanner. I was used to use the String method (scanner.nextLine). In the next step, I turned the singlechar-String to a char with char ... = s.charAt and from there I wanted to get the hex and ASCII. Whatever I do my Scanner wont scan the String. Here's the code:

```<code>do{

    System.out.println("Geben Sie ein Zeichen ein um den dazugehoerigen ASCII- und Unicode anzuzeigen");
    input = scan.nextLine();

} while(input.length() >= 2 & input.length() < 1);

zeichen = input.charAt(0);

i = (int) zeichen;

System.out.println("Sie haben " + zeichen + " gewählt.\nDer dazugehoerige ASCII-Code ist " + i + "\nDer dazugehoerige Unicode ist " + (buffer.toString()+ Integer.toHexString(i)));
</code>```

答:
I agree with all the previous comments.
You had to add further code, so we could have checked your Scanner (is it initialized with System.in ?) and further things.

Do you only have to regard single-char inputs?
Otherwise, a for-loop, where every char in the string is changed to ASCII and UNICODE would make more sense to me; if you have only single-char inputs I would recommend an error statement or an exeption so the user knows about his input mistake!

And finally, if you name your variables in German (which is not bad), do it with all of them, cause otherwise one gets confused a little! I do this mistake myself and sometimes loose track of my variables!

Here is one example of the for-loop I talked about:

```<code>    String input = "";
    Scanner scan = new Scanner(System.in);
    char zeichen = ' ';

    System.out.println("Geben Sie ein Zeichen ein");
    input = scan.nextLine();

    for(int a=0; a<input.length();a++)
    {
        zeichen = input.charAt(a);
        int i = (int) zeichen;
        System.out.println("Sie haben " + zeichen + " Ascii: " + i + " Unicode: "); //this line has been slightly simplified
    }
</code>```

Body:
We received an exercise at college about unicode and ASCII and chars and so on. One part of the exercise is to find a way to read the users input in console that have to be a char and give back the ASCII and Unicode.

Quite easy I think, but my scanner won't scan. Because there's no .nextChar method for the scanner. I was used to use the String method (scanner.nextLine). In the next step, I turned the singlechar-String to a char with char ... = s.charAt and from there I wanted to get the hex and ASCII. Whatever I do my Scanner wont scan the String. Here's the code:

do{

    System.out.println("Geben Sie ein Zeichen ein um den dazugehoerigen ASCII- und Unicode anzuzeigen");
    input = scan.nextLine();

} while(input.length() >= 2 & input.length() < 1);

zeichen = input.charAt(0);

i = (int) zeichen;

System.out.println("Sie haben " + zeichen + " gewählt.\nDer dazugehoerige ASCII-Code ist " + i + "\nDer dazugehoerige Unicode ist " + (buffer.toString()+ Integer.toHexString(i)));

Body:
I agree with all the previous comments.
You had to add further code, so we could have checked your Scanner (is it initialized with System.in ?) and further things.

Do you only have to regard single-char inputs?
Otherwise, a for-loop, where every char in the string is changed to ASCII and UNICODE would make more sense to me; if you have only single-char inputs I would recommend an error statement or an exeption so the user knows about his input mistake!

And finally, if you name your variables in German (which is not bad), do it with all of them, cause otherwise one gets confused a little! I do this mistake myself and sometimes loose track of my variables!

Here is one example of the for-loop I talked about:

    String input = "";
    Scanner scan = new Scanner(System.in);
    char zeichen = ' ';

    System.out.println("Geben Sie ein Zeichen ein");
    input = scan.nextLine();

    for(int a=0; a<input.length();a++)
    {
        zeichen = input.charAt(a);
        int i = (int) zeichen;
        System.out.println("Sie haben " + zeichen + " Ascii: " + i + " Unicode: "); //this line has been slightly simplified
    }


问:
Adding fragment destroys activity
I have an Activity with a container being a FrameLayout. I need to add a fragment to that container, but doing so throws an IllegalStateException, destroying my Activity.

This is my container in the activity layout:

```<code><FrameLayout
    android:id="@+id/seeMoreContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>
</code>```

This is how I add the fragment to the activity

```<code>PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
Bundle bundle = new Bundle();
bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
placesSeeMoreFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer,
placesSeeMoreFragment).commit();
</code>```

And this is the logcat

```<code>java.lang.IllegalStateException: Activity has been destroyed
                                                                   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
                                                                   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
                                                                   at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)
                                                                   at net.ilb.Activities.PlacesActivity.openPlaceSeeMore(PlacesActivity.java:140)
</code>```

What am I doing wrong here?

EDIT:

I add the fragment to the activity from a public method, which I call from onItemClickListener of a ListView

This is the whole method

```<code>public void openPlaceSeeMore(int poiID){
    PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
    Bundle bundle = new Bundle();
    bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
    placesSeeMoreFragment.setArguments(bundle);
    getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer, placesSeeMoreFragment).commit();
}
</code>```

And this is how the method is called

```<code>mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PlacesActivity placesActivity = new PlacesActivity();
            placesActivity.openPlaceSeeMore(poi.getId());
        }
    });
</code>```

答:
try this ,</p>

```<code>    PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
    Bundle bundle = new Bundle();
    bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
    placesSeeMoreFragment.setArguments(bundle);
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction=manager.beginTransaction();
                    transaction.add(R.id.seeMoreContainer, placesSeeMoreFragment );
    transaction.commit();
</code>```

Title: Adding fragment destroys activity

Body:
I have an Activity with a container being a FrameLayout. I need to add a fragment to that container, but doing so throws an IllegalStateException, destroying my Activity.

This is my container in the activity layout:

<FrameLayout
    android:id="@+id/seeMoreContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

This is how I add the fragment to the activity

PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
Bundle bundle = new Bundle();
bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
placesSeeMoreFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer,
placesSeeMoreFragment).commit();

And this is the logcat

java.lang.IllegalStateException: Activity has been destroyed
                                                                   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
                                                                   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
                                                                   at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)
                                                                   at net.ilb.Activities.PlacesActivity.openPlaceSeeMore(PlacesActivity.java:140)

What am I doing wrong here?

EDIT:

I add the fragment to the activity from a public method, which I call from onItemClickListener of a ListView

This is the whole method

public void openPlaceSeeMore(int poiID){
    PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
    Bundle bundle = new Bundle();
    bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
    placesSeeMoreFragment.setArguments(bundle);
    getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer, placesSeeMoreFragment).commit();
}

And this is how the method is called

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PlacesActivity placesActivity = new PlacesActivity();
            placesActivity.openPlaceSeeMore(poi.getId());
        }
    });

Body:
try this ,

    PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
    Bundle bundle = new Bundle();
    bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
    placesSeeMoreFragment.setArguments(bundle);
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction=manager.beginTransaction();
                    transaction.add(R.id.seeMoreContainer, placesSeeMoreFragment );
    transaction.commit();


问:
Loading animation doesn't work in IE
I want show loading div while my page fully loaded. CSS rotate features work  perfectly on Google Chrome but it is not working IE.

My CSS code and html code is below.

/*Transparent*/
.tr_loading {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0,0,0,.5);
}
.tr_loading-wheel {
    width: 20px;
    height: 20px;
    margin-top: -40px;
    margin-left: -40px;

    position: absolute;
    top: 50%;
    left: 50%;

    border-width: 30px;
    border-radius: 50%;
    -webkit-animation: spin 1s linear infinite;
    -o-animation: spin 1s linear infinite;
    animation:spin 1s linear infinite;
}
.style-2 .tr_loading-wheel {
    border-style: double;
    border-color: #ccc transparent;
}
@-webkit-keyframes spin {
    0% {
        -webkit-transform: rotate(0deg);
    }
    100% {
        -webkit-transform: rotate(-360deg);
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tr_loading style-2">
    <div class="tr_loading-wheel"></div>
</div></code>```

答:
Following is an example of vendor prefixed code and is not supported by all browsers.

```<code>@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(-360deg);
  }
}
</code>```

Use standard variant i.e:

```<code>@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(-360deg);
  }
}
</code>```

See detailed documentation for @keyframes on MDN.

Working Demo:

/*Transparent*/
.tr_loading {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0,0,0,.5);
}
.tr_loading-wheel {
  width: 20px;
  height: 20px;
  margin-top: -40px;
  margin-left: -40px;

  position: absolute;
  top: 50%;
  left: 50%;

  border-width: 30px;
  border-radius: 50%;
  -webkit-animation: spin 1s linear infinite;
  -o-animation: spin 1s linear infinite;
  animation:spin 1s linear infinite;
}
.style-2 .tr_loading-wheel {
  border-style: double;
  border-color: #ccc transparent;
}
@keyframes spin {
  0% {
      transform: rotate(0deg);
  }
  100% {
      transform: rotate(-360deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tr_loading style-2">
    <div class="tr_loading-wheel"></div>
</div></code>```

Title: Loading animation doesn't work in IE

Body:
Following is an example of vendor prefixed code and is not supported by all browsers.

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(-360deg);
  }
}

Use standard variant i.e:

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(-360deg);
  }
}

See detailed documentation for @keyframes on MDN.

Working Demo:

/*Transparent*/
.tr_loading {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0,0,0,.5);
}
.tr_loading-wheel {
  width: 20px;
  height: 20px;
  margin-top: -40px;
  margin-left: -40px;

  position: absolute;
  top: 50%;
  left: 50%;

  border-width: 30px;
  border-radius: 50%;
  -webkit-animation: spin 1s linear infinite;
  -o-animation: spin 1s linear infinite;
  animation:spin 1s linear infinite;
}
.style-2 .tr_loading-wheel {
  border-style: double;
  border-color: #ccc transparent;
}
@keyframes spin {
  0% {
      transform: rotate(0deg);
  }
  100% {
      transform: rotate(-360deg);
  }
}

<div class="tr_loading style-2">
    <div class="tr_loading-wheel"></div>
</div>


问:
[C++]Would this be a valid approach for a 'sleep' function in a thread?
I would like to implement a sleep() function in my thread class, but I don't know if this is a valid/proper way to do it.
This is my entire thread class (thread.h):

```<code>#include <process.h>

struct RUNNABLE{
    virtual void run() = 0;
};

class thread{
public:
    void start(void *ptr){
        DWORD thr_id;
        HANDLE thr_handl = (HANDLE)_beginthreadex(NULL, 0, thread_proc, ptr, 0, (unsigned int*)&thr_id);
    }

    void sleep(int sleep_time, bool alertable){
        SleepEx(sleep_time, alertable);
    }
private:
    static unsigned int __stdcall thread_proc(void *param){
        ((RUNNABLE*)param)->run();
        _endthreadex(0);
        return 0;
    }
};
</code>```

And as you're probably able to sort out, this is my sleep() function:

```<code>void sleep(int sleep_time, bool alertable){
    SleepEx(sleep_time, alertable);
}
</code>```

But will this make the actual thread contained inside this thread instance sleep for the specified amount of milliseconds?

Best regards,
Benjamin :).

EDIT:

So according to atzz, I could define the sleep function as a static member function, and have that call ::SleepEx(), and that would allow me to call it like this:

```<code>class test : RUNNABLE{
    virtual void run(){
        printf("hi");
        thread::sleep(1000, false);
    }
};
</code>```

and then that'll cause the thread executing the 'test' runnable to sleep 1000 milliseonds?

答:
Yes it will -- provided that it's called from that thread (i.e. from within thread::run()).
Due to this, I'd recommend making sleep() a protected member function.

Or, as an alternative, make it a static method, with semantics of thread::sleep() being a service that pauses calling thread (this approach is used, e.g., in Java standard library).

It is not possible to make an other than calling thread sleep, because the thread can be in the middle of something at that moment.

Body:
I would like to implement a sleep() function in my thread class, but I don't know if this is a valid/proper way to do it.
This is my entire thread class (thread.h):

#include <process.h>

struct RUNNABLE{
    virtual void run() = 0;
};

class thread{
public:
    void start(void *ptr){
        DWORD thr_id;
        HANDLE thr_handl = (HANDLE)_beginthreadex(NULL, 0, thread_proc, ptr, 0, (unsigned int*)&thr_id);
    }

    void sleep(int sleep_time, bool alertable){
        SleepEx(sleep_time, alertable);
    }
private:
    static unsigned int __stdcall thread_proc(void *param){
        ((RUNNABLE*)param)->run();
        _endthreadex(0);
        return 0;
    }
};

And as you're probably able to sort out, this is my sleep() function:

void sleep(int sleep_time, bool alertable){
    SleepEx(sleep_time, alertable);
}

But will this make the actual thread contained inside this thread instance sleep for the specified amount of milliseconds?

Best regards,
Benjamin :).

EDIT:

So according to atzz, I could define the sleep function as a static member function, and have that call ::SleepEx(), and that would allow me to call it like this:

class test : RUNNABLE{
    virtual void run(){
        printf("hi");
        thread::sleep(1000, false);
    }
};

and then that'll cause the thread executing the 'test' runnable to sleep 1000 milliseonds?


问:
Looped checks in Ansible
For example, I have a list like this:

```<code>vms:
  - name: "vm1"
    desc: "first"
    network:
      ip: "10.0.0.10"
      prefix: "16"
  - name: "vm2"
    desc: "second"
    network:
      ip: "10.0.0.11"
      prefix: "16"
</code>```

I want to create VMs with OpenNebula in a loop with checking if there is already created VM. I've made a check task:

```<code>- name: Check if VM "{{ item.name }}" already created
  become_user: oneadmin
  ignore_errors: yes
  shell: onevm list --csv | grep "{{ item.name }}"
  register: created_vms
  with_items:
    - "{{ vms }}"
</code>```

but I don't know how to make "Create VM" task correctly with loop + 'when' statement.

答:
Thanks to @Konstantin Suvorov for his comment!
Here is an answer for my case:</p>

```<code>- name: Check if VMs already created
  become_user: oneadmin
  ignore_errors: yes
  shell: onevm list --csv | grep "{{ item.name }}"
  register: created_vms
  with_items: "{{ vms }}"

- name: Create VMs
  become_user: oneadmin
  command: onevm create --name "{{ item.1.name }}"
  when: item.0|failed
  with_together:
    - "{{ created_vms.results }}"
    - "{{ vms }}"
</code>```

Title: Looped checks in Ansible

Body:
For example, I have a list like this:

vms:
  - name: "vm1"
    desc: "first"
    network:
      ip: "10.0.0.10"
      prefix: "16"
  - name: "vm2"
    desc: "second"
    network:
      ip: "10.0.0.11"
      prefix: "16"

I want to create VMs with OpenNebula in a loop with checking if there is already created VM. I've made a check task:

- name: Check if VM "{{ item.name }}" already created
  become_user: oneadmin
  ignore_errors: yes
  shell: onevm list --csv | grep "{{ item.name }}"
  register: created_vms
  with_items:
    - "{{ vms }}"

but I don't know how to make "Create VM" task correctly with loop + 'when' statement.

Body:
Thanks to @Konstantin Suvorov for his comment!
Here is an answer for my case:

- name: Check if VMs already created
  become_user: oneadmin
  ignore_errors: yes
  shell: onevm list --csv | grep "{{ item.name }}"
  register: created_vms
  with_items: "{{ vms }}"

- name: Create VMs
  become_user: oneadmin
  command: onevm create --name "{{ item.1.name }}"
  when: item.0|failed
  with_together:
    - "{{ created_vms.results }}"
    - "{{ vms }}"


问:
How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?
Wireless debugging was recently added as a feature in Xcode 9, iOS 11, and tvOS 11. Apple TV 4K doesn't have a USB port, so it requires wireless debugging. How do you perform this wireless debugging in Xcode?</p>

答:
In the new Xcode9-beta, we can use wireless debugging as said by Apple:

Cut the Cord

  Choose any of your iOS or tvOS devices on the local network to install, run, and debug your apps – without a USB cord plugged into your Mac. Simply click the ‘Connect via Network’ checkbox the first time you use a new iOS device, and that device will be available over the network from that point forward. Wireless development also works in other apps, including Instruments, Accessibility Inspector, Quicktime Player, and Console.

Try this!

If facing disconnection issues, try this:

Workaround: Enable airplane mode on your device for 10 seconds and then disable airplane mode to re-establish your connection


问:
Error when trying to get full list of recent search suggestion from SearchRecentSuggestionsProvider
Want to do:
Get a list of recent search suggestions and then show in listview, below is code, PS. already have some suggestion word in database.

```<code>......
private String string_uri = "content://com.xyz.music_search_provider/" + SearchManager.SUGGEST_URI_PATH_QUERY;
private Uri uri=Uri.parse(string_uri);
private String[] projection={SearchManager.SUGGEST_COLUMN_QUERY};
.....
cursor=getContentResolver().query(uri,projection,null,null,null);
search_history_list=(ListView)findViewById(R.id.search_history_list);
simpleCursorAdapter=new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,cursor,
            new String[] { SearchManager.SUGGEST_COLUMN_QUERY },new int[]{android.R.id.text1},SearchManager.FLAG_QUERY_REFINEMENT);
search_history_list.setAdapter(simpleCursorAdapter);
</code>```

And custom search provider extend SearchRecentSuggestionsProvider

```<code>public class MusicSearchProvider extends SearchRecentSuggestionsProvider {

public MusicSearchProvider() {
    setupSuggestions("com.xyz.music_search_provider",DATABASE_MODE_QUERIES|DATABASE_MODE_2LINES);
   }
}
</code>```

Issue is, when runtime, error shows

```<code>cursor=getContentResolver().query(uri,projection,null,null,null);
Caused by: java.lang.NullPointerException: Attempt to read from null array
</code>```

Changed like below,

```<code>cursor=getContentResolver().query(uri,null,null,null,null);
</code>```

error is same.
But change like,

```<code>cursor=getContentResolver().query(uri,null,null,new String[]{query},null);
</code>```

No error showing, but only one result is showing in the listview.
Anyone know why and how to fix this, please help me through.

答:
Find the solution, but be still not much clear, changed like below,

```<code>cursor=getContentResolver().query(uri,null,null,new String[]{""},null);
</code>```

Not set selectionArgs as null, but set "" that will show all the results in SearchRecentSuggestionsProvider

Body:
Want to do:
Get a list of recent search suggestions and then show in listview, below is code, PS. already have some suggestion word in database.

......
private String string_uri = "content://com.xyz.music_search_provider/" + SearchManager.SUGGEST_URI_PATH_QUERY;
private Uri uri=Uri.parse(string_uri);
private String[] projection={SearchManager.SUGGEST_COLUMN_QUERY};
.....
cursor=getContentResolver().query(uri,projection,null,null,null);
search_history_list=(ListView)findViewById(R.id.search_history_list);
simpleCursorAdapter=new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,cursor,
            new String[] { SearchManager.SUGGEST_COLUMN_QUERY },new int[]{android.R.id.text1},SearchManager.FLAG_QUERY_REFINEMENT);
search_history_list.setAdapter(simpleCursorAdapter);

And custom search provider extend SearchRecentSuggestionsProvider

public class MusicSearchProvider extends SearchRecentSuggestionsProvider {

public MusicSearchProvider() {
    setupSuggestions("com.xyz.music_search_provider",DATABASE_MODE_QUERIES|DATABASE_MODE_2LINES);
   }
}

Issue is, when runtime, error shows

cursor=getContentResolver().query(uri,projection,null,null,null);
Caused by: java.lang.NullPointerException: Attempt to read from null array

Changed like below,

cursor=getContentResolver().query(uri,null,null,null,null);

error is same.
But change like,

cursor=getContentResolver().query(uri,null,null,new String[]{query},null);

No error showing, but only one result is showing in the listview.
Anyone know why and how to fix this, please help me through.

Body:
Find the solution, but be still not much clear, changed like below,

cursor=getContentResolver().query(uri,null,null,new String[]{""},null);

Not set selectionArgs as null, but set "" that will show all the results in SearchRecentSuggestionsProvider


问:
Javascript Regular Expression allow only one plus (+) sign at start and length of string should not more than 15 character number only
Hello All,

                I want JavaScript regular expression which allow (+) sign once at start as well as whole length of string should not be more than 15 numeric  character  i.e 0 to 9.

答:
Try this:

/^\+\d{0,14}$/ - if yours string overall length should be maximum of 15 characters long
/^\+\d{0,15}$/ - if you want '+' and no more than 15 0-9 characters

You can also experiment on http://regexr.com/


问:
Unable to create web app in azure through Azure Management Library
I have trying to create a web app through fluent Azure Management Library.

I am currently on DreamSpark Subscription.

Here is my program.cs

```<code>static void Main(string[] args)
        {
            // Set some variables...
            string rgName = "numbers1102rg";
            string appName = SdkContext.RandomResourceName("WebApp", 20);

            // Authenticate
            var credentials = SdkContext.AzureCredentialsFactory
                .FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

            var azure = Azure
                .Configure()
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .Authenticate(credentials)
                .WithDefaultSubscription();

            // Create the web app
            Console.WriteLine("Creating Web App...");
            var app = azure.WebApps.Define(appName)
                .WithRegion(Region.USEast)
                .WithNewResourceGroup(rgName)
                .WithNewFreeAppServicePlan()
                .DefineSourceControl()
                .WithPublicGitRepository("https://github.com/Azure-Samples/app-service-web-dotnet-get-started")
                .WithBranch("master")
                .Attach()
                .Create();
            Console.WriteLine("Your web app is live at: https://{0}", app.HostNames.First());

            // Wait for the user
            Console.WriteLine("Press enter to continue...");
            Console.ReadLine();
        }
</code>```

I have also, done the azureauth.properties setup.

Here is the error it throws while creating:

I have also performed steps to be a contributor from here:

https://learn.microsoft.com/en-us/dotnet/azure/dotnet-sdk-azure-get-started?view=azure-dotnet

And the app is a contributor to that resource:

答:
You're getting this error because the user for which access token is fetched doesn't have permission to create a resource (WebApp in your case) in the resource group you're using.

To fix this error, please assign a role (say a Contributor) to that user in the resource group you're using.

Please see this link regarding how you can assign role to a user using Azure Portal: https://learn.microsoft.com/en-us/azure/active-directory/role-based-access-control-configure.

Body:
I have trying to create a web app through fluent Azure Management Library.

I am currently on DreamSpark Subscription.

Here is my program.cs

static void Main(string[] args)
        {
            // Set some variables...
            string rgName = "numbers1102rg";
            string appName = SdkContext.RandomResourceName("WebApp", 20);

            // Authenticate
            var credentials = SdkContext.AzureCredentialsFactory
                .FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

            var azure = Azure
                .Configure()
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .Authenticate(credentials)
                .WithDefaultSubscription();

            // Create the web app
            Console.WriteLine("Creating Web App...");
            var app = azure.WebApps.Define(appName)
                .WithRegion(Region.USEast)
                .WithNewResourceGroup(rgName)
                .WithNewFreeAppServicePlan()
                .DefineSourceControl()
                .WithPublicGitRepository("https://github.com/Azure-Samples/app-service-web-dotnet-get-started")
                .WithBranch("master")
                .Attach()
                .Create();
            Console.WriteLine("Your web app is live at: https://{0}", app.HostNames.First());

            // Wait for the user
            Console.WriteLine("Press enter to continue...");
            Console.ReadLine();
        }

I have also, done the azureauth.properties setup.

Here is the error it throws while creating:

I have also performed steps to be a contributor from here:

https://learn.microsoft.com/en-us/dotnet/azure/dotnet-sdk-azure-get-started?view=azure-dotnet

And the app is a contributor to that resource:


问:
An empty sqlite database takes 74 Mb?

Why?

答: Deleting tables from Database does not decrease its size in Sqlite. Its size will remain same as the maximum size attained yet</p>

Title: An empty sqlite database takes 74 Mb?

Body: Why?


问:
DataTables YajraBox Laravel extension with Eloquent Query String Filtering
im newbie Laravel, im trying to create a data table with YajraBox extension.

Im stuck on ajax controller:

```<code>public function indexData(LotFilters $filters)
    {
       $lots  = Lot::filter($filters)->get();

        return Datatables::of($lots)->make(true);
    }
</code>```

This is my route:

```<code>Route::get('data', 'LotController@indexData');
</code>```

When i go: http://127.0.0.1:8000/data it gives me an error:

Allowed memory size of 134217728 bytes exhausted (tried to allocate
  140673944 bytes)

It think i need to set up a pagination, but i didn't find a example how to do it, maybe you guys can help me?

答: you are making get request which may cause this error. Try to make a post request.</p>

Body:
im newbie Laravel, im trying to create a data table with YajraBox extension.

Im stuck on ajax controller:

public function indexData(LotFilters $filters)
    {
       $lots  = Lot::filter($filters)->get();

        return Datatables::of($lots)->make(true);
    }

This is my route:

Route::get('data', 'LotController@indexData');

When i go: http://127.0.0.1:8000/data it gives me an error:

Allowed memory size of 134217728 bytes exhausted (tried to allocate
  140673944 bytes)

It think i need to set up a pagination, but i didn't find a example how to do it, maybe you guys can help me?


问:
required percentage of column
I have three column a,b,c I want to fill true or false in the 'c' column if the value of 'b' column under or above 10% of 'a' column ............
actually, I want to update column 'b' if the value nearest column a </p>

```<code>a   |  b   |  c
100 | 90   | true
100 | 110  | true
100 | 88   | false
</code>```

<p>I want to generate a query in PostgreSQL </p>

答:
You want to know whether

```<code>b between a * 0.9 and a * 1.1
</code>```

When this is not the case (or so I understand it) you want b to be set to a * 0.9 or a * 1.1:

```<code>update mytable
set b = case when b < a then a * 0.9 else a * 1.1 end
where b not between a * 0.9 and a * 1.1;
</code>```

(These formulas only work for positive values. You'd have to adjust them, if your table also contains negative values.)

Title: required percentage of column

Body:
I have three column a,b,c I want to fill true or false in the 'c' column if the value of 'b' column under or above 10% of 'a' column ............
actually, I want to update column 'b' if the value nearest column a

a   |  b   |  c
100 | 90   | true
100 | 110  | true
100 | 88   | false

I want to generate a query in PostgreSQL

Body:
You want to know whether

b between a * 0.9 and a * 1.1

When this is not the case (or so I understand it) you want b to be set to a * 0.9 or a * 1.1:

update mytable
set b = case when b < a then a * 0.9 else a * 1.1 end
where b not between a * 0.9 and a * 1.1;

(These formulas only work for positive values. You'd have to adjust them, if your table also contains negative values.)


问:
Not able to launch URL from ionic2 Cordova InAppBrowser Plugin
I am using InAppBrowser Plugin for launching a link from my application.But when i do click then it goes to localhost:/URL/..

What am i doing wrong?

INTERNET:
{{navigateUrl}}```
</div>
</div>
</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-html lang-html prettyprint-override"><code> launch(url)
  {
    this.platform.ready().then(()=>{
      cordova.InAppBrowser.open(url,"_system","location=true");
    });
  }</code>```

答:
This is a Cordova plugin, which requires the Cordova platform to be running in order to function.

Try ionic run android (or ios) to test it on a device or emulator instead.

Body:
I am using InAppBrowser Plugin for launching a link from my application.But when i do click then it goes to localhost:/URL/..

What am i doing wrong?

INTERNET:
{{navigateUrl}}

 launch(url)
  {
    this.platform.ready().then(()=>{
      cordova.InAppBrowser.open(url,"_system","location=true");
    });
  }


问:
MongoDB define collection that has an array as document
I'm a newbie to mongodb and I'm trying to create my first database.

This is my scenario: A user can connect to a FTP Location and get/put some files. Each user can have more than one FTP Storage that he can access.

These are the fields required for the user document:

```<code>username: String
password: String
</code>```

And these are the fields required for the ftp document:

```<code>host: String
port: Number
user: String
pass: String
</code>```

And here comes my question...Can I have a single collection that contains both documents mentioned above?

More precisely, I need to know how I can get a record like this and how my database should look...

```<code>{
    "username": "User",
    "password": "test",
    [
      {
        "host": "first-host",
        "port": 21,
        "user": "defined-user",
        "pass": "defined-pass"
      },
      {
        "host": "second-host",
        "port": 21,
        "user": "defined-user",
        "pass": "defined-pass"
      }
    ]
}
</code>```

Not sure if my question is clearly enough, but please let me know if I need to specify additional information to get some answers

答: BSON documents are basically JSON/JS objects (with a few additional types). So, your mongodb document MUST be a valid json/js object. The desired document shape from your question is not valid js object and, as such, is impossible in mongodb.

Body:
I'm a newbie to mongodb and I'm trying to create my first database.

This is my scenario: A user can connect to a FTP Location and get/put some files. Each user can have more than one FTP Storage that he can access.

These are the fields required for the user document:

username: String
password: String

And these are the fields required for the ftp document:

host: String
port: Number
user: String
pass: String

And here comes my question...Can I have a single collection that contains both documents mentioned above?

More precisely, I need to know how I can get a record like this and how my database should look...

{
    "username": "User",
    "password": "test",
    [
      {
        "host": "first-host",
        "port": 21,
        "user": "defined-user",
        "pass": "defined-pass"
      },
      {
        "host": "second-host",
        "port": 21,
        "user": "defined-user",
        "pass": "defined-pass"
      }
    ]
}

Not sure if my question is clearly enough, but please let me know if I need to specify additional information to get some answers


问:
What CSS properties are likely to cause problems in Internet Explorer?
I designed a web page with lot of CSS properties, and when viewing it in IE its alignment is not so proper compared to all other browsers.

For the next time, what are the CSS properties I should take care with in IE?

Thank you.

答: Very nearly everything breaks IE.</p>

Body: Very nearly everything breaks IE.