问:
I have a <List /> with row items of unknown DOM height
Given a react-virtualized List with variable content in each row the DOM height needs to be calculated by a rowHeight function - however since that gets called before the row is rendered I am unsure how to actually get the row height.

The examples given for dynamic List row height basically go off a predefined number in the list item's props which doesn't help.

What I think I want to do is render the row on the page at a default height and then get the overflow height on the DOM and set that as the row height. How can I hook into an afterRowRender function or something like that? I imagine performance would suffer so maybe there is a better way of doing this that I am missing.

答:
Check out the docs on CellMeasurer. You can see it in action here.

Basically you'll be looking for something like this:

```<code>import React from 'react';
import { CellMeasurer, CellMeasurerCache, Grid } from 'react-virtualized';

const cache = new CellMeasurerCache({
  fixedWidth: true,
  minHeight: 50,
});

function rowRenderer ({ index, isScrolling, key, parent, style }) {
  const source // This comes from your list data

  return (
    <CellMeasurer
      cache={cache}
      columnIndex={0}
      key={key}
      parent={parent}
      rowIndex={index}
    >
      {({ measure }) => (
        // 'style' attribute required to position cell (within parent List)
        <div style={style}>
          // Your content here
        </div>
      )}
    </CellMeasurer>
  );
}

function renderList (props) {
  return (
    <List
      {...props}
      deferredMeasurementCache={cache}
      rowHeight={cache.rowHeight}
      rowRenderer={rowRenderer}
    />
  );
}
</code>```

Body:
Check out the docs on CellMeasurer. You can see it in action here.

Basically you'll be looking for something like this:

import React from 'react';
import { CellMeasurer, CellMeasurerCache, Grid } from 'react-virtualized';

const cache = new CellMeasurerCache({
  fixedWidth: true,
  minHeight: 50,
});

function rowRenderer ({ index, isScrolling, key, parent, style }) {
  const source // This comes from your list data

  return (
    <CellMeasurer
      cache={cache}
      columnIndex={0}
      key={key}
      parent={parent}
      rowIndex={index}
    >
      {({ measure }) => (
        // 'style' attribute required to position cell (within parent List)
        <div style={style}>
          // Your content here
        </div>
      )}
    </CellMeasurer>
  );
}

function renderList (props) {
  return (
    <List
      {...props}
      deferredMeasurementCache={cache}
      rowHeight={cache.rowHeight}
      rowRenderer={rowRenderer}
    />
  );
}


来源: stackexchange

问:
Google API: Gmail Service Push Notification (Watch) - User not authorized to perform this action
I am trying to call watch() on a mailbox. I set up a service Iam account, and created a topic and suscription.  I gave my service account full(owner) rights to my topic and subscription. But when calling execute on watch(), I get the error:

```<code>Google.Apis.Requests.RequestError Error sending test message to Cloud PubSub projects/projectid/topics/topicname : User not authorized to perform this action. [403] Errors [ Message[Error sending test message to Cloud PubSub projects/projectid/topics/topicname : User not authorized to perform this action.] Location[ - ] Reason[forbidden] Domain[global] ]
</code>```

Here is the code I use to set up my  service:

```<code> credential = new X509Certificate2("file.p12"), "password", X509KeyStorageFlags.Exportable);
var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = applicationame,
        });

WatchRequest body = new WatchRequest()
    {
        TopicName = "projects/projectid/topics/topicname",
        LabelIds = new[] {"INBOX"}
string userId = "me";
UsersResource.WatchRequest watchRequest = service.Users.Watch(body, userId);
WatchResponse test = watchRequest.Execute();
</code>```

My service account has access to all the following scopes:

```<code>https://mail.google.com/
https://www.googleapis.com/auth/gmail.modify
https://www.googleapis.com/auth/gmail.readonly
https://www.googleapis.com/auth/gmail.metadata
</code>```

Am I missing something here?

EDIT

Added the following scope, but still not success: https://www.googleapis.com/auth/pubsub

EDIT
Also added the following with no success: https://www.googleapis.com/auth/cloud-platform

答:
Just need the scopes:

https://www.googleapis.com/auth/gmail.modify
https://www.googleapis.com/auth/pubsub

In the Cloud Pub/Sub Developer Console you need to grant publish privileges to serviceAccount:gmail-api-push@system.gserviceaccount.com

ContentLicense: CC BY-SA 3.0

Body:
I am trying to call watch() on a mailbox. I set up a service Iam account, and created a topic and suscription.  I gave my service account full(owner) rights to my topic and subscription. But when calling execute on watch(), I get the error:

Google.Apis.Requests.RequestError Error sending test message to Cloud PubSub projects/projectid/topics/topicname : User not authorized to perform this action. [403] Errors [ Message[Error sending test message to Cloud PubSub projects/projectid/topics/topicname : User not authorized to perform this action.] Location[ - ] Reason[forbidden] Domain[global] ]

Here is the code I use to set up my  service:

 credential = new X509Certificate2("file.p12"), "password", X509KeyStorageFlags.Exportable);
var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = applicationame,
        });

WatchRequest body = new WatchRequest()
    {
        TopicName = "projects/projectid/topics/topicname",
        LabelIds = new[] {"INBOX"}
string userId = "me";
UsersResource.WatchRequest watchRequest = service.Users.Watch(body, userId);
WatchResponse test = watchRequest.Execute();

My service account has access to all the following scopes:

https://mail.google.com/
https://www.googleapis.com/auth/gmail.modify
https://www.googleapis.com/auth/gmail.readonly
https://www.googleapis.com/auth/gmail.metadata

Am I missing something here?

EDIT

Added the following scope, but still not success: https://www.googleapis.com/auth/pubsub

EDIT
Also added the following with no success: https://www.googleapis.com/auth/cloud-platform


问:
C++ - structs... function parameter issue
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

It has the following code:

```<code>// Declare a DateStruct variable
DateStruct sToday;

// Initialize it manually
sToday.nMonth = 10;
sToday.nDay = 14;
sToday.nYear = 2020;

// Here is a function to initialize a date
void SetDate(DateStruct &sDate, int nMonth, int nDay, int Year)
{
    sDate.nMonth = nMonth;
    sDate.nDay = nDay;
    sDate.nYear = nYear;
}

// Init our date to the same date using the function
SetDate(sToday, 10, 14, 2020);
</code>```

What is the purpose of the

DateStruct &sDate

parameter in the function signature, especially that I cannot see a use of it in the function body?

Thanks.

答:
It means it will take as a first argument a reference to a DateStruct and that this reference will be called sDate in the function's body.
The sDate reference is then used in each lines of the body:</p>

```<code>sDate.nMonth = nMonth;
sDate.nDay = nDay;
sDate.nYear = nYear;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

It has the following code:

// Declare a DateStruct variable
DateStruct sToday;

// Initialize it manually
sToday.nMonth = 10;
sToday.nDay = 14;
sToday.nYear = 2020;

// Here is a function to initialize a date
void SetDate(DateStruct &sDate, int nMonth, int nDay, int Year)
{
    sDate.nMonth = nMonth;
    sDate.nDay = nDay;
    sDate.nYear = nYear;
}

// Init our date to the same date using the function
SetDate(sToday, 10, 14, 2020);

What is the purpose of the

DateStruct &sDate

parameter in the function signature, especially that I cannot see a use of it in the function body?

Thanks.

Body:
It means it will take as a first argument a reference to a DateStruct and that this reference will be called sDate in the function's body.
The sDate reference is then used in each lines of the body:

sDate.nMonth = nMonth;
sDate.nDay = nDay;
sDate.nYear = nYear;


问:
When clearing another class' attribute in another class why would it not work?
I am writing a function to load a previously saved game in chess using Pygame. I have six classes: main2, GUI2, navigation2, calc, board and pieces. I store the attribute that stores where each chess piece is on the board class like so:

```<code>class board:
def __init__(self,main):
    self.main = main
    self.pieces = self.main.pieces
    self.prv_pos = []
    self.dict = self.pieces.dict
    A = ["bRook","bKnight","bBishop","bQueen","bKing","bBishop","bKnight","bRook"]
    B = ["bPawn","bPawn","bPawn","bPawn","bPawn","bPawn","bPawn","bPawn"]
    C = [0,0,0,0,0,0,0,"wKing"]
    D = [0,0,0,0,0,0,0,0]
    E = [0,0,0,0,"wQueen",0,0,0]
    F = [0,0,0,0,0,0,0,0]
    G = ["wPawn","wPawn","wPawn","wPawn","wPawn","wPawn","wPawn","wPawn"]
    H = ["wRook","wKnight","wBishop","wQueen",0,"wBishop","wKnight","wRook"]
    self.piece_pos= [A,B,C,D,E,F,G,H]
</code>```

I also have a class called main that is passed an instance on each class possible thus all my objects interact with each other through the main class. Thus in my navigation class that hosts the functions to save and load the game I wrote this:

```<code>class navigation:
def __init__(self,GUI):
    self.GUI = GUI
    self.main = self.GUI.main
    self.piece_pos = self.GUI.main.board.piece_pos
    self.GUI.draw_button("save",self.GUI.SQ_DIM*8,self.GUI.SQ_DIM)
    self.GUI.draw_button("load",self.GUI.SQ_DIM*8,self.GUI.SQ_DIM*3)
    self.GUI.draw_button("exit",self.GUI.SQ_DIM*8,self.GUI.SQ_DIM*5)

def game_save(self):
    file = open("Save file.txt","w")
    for line in self.piece_pos:
        for item in line:
            file.write(str(item)+",")
        file.write("\n")
    file.close()

def game_load(self): #WIP
    self.piece_pos = []
    self.GUI.draw_board()
</code>```

As you may notice that the game_load function is pretty empty; that is because I wanted to check that in the self.piece_pos = [] line that the attribute is actually cleared throughout the classes. But when I call the self.GUI.draw_board() function which just draws the current board positions which are stored in piece_pos in the class board the board's appearance in the GUI is the same. I expect an error message in the python shell telling me there is no self.piece_pos[i][j] but it seems to me that the attribute hasn't changed whatsoever.

The function for draw_board() is stored in the class 'GUI'.

```<code>def draw_board(self):
    X = 0
    Y = 0
    Ycounter = False
    sqcounter = False
    #Draw the board
    print("GUI update")
    for i in range(0,8):
        for j in range(0,8):
            print()
            print("Piece at:")
            print(i,j)
            print(self.main.piece_at(i,j))
            pg.draw.rect(self.window, self.sq_colour[i][j],(X,Y,self.SQ_DIM,self.SQ_DIM),0)
            if self.main.piece_at(i,j) == 0:
                print("square empty")
                pass
            else:
                print("square occupied")
                self.window.blit(self.dict[self.main.piece_at(i,j)],(X,Y))

            #Change of X coord
            if X >(self.SQ_DIM*6):
                X = 0
                Ycounter = True
                sqcounter = True
            else:
                X +=(self.SQ_DIM)

            #Change of Y coord
            if Ycounter == True:
                Y +=self.SQ_DIM
                Ycounter = False
            else:
                pass
</code>```

So I have come to the conclusions that I am not understanding something about how to globalize the piece_pos attribute. But I don't know how to solve this conundrum? Any ideas why?

答:
This is because in game_load(), self.piece_pos refers to navigation.piece_pos, while draw_board() uses the object referenced by GUI.main.board.piece_pos.

You're effectively doing this

```<code>a = [5]
b = a
print(a, b)   # prints [5] [5]

# By reassigning `b` you only change what it refers to,
# it doesn't affect what it used to refer to before.
b = []
print(a, b)   # prints [5] []

# Instead, if you make an *in-place* modification, then the underlying
# object will indeed change, as both names refer to the same object.
a = b = [5]
b.append(3)
print(a, b)  # prints [5, 3] [5, 3]
</code>```

If you really want to make a change, it should be

```<code>def game_load(self): #WIP
    self.main.board.piece_pos = []
    self.GUI.draw_board()
</code>```

Since the navigation class is a wrapper of GUI, it might be best to get rid of self.piece_pos and use function calls to get/set the piece positions, e.g.,

```<code>def get_piece_pos(self):
    return self.main.board.piece_pos

def set_piece_pos(self, new_pos):
    self.main.board.piece_pos = new_pos
</code>```

Overall though, I don't see the point of this class. The save/load/exit buttons belong to the GUI, as should the respective save/load functions. I would just integrate this functionality in the GUI class, as this is the object the user interacts with.

Body:
I am writing a function to load a previously saved game in chess using Pygame. I have six classes: main2, GUI2, navigation2, calc, board and pieces. I store the attribute that stores where each chess piece is on the board class like so:

class board:
def __init__(self,main):
    self.main = main
    self.pieces = self.main.pieces
    self.prv_pos = []
    self.dict = self.pieces.dict
    A = ["bRook","bKnight","bBishop","bQueen","bKing","bBishop","bKnight","bRook"]
    B = ["bPawn","bPawn","bPawn","bPawn","bPawn","bPawn","bPawn","bPawn"]
    C = [0,0,0,0,0,0,0,"wKing"]
    D = [0,0,0,0,0,0,0,0]
    E = [0,0,0,0,"wQueen",0,0,0]
    F = [0,0,0,0,0,0,0,0]
    G = ["wPawn","wPawn","wPawn","wPawn","wPawn","wPawn","wPawn","wPawn"]
    H = ["wRook","wKnight","wBishop","wQueen",0,"wBishop","wKnight","wRook"]
    self.piece_pos= [A,B,C,D,E,F,G,H]

I also have a class called main that is passed an instance on each class possible thus all my objects interact with each other through the main class. Thus in my navigation class that hosts the functions to save and load the game I wrote this:

class navigation:
def __init__(self,GUI):
    self.GUI = GUI
    self.main = self.GUI.main
    self.piece_pos = self.GUI.main.board.piece_pos
    self.GUI.draw_button("save",self.GUI.SQ_DIM*8,self.GUI.SQ_DIM)
    self.GUI.draw_button("load",self.GUI.SQ_DIM*8,self.GUI.SQ_DIM*3)
    self.GUI.draw_button("exit",self.GUI.SQ_DIM*8,self.GUI.SQ_DIM*5)

def game_save(self):
    file = open("Save file.txt","w")
    for line in self.piece_pos:
        for item in line:
            file.write(str(item)+",")
        file.write("\n")
    file.close()

def game_load(self): #WIP
    self.piece_pos = []
    self.GUI.draw_board()

As you may notice that the game_load function is pretty empty; that is because I wanted to check that in the self.piece_pos = [] line that the attribute is actually cleared throughout the classes. But when I call the self.GUI.draw_board() function which just draws the current board positions which are stored in piece_pos in the class board the board's appearance in the GUI is the same. I expect an error message in the python shell telling me there is no self.piece_pos[i][j] but it seems to me that the attribute hasn't changed whatsoever.

The function for draw_board() is stored in the class 'GUI'.

def draw_board(self):
    X = 0
    Y = 0
    Ycounter = False
    sqcounter = False
    #Draw the board
    print("GUI update")
    for i in range(0,8):
        for j in range(0,8):
            print()
            print("Piece at:")
            print(i,j)
            print(self.main.piece_at(i,j))
            pg.draw.rect(self.window, self.sq_colour[i][j],(X,Y,self.SQ_DIM,self.SQ_DIM),0)
            if self.main.piece_at(i,j) == 0:
                print("square empty")
                pass
            else:
                print("square occupied")
                self.window.blit(self.dict[self.main.piece_at(i,j)],(X,Y))

            #Change of X coord
            if X >(self.SQ_DIM*6):
                X = 0
                Ycounter = True
                sqcounter = True
            else:
                X +=(self.SQ_DIM)

            #Change of Y coord
            if Ycounter == True:
                Y +=self.SQ_DIM
                Ycounter = False
            else:
                pass

So I have come to the conclusions that I am not understanding something about how to globalize the piece_pos attribute. But I don't know how to solve this conundrum? Any ideas why?

Body:
This is because in game_load(), self.piece_pos refers to navigation.piece_pos, while draw_board() uses the object referenced by GUI.main.board.piece_pos.

You're effectively doing this

a = [5]
b = a
print(a, b)   # prints [5] [5]

# By reassigning `b` you only change what it refers to,
# it doesn't affect what it used to refer to before.
b = []
print(a, b)   # prints [5] []

# Instead, if you make an *in-place* modification, then the underlying
# object will indeed change, as both names refer to the same object.
a = b = [5]
b.append(3)
print(a, b)  # prints [5, 3] [5, 3]

If you really want to make a change, it should be

def game_load(self): #WIP
    self.main.board.piece_pos = []
    self.GUI.draw_board()

Since the navigation class is a wrapper of GUI, it might be best to get rid of self.piece_pos and use function calls to get/set the piece positions, e.g.,

def get_piece_pos(self):
    return self.main.board.piece_pos

def set_piece_pos(self, new_pos):
    self.main.board.piece_pos = new_pos

Overall though, I don't see the point of this class. The save/load/exit buttons belong to the GUI, as should the respective save/load functions. I would just integrate this functionality in the GUI class, as this is the object the user interacts with.


问:
Adding Photos to Array and Displaying to UICollection View error
QUESTION

This code works to set an image to an array but comes up with the following error - 2017-12-06 12:31:21.264812+0000 SmartReceipts[880:172369] [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}

I need to know what this means and if there is a possible fix around it?

```<code>import UIKit

class GalleryController: UICollectionViewController,
                         UIImagePickerControllerDelegate,
                         UINavigationControllerDelegate {

    var Receipts = [UIImage?]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView?.reloadData()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        //self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        self.dismiss(animated: true, completion: nil)
        print(info);
        let newReceipts = info[UIImagePickerControllerEditedImage] as? UIImage
        self.Receipts.append(newReceipts)

        print("Array Contains \(self.Receipts.count) Receipts")
        print(self.Receipts)
        self.collectionView?.reloadData()

        print("completedIfStatement")
        }

    @IBAction func getReceipts(_ sender: Any) {
        print("PlusButtonPressed")

        let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)

        // 2
        let albumAction = UIAlertAction(title: "Album", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            print("PhotosOption")
            self.getFromReceipts()
        })
        let cameraAction = UIAlertAction(title: "Camera", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            print("CameraOption")
            self.getFromCamera()
        })

        //
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
            (alert: UIAlertAction!) -> Void in
            print("Cancel")
        })

        // 4
        optionMenu.addAction(albumAction)
        optionMenu.addAction(cameraAction)
        optionMenu.addAction(cancelAction)

        // 5
        self.present(optionMenu, animated: true, completion: nil)

    }

    func getFromReceipts() {

        print("GetFromReceipts")
        let cameraPicker = UIImagePickerController()
        cameraPicker.delegate = self
        cameraPicker.sourceType = .photoLibrary

        self.present(cameraPicker, animated: true, completion: nil )

    }

    func getFromCamera() {
        print("GetFromCamera")
        let cameraPicker = UIImagePickerController()
        cameraPicker.delegate = self
        cameraPicker.sourceType = .camera

        self.present(cameraPicker, animated: true, completion: nil )

    }

    //Number of Views
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.Receipts.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtindexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Receipts, for: indexPath as IndexPath) as? PhotoCell

        cell?.imageView.image = self.Receipts[indexPath.row]
        return cell!

    }

}
</code>```

答:
The error maybe comes from not requesting the authorization to load an photo from the camera or the photo library. So you need to request for authorization before opening the camera like:

https://developer.apple.com/documentation/photos/phphotolibrary/1620736-requestauthorization

Body:
QUESTION

This code works to set an image to an array but comes up with the following error - 2017-12-06 12:31:21.264812+0000 SmartReceipts[880:172369] [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}

I need to know what this means and if there is a possible fix around it?

import UIKit

class GalleryController: UICollectionViewController,
                         UIImagePickerControllerDelegate,
                         UINavigationControllerDelegate {

    var Receipts = [UIImage?]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView?.reloadData()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        //self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        self.dismiss(animated: true, completion: nil)
        print(info);
        let newReceipts = info[UIImagePickerControllerEditedImage] as? UIImage
        self.Receipts.append(newReceipts)

        print("Array Contains \(self.Receipts.count) Receipts")
        print(self.Receipts)
        self.collectionView?.reloadData()

        print("completedIfStatement")
        }

    @IBAction func getReceipts(_ sender: Any) {
        print("PlusButtonPressed")

        let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)

        // 2
        let albumAction = UIAlertAction(title: "Album", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            print("PhotosOption")
            self.getFromReceipts()
        })
        let cameraAction = UIAlertAction(title: "Camera", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            print("CameraOption")
            self.getFromCamera()
        })

        //
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
            (alert: UIAlertAction!) -> Void in
            print("Cancel")
        })

        // 4
        optionMenu.addAction(albumAction)
        optionMenu.addAction(cameraAction)
        optionMenu.addAction(cancelAction)

        // 5
        self.present(optionMenu, animated: true, completion: nil)

    }

    func getFromReceipts() {

        print("GetFromReceipts")
        let cameraPicker = UIImagePickerController()
        cameraPicker.delegate = self
        cameraPicker.sourceType = .photoLibrary

        self.present(cameraPicker, animated: true, completion: nil )

    }

    func getFromCamera() {
        print("GetFromCamera")
        let cameraPicker = UIImagePickerController()
        cameraPicker.delegate = self
        cameraPicker.sourceType = .camera

        self.present(cameraPicker, animated: true, completion: nil )

    }

    //Number of Views
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.Receipts.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtindexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Receipts, for: indexPath as IndexPath) as? PhotoCell

        cell?.imageView.image = self.Receipts[indexPath.row]
        return cell!

    }

}


问:
Is it possible to use vue-router without a component in vue 2?
I have a very simple page, just a few lines of code and I would like to use vue-router without a vue-component.

I would like to get the string "my-search-query" after the root:

```<code>www.example.com/my-search-query
</code>```

and use it in my main Vue() object. Is this possible?

Thank you!

答:
As tom_h has said you can use window.location.pathname if you just want to get the path name. If you want to be notified when this pathname changes, then first initialize it to your data(){} object and watch it as:

```<code>data () {
  return {
    path: window.location.pathname
  }
},

watch: {
  path (newpath, oldpath) {
    alert('location path just changed from ' + newpath + ' to ' + oldpath )
  }
}
</code>```

Body:
I have a very simple page, just a few lines of code and I would like to use vue-router without a vue-component.

I would like to get the string "my-search-query" after the root:

www.example.com/my-search-query

and use it in my main Vue() object. Is this possible?

Thank you!

Body:
As tom_h has said you can use window.location.pathname if you just want to get the path name. If you want to be notified when this pathname changes, then first initialize it to your data(){} object and watch it as:

data () {
  return {
    path: window.location.pathname
  }
},

watch: {
  path (newpath, oldpath) {
    alert('location path just changed from ' + newpath + ' to ' + oldpath )
  }
}


问:
Intellij - conflicting module versions - how to find source of dependency
I have a groovy class in maven java project. I upgraded the groovy dependency from 2.4.4. to 2.4.11. If I build the project using maven - it works. However, if I build it with IntelliJ - I get this error:

```<code>Information:Groovyc: While compiling MyProject: Conflicting module versions. Module [groovy-jsr223 is loaded in version 2.4.11 and you are trying to load version 2.4.4
java.lang.ExceptionInInitializerError.
</code>```

When I go to project structre -> dependencies, I see: Maven: org.codehaus.groovy:groovy-jsr233:2.4.4.
When I search all my pom.xml fiels for 2.4.4 - there is nothing left - everywhere I have 2.4.11.

I tried rebuilding all with maven, reimporting maven projects in IntelliJ - nothing works.

Where should I look for this dependency? Is there a quick way to track it?

答: I have found a solution - Maven Helper plugin (https://plugins.jetbrains.com/plugin/7179-maven-helper). It adds "Dependency Analyzer" tab to pom files view.</p>

Body:
I have a groovy class in maven java project. I upgraded the groovy dependency from 2.4.4. to 2.4.11. If I build the project using maven - it works. However, if I build it with IntelliJ - I get this error:

Information:Groovyc: While compiling MyProject: Conflicting module versions. Module [groovy-jsr223 is loaded in version 2.4.11 and you are trying to load version 2.4.4
java.lang.ExceptionInInitializerError.

When I go to project structre -> dependencies, I see: Maven: org.codehaus.groovy:groovy-jsr233:2.4.4.
When I search all my pom.xml fiels for 2.4.4 - there is nothing left - everywhere I have 2.4.11.

I tried rebuilding all with maven, reimporting maven projects in IntelliJ - nothing works.

Where should I look for this dependency? Is there a quick way to track it?


问:
iOS Device Enrollment with Self-Developed MDM?
I am in the process of trying to develop a really simple proof-of-concept iOS MDM that will allow for OTA enrollment of iOS devices.  This isn't meant to be some MobileIron replacement or anything.  It's really just a learning exercise.  I am developing my code in Java, with JAX-RS for the RESTful service endpoints.

At this point, I am able to it a URL (http://myhost/enroll) from my iOS that will return an enrollment response to kickoff the device enrollment process.  The response returned looks something like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Inc//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>PayloadContent</key>
        <dict>
            <key>URL</key>
            <string>https://myhost/profile</string>
            <key>DeviceAttributes</key>
            <array>
                <string>UDID</string>
                <string>IMEI</string>
                <string>ICCID</string>
                <string>VERSION</string>
                <string>PRODUCT</string>
            </array>
            <key>Challenge</key>
            <string>MySuperSecureChallenge</string>
        </dict>
        <key>PayloadOrganization</key>
        <string>Example Inc.</string>
        <key>PayloadDisplayName</key>
        <string>Profile Service</string>
        <key>PayloadVersion</key>
        <integer>1</integer>
        <key>PayloadUUID</key>
        <string>fdb376e5-b5bb-4d8c-829e-e90865f990c9</string>
        <key>PayloadIdentifier</key>
        <string>com.example.mobileconfig.profile-service</string>
        <key>PayloadDescription</key>
        <string>Enter device into the Example Inc encrypted profile service</string>
        <key>PayloadType</key>
        <string>Profile Service</string>
    </dict>
</plist>
</code>```

Once my device receives this payload, it takes me to the Settings app and prompts me to install the profile.  When I click "Install", it performs an HTTP POST to another URL (http://myhost/profile) and includes the attributes I requested in the response from /enroll.

My /profile endpoint is able to successfully extract the signed response from my iOS device, which looks something like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>CHALLENGE</key>
        <string>MySuperSecureChallenge</string>
        <key>IMEI</key>
        <string>__MY_IMEI__</string>
        <key>PRODUCT</key>
        <string>iPhone10,4</string>
        <key>UDID</key>
        <string>__MY_UDID__</string>
        <key>VERSION</key>
        <string>15B202</string>
    </dict>
</plist>
</code>```

My question is:  now what??  I've found example payloads like this (from Apple) that show how to do SCEP enrollment.  However, I don't want to do SCEP for this simple proof-of-concept.  Is there something else I can return at this stage?  If so, what should the response contain and look like?  I haven't found any documentation outlining what should be returned by my /profile endpoint if I'm not using SCEP, so I'm a little stuck.

UPDATE:  I found some resources online that imply that I need to either use SCEP or provide a PKCS#12-formatted certificate in the payload.  So, I have updated the return value of the /profile to look something like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Inc//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>PayloadVersion</key>
        <integer>1</integer>
        <key>PayloadType</key>
        <string>Configuration</string>
        <key>PayloadContent</key>
        <array>
            <dict>
                <key>PayloadContent</key>
                <dict>
                    <key>Challenge</key>
                    <string>MyChallengeGoesHere</string>
                </dict>
                <key>PayloadDescription</key>
                <string>Provides device encryption identity</string>
                <key>PayloadUUID</key>
                <string>fd8a6b9e-0fed-406f-9571-8ec98722b713</string>
                <key>PayloadType</key>
                <string>com.apple.security.pkcs12</string>
                <key>PayloadDisplayName</key>
                <string>Cert Test</string>
                <key>PayloadVersion</key>
                <integer>1</integer>
                <key>PayloadOrganization</key>
                <string>Example, Inc.</string>
                <key>PayloadIdentifier</key>
                <string>com.example.profileservice.webclip</string>
                <key>PayloadContent</key>
                <string>__MY_BASE64_ENCODED_PKCS12_CERT__</string>
                <key>Password</key>
                <string>__MY_CERT_PASSWORD__</string>
            </dict>
        </array>
    </dict>
</plist>
</code>```

I'm returning this value back to the client, but when I click Install on my iOS device, I get an error saying:

Profile Installation Failed A connection to the server could not be
  established.

Now, I know that communication isn't an issue, because I see the connection to /profile in my logs and debugger.  Is there something else I'm missing?  Does the profile need to be digitally signed?  If so, what format is it?  Which certificate should I be using to sign it?

答:
After LOTS of trial and error, I have finally figured out what the issue was for this profile.  I was missing a couple of parameters:  PayloadIdentifier and PayloadUUID.  Further, the value for the PayloadContent parameter containing my base64-encoded certificate should be data, not string.  So, my new profile looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Inc//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>PayloadVersion</key>
        <integer>1</integer>
        <key>PayloadType</key>
        <string>Configuration</string>
        <key>PayloadUUID</key>
            <string>9f93912b-5fd2-4455-99fd-13b9a47b4581</string>
            <key>PayloadIdentifier</key>
            <string>org.example.mymdm</string>
        <key>PayloadContent</key>
        <array>
            <dict>
                <key>PayloadType</key>
                <string>com.apple.security.pkcs12</string>
                <key>PayloadUUID</key>
                <string>f78c5002-3907-4f67-b631-d41c44283628</string>
                <key>PayloadVersion</key>
                <integer>1</integer>
                <key>PayloadIdentifier</key>
                <string>com.mymdm.cert</string>
                <key>Password</key>
                <string>__MY_CERT_PASSWORD__</string>
                <key>PayloadContent</key>
                <data>__MY_BASE64_ENCODED_P12__</data>
              </dict>
          </array>
    </dict>
</plist>
</code>```

Once I made these changes, I was able to successfully install the profile on my iOS device.

Body:
I am in the process of trying to develop a really simple proof-of-concept iOS MDM that will allow for OTA enrollment of iOS devices.  This isn't meant to be some MobileIron replacement or anything.  It's really just a learning exercise.  I am developing my code in Java, with JAX-RS for the RESTful service endpoints.

At this point, I am able to it a URL (http://myhost/enroll) from my iOS that will return an enrollment response to kickoff the device enrollment process.  The response returned looks something like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Inc//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>PayloadContent</key>
        <dict>
            <key>URL</key>
            <string>https://myhost/profile</string>
            <key>DeviceAttributes</key>
            <array>
                <string>UDID</string>
                <string>IMEI</string>
                <string>ICCID</string>
                <string>VERSION</string>
                <string>PRODUCT</string>
            </array>
            <key>Challenge</key>
            <string>MySuperSecureChallenge</string>
        </dict>
        <key>PayloadOrganization</key>
        <string>Example Inc.</string>
        <key>PayloadDisplayName</key>
        <string>Profile Service</string>
        <key>PayloadVersion</key>
        <integer>1</integer>
        <key>PayloadUUID</key>
        <string>fdb376e5-b5bb-4d8c-829e-e90865f990c9</string>
        <key>PayloadIdentifier</key>
        <string>com.example.mobileconfig.profile-service</string>
        <key>PayloadDescription</key>
        <string>Enter device into the Example Inc encrypted profile service</string>
        <key>PayloadType</key>
        <string>Profile Service</string>
    </dict>
</plist>

Once my device receives this payload, it takes me to the Settings app and prompts me to install the profile.  When I click "Install", it performs an HTTP POST to another URL (http://myhost/profile) and includes the attributes I requested in the response from /enroll.

My /profile endpoint is able to successfully extract the signed response from my iOS device, which looks something like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>CHALLENGE</key>
        <string>MySuperSecureChallenge</string>
        <key>IMEI</key>
        <string>__MY_IMEI__</string>
        <key>PRODUCT</key>
        <string>iPhone10,4</string>
        <key>UDID</key>
        <string>__MY_UDID__</string>
        <key>VERSION</key>
        <string>15B202</string>
    </dict>
</plist>

My question is:  now what??  I've found example payloads like this (from Apple) that show how to do SCEP enrollment.  However, I don't want to do SCEP for this simple proof-of-concept.  Is there something else I can return at this stage?  If so, what should the response contain and look like?  I haven't found any documentation outlining what should be returned by my /profile endpoint if I'm not using SCEP, so I'm a little stuck.

UPDATE:  I found some resources online that imply that I need to either use SCEP or provide a PKCS#12-formatted certificate in the payload.  So, I have updated the return value of the /profile to look something like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Inc//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>PayloadVersion</key>
        <integer>1</integer>
        <key>PayloadType</key>
        <string>Configuration</string>
        <key>PayloadContent</key>
        <array>
            <dict>
                <key>PayloadContent</key>
                <dict>
                    <key>Challenge</key>
                    <string>MyChallengeGoesHere</string>
                </dict>
                <key>PayloadDescription</key>
                <string>Provides device encryption identity</string>
                <key>PayloadUUID</key>
                <string>fd8a6b9e-0fed-406f-9571-8ec98722b713</string>
                <key>PayloadType</key>
                <string>com.apple.security.pkcs12</string>
                <key>PayloadDisplayName</key>
                <string>Cert Test</string>
                <key>PayloadVersion</key>
                <integer>1</integer>
                <key>PayloadOrganization</key>
                <string>Example, Inc.</string>
                <key>PayloadIdentifier</key>
                <string>com.example.profileservice.webclip</string>
                <key>PayloadContent</key>
                <string>__MY_BASE64_ENCODED_PKCS12_CERT__</string>
                <key>Password</key>
                <string>__MY_CERT_PASSWORD__</string>
            </dict>
        </array>
    </dict>
</plist>

I'm returning this value back to the client, but when I click Install on my iOS device, I get an error saying:

Profile Installation Failed A connection to the server could not be
  established.

Now, I know that communication isn't an issue, because I see the connection to /profile in my logs and debugger.  Is there something else I'm missing?  Does the profile need to be digitally signed?  If so, what format is it?  Which certificate should I be using to sign it?

Body:
After LOTS of trial and error, I have finally figured out what the issue was for this profile.  I was missing a couple of parameters:  PayloadIdentifier and PayloadUUID.  Further, the value for the PayloadContent parameter containing my base64-encoded certificate should be data, not string.  So, my new profile looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Inc//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>PayloadVersion</key>
        <integer>1</integer>
        <key>PayloadType</key>
        <string>Configuration</string>
        <key>PayloadUUID</key>
            <string>9f93912b-5fd2-4455-99fd-13b9a47b4581</string>
            <key>PayloadIdentifier</key>
            <string>org.example.mymdm</string>
        <key>PayloadContent</key>
        <array>
            <dict>
                <key>PayloadType</key>
                <string>com.apple.security.pkcs12</string>
                <key>PayloadUUID</key>
                <string>f78c5002-3907-4f67-b631-d41c44283628</string>
                <key>PayloadVersion</key>
                <integer>1</integer>
                <key>PayloadIdentifier</key>
                <string>com.mymdm.cert</string>
                <key>Password</key>
                <string>__MY_CERT_PASSWORD__</string>
                <key>PayloadContent</key>
                <data>__MY_BASE64_ENCODED_P12__</data>
              </dict>
          </array>
    </dict>
</plist>

Once I made these changes, I was able to successfully install the profile on my iOS device.


问:
ruby (5) on rails - SQLite3::SQLException: no such table
I created another table in my SQLite database but unfortunately cannot access it through the rails console. I added one row of data through the GUI (DB Browser for SQLite) and am now trying to access it through but it gives me the error
"ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table:"

In my schema I can see it already:

```<code>create_table "user_information", force: :cascade do |t|
t.string "charity_name", limit: 100
t.string "res_exp_contact_name", limit: 50
t.string "res_exp_contact_email", limit: 100, default: "", null: false
t.string "grants_contact_name", limit: 50
t.string "grants_contact_email", limit: 100, default: "", null: false
t.boolean "submission_status_res_exp"
t.integer "submission_status_grants"
t.string "category"
t.string "username"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.index ["username"], name: "index_user_information_on_username"
end
</code>```

This is how the terminal looks like:

```<code>ck$ rails console
Running via Spring preloader in process 8442
Loading development environment (Rails 5.1.4)
Cannot read termcap database;
using dumb terminal settings.
irb(main):001:0> user = UserInformation.first
   UserInformation Load (0.2ms)  SELECT  "user_informations".* FROM
   "user_informations" ORDER BY "user_informations"."id" ASC LIMIT ?
[["LIMIT", 1]]
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table:
user_informations: SELECT  "user_informations".* FROM
"user_informations" ORDER BY "user_informations"."id" ASC LIMIT ?
    from (irb):1
</code>```

Does anyone know a solution to this? I'm grateful for any tips! :-)

答: Solved it. The answer is that you always name tables in plural so I added a migration that renamed my table from "user_information" to "user_informations". Now it works!</p>

Body:
I created another table in my SQLite database but unfortunately cannot access it through the rails console. I added one row of data through the GUI (DB Browser for SQLite) and am now trying to access it through but it gives me the error
"ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table:"

In my schema I can see it already:

create_table "user_information", force: :cascade do |t|
t.string "charity_name", limit: 100
t.string "res_exp_contact_name", limit: 50
t.string "res_exp_contact_email", limit: 100, default: "", null: false
t.string "grants_contact_name", limit: 50
t.string "grants_contact_email", limit: 100, default: "", null: false
t.boolean "submission_status_res_exp"
t.integer "submission_status_grants"
t.string "category"
t.string "username"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.index ["username"], name: "index_user_information_on_username"
end

This is how the terminal looks like:

ck$ rails console
Running via Spring preloader in process 8442
Loading development environment (Rails 5.1.4)
Cannot read termcap database;
using dumb terminal settings.
irb(main):001:0> user = UserInformation.first
   UserInformation Load (0.2ms)  SELECT  "user_informations".* FROM
   "user_informations" ORDER BY "user_informations"."id" ASC LIMIT ?
[["LIMIT", 1]]
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table:
user_informations: SELECT  "user_informations".* FROM
"user_informations" ORDER BY "user_informations"."id" ASC LIMIT ?
    from (irb):1

Does anyone know a solution to this? I'm grateful for any tips! :-)


问:
Visual Studio 2010 Ultimate - receiving a startup error of System.ExecutionEngineException
I recently installed VS2010 Ultimate on my Windows 7 Ultimate 64-bit Edition computer and I receive "An unhandled exception of type 'System.ExecutionEngineException' occurred in mscorlib.dll" randomly (or so it seems) when starting the IDE.  If I reboot the computer then about 50% of the time the IDE will start normally.  If not, I have to keep rebooting until it finally behaves normally.

I've looked around on various sites and this seems like an error that comes from many different problems ... any idea on why I might be receiving it, or something I should be checking for?

Thanks for any help or advice you care to offer.

答:
Have you checked the system event log? There might be some clues there. You can also try a couple of the VS command line parameters such as Log, SafeMode, ResetSettings.

Another approach which is more advanced and not for the faint of heart is to use Debugging Tools for Windows to start devenv.exe from WinDbg to see what causes the crash by looking at what threads are doing (stack trace, etc.).


问:
How to do str_extract with base R?
I am balancing several versions of R and want to change my R libraries loaded depending on which R and which operating system I'm using. As such, I want to stick with base R functions.

I was reading this page to see what the base R equivalent to stringr::str_extract was:

http://stat545.com/block022_regular-expression.html

It suggested I could replicate this functionality with grep. However, I haven't been able to get grep to do more than return the whole string if there is a match. Is this possible with grep alone, or do I need to combine it with another function? In my case I'm trying to distinguish between CentOS versions 6 and 7.

```<code>grep(pattern = "release ([0-9]+)", x = readLines("/etc/system-release"), value = TRUE)
</code>```

答:
You could do</p>

```<code>txt <- c("foo release 123", "bar release", "foo release 123 bar release 123")
pattern <- "release ([0-9]+)"
stringr::str_extract(txt, pattern)
# [1] "release 123" NA            "release 123"
sapply(regmatches(txt, regexec(pattern, txt)), "[", 1)
# [1] "release 123" NA            "release 123"
</code>```

Title: How to do str_extract with base R?

Body:
I am balancing several versions of R and want to change my R libraries loaded depending on which R and which operating system I'm using. As such, I want to stick with base R functions.

I was reading this page to see what the base R equivalent to stringr::str_extract was:

http://stat545.com/block022_regular-expression.html

It suggested I could replicate this functionality with grep. However, I haven't been able to get grep to do more than return the whole string if there is a match. Is this possible with grep alone, or do I need to combine it with another function? In my case I'm trying to distinguish between CentOS versions 6 and 7.

grep(pattern = "release ([0-9]+)", x = readLines("/etc/system-release"), value = TRUE)

Body:
You could do

txt <- c("foo release 123", "bar release", "foo release 123 bar release 123")
pattern <- "release ([0-9]+)"
stringr::str_extract(txt, pattern)
# [1] "release 123" NA            "release 123"
sapply(regmatches(txt, regexec(pattern, txt)), "[", 1)
# [1] "release 123" NA            "release 123"


问:
removing Li if duplicate  tag found
Removing
 if duplicate  tag found (after trimming  for trailing space from url and text).

I am using seen but the duplicate is still showing. It looks like Dashboard is duplicating but the 2nd Dashboard has a trailing space in the link url and title.

var seen = {};
$('.nav-report-category a').each(function() {
  var txt = $(this).text();
  if (seen[txt]) $(this).closest("li").remove();
  else seen[txt] = true;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-report-category {
  border: none !important;
}

.nav-report-category li {
  font-size: 16px;
  padding: 10px 0px;
  width: 110px;
  display: inline-block;
  background-color: rgb(74, 137, 220);
  color: #fff!important;
  margin-right: 5px;
  text-align: center;
  -moz-border-radius: 9px 9px 0px 0px;
  -webkit-border-radius: 9px 9px 0px 0px;
  border-radius: 9px 9px 0px 0px;
  font-color: #fff!important;
}

.nav-report-category li.active {
  background-color: #CB6015!important;
  color: #fff!important;
}

.nav-report-category li a:visited {
  color: #fff!important;
}

.nav-report-category li a {
  color: #fff!important;
}

.nav-report-category li:Hover {
  background-color: #BE3A34;
  text-decoration: none;
}

.tab-desc {
  background-color: rgb(93, 156, 236);
  color: #fff !important;
  padding: 5px;
}

.tab-desc H2 {
  color: #fff !important;
}

#txt-Business-Function {
  font-family: "Segoe UI Light", "Segoe UI", "Segoe", Tahoma, Helvetica, Arial, sans-serif;
  color: #BE3A34;
  font-size: 22px;
  font-weight: bolder;
}</code>```

Inventory

Manufacturing

Metrics

Operational

Planning

Procurement

Sales Order

Dashboard

International Operations

Purchasing

Dashboard

Strategic Sourcing

```

答:
```<code>var seen = {};
$('.nav-report-category a').each(function() {

  var txt1 = decodeURI($(this).text());
  var txt = txt1.replace(/[^a-zA-Z ]/g, "");
  if (seen[txt]) $(this).closest("li").remove();
  else seen[txt] = true;
});
</code>```

Title: removing Li if duplicate <a> tag found

Body:
Removing
 if duplicate  tag found (after trimming  for trailing space from url and text).

I am using seen but the duplicate is still showing. It looks like Dashboard is duplicating but the 2nd Dashboard has a trailing space in the link url and title.

var seen = {};
$('.nav-report-category a').each(function() {
  var txt = $(this).text();
  if (seen[txt]) $(this).closest("li").remove();
  else seen[txt] = true;
});

.nav-report-category {
  border: none !important;
}

.nav-report-category li {
  font-size: 16px;
  padding: 10px 0px;
  width: 110px;
  display: inline-block;
  background-color: rgb(74, 137, 220);
  color: #fff!important;
  margin-right: 5px;
  text-align: center;
  -moz-border-radius: 9px 9px 0px 0px;
  -webkit-border-radius: 9px 9px 0px 0px;
  border-radius: 9px 9px 0px 0px;
  font-color: #fff!important;
}

.nav-report-category li.active {
  background-color: #CB6015!important;
  color: #fff!important;
}

.nav-report-category li a:visited {
  color: #fff!important;
}

.nav-report-category li a {
  color: #fff!important;
}

.nav-report-category li:Hover {
  background-color: #BE3A34;
  text-decoration: none;
}

.tab-desc {
  background-color: rgb(93, 156, 236);
  color: #fff !important;
  padding: 5px;
}

.tab-desc H2 {
  color: #fff !important;
}

#txt-Business-Function {
  font-family: "Segoe UI Light", "Segoe UI", "Segoe", Tahoma, Helvetica, Arial, sans-serif;
  color: #BE3A34;
  font-size: 22px;
  font-weight: bolder;
}

Inventory

Manufacturing

Metrics

Operational

Planning

Procurement

Sales Order

Dashboard

International Operations

Purchasing

Dashboard

Strategic Sourcing


问:
react-native-fb sdk com.android.support dependency error
```<code> > A problem occurred configuring project ':react-native-fbsdk'.
  > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
     > Could not find com.android.support:appcompat-v7:27.0.1.
       Searched in the following locations:
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           file:/<location_to_app>/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
       Required by:
           newPtMobile:react-native-fbsdk:unspecified
</code>```

This issue started happening this morning when running react-native run-android without making any changes to the code or adding new packages, it was working fine untill now!

"react-native":"0.50.3", "react-native-fbsdk":"0.6.3"

I can see that I am missing android support libraries in my sdk/extras/android/m2repository/com/android/support subfolders, all the subfolders have the 26.0.0-alpha1 folder as the last one.
I already tried removing support repository and installing again through android studio and downloading the latest android_m2repository manually but the folders are still missing.

What I am having trouble understanding is why google's maven repository (https://dl.google.com/dl/android/maven2/index.html) states that under for example m2repository/com/android/support/appcompat-v7 I should have a folder named 27.0.2 (along with some previous versions which are also missing) but even in the latest android_m2repository which they offer it is also missing!

https://dl.google.com/android/repository/android_m2repository_r48.zip

答:
i have same problem, and i solved with :

edit package.json and i am edit react-native-fbsdk from react-native-fbsdk": "0.6.3" to react-native-fbsdk": "0.6.0"

go to your node_modules/react-native-fbsdk/android/build.gradle. open build.gradle file.

Change compile('com.facebook.android:facebook-android-sdk:4++') to compile('com.facebook.android:facebook-android-sdk:4.22.1'),

but I don't know if this is the best way for this problem,
thank you

Body:
 > A problem occurred configuring project ':react-native-fbsdk'.
  > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
     > Could not find com.android.support:appcompat-v7:27.0.1.
       Searched in the following locations:
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           file:/<location_to_app>/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
       Required by:
           newPtMobile:react-native-fbsdk:unspecified

This issue started happening this morning when running react-native run-android without making any changes to the code or adding new packages, it was working fine untill now!

"react-native":"0.50.3", "react-native-fbsdk":"0.6.3"

I can see that I am missing android support libraries in my sdk/extras/android/m2repository/com/android/support subfolders, all the subfolders have the 26.0.0-alpha1 folder as the last one.
I already tried removing support repository and installing again through android studio and downloading the latest android_m2repository manually but the folders are still missing.

What I am having trouble understanding is why google's maven repository (https://dl.google.com/dl/android/maven2/index.html) states that under for example m2repository/com/android/support/appcompat-v7 I should have a folder named 27.0.2 (along with some previous versions which are also missing) but even in the latest android_m2repository which they offer it is also missing!

https://dl.google.com/android/repository/android_m2repository_r48.zip


问:
Easy admin : collection of forms
I am trying to build a simple backend application based on EasyAdmin. The ORM is Doctrine.

I have set up 3 entities :
* Entity A has a unidirectional many-to-many relation to entity B
* Entity B has a one-to-one relation to entity C
* Entity C has some basic properties

In EasyAdmin I have set up the Entity A and Entity C. The purpose is to add/edit Entity B while adding/editing entity A. II found the following which is exactly what I want. symfony easyadmin one to many form.

But when I want to add an Entity B while adding Entity A, it creates a form with the appropriate fields but the form has its own save button. Which seems to conflict with the main save button. Results

Is there a working example of what I want to achieve or some documentation on how to do it ?

Regards

Christophe Absil

答:
I think that a good idea would be to override the 'new' and 'edit' templates. You have here the official documentation to help you.

While rendering the form, you will be able to hide/add labels & buttons; in order to hide a form element, just add:

```<code> {{ form_end(form, {'render_rest': false}) }}
</code>```

A final step would be to override EasyAdmin's AdminController in order to persist the second entity; this is the official page.

Good luck!

Title: Easy admin : collection of forms

Body:
I think that a good idea would be to override the 'new' and 'edit' templates. You have here the official documentation to help you.

While rendering the form, you will be able to hide/add labels & buttons; in order to hide a form element, just add:

 {{ form_end(form, {'render_rest': false}) }}

A final step would be to override EasyAdmin's AdminController in order to persist the second entity; this is the official page.

Good luck!


问:
Azure Functions without public endpoint
Is there a way to deploy some code as an Azure Function, but not expose it publicly? From what I see in documentation, AF always gets a public endpoint. Is that the only solution? I would like to build a solution in which AF are accessible only internally, by services which are behind firewall (no public access either). Is that possible?</p>

答:
Short Answer - No. If you're using the managed version through the Azure Portal, it's a public-facing service.
However, there are some options that require more work on your part:

There is an on-premise Azure Functions. You can get more details about that here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-runtime-overview

Azure Functions is open-source. You can deploy it yourself. The repro and more instructions are at: https://github.com/azure/azure-webjobs-sdk-script

Title: Azure Functions without public endpoint


问:
Uncaught ReferenceError: addFields is not defined
I hope someone will help me to solve this little problem with javascript. I did create a javascript function to render automatically 2 different forms according to the value selected by the user from a selectbox. The function is triggered when the user click on a button. The problem is that the forms are not generated instead i'm getting an error message: "Uncaught ReferenceError: addFields is not defined".

Html Code:

```<code><div class="form-group " style="margin-left: 80%">

                                    <div class="col-sm-10">
                                        <button type="button" class="btn btn-success btn-lg" onclick="addFields()">Formular erstellen</button>
                                    </div>
                                </div>
</code>```

Javascript code:

```<code><script type="text/javascript">
        function addFields() {
            // Number of inputs to create
            var number = document.getElementById("anzahlFragen").value;
            // Type of Quiz
            var type = document.getElementById("quizTyp");
            var selectedType = type.options[type.selectedIndex].text;
            // Container <div> where dynamic content will be placed
            var myContainer = document.getElementById("myContainer");
            // Clear previous contents of the container
            while (myContainer.hasChildNodes()) {
                myContainer.removeChild(myContainer.lastChild);
            }
            if (selectedType === "Multiple choices") {
                for (i = 1; i <= number; i++) {

                    var div1 = document.createElement("div");
                    div1.className = "form-group";
                    var div2 = document.createElement("div");
                    div2.className = "col-sm-9";
                    var labelFr = document.createElement("label");
                    var tFr = document.createTextNode("Frage Nr " + i);
                    labelFr.appendChild(tFr);
                    labelFr.className = "col-sm-2 control-label";
                    div1.appendChild(labelFr);
                    var inputFr = document.createElement("input");
                    inputFr.type = "text";
                    inputFr.name = "frage" + i;
                    inputFr.className = "form-control round-form";
                    div2.appendChild(inputFr);
                    div2.appendChild(document.createElement("br"));

                    for (j = 1; j <= 4; j++) {

                        var labelAn = document.createElement("label");
                        var tAn = document.createTextNode("Antwort Nr " + i + j);
                        labelAn.appendChild(tAn);
                        div2.appendChild(labelAn);
                        var inputAn = document.createElement("input");
                        inputAn.type = "text";
                        inputAn.name = "antwort" + i + j;
                        inputAn.className = "form-control round-form";
                        div2.appendChild(inputAn);
                        var labelRichtig = document.createElement("label");
                        var tRichtig = document.createTextNode("Richtig " + i + j);
                        labelRichtig.appendChild(tRichtig);
                        div2.appendChild(labelRichtig);
                        var richtigAn = document.createElement("input");
                        richtigAn.type = "radio";
                        richtigAn.name = "Richtig" + i;
                        div2.appendChild(richtigAn);
                        div2.appendChild(document.createElement("br"));
                        div2.appendChild(document.createElement("br"));

                    }
                    div1.appendChild(div2);
                    myContainer.appendChild(div1);
                    myContainer.appendChild(document.createElement("br"));
                }
            } else {
                for (i = 1; i <= number; i++) {

                    var div1 = document.createElement("div");
                    div1.className = "form-group";
                    var div2 = document.createElement("div");
                    div2.className = "col-sm-9";
                    var labelFr = document.createElement("label");
                    var tFr = document.createTextNode("Frage Nr " + i);
                    labelFr.appendChild(tFr);
                    labelFr.className = "col-sm-2 control-label";
                    div1.appendChild(labelFr);
                    var inputFr = document.createElement("input");
                    inputFr.type = "text";
                    inputFr.name = "frage" + i;
                    inputFr.className = "form-control round-form";
                    div2.appendChild(inputFr);
                    div2.appendChild(document.createElement("br"));

                    for (j = 1; j <= 4; j++) {

                        var labelAn = document.createElement("label");
                        var tAn = document.createTextNode("Antwort Nr " + i + j);
                        labelAn.appendChild(tAn);
                        div2.appendChild(labelAn);
                        var inputAn = document.createElement("input");
                        inputAn.type = "text";
                        inputAn.name = "antwort" + i + j;
                        inputAn.className = "form-control round-form";
                        div2.appendChild(inputAn);
                        var profilAn = document.createElement("select");
                        profilAn.name = "profil" + i + j;
                        div2.appendChild(profilAn);

                        optionAn1 = document.createElement("option");
                        optionAn1.setAttribute("value", "1"),
                        var optionT1 = document.createTextNode("Profil 1");
                        optionAn1.appendChild(optionT1);

                        optionAn2 = document.createElement("option");
                        optionAn2.setAttribute("value", "2"),
                        var optionT2 = document.createTextNode("Profil 2");
                        optionAn2.appendChild(optionT2);

                        optionAn3 = document.createElement("option");
                        optionAn3.setAttribute("value", "3"),
                        var optionT3 = document.createTextNode("Profil 3");
                        optionAn3.appendChild(optionT3);

                        optionAn4 = document.createElement("option");
                        optionAn4.setAttribute("value", "4"),
                        var optionT4 = document.createTextNode("Profil 4");
                        optionAn4.appendChild(optionT4);

                        document.getElementsByTagName("select").appendChild(optionAn1);
                        document.getElementsByTagName("select").appendChild(optionAn2);
                        document.getElementsByTagName("select").appendChild(optionAn3);
                        document.getElementsByTagName("select").appendChild(optionAn4);

                        div2.appendChild(document.createElement("br"));
                        div2.appendChild(document.createElement("br"));

                    }
                    div1.appendChild(div2);
                    myContainer.appendChild(div1);
                    myContainer.appendChild(document.createElement("br"));
                }
            }
        }
    </script>
</code>```

答: You have placed commas instead of semicolon at the end of the lines above the declaration of the variables optionT1, optionT2, optionT3and optionT4.

Body:
I hope someone will help me to solve this little problem with javascript. I did create a javascript function to render automatically 2 different forms according to the value selected by the user from a selectbox. The function is triggered when the user click on a button. The problem is that the forms are not generated instead i'm getting an error message: "Uncaught ReferenceError: addFields is not defined".

Html Code:

                                        <button type="button" class="btn btn-success btn-lg" onclick="addFields()">Formular erstellen</button>

Javascript code:


问:
Elixir/Phoenix - Test pass when running file individually but fails when using mix test
I’m having an issue where running an individual test file like so would pass:

mix test test/app_web/controllers/page_controller_test.exs

but running the entire test suite would fail:
mix test

```<code> 1) test GET / (AppWeb.PageControllerTest)
 test/app_web/controllers/page_controller_test.exs:4
 ** (RuntimeError) expected response with status 200, got: 302, with body:
 <html><body>You are being <a href="http://localhost:3000">redirected</a>.</body></html>
 code: assert html_response(conn, 200) =~ "Welcome to Phoenix!"
 stacktrace:
   (phoenix) lib/phoenix/test/conn_test.ex:362: Phoenix.ConnTest.response/2
   (phoenix) lib/phoenix/test/conn_test.ex:376: Phoenix.ConnTest.html_response/2
   test/app_web/controllers/page_controller_test.exs:6: (test)
</code>```

I’m not too sure what’s going on but I have a Plug in my router that checks whether a specific cookie has been set for all incoming requests.

So I edited the default setup in test/support/conn_case.ex to add that cookie to the conn. Like so (my app requires no database).

```<code>setup do
  token = Support.Token.generate_token()

  conn =
    ConnTest.build_conn()
    |> ConnTest.put_req_cookie("session_token", token)
    |> Plug.Conn.fetch_cookies()

  {:ok, conn: conn}
end
</code>```

Does anyone have any idea what’s going on?

答: In your error log it says 302 . It means its re directing to other URI . Thats why its showing content of your html file. It's some thing wrong with your re directing.  </p>

Body:
I’m having an issue where running an individual test file like so would pass:

mix test test/app_web/controllers/page_controller_test.exs

but running the entire test suite would fail:
mix test

 1) test GET / (AppWeb.PageControllerTest)
 test/app_web/controllers/page_controller_test.exs:4
 ** (RuntimeError) expected response with status 200, got: 302, with body:
 You are being redirected.
 code: assert html_response(conn, 200) =~ "Welcome to Phoenix!"
 stacktrace:
   (phoenix) lib/phoenix/test/conn_test.ex:362: Phoenix.ConnTest.response/2
   (phoenix) lib/phoenix/test/conn_test.ex:376: Phoenix.ConnTest.html_response/2
   test/app_web/controllers/page_controller_test.exs:6: (test)

I’m not too sure what’s going on but I have a Plug in my router that checks whether a specific cookie has been set for all incoming requests.

So I edited the default setup in test/support/conn_case.ex to add that cookie to the conn. Like so (my app requires no database).

setup do
  token = Support.Token.generate_token()

  conn =
    ConnTest.build_conn()
    |> ConnTest.put_req_cookie("session_token", token)
    |> Plug.Conn.fetch_cookies()

  {:ok, conn: conn}
end

Does anyone have any idea what’s going on?


问:
Replacing C code macros and defining constants in C++ code

Essentials of my problem: My project consists of both C and C++ files, some string constants (they are hardcoded in C part of project with #define) are required to connect to computer via USB, but if I connect two or more of same type devices, they stop responding because those constants are same. Solution to this problem would be assigning those constants dynamically, from C++ files, so that variable from C++ code could reach C part, where those values are used.

What I have now: Values are defined in C headers as #define IDENTIFIER VALUE (hardcoded), where both VALUE is a C primitive constant an int like 0x1234 or char array like "Some string". For instance:

#define IDENTIFIER1 0x1234
#define IDENTIFIER2 0x5678
#define IDENTIFIER3 "Some string"
#define IDENTIFIER4 "Another string"
```

<p>I know that methods in C use those identifiers with other macros such as <code>LOBYTE</code> and <code>HIBYTE</code>, also values are passed to some functions.</p>

<p>I tried approaching this problem by replacing the string <code>defines</code> with <code>static cast char[]</code> variable definition wrapped in <code>#ifndef</code>, but compiler noted that the identifiers are initializing non-const variables in some functions or is passed as a parameter.</p>

<p>I successfully compiled code in which i changed defining strings from <code>#define IDENTIFIER VALUE</code> to <code>static const unsigned char IDENTIFIER[] = VALUE;</code>, but I still need to define them in C++.</p>

<p>However I struggle to define hexadecimal numbers like <code>0x1234</code>. I've found other question including something related to my problem, so far I've tried to define hexadecimal values in following ways (found out that uint8_t is just a typedef of unsigned char, also found some questions about casting numbers to <code>unsigned char</code> and some answers to questions about casting types):</p>

<pre class="lang-cpp prettyprint-override"><code>static uint8_t IDENTIFIER[] = {0x12, 0x34, 0};

static const uint8_t IDENTIFIER[] = {0x12, 0x34, 0};

static const uint8_t IDENTIFIER[] = (uint8_t*)0x1234;

static const uint16_t identifier_int = 0x1234;
static const unsigned char IDENTIFIER[3] = identifier_int;
</code>```

there is a function which uses IDENTIFIERs as arguments, its prototype looks like this:

```<code>void foo (uint8_t *bar, /*other arguments*/);
</code>```

and later this is called like that:

```<code>foo(IDENTIFIER, /*other arguments*/)
</code>```

What I want to achieve: Values should be defined in C++ code, where it should use some method to pass those values to C code.

Questions:

What is best way to pass values from C++ code to C code? What alternatives there are?

Please inform me if I could increase clarity of my question!

Great thanks to @AhmedMasud for helping me out in defining my problem more clearly and giving few tips to clarify questions.

答:
I would start with simple replace of macros definitions

```<code>#define IDENTIFIER1 0x1234
#define IDENTIFIER2 0x5678
#define IDENTIFIER3 "Some string"
#define IDENTIFIER4 "Another string"
</code>```

with

```<code>const auto IDENTIFIER1 = 0x1234;
const auto IDENTIFIER2 = 0x5678;
const auto IDENTIFIER3 = "Some string";
const auto IDENTIFIER4 = "Another string";
</code>```

After that I would solve further problems step by step if they occur.

Body:
Essentials of my problem: My project consists of both C and C++ files, some string constants (they are hardcoded in C part of project with #define) are required to connect to computer via USB, but if I connect two or more of same type devices, they stop responding because those constants are same. Solution to this problem would be assigning those constants dynamically, from C++ files, so that variable from C++ code could reach C part, where those values are used.

What I have now: Values are defined in C headers as #define IDENTIFIER VALUE (hardcoded), where both VALUE is a C primitive constant an int like 0x1234 or char array like "Some string". For instance:

#define IDENTIFIER1 0x1234
#define IDENTIFIER2 0x5678
#define IDENTIFIER3 "Some string"
#define IDENTIFIER4 "Another string"

I know that methods in C use those identifiers with other macros such as LOBYTE and HIBYTE, also values are passed to some functions.

I tried approaching this problem by replacing the string defines with static cast char[] variable definition wrapped in #ifndef, but compiler noted that the identifiers are initializing non-const variables in some functions or is passed as a parameter.

I successfully compiled code in which i changed defining strings from #define IDENTIFIER VALUE to static const unsigned char IDENTIFIER[] = VALUE;, but I still need to define them in C++.

However I struggle to define hexadecimal numbers like 0x1234. I've found other question including something related to my problem, so far I've tried to define hexadecimal values in following ways (found out that uint8_t is just a typedef of unsigned char, also found some questions about casting numbers to unsigned char and some answers to questions about casting types):

static uint8_t IDENTIFIER[] = {0x12, 0x34, 0};

static const uint8_t IDENTIFIER[] = {0x12, 0x34, 0};

static const uint8_t IDENTIFIER[] = (uint8_t*)0x1234;

static const uint16_t identifier_int = 0x1234;
static const unsigned char IDENTIFIER[3] = identifier_int;

there is a function which uses IDENTIFIERs as arguments, its prototype looks like this:

void foo (uint8_t *bar, /*other arguments*/);

and later this is called like that:

foo(IDENTIFIER, /*other arguments*/)

What I want to achieve: Values should be defined in C++ code, where it should use some method to pass those values to C code.

Questions:

What is best way to pass values from C++ code to C code? What alternatives there are?

Please inform me if I could increase clarity of my question!

Great thanks to @AhmedMasud for helping me out in defining my problem more clearly and giving few tips to clarify questions.

Body:
I would start with simple replace of macros definitions

#define IDENTIFIER1 0x1234
#define IDENTIFIER2 0x5678
#define IDENTIFIER3 "Some string"
#define IDENTIFIER4 "Another string"

with

const auto IDENTIFIER1 = 0x1234;
const auto IDENTIFIER2 = 0x5678;
const auto IDENTIFIER3 = "Some string";
const auto IDENTIFIER4 = "Another string";

After that I would solve further problems step by step if they occur.


问:
CSS transition hover on parent effect on child
I'm trying to animate inside button but for some reason it won't work. Width of the button should shrink to 0 to the left

HTML

```<code><div class="siteBtnShare">
    <div class="share-text-wrapper">
        <span class="share-text">SHARE</span>
    </div>
</div>
</code>```

SCSS

```<code>.siteBtnShare  {
position: relative;
display: inline-block;
font-family: 'Novecentosanswide-Medium';
width: 40px;
transition: width 1s;
overflow:hidden;

.share-text-wrapper{
    width: 40px;
    display: inline-block;
}

&:hover .share-text-wrapper{
    width: 0;
}

}
</code>```

EDIT: - Inside the button should shrink to 0, but it doesn't do anything. It remains visible

答:
Try this, without the FontAwesome icon or with, as per your preference.

SCSS

```<code>.siteBtnShare {
    background: #eee;
    display: inline-block;
    padding: 10px;
    height: 20px;
    width: auto;
  color: #333;
    &:hover {
        .share-text-wrapper {
            .share-text {
                width: 100%;
            }
        }
    }
}
.label {
    display: inline-block;
    width: 1em;
  color: #888;
}
.share-text-wrapper {
    display: inline-block;
    white-space: nowrap;
    margin-left: -1em;
    padding-left: 1em;
    .share-text {
        display: inline-block;
        width: 0%;
        overflow: hidden;
        -webkit-transition: width 1s ease-in-out;
        -moz-transition: width 1s ease-in-out;
        -o-transition: width 1s ease-in-out;
        transition: width 1s ease-in-out;
    }
}
</code>```

HTML

```<code><div class="siteBtnShare">
    <span class="label"><i class="fa fa-share-alt" aria-hidden="true"></i></span>
    <div class="share-text-wrapper">
        <div class="share-text">
            Share It Out
        </div>
    </div>
</div>
</code>```

JSFiddle: https://jsfiddle.net/Jabideau/3bo4zxgc/

Body:
I'm trying to animate inside button but for some reason it won't work. Width of the button should shrink to 0 to the left

HTML

        SHARE

SCSS

.siteBtnShare  {
position: relative;
display: inline-block;
font-family: 'Novecentosanswide-Medium';
width: 40px;
transition: width 1s;
overflow:hidden;

.share-text-wrapper{
    width: 40px;
    display: inline-block;
}

&:hover .share-text-wrapper{
    width: 0;
}

}

EDIT: - Inside the button should shrink to 0, but it doesn't do anything. It remains visible

Body:
Try this, without the FontAwesome icon or with, as per your preference.

SCSS

.siteBtnShare {
    background: #eee;
    display: inline-block;
    padding: 10px;
    height: 20px;
    width: auto;
  color: #333;
    &:hover {
        .share-text-wrapper {
            .share-text {
                width: 100%;
            }
        }
    }
}
.label {
    display: inline-block;
    width: 1em;
  color: #888;
}
.share-text-wrapper {
    display: inline-block;
    white-space: nowrap;
    margin-left: -1em;
    padding-left: 1em;
    .share-text {
        display: inline-block;
        width: 0%;
        overflow: hidden;
        -webkit-transition: width 1s ease-in-out;
        -moz-transition: width 1s ease-in-out;
        -o-transition: width 1s ease-in-out;
        transition: width 1s ease-in-out;
    }
}

HTML

<div class="siteBtnShare">
    <span class="label"><i class="fa fa-share-alt" aria-hidden="true"></i></span>
    <div class="share-text-wrapper">
        <div class="share-text">
            Share It Out
        </div>
    </div>
</div>

JSFiddle: https://jsfiddle.net/Jabideau/3bo4zxgc/


问:
Finding filenames with specific string in a shell script
I am trying to write a bash script to do a batch processing of some fMRI data. My problem is that I am not able to get the filenames that match a specific pattern within the directory of interest.

My scripts looks like this

```<code>#!/bin/bash

inputpath="/Volumes/External_HD/Experiments/MRI_Data"
outputpath="/Volumes/External_HD/Experiments/MRI_Data_output"

anatomical_scans=$find `$inputpath` -name *mprage

# RUN BET
bet $anatomical_scans $outputpath

echo 'Finished!!!'
</code>```

The only output that I get is the following error message

```<code>-name: command not found
</code>```

I am definetely not familiar with shell scripting so I am sorry if the question may sound trivial.
Any help will be much appreciated.

Antonio

EDIT:: SOLVED

Exploring the suggestions I found the correct way to make it running with no errors

```<code>anatomical_scans=$(find $input_path -name "*mprage*")
</code>```

Thanks

答:
You can do the following:</p>

```<code>#!/bin/bash

inputpath="/Volumes/External_HD/Experiments/MRI_Data"
outputpath="/Volumes/External_HD/Experiments/MRI_Data_output"

function anatomical_scans {
    find $inputpath -name "*mprage"
}

# RUN BET
bet anatomical_scans $outputpath

echo "Finished!!!"
</code>```

Body:
I am trying to write a bash script to do a batch processing of some fMRI data. My problem is that I am not able to get the filenames that match a specific pattern within the directory of interest.

My scripts looks like this

#!/bin/bash

inputpath="/Volumes/External_HD/Experiments/MRI_Data"
outputpath="/Volumes/External_HD/Experiments/MRI_Data_output"

anatomical_scans=$find `$inputpath` -name *mprage

# RUN BET
bet $anatomical_scans $outputpath

echo 'Finished!!!'

The only output that I get is the following error message

-name: command not found

I am definetely not familiar with shell scripting so I am sorry if the question may sound trivial.
Any help will be much appreciated.

Antonio

EDIT:: SOLVED

Exploring the suggestions I found the correct way to make it running with no errors

anatomical_scans=$(find $input_path -name "*mprage*")

Thanks

Body:
You can do the following:

#!/bin/bash

inputpath="/Volumes/External_HD/Experiments/MRI_Data"
outputpath="/Volumes/External_HD/Experiments/MRI_Data_output"

function anatomical_scans {
    find $inputpath -name "*mprage"
}

# RUN BET
bet anatomical_scans $outputpath

echo "Finished!!!"


问:
Temporary store a value using `java-stream`
I was wondering if there is a way of temporary storing/carrying a value within a java-stream?

```<code>List<Department> departments = (ArrayList<Department>) departmentRepository.findAll();

departments.parallelStream()
        .filter(e -> e.getUnderstuffCount(date) > 0)
        .forEach(e -> {
            holidaysPlaningProblemManager.addProblem(e, date, e.getUnderstuffCount(date));
        });
</code>```

the multiple calls for e.getUnderstuffCount(date) seams "dirty" and I was wondering if there is a way to avoid it by carrying the result of a single call?

EDIT:

Please consider this as a java-stream question. There are a lot of ways to solve this, for example a @Transient field in the Department @Entity can store the value and a simple getter can return it.

But i'm interested if this can be done using the java-stream

答:
If you want to filter the departments, I think you should filter it first before retrieving it from the database and have the problem manager accept a list.

```<code>List<Department> departments = departmentRepository.someMethod(date);
holidaysPlaningProblemManager.addProblems(date, departments);
</code>```

Unless you still have something to do with the elements in the collection.

Body:
I was wondering if there is a way of temporary storing/carrying a value within a java-stream?

List<Department> departments = (ArrayList<Department>) departmentRepository.findAll();

departments.parallelStream()
        .filter(e -> e.getUnderstuffCount(date) > 0)
        .forEach(e -> {
            holidaysPlaningProblemManager.addProblem(e, date, e.getUnderstuffCount(date));
        });

the multiple calls for e.getUnderstuffCount(date) seams "dirty" and I was wondering if there is a way to avoid it by carrying the result of a single call?

EDIT:

Please consider this as a java-stream question. There are a lot of ways to solve this, for example a @Transient field in the Department @Entity can store the value and a simple getter can return it.

But i'm interested if this can be done using the java-stream

Body:
If you want to filter the departments, I think you should filter it first before retrieving it from the database and have the problem manager accept a list.

List<Department> departments = departmentRepository.someMethod(date);
holidaysPlaningProblemManager.addProblems(date, departments);

Unless you still have something to do with the elements in the collection.


问:
returning single result using LINQ
I have a query

```<code>row.GetChildRows("EventCategoryRelation")
  .Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
  .Select(x => Int32.Parse(x["category_id"].ToString()))
</code>```

This query returns an IEnumerable. I am expecting an 'int'

Help me modify my LINQ query

答:
If you expect your query only to return a single value use the Single extension method.

```<code>row.GetChildRows("EventCategoryRelation")
   .Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
   .Select(x => Int32.Parse(x["category_id"].ToString()))
   .Single();
</code>```

Note that Single will throw an exception if there is no value. If that is not what you want, use SingleOrDefault.

Title: returning single result using LINQ

Body:
I have a query

row.GetChildRows("EventCategoryRelation")
  .Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
  .Select(x => Int32.Parse(x["category_id"].ToString()))

This query returns an IEnumerable. I am expecting an 'int'

Help me modify my LINQ query

Body:
If you expect your query only to return a single value use the Single extension method.

row.GetChildRows("EventCategoryRelation")
   .Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
   .Select(x => Int32.Parse(x["category_id"].ToString()))
   .Single();

Note that Single will throw an exception if there is no value. If that is not what you want, use SingleOrDefault.


问:
How do you write multi-line function definitions in typescript?
how do you usually write functions with a lot of parameters?
this way:

```<code>function foo(
    a: number,
    b: string,
    c: boolean): boolean {

....

}
</code>```

or this way:

```<code>function foo(
    a: number,
    b: string,
    c: boolean
): boolean {

....

}
</code>```

?

答:
While this is a style choice, there is something you can consider:

```<code>let c: number = 10

function foo(
  a: number,
  b: string) {
  c = 123
}
</code>```

You can see that this create confusion on where the parameter list ends and where the code block starts.
I used to do this myself, but I'm considering changing to

```<code>function foo(
  a: number,
  b: string)
{
  c = 123
}

// or, to be more JavaScript friendly
function foo(
  a: number,
  b: string
) {
  c = 123
}
</code>```

Again, this is about personal and team preference at the end.

Body:
how do you usually write functions with a lot of parameters?
this way:

function foo(
    a: number,
    b: string,
    c: boolean): boolean {

....

}

or this way:

function foo(
    a: number,
    b: string,
    c: boolean
): boolean {

....

}

?

Body:
While this is a style choice, there is something you can consider:

let c: number = 10

function foo(
  a: number,
  b: string) {
  c = 123
}

You can see that this create confusion on where the parameter list ends and where the code block starts.
I used to do this myself, but I'm considering changing to

function foo(
  a: number,
  b: string)
{
  c = 123
}

// or, to be more JavaScript friendly
function foo(
  a: number,
  b: string
) {
  c = 123
}

Again, this is about personal and team preference at the end.


问:
Need with Javascript function for Select check
I tried to create a function to check on a drop-down option on select box. It requires a user to select a user name before submit. I put '0' and check if this = 0, then return false, but it didn't work.

I added a function to check radio buttons and they all worked fine. However, the select Staff doesn't work. I mean, when I click on Submit after checking all radio boxes, it get submitted anyway. How do I fix it to make it work?

Can you help me?

```<code><script language="javascript">
function validateForm(daForm) {
nCount = document.frmReport.txtCount.value;
    // check all rb radio buttons
    for (var i = 1; i < nCount; i++) {
        if (! getCheckedRadioValue(daForm["Report"+i])) {
            alert ("Please select a value for option " + i)
            return false
         }
if (UserID.options[UserID.selectedIndex].value == 0) {
                alert("Please select a user");
                return false
    }
    // add other checks here...
                alert ("Thank you!")
                window.open("Search.asp")
    return true
}
<body>
<form action="" method="post" id="newMenu" name="frmReport" onSubmit="return validateForm(this)">
    <select name="UserID">
          <option value=0>Staff name:</option>
          <option value=1>Jenny</option>
          <option value=2>David</option>
     </select>
    <input type="submit" value="Submit">
</form>
</code>```

Thank you very much!

答:
It looks like something is wrong with the selector.

Comparing against a "0" value seems to work just fine. I've included a snippet which shows this.

In short, change this...

```<code>if (UserID.options[UserID.selectedIndex].value == 0) {
     alert("Please select a staff");
     return false
}
</code>```

To this

```<code>if (document.querySelector("[name='UserID']").value == 0) {
     alert("Please select a staff");
     return false
}
</code>```

Make multiple selections and submit to see the results.

function validateForm(daForm){
  var select = document.querySelector("[name='UserID']")

  if(select.value == 0){
    console.log("Please select a value");
  }else{
    console.log("Selection made.");
  }

  return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="" method="post" id="newMenu" name="frmReport" onSubmit="return validateForm(this)">
    <select name="UserID">
          <option value=0>Staff name:</option>
          <option value=1>Jenny</option>
          <option value=2>David</option>
     </select>

     <input type="submit">
 </form></code>```

Body:
It looks like something is wrong with the selector.

Comparing against a "0" value seems to work just fine. I've included a snippet which shows this.

In short, change this...

if (UserID.options[UserID.selectedIndex].value == 0) {
     alert("Please select a staff");
     return false
}

To this

if (document.querySelector("[name='UserID']").value == 0) {
     alert("Please select a staff");
     return false
}

Make multiple selections and submit to see the results.

function validateForm(daForm){
  var select = document.querySelector("[name='UserID']")

  if(select.value == 0){
    console.log("Please select a value");
  }else{
    console.log("Selection made.");
  }

  return false;
}

<form action="" method="post" id="newMenu" name="frmReport" onSubmit="return validateForm(this)">
    <select name="UserID">
          <option value=0>Staff name:</option>
          <option value=1>Jenny</option>
          <option value=2>David</option>
     </select>

     <input type="submit">
 </form>


问:
Count number of Special Character in Unix Shell
I have a delimited file that is separated by octal \036 or Hexadecimal value 1e.

I need to count the number of delimiters on each line using a bash shell script.

I was trying to use awk, not sure if this is the best way.

Sample Input (| is a representation of \036)

```<code>Example|Running|123|
</code>```

Expected output:

```<code>3
</code>```

答:
```<code>awk -F'|' '{print NF-1}' file
</code>```

Change | to whatever separator you like. If your file can have empty lines then you need to tweak it to:

```<code>awk -F'|' '{print (NF ? NF-1 : 0)}' file
</code>```

Body:
I have a delimited file that is separated by octal \036 or Hexadecimal value 1e.

I need to count the number of delimiters on each line using a bash shell script.

I was trying to use awk, not sure if this is the best way.

Sample Input (| is a representation of \036)

Example|Running|123|

Expected output:

3

Body:
awk -F'|' '{print NF-1}' file

Change | to whatever separator you like. If your file can have empty lines then you need to tweak it to:

awk -F'|' '{print (NF ? NF-1 : 0)}' file


问:
Setting up a personal (Java) workspace: What do I need?
I want to set up a personal workspace on my home machine. I mainly intend to use it for Java development on home projects. Which tools do you recommend me to use? (I prefer free tools, since this is just for home use.)

I hope you could recommend some tools for me, and I'd be grateful if you could give me a brief comparison of some tools in each category. For example, I'm thinking about source control and issue tracking tools, but any other categories are welcome.

I also hope to get some information about the ability to move between suggested tools (e.g. migrate between CVS and SVN), and even between operating systems if applicable. (I'm currently using Windows Vista, but I may want to switch to Linux sometime soon.) Maybe even information about how easy it would be to move the project to an open-source repository (e.g. SF.net).

Thank you.

(P.S. Any comments on how to enhance/clarify my question are more than welcome.)

答:
The question is too generic, but let me attempt to give it a try:

Netbeans or Eclipse IDE. If you do GUI development, I suggest Netbeans, otherwise go for eclipse.

Git or Mercurial as a VCS. If you're dealing with a large code base or if you dig the UNIX philosophy go for Git. If you don't want to handle cross-OS differences, go for Hg.

Any of these IDE gives you integration with the source control system, so you're just a google search away from it.

As for opensource, if you use Git, just push to github. If you use Hg, push it to bitbucket and you're done.

For issue tracking I suggest you hosted Redmine (RoR app) that integrates with CVS, SVN, Git, Mercurial and a few others.

If you choose Eclipse, you can integrate it with Mylyn.

OwnerDisplayName: Hosam Aly

OwnerDisplayName: Alcides


答:
You can always add this to the end of your query:

```<code>.Single();
</code>```

That will return the one value if your enumerable contains only one, or throw an exception if it contains another amount than one.

Title: returning single result using LINQ

Body:
You can always add this to the end of your query:

.Single();

That will return the one value if your enumerable contains only one, or throw an exception if it contains another amount than one.


问:
Sed replace hyphen with underscore
new to regex and have a problem. I want to replace hyphens with underscores in certain places in a file. To simplify things, let's say I want to replace the first hyphen. Here's an example "file":

```<code>dont-touch-these-hyphens
leaf replace-these-hyphens
</code>```

I want to replace hyphens in all lines found by

```<code>grep -P "leaf \w+-" file
</code>```

I tried

```<code>sed -i 's/leaf \(\w+\)-/leaf \1_/g' file
</code>```

but nothing happens (wrong replacement would have been better than nothing). I've tried a few tweaks but still nothing. Again, I'm new to this so I figure the above "should basically work". What's wrong with it, and how do I get what I want? Thanks.

答:
You can simplify things by using two distinct regex's ; one for matching the lines that need processing, and one for matching what must be modified.

You can try something like this:

```<code>$ sed '/^leaf/ s/-/_/' file
dont-touch-these-hyphens
leaf replace_these-hyphens
</code>```

Title: Sed replace hyphen with underscore

Body:
new to regex and have a problem. I want to replace hyphens with underscores in certain places in a file. To simplify things, let's say I want to replace the first hyphen. Here's an example "file":

dont-touch-these-hyphens
leaf replace-these-hyphens

I want to replace hyphens in all lines found by

grep -P "leaf \w+-" file

I tried

sed -i 's/leaf \(\w+\)-/leaf \1_/g' file

but nothing happens (wrong replacement would have been better than nothing). I've tried a few tweaks but still nothing. Again, I'm new to this so I figure the above "should basically work". What's wrong with it, and how do I get what I want? Thanks.

Body:
You can simplify things by using two distinct regex's ; one for matching the lines that need processing, and one for matching what must be modified.

You can try something like this:

$ sed '/^leaf/ s/-/_/' file
dont-touch-these-hyphens
leaf replace_these-hyphens


问:
Jmeter setting for sampler that it should not be in view results tree
I want that some beanshell samplers of my testplan should not be shown in view results tree. Is that somehow possible?

Best regards,
Peter

答:
Beanshell preprocessor should be used instead of beanshell sampler.
It doesn't appear in the result tree. </p>