问:
Set table view height based on cell height for x visible cells
I want to adjust my table view height so that it shows only x cells at a time. The cell's layout is configurable so I don't know its height beforehand.

For simplicity's sake, I've tried to set up the simplest example of a cell with two labels with fixed text stacked vertically.

MyCustomViewCell.swift

```<code>class MyCustomViewCell: UITableViewCell {

    let label: UILabel
    let label2: UILabel

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        label = UILabel()
        label2 = UILabel()
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.contentView.addSubview(label)
        self.contentView.addSubview(label2)

        label.translatesAutoresizingMaskIntoConstraints = false

        label.topAnchor.constraint(equalTo: self.contentView.topAnchor).isActive = true
        label.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor).isActive = true
        label.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor).isActive = true

        label2.translatesAutoresizingMaskIntoConstraints = false
        label2.topAnchor.constraint(equalTo: label.bottomAnchor).isActive = true
        label2.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor).isActive = true
        label2.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor).isActive = true
        label2.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor).isActive = true

        label.text = "string 1"
        label2.text = "string 2"
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

I have managed to achieve the desired behavior by setting the height constraint (with a lower than 1000 priority) when initializing the table view and then setting the actual height on cellForRowAtIndexPath based on the cell's frame and the amount of cells I wanted to be visible (in this case, 5).

```<code>class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let cellIdentifier = "cellIdentifier"

    override func viewDidLoad() {
        super.viewDidLoad()

        let tableView = UITableView(frame: .zero, style: .plain)
        setupTableViewConstraints(tableView: tableView)

        tableView.register(MyCustomViewCell.self, forCellReuseIdentifier: cellIdentifier)
        tableView.dataSource = self
        tableView.delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func setupTableViewConstraints(tableView: UITableView) {
        self.view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false

        tableView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true
        let heightConstraint = tableView.heightAnchor.constraint(equalToConstant: 300)
        heightConstraint.priority = 900
        heightConstraint.isActive = true

        tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 10).isActive = true
        tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -10).isActive = true

        tableView.layer.borderColor = UIColor.black.cgColor
        tableView.layer.borderWidth = 0.5
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10000
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath as IndexPath) as! MyCustomViewCell

        tableView.heightAnchor.constraint(equalToConstant: cell.frame.height*5).isActive = true
        return cell
    }
}
</code>```

However, this approach doesn't seem right to me. All the way from setting a "dummy" height only to be adjusted later to setting the table view height every time cellForRowAtIndexPath is executed.

Can anyone point me in the direction of a more elegant solution?

答:
In your example you are updating the height of your tableview every time it asks you to load a cell.

While this would work, it seems a bit overkill knowing that this method is constantly called by the tableview even before the cells are visible.

Why not wait until the tableview has finished loading and only then update the height?

You could do this in willDisplayCell instead which is trigged only when the cells are about to be displayed or perhaps with a completion closure like so:

```<code>self.tableView.reloadData()
DispatchQueue.main.async {
    // This closure is only called when the data has been reloaded
    // and thus will enable you to calculate the final content height
}
</code>```

Body:
I want to adjust my table view height so that it shows only x cells at a time. The cell's layout is configurable so I don't know its height beforehand.

For simplicity's sake, I've tried to set up the simplest example of a cell with two labels with fixed text stacked vertically.

MyCustomViewCell.swift

class MyCustomViewCell: UITableViewCell {

    let label: UILabel
    let label2: UILabel

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        label = UILabel()
        label2 = UILabel()
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.contentView.addSubview(label)
        self.contentView.addSubview(label2)

        label.translatesAutoresizingMaskIntoConstraints = false

        label.topAnchor.constraint(equalTo: self.contentView.topAnchor).isActive = true
        label.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor).isActive = true
        label.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor).isActive = true

        label2.translatesAutoresizingMaskIntoConstraints = false
        label2.topAnchor.constraint(equalTo: label.bottomAnchor).isActive = true
        label2.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor).isActive = true
        label2.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor).isActive = true
        label2.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor).isActive = true

        label.text = "string 1"
        label2.text = "string 2"
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

I have managed to achieve the desired behavior by setting the height constraint (with a lower than 1000 priority) when initializing the table view and then setting the actual height on cellForRowAtIndexPath based on the cell's frame and the amount of cells I wanted to be visible (in this case, 5).

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let cellIdentifier = "cellIdentifier"

    override func viewDidLoad() {
        super.viewDidLoad()

        let tableView = UITableView(frame: .zero, style: .plain)
        setupTableViewConstraints(tableView: tableView)

        tableView.register(MyCustomViewCell.self, forCellReuseIdentifier: cellIdentifier)
        tableView.dataSource = self
        tableView.delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func setupTableViewConstraints(tableView: UITableView) {
        self.view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false

        tableView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true
        let heightConstraint = tableView.heightAnchor.constraint(equalToConstant: 300)
        heightConstraint.priority = 900
        heightConstraint.isActive = true

        tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 10).isActive = true
        tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -10).isActive = true

        tableView.layer.borderColor = UIColor.black.cgColor
        tableView.layer.borderWidth = 0.5
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10000
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath as IndexPath) as! MyCustomViewCell

        tableView.heightAnchor.constraint(equalToConstant: cell.frame.height*5).isActive = true
        return cell
    }
}

However, this approach doesn't seem right to me. All the way from setting a "dummy" height only to be adjusted later to setting the table view height every time cellForRowAtIndexPath is executed.

Can anyone point me in the direction of a more elegant solution?

Body:
In your example you are updating the height of your tableview every time it asks you to load a cell.

While this would work, it seems a bit overkill knowing that this method is constantly called by the tableview even before the cells are visible.

Why not wait until the tableview has finished loading and only then update the height?

You could do this in willDisplayCell instead which is trigged only when the cells are about to be displayed or perhaps with a completion closure like so:

self.tableView.reloadData()
DispatchQueue.main.async {
    // This closure is only called when the data has been reloaded
    // and thus will enable you to calculate the final content height
}


来源: stackexchange

问:
How to create a random matches in a league database with the ID of the clubs?
I work on a project about chess league. I have a table consists of ( round_id, home_club, away_club, home_results, away_results ). I want to generate a random matches for 18 rounds ( the league consists of 10 clubs) so that in home_club and away_club we have a club_id from another table but not repeated in each round.</p>

答:
Let, there is a table clubs in your database with ID column, that contains identificators (from 1 to 10 for example). Then use following:

```<code>SELECT home.ID, away.ID
FROM clubs home, clubs away
WHERE home.ID <> away.ID
ORDER BY RAND()
LIMIT 18;
</code>```

The SELECT home.ID, away.ID FROM clubs home, clubs away creates all combinations of identificators. The WHERE clause prevents equality of home.ID and away.ID values in the result. The ORDER BY RAND() returns rows in random order. Finally, we get first 18 rows only.

Thus, the 18 random combinations identificators of clubs will be returned. The query result is able to be inserted into home_club and away_club columns of your tournament table.

ContentLicense: CC BY-SA 3.0

Body:
Let, there is a table clubs in your database with ID column, that contains identificators (from 1 to 10 for example). Then use following:

SELECT home.ID, away.ID
FROM clubs home, clubs away
WHERE home.ID <> away.ID
ORDER BY RAND()
LIMIT 18;

The SELECT home.ID, away.ID FROM clubs home, clubs away creates all combinations of identificators. The WHERE clause prevents equality of home.ID and away.ID values in the result. The ORDER BY RAND() returns rows in random order. Finally, we get first 18 rows only.

Thus, the 18 random combinations identificators of clubs will be returned. The query result is able to be inserted into home_club and away_club columns of your tournament table.


问:
UnsupportedOperation: not writable python
```<code> with open(r'G:\Programs\abc.txt') as f:
    for line in f:
          if line.startswith('logan'):
                 f.write('Johann Sebastian Bach')
                 print("Renewed line = ", line)
</code>```

error message:

```<code>    runfile('G:/Python Programs/p17.py', wdir='G:/Python Programs')
Traceback (most recent call last):

  File "<ipython-input-2-393638b0e5ce>", line 1, in <module>
    runfile('G:/Python Programs/p17.py', wdir='G:/Python Programs')

  File "G:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "G:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "G:/Python Programs/p17.py", line 11, in <module>
    khand.write('Johann Sebastian Bach')

UnsupportedOperation: not writable
</code>```

I have listed this code in python3.6 still I am getting an error message. I have required file in directory. Any suggestions?

答:
Opening the file without a mode defaults to opening it in readonly mode. If you want to write to it while reading, you've to specify the mode as r+.

```<code>with open(r'G:\Programs\abc.txt', mode='r+') as khand:
    ...
</code>```

w+ will also open the file in r/w mode, however, it wipes the contents clean.

You also use the a+ mode which will append to the end of the file, while still letting you read from it.

Body:
 with open(r'G:\Programs\abc.txt') as f:
    for line in f:
          if line.startswith('logan'):
                 f.write('Johann Sebastian Bach')
                 print("Renewed line = ", line)

error message:

    runfile('G:/Python Programs/p17.py', wdir='G:/Python Programs')
Traceback (most recent call last):

  File "<ipython-input-2-393638b0e5ce>", line 1, in <module>
    runfile('G:/Python Programs/p17.py', wdir='G:/Python Programs')

  File "G:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "G:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "G:/Python Programs/p17.py", line 11, in <module>
    khand.write('Johann Sebastian Bach')

UnsupportedOperation: not writable

I have listed this code in python3.6 still I am getting an error message. I have required file in directory. Any suggestions?

Body:
Opening the file without a mode defaults to opening it in readonly mode. If you want to write to it while reading, you've to specify the mode as r+.

with open(r'G:\Programs\abc.txt', mode='r+') as khand:
    ...

w+ will also open the file in r/w mode, however, it wipes the contents clean.

You also use the a+ mode which will append to the end of the file, while still letting you read from it.


问:
A more readable way of joining some lists with some lists returned by lapply in R
Say I want to create a list of four lists. The first two are manually defined, the second two are the result of lapply. So to be specific, I have these three items:

```<code>> list("a" = 1)
> list("b" = 1)
> lapply(1:2,FUN=function(i) { list("c"=i) }
</code>```

And I want to combine them so that the output list is:

```<code>[[1]]
[[1]]$a
[1] 1

[[2]]
[[2]]$b
[1] 1

[[3]]
[[3]]$c
[1] 1

[[4]]
[[4]]$c
[1] 2
</code>```

I can achieve it using the following:

```<code>> unlist(recursive=FALSE,
         list(
              list(list("a"=1),list("b"=1)),
              lapply(1:2,FUN = function(i) { list("c"=i) })
              )
         )
</code>```

But all this lists of lists of lists business seems a bit verbose! I know I can of course just write a function to do this, but I'm wondering if there is a cleaner one liner?

答:
```<code>c(list(list("a" = 1),list("b" = 1)),lapply(1:2,FUN=function(i) { list("c"=i) }))
</code>```

Body:
Say I want to create a list of four lists. The first two are manually defined, the second two are the result of lapply. So to be specific, I have these three items:

> list("a" = 1)
> list("b" = 1)
> lapply(1:2,FUN=function(i) { list("c"=i) }

And I want to combine them so that the output list is:

[[1]]
[[1]]$a
[1] 1

[[2]]
[[2]]$b
[1] 1

[[3]]
[[3]]$c
[1] 1

[[4]]
[[4]]$c
[1] 2

I can achieve it using the following:

> unlist(recursive=FALSE,
         list(
              list(list("a"=1),list("b"=1)),
              lapply(1:2,FUN = function(i) { list("c"=i) })
              )
         )

But all this lists of lists of lists business seems a bit verbose! I know I can of course just write a function to do this, but I'm wondering if there is a cleaner one liner?


问:
Where is SVN caching the hostname?
When I perform a SVN checkout and specify a hostname, SVN is attempting to resolve a hostname to an old repo that I no longer use. I cannot find where this old hostname (codespaces.com) is being cached.

Checkout from http://mysubdomain.unfuddle.com/svn/, revision HEAD, Fully recursive, Externals included
OPTIONS of 'http://mysubdomain.unfuddle.com/svn/': Could not resolve
hostname `https://svn.codespaces.com/my-old-project/': The requested name is valid,
but no data of the requested type was found.
 (http://mysubdomain.unfuddle.com)

I have uninstalled TortoiseSVN and SVN itself. And reinstalled them one by one. I have searched the C drive and the registry for the string literal codespaces.com - to no avail.

This has had me banging my head on the table for 2 full days and I am at my wits end. Can anybody shed some light on how to resolve this issue?

答: Did you try relocating? Read this page to know how to do this with Tortoisse.</p>

ContentLicense: CC BY-SA 2.5

Title: Where is SVN caching the hostname?


问:
jsPlumb positioning the boxes automatically
I'm fairly new to jsPlumb and I was wondering if there's a way for the boxes/divs (the boxes that get connected to each other) to be automatically positioned in the page. I have a lot of "entities" which will be dynamically fetched from a database, so "manual" positioning is really not an option here. It doesn't matter where they are as long as they are not overlapping each other.

From what I've searched until now, jsPlumb has no documentation regarding this matter. I'm not sure how I would achieve some proper positioning of my boxes.

From the example below you  can see that the positioning of the boxes is taken care of manually by writing a bunch of CSS for each box - I definitely do not need that:

```<code>#window1 { top:30em;left:10em;}
#window2 { top:-2em; left:36em;}
#window3 { top:20em;left:45em; }
#window4 { top:17em; left:22em;}
</code>```

Example: http://www.lively-kernel.org/repository/webwerkstatt/users/tmohr/libs/jsPlumb/demo/jquery/flowchartConnectorsDemo.html#

JSFiddle: http://jsfiddle.net/evycd00u/3

答:
The position is CSS. So you could use Javascript or JQuery to set the position of your boxes using some process:</p>

```<code>// e.g. this uses JQuery
for (var i=0; i<4; i++) {
    $("#window"+i).css({top: 50+80*i, left: 200});
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm fairly new to jsPlumb and I was wondering if there's a way for the boxes/divs (the boxes that get connected to each other) to be automatically positioned in the page. I have a lot of "entities" which will be dynamically fetched from a database, so "manual" positioning is really not an option here. It doesn't matter where they are as long as they are not overlapping each other.

From what I've searched until now, jsPlumb has no documentation regarding this matter. I'm not sure how I would achieve some proper positioning of my boxes.

From the example below you  can see that the positioning of the boxes is taken care of manually by writing a bunch of CSS for each box - I definitely do not need that:

#window1 { top:30em;left:10em;}
#window2 { top:-2em; left:36em;}
#window3 { top:20em;left:45em; }
#window4 { top:17em; left:22em;}

Example: http://www.lively-kernel.org/repository/webwerkstatt/users/tmohr/libs/jsPlumb/demo/jquery/flowchartConnectorsDemo.html#

JSFiddle: http://jsfiddle.net/evycd00u/3

Body:
The position is CSS. So you could use Javascript or JQuery to set the position of your boxes using some process:

// e.g. this uses JQuery
for (var i=0; i<4; i++) {
    $("#window"+i).css({top: 50+80*i, left: 200});
}


问:
password protect a web page using css/html?
I've seen several questions about password protecting pages, but none of them seem to be exactly what I'm looking for. JavaScript, or Apache, and such aren't options that I'm able to consider currently. I also don't have the ability to download a product or buy one since this isn't exactly for me but its for my boss' website, so please refrain from suggestions like that.

The site is currently written in CSS and HTML, and that's also the extent of my coding knowledge unfortunately. I saw a few places where people used PHP coding, but every time I tried I just got a blank page or it didn't work out properly, or nothing would happen when I entered the password.There also haven't been any really good detailed instructions on it, so I never know where I'm supposed to put the PHP code (does it go on its own page or is it integrated?) or how to connect it to the actual web page.

Truthfully it doesn't have to be anything fantastic, because a lot of the people who will be looking at this site are people who aren't very computer savvy, just a simple form box with a password field. It would be best if there was a code I could put right into the HTML on the page. If I have to make a separate HTML page I don't mind doing that either. There's going to be one password given to the Salesmen so they can access the private pages while on the road from their laptops or tablets.

I saw something about .htpassword and another one I cant remember, but I haven't been able to find any step by step instructions or detailed information about it (detailed meaning info I can understand...). I saw also the thing about password_protect.php, but that requires a username field I think, and I cant really use one like that. There wont be a username, and sadly that's asking too much of the salesmen to remember two things heh.

Anyways, I apologize for my ignorance on the subject, and thank anyone for their help in advance!

答:
If you add javascript, with a bit of pre-processing it is possible to securely password protect a page, no server-side validation needed.

Encrypt your content with a symmetric key algo like AES (that's the pre-processing), put it online and use javascript to decrypt that content with a user provided password.

Everything can then happen client-side in the browser. It doesn't matter if the code is open for everyone to see.

Pseudo-code:

```<code><input type="password" id="password">
<button class="decrypt">Decrypt</button>
<script>
    var myEncryptedPage = '<html-string-pre-encrypted-with-your-password>';
    $('.decrypt').click(function(){
        var password = $('#password').val();
        // 'decrypt' tries to decrypt your string with the user provided password
        document.write(decrypt(myEncryptedPage, password));
    });
</script>
</code>```

For reference if you want to see a possible implementation I wrote a simple PoC using the crypto-js library showing that idea (StatiCrypt), where you can do the pre-processing and encrypt your page with a password prompt.

Body:
If you add javascript, with a bit of pre-processing it is possible to securely password protect a page, no server-side validation needed.

Encrypt your content with a symmetric key algo like AES (that's the pre-processing), put it online and use javascript to decrypt that content with a user provided password.

Everything can then happen client-side in the browser. It doesn't matter if the code is open for everyone to see.

Pseudo-code:

<input type="password" id="password">
<button class="decrypt">Decrypt</button>
<script>
    var myEncryptedPage = '<html-string-pre-encrypted-with-your-password>';
    $('.decrypt').click(function(){
        var password = $('#password').val();
        // 'decrypt' tries to decrypt your string with the user provided password
        document.write(decrypt(myEncryptedPage, password));
    });
</script>

For reference if you want to see a possible implementation I wrote a simple PoC using the crypto-js library showing that idea (StatiCrypt), where you can do the pre-processing and encrypt your page with a password prompt.


问:
Bing for Sharepoint?
Is it possible to add an out-of-the-box Bing site search box to my SharePoint extranet and have it actually work?  My mind says no, since it can't possibly index my pages, right?  Just wanted to know your thoughts.</p>

答: You can add bing search box and you would get results as well but only pages from your site which are allowed for anonymous access will be crawled by Bing. My question to you is this when share point already provides Such a wonderful search engine why do you need anything else for crawling of your internal content.</p>

Title: Bing for Sharepoint?


问:
SQL Server - enclose a long script in single quotations for a function using sp_executesql
I have the following example of script. It works fine for this example as it is small and basic. I have a far bigger script with around 50 steps that works fine on its own. As in, hit F5 and does everything, checks if table exists, deletes, writes to tables, drops temps and all results are written to the necessary places. I can't seem to place this large script into this small example:

```<code>alter procedure james_tester
    @tablename nvarchar(200)
as
BEGIN
    declare @sql nvarchar(max)

    set @sql =

        ---->
        'select * from'
        ---->

        + @tablename
        EXECUTE sp_executesql @sql
        END

 ---When executing:
 execute james_tester 'dbo.calendar_delete'
</code>```

In my case the section in between the arrows is large and will have numerous variables. I just want to know if there is a function or possibly another way to place a large piece of script at a time in that single quote part. I hope I am describing this sufficiently. What affects the entire script currently from just putting a single quote before and after, is that there are already many comments, and single quotes used in the script that seem to stop the entire script from being highlighted red as text and working fine.

James

答:
It is in fact only the presence of single quotes that will cause problems.  Take the following illustration:

```<code>declare @bigText varchar(max);

SET @bigText = '"The time has come," the Walrus said,
"To talk of many things:
Of shoes and ships and sealing-wax --SQL Comment has no impact
Of cabbages and kings /* c/c++ comment has no impact */
And why the sea is boiling hot //c# comment has no impact
And whether pigs have wings."';

 SELECT @bigText;
</code>```

Single quotes can be doubled using regex or some other string replace function, so that should not be too hard either.

BUT (and there always is a but of course) whether the remaining text is a legal SQL string, which you can execute is an entirely different question. The presence of extraneous comments etc. will almost certainly bite you.

Body:
I have the following example of script. It works fine for this example as it is small and basic. I have a far bigger script with around 50 steps that works fine on its own. As in, hit F5 and does everything, checks if table exists, deletes, writes to tables, drops temps and all results are written to the necessary places. I can't seem to place this large script into this small example:

alter procedure james_tester
    @tablename nvarchar(200)
as
BEGIN
    declare @sql nvarchar(max)

    set @sql =

        ---->
        'select * from'
        ---->

        + @tablename
        EXECUTE sp_executesql @sql
        END

 ---When executing:
 execute james_tester 'dbo.calendar_delete'

In my case the section in between the arrows is large and will have numerous variables. I just want to know if there is a function or possibly another way to place a large piece of script at a time in that single quote part. I hope I am describing this sufficiently. What affects the entire script currently from just putting a single quote before and after, is that there are already many comments, and single quotes used in the script that seem to stop the entire script from being highlighted red as text and working fine.

James

Body:
It is in fact only the presence of single quotes that will cause problems.  Take the following illustration:

declare @bigText varchar(max);

SET @bigText = '"The time has come," the Walrus said,
"To talk of many things:
Of shoes and ships and sealing-wax --SQL Comment has no impact
Of cabbages and kings /* c/c++ comment has no impact */
And why the sea is boiling hot //c# comment has no impact
And whether pigs have wings."';

 SELECT @bigText;

Single quotes can be doubled using regex or some other string replace function, so that should not be too hard either.

BUT (and there always is a but of course) whether the remaining text is a legal SQL string, which you can execute is an entirely different question. The presence of extraneous comments etc. will almost certainly bite you.


问:
How to center HTML5 Videos?
I'm just messing around with some HTML5, and I was trying to center a video on the page. For some reason I can't get it to center. I've tried to add a class to the video tag itself, and I've wrapped the video in a separate div. However, the video stays on the left.

```<code><!DOCTYPE HTML>
<html>
  <head>
    <title>Test</title>
    <script type="text/css">
    .center {
      margin: 0 auto;
    }
    </script>
  </head>
  <body>
    <div class="center">
      <video controls="controls">
        <source src="/media/MVI_2563.ogg" type="video/ogg" />
        Your browser does not support the video tag.
      </video>
    </div>
  </body>
</html>
</code>```

I know this must be something I'm overlooking in the wee hours of the morning, but any help would be appreciated.

Thanks

答:
Use margins <video> is an inline element so you'll have to add display block;to your css class.

You can use specific with, but I wouldn’t use px values. Use % to make it responsive, like:

```<code>width: 50%;
</code>```

That’ll make the video half of the viewport width.

See the original documentation here O World Wide Web Consortium W3C

mystyle.css

video {
      width: 50% !important;
      height: auto !important;
      margin: 0 auto;
      display: block;
    }

    h1 {
      text-align: center;
      color: #C42021;
      font-size: 20px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
        <html>
           <head>
              <meta charset="UTF-8">
              <title>Test</title>
               <link rel="stylesheet" type="text/css" href="mystyle.css">
           </head>
           <body>
              <h1>
                 How do you center a video
              </h1>
              <div class="center">
                 <video controls="controls">
                    <source src="https://repositorio.ufsc.br/xmlui/bitstream/handle/123456789/100149/Vídeo%20convertido.mp4" type="video/mp4" />
                 </video>
              </div>
           </body>
        </html></code>```

See the code ready here for more understanding.

You can view the code online Fiddle

Title: How to center HTML5 Videos?

Body:
I'm just messing around with some HTML5, and I was trying to center a video on the page. For some reason I can't get it to center. I've tried to add a class to the video tag itself, and I've wrapped the video in a separate div. However, the video stays on the left.

<!DOCTYPE HTML>

    <title>Test</title>

      <video controls="controls">
        <source src="/media/MVI_2563.ogg" type="video/ogg" />
        Your browser does not support the video tag.
      </video>

I know this must be something I'm overlooking in the wee hours of the morning, but any help would be appreciated.

Thanks

Body:
Use margins <video> is an inline element so you'll have to add display block;to your css class.

You can use specific with, but I wouldn’t use px values. Use % to make it responsive, like:

width: 50%;

That’ll make the video half of the viewport width.

See the original documentation here O World Wide Web Consortium W3C

mystyle.css

video {
      width: 50% !important;
      height: auto !important;
      margin: 0 auto;
      display: block;
    }

    h1 {
      text-align: center;
      color: #C42021;
      font-size: 20px;
    }

<!DOCTYPE html>
        <html>
           <head>
              <meta charset="UTF-8">
              <title>Test</title>
               <link rel="stylesheet" type="text/css" href="mystyle.css">
           </head>
           <body>
              <h1>
                 How do you center a video
              </h1>
              <div class="center">
                 <video controls="controls">
                    <source src="https://repositorio.ufsc.br/xmlui/bitstream/handle/123456789/100149/Vídeo%20convertido.mp4" type="video/mp4" />
                 </video>
              </div>
           </body>
        </html>

See the code ready here for more understanding.

You can view the code online Fiddle


问:
Hide a container and show another
I have a container and three elements inside it. I need to hide .short-post, show .long-post and modify the parent width.

.container, .short-post, .read-more
{
    display: block;
}

.long-post
{
    display: none;
}

.read-more:active > .short-post
{
    display: none;
}

.read-more:active > .long-post
{
    display: block;
}

.read-more:active > .container
{
    /*Previous width = 623px*/
    width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="short-post">
    something
    </div>
    <div class="long-post">
    something bigger
    </div>
    <span class="read-more">
    READ MORE
    </span>
</div></code>```

I know I can't use the selector > but I can't find one that fits my code, I'm reading all references here W3Schools CSS Selectors and testing them all. Is there a way to do what I want with CSS? I know that it's possible with JavaScript.

答:
CSS only approach using HTML details element

details {
  position: relative;
  width: 630px;
}

summary {
  display: block;
}

summary::-webkit-details-marker {
  display: none;
}

summary::before {
  content: 'READ MORE';
  position: absolute;
  bottom: -20px;
  cursor: pointer;
}

details[open]>summary {
  font-size: 0;
}

details[open]>summary::before {
  content: 'READ LESS';
  font-size: 16px;
}

details p {
  margin-top: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><details>
  <summary>something</summary>
  <p>something bigger</p>
</details></code>```

Title: Hide a container and show another

Body:
I have a container and three elements inside it. I need to hide .short-post, show .long-post and modify the parent width.

.container, .short-post, .read-more
{
    display: block;
}

.long-post
{
    display: none;
}

.read-more:active > .short-post
{
    display: none;
}

.read-more:active > .long-post
{
    display: block;
}

.read-more:active > .container
{
    /*Previous width = 623px*/
    width: 100%;
}

    something

    something bigger

    READ MORE

I know I can't use the selector > but I can't find one that fits my code, I'm reading all references here W3Schools CSS Selectors and testing them all. Is there a way to do what I want with CSS? I know that it's possible with JavaScript.

Body:
CSS only approach using HTML details element

details {
  position: relative;
  width: 630px;
}

summary {
  display: block;
}

summary::-webkit-details-marker {
  display: none;
}

summary::before {
  content: 'READ MORE';
  position: absolute;
  bottom: -20px;
  cursor: pointer;
}

details[open]>summary {
  font-size: 0;
}

details[open]>summary::before {
  content: 'READ LESS';
  font-size: 16px;
}

details p {
  margin-top: 0px;
}

<details>
  <summary>something</summary>
  <p>something bigger</p>
</details>


问:
Cannot delete record using laravel 5.4
I have button delete

```<code>{!! Form::open([
                    'route' => ['articles.destroy', $art->id],
                    'method' => 'DELETE',
                    'class' => ''
                ]) !!}
                    <button type="button" class="delete btn btn-danger glyphicon glyphicon-trash">  DELETE</button>
                {!! Form::close() !!}
</code>```

My route :

```<code>Route::delete('/articles/delete/{id}', [
'as' => 'articles.destroy',
'uses' => 'ArticlesController@destroy'
</code>```

]);

My Controller :

```<code>public function destroy($id)
{
    $article = Article::find($id);
    $article->delete();
}
</code>```

My problem is when I click the delete button it doesn't do anything

答: The form has to be submitted to call the route. To do this you should change type="button" to type="submit".

Title: Cannot delete record using laravel 5.4

Body:
I have button delete

{!! Form::open([
                    'route' => ['articles.destroy', $art->id],
                    'method' => 'DELETE',
                    'class' => ''
                ]) !!}
                    <button type="button" class="delete btn btn-danger glyphicon glyphicon-trash">  DELETE</button>
                {!! Form::close() !!}

My route :

Route::delete('/articles/delete/{id}', [
'as' => 'articles.destroy',
'uses' => 'ArticlesController@destroy'

]);

My Controller :

public function destroy($id)
{
    $article = Article::find($id);
    $article->delete();
}

My problem is when I click the delete button it doesn't do anything


问:
DropDownListFor in an MVC ASP application
I have a view model which you see below

```<code>public class AssetCategoryViewModel : IEnumerable<AssetCategory>
{
    DataModelContext db = new DataModelContext();
    public AssetCategory AssetCategory { get; set; }
    public Guid Id { get; set; }
    public IList<AssetCategory> AssetCategoryList { get; set; }
    public IEnumerable<SelectListItem> AssetCategoryNames { get; set; }
    public AssetCategoryViewModel()
    {
        AssetCategoryList = (from x in db.AssetCategory
                             select x).ToList();
        AssetCategoryNames = (from x in db.AssetCategory
                              select new SelectListItem
                              {
                                  Text = x.Name,
                                  Value = x.Code
                              });
    }

    public IEnumerator<AssetCategory> GetEnumerator()
    {
        return AssetCategoryList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}
</code>```

and I want to send  SelectlistItem to to view for using dropdownlist.

action method :

```<code>    public ActionResult AddNewCategory()
    {
        AssetCategoryViewModel acvm = new AssetCategoryViewModel();

        return View(acvm);
    }
</code>```

and div class (included dropdownlistfor helper method)

```<code>                <div class="form-group">
                    @Html.LabelFor(model => model.AssetCategory.MasterCategory, htmlAttributes: new { @class = "control-label" })
                    @Html.DropDownListFor(model => model.AssetCategoryNames, Model.AssetCategoryNames, "Seçim yapınız", htmlAttributes: new { @class = "form-control" })
                </div>
</code>```

and I got error

Server Error in '/' Application.
  Object reference not set to an instance of an object.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
  Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

I am stuck on this.

答:
I reccomend you to do this way to make dropdownlistfor
 Instead of using view model you create a model class and add a function which retrieves the data from the database

your model class should be like,`

```<code>public list<selectListItem> function()
{
    AssetCategoryList = (from x in db.AssetCategory
                                 select x).ToList();
            AssetCategoryNames = (from x in db.AssetCategory
                                  select new SelectListItem
                                  {
                                      Text = x.Name,
                                      Value = x.Code
                                  });`
}
return list;
</code>```

and it should return the value as list.

then the controller part should be

```<code> public ActionResult AddNewCategory()
    {
        AssetCategoryModel acm = new AssetCategoryModel();
viewmodel vm=new viewmodel();
vm.assetcatagorylist=acm.function();

        return View("viewname",vm);
    }
</code>```

then you should make to render the data to the view by passing the viewmodel data to ur view,

your view be like

```<code>@using projectname.ViewModel
@model ViewModel
<html>

//your design part

     @Html.DropDownListFor(m => m.assetcatagorylist, Model.assetcatagorylist, new { @id ="hi" })

</html>
</code>```

IT WORKS PERFECTLY
CHEERS,

Body:
I have a view model which you see below

public class AssetCategoryViewModel : IEnumerable<AssetCategory>
{
    DataModelContext db = new DataModelContext();
    public AssetCategory AssetCategory { get; set; }
    public Guid Id { get; set; }
    public IList<AssetCategory> AssetCategoryList { get; set; }
    public IEnumerable<SelectListItem> AssetCategoryNames { get; set; }
    public AssetCategoryViewModel()
    {
        AssetCategoryList = (from x in db.AssetCategory
                             select x).ToList();
        AssetCategoryNames = (from x in db.AssetCategory
                              select new SelectListItem
                              {
                                  Text = x.Name,
                                  Value = x.Code
                              });
    }

    public IEnumerator<AssetCategory> GetEnumerator()
    {
        return AssetCategoryList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

and I want to send  SelectlistItem to to view for using dropdownlist.

action method :

    public ActionResult AddNewCategory()
    {
        AssetCategoryViewModel acvm = new AssetCategoryViewModel();

        return View(acvm);
    }

and div class (included dropdownlistfor helper method)

                    @Html.LabelFor(model => model.AssetCategory.MasterCategory, htmlAttributes: new { @class = "control-label" })
                    @Html.DropDownListFor(model => model.AssetCategoryNames, Model.AssetCategoryNames, "Seçim yapınız", htmlAttributes: new { @class = "form-control" })

and I got error

Server Error in '/' Application.
  Object reference not set to an instance of an object.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
  Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

I am stuck on this.

Body:
I reccomend you to do this way to make dropdownlistfor
 Instead of using view model you create a model class and add a function which retrieves the data from the database

your model class should be like,`

public list<selectListItem> function()
{
    AssetCategoryList = (from x in db.AssetCategory
                                 select x).ToList();
            AssetCategoryNames = (from x in db.AssetCategory
                                  select new SelectListItem
                                  {
                                      Text = x.Name,
                                      Value = x.Code
                                  });`
}
return list;

and it should return the value as list.

then the controller part should be

 public ActionResult AddNewCategory()
    {
        AssetCategoryModel acm = new AssetCategoryModel();
viewmodel vm=new viewmodel();
vm.assetcatagorylist=acm.function();

        return View("viewname",vm);
    }

then you should make to render the data to the view by passing the viewmodel data to ur view,

your view be like

@using projectname.ViewModel
@model ViewModel
<html>

//your design part

     @Html.DropDownListFor(m => m.assetcatagorylist, Model.assetcatagorylist, new { @id ="hi" })

</html>

IT WORKS PERFECTLY
CHEERS,


问:
Nested hyperlinked areas without nested link elements in HTML source
I'd like to have something that looks and behaves as hyperlink inside larger rectangle (full page wide) which is also hyperlink. Below there is ASCII-art representation of what it should look like:

```
|-------------------------------------------|
| Some text  [_link_]                            |
|-------------------------------------------|
```

The whole outer rectangle (block element) is to be hyperlink. Inside this rectangle there should be some text, and at the end of this text there should be another link.

Unfortunately nesting links (A elements) is illegal in (X)HTML:

12.2.2 Nested links are illegal

Links and anchors defined by the A element must not be nested;
   an A element must not contain any other A elements.

(from http://www.w3.org/TR/html401/struct/links.html#h-12.2.2), so the most natural way of implementing above

```<code><a href="xxx" style="display: block">
  Some text
  <a href="yyy">link</a>
</a>
</code>```

is not valid HTML. What is even worse is that some web browsers in some cases enforce this requirement by moving inner link element just outside closing element of outer link element. This of course utterly breaks layout.

So what I'd like to ask is how to arrive at layout presented above using HTML and CSS (but no JavaScript), but without nested link elements in HTML source. It would be nice if behaviour was as close as possible to the one with nested link elements (for browsers which are not overly strict in implementing HTML standard).

Edit (16-01-2009)

Clarification: Solutions which use more than two link elements are perfectly acceptable

```<code><a href="xxx" ...>Some text</a>
<a href="yyy" ...>Link</a>
<a href="xxx" ...>& nbsp;</a>
...
</code>```

答:
What I have done in the past is use Javascript to attach the proper functionality to the div (assuming that is the parent element) so that when it is clicked, window.location is ran opening the .href attribute of the child link.

Something like this perhaps.

```<code>// jQuery Code
$(".parentDivLink").click(function(){
  window.location = $(this).find("a.mainLink").attr("href");
});

<div class="parentDivLink">
  <a href="http://www.google.com" title="Google" class="mainLink">Click Me</a>
</div>
</code>```

OwnerDisplayName: Jakub Narębski

Body:
I'd like to have something that looks and behaves as hyperlink inside larger rectangle (full page wide) which is also hyperlink. Below there is ASCII-art representation of what it should look like:

|-------------------------------------------|
| Some text  [_link_]                            |
|-------------------------------------------|

The whole outer rectangle (block element) is to be hyperlink. Inside this rectangle there should be some text, and at the end of this text there should be another link.

Unfortunately nesting links (A elements) is illegal in (X)HTML:

12.2.2 Nested links are illegal

Links and anchors defined by the A element must not be nested;
   an A element must not contain any other A elements.

(from http://www.w3.org/TR/html401/struct/links.html#h-12.2.2), so the most natural way of implementing above

  Some text
  link

is not valid HTML. What is even worse is that some web browsers in some cases enforce this requirement by moving inner link element just outside closing element of outer link element. This of course utterly breaks layout.

So what I'd like to ask is how to arrive at layout presented above using HTML and CSS (but no JavaScript), but without nested link elements in HTML source. It would be nice if behaviour was as close as possible to the one with nested link elements (for browsers which are not overly strict in implementing HTML standard).

Edit (16-01-2009)

Clarification: Solutions which use more than two link elements are perfectly acceptable

Some text
Link
& nbsp;
...

LastEditorDisplayName: Jakub Narębski

Body:
What I have done in the past is use Javascript to attach the proper functionality to the div (assuming that is the parent element) so that when it is clicked, window.location is ran opening the .href attribute of the child link.

Something like this perhaps.

// jQuery Code
$(".parentDivLink").click(function(){
  window.location = $(this).find("a.mainLink").attr("href");
});

<div class="parentDivLink">
  <a href="http://www.google.com" title="Google" class="mainLink">Click Me</a>
</div>

OwnerDisplayName: Jonathan Sampson


问:
How to split list to lists by condition?
I want split a list into multiple lists, based on a condition. If the difference in the series grows more than 4, then it is trigger to split the list till that item from last split item.

For example:

```<code>in = [1,2,3,9,10,11,100,200]
out = [ [1,2,3 ], [ 9,10,11 ], [100], [200]  ]
</code>```

by condition

```<code>If (next - prev) > 4
</code>```

Body:
I want split a list into multiple lists, based on a condition. If the difference in the series grows more than 4, then it is trigger to split the list till that item from last split item.

For example:

in = [1,2,3,9,10,11,100,200]
out = [ [1,2,3 ], [ 9,10,11 ], [100], [200]  ]

by condition

If (next - prev) > 4

Body:
def splitlist(L):
    if not L: return []
    answer = [[L[0]]]

    for i in L[1:]:
        if i - answer[-1][-1] < 4:
            answer[-1].append(i)
        else:
            answer.append([i])
    return answer

Output:

In [112]: splitlist([1,2,3,9,10,11,100,200])
Out[112]: [[1, 2, 3], [9, 10, 11], [100], [200]]


问:
How to "redefine" one char * to another char *?
Something like that: (it is task, how to do this, and not to change body of main function)

I thought that it is too simple... but... I don't know how to do it...

```<code>#include <iostream>

#define "a" "b"

int main( int argc,char ** argv) {
   std::cout << "a";
   return 0;
}
</code>```

// output: b

How to do it?

答: You can't. The preprocessor doesn't "look into" string literals.</p>

Body:
Something like that: (it is task, how to do this, and not to change body of main function)

I thought that it is too simple... but... I don't know how to do it...

#include <iostream>

#define "a" "b"

int main( int argc,char ** argv) {
   std::cout << "a";
   return 0;
}

// output: b

How to do it?


问:
NameError: name 'predict_from_url' is not defined
I am trying an MXNet tutorial mentioned at http://mxnet.io/tutorials/embedded/wine_detector.html (Section "Running the Model" on a raspberry pi3 using python3.4, specifically the script "inception_predict.py". I managed to fix a couple of issue but am getting stumped at this error:

>> import inception_predict

  [23:43:37] src/nnvm/legacy_json_util.cc:190: Loading symbol saved by previous version v0.8.0. Attempting to upgrade...

  [23:43:37] src/nnvm/legacy_json_util.cc:198: Symbol successfully upgraded!

>> predict_from_url("http://imgur.com/HzafyBA")

  Traceback (most recent call last):

   File "", line 1, in

  NameError: name 'predict_from_url' is not defined

Function predict_from_url is defined in the imported file inception_predict.py (as mentioned in the tutorial) so why is python telling me it is not defined?
 What am I doing wrong?

答:
The tutorial has a few errors that you need to fix to make it run:

add time to the import list in the inception_predict.py

...
import cv2, os, urllib, time
...

use a URL that you can actually download directly (use your favorite image search engine to find ones)

call the full name function

inception_predict. predict_from_url("https://media.mnn.com/assets/images/2017/01/cow-in-pasture.jpg.838x0_q80.jpg")

After these small changes you will see something like this:

```<code>pre-processed image in 0.27312707901
MKL Build:20170209
forward pass in 0.131096124649
probability=0.784963, class=n02403003 ox
probability=0.099463, class=n03868242 oxcart
probability=0.035585, class=n03967562 plow, plough
probability=0.033620, class=n02415577 bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis
probability=0.015443, class=n02412080 ram, tup
[(0.78496253, 'n02403003 ox'), (0.09946309, 'n03868242 oxcart'), (0.035584591, 'n03967562 plow, plough'), (0.033620458, 'n02415577 bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis'), (0.015442736, 'n02412080 ram, tup')]
</code>```

Body:
The tutorial has a few errors that you need to fix to make it run:

add time to the import list in the inception_predict.py

...
import cv2, os, urllib, time
...

use a URL that you can actually download directly (use your favorite image search engine to find ones)

call the full name function

inception_predict. predict_from_url("https://media.mnn.com/assets/images/2017/01/cow-in-pasture.jpg.838x0_q80.jpg")

After these small changes you will see something like this:

pre-processed image in 0.27312707901
MKL Build:20170209
forward pass in 0.131096124649
probability=0.784963, class=n02403003 ox
probability=0.099463, class=n03868242 oxcart
probability=0.035585, class=n03967562 plow, plough
probability=0.033620, class=n02415577 bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis
probability=0.015443, class=n02412080 ram, tup
[(0.78496253, 'n02403003 ox'), (0.09946309, 'n03868242 oxcart'), (0.035584591, 'n03967562 plow, plough'), (0.033620458, 'n02415577 bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis'), (0.015442736, 'n02412080 ram, tup')]


问:
Client-server app developing
As for practice project I'm making desktop(later android) pizza order app. I already made the test app with things its going to have and logic to run the processes but in order to achieve that I need client-server app. Could anyone share any general knowledge on how can It be achieved and any books/tutorials that could help me get the knowledge to get the project running.

I was making app in c#, also I stumbled upon this: http://www.networkcomms.net/

Could anyone tell me could it be achieved with this pack features?

Thanks everyone.

答:
Create an app is too general. but my recommendation is to built make a server first in some web technology, I work on ruby on rails you may create an api to supply the data to your client app. It does not matter if you are building your client app in javascript/html, IOS or android. your server can work across any client.

If your aim is to create an app later you could reuse the server side.

Hope it helps.

Some resources:

API book:
http://shop.oreilly.com/product/0636920021575.do

Rails book:
https://www.railstutorial.org/book

Title: Client-server app developing


问:
mongodb php MongoRegex slash
hi i have some problom with mongodb MongoRegex and php driver
i have string pc/mobile;

i need to serach in db like this

```<code>$string  = "pc/mobile";
$query = array( "cat" => new MongoRegex('/'.$string.'/') );
$cursor = $account_cat->find($query)->limit(1);
$array = iterator_to_array($cursor,false);
</code>```

i have tried

```<code>new MongoRegex('/'.$string.'/\')
</code>```

and this

```<code>new MongoRegex('/'.$string.'/i')
</code>```

which is working but i need not case sensitive.

can someone help? thanks

答:
As you have a / in your pattern, you need to escape that when sending it to MongoRegex. For example:

```<code>$cat = new MongoRegex( '/' . addslashes( $string ) . '/' );
$query = array( "cat" => $cat );
</code>```

But if you are just matching against a value, you should not need a regular expression.

Title: mongodb php MongoRegex slash

Body:
hi i have some problom with mongodb MongoRegex and php driver
i have string pc/mobile;

i need to serach in db like this

$string  = "pc/mobile";
$query = array( "cat" => new MongoRegex('/'.$string.'/') );
$cursor = $account_cat->find($query)->limit(1);
$array = iterator_to_array($cursor,false);

i have tried

new MongoRegex('/'.$string.'/\')

and this

new MongoRegex('/'.$string.'/i')

which is working but i need not case sensitive.

can someone help? thanks

Body:
As you have a / in your pattern, you need to escape that when sending it to MongoRegex. For example:

$cat = new MongoRegex( '/' . addslashes( $string ) . '/' );
$query = array( "cat" => $cat );

But if you are just matching against a value, you should not need a regular expression.


问:
rows csv into nested list
I'm a beginner in programming, but for a natural language processing project I need to work with csv.
I have this csv file with annotated text. The sentences are separated from each other with an empty row. Each row is a token (word or punctuation with it's annotation). What I need is a nested list like this [[[I,pronoun],[need, verb], [you, pronoun]], [[Do, verb], [you, pronoun], [need, verb], [me, pronoun]]]

The text looks like this in the csv:

```<code>I  pronoun
need  verb
you  pronoun

Do  pronoun
you  pronoun
need verb
me  pronoun
</code>```

I tried the following code, but then I only get one big list and not a nested list. I don't know how to split the sentences into different lists on the empty row.

```<code> sentences = []
    for row in text:
        sentences.append(list(row))
 print(sentences)
</code>```

Any suggestions?

答:
You can do something like

```<code>sentences = []
with open('my_file.csv', 'r') as R:
  curr = [] # store current sentence
  for row in R:
    if len(row) == 0:
      # empty line
      sentences.append(curr) # add current sentence to pool
      curr = [] # start a new sentence
      continue
    curr.append(row.strip().split()) # assuming no leading 1. etc.
</code>```

I am using strip to remove empty spaces from the beginning/end of the line, and split to split a string (row) into list elements.

Title: rows csv into nested list

Body:
I'm a beginner in programming, but for a natural language processing project I need to work with csv.
I have this csv file with annotated text. The sentences are separated from each other with an empty row. Each row is a token (word or punctuation with it's annotation). What I need is a nested list like this [[[I,pronoun],[need, verb], [you, pronoun]], [[Do, verb], [you, pronoun], [need, verb], [me, pronoun]]]

The text looks like this in the csv:

I  pronoun
need  verb
you  pronoun

Do  pronoun
you  pronoun
need verb
me  pronoun

I tried the following code, but then I only get one big list and not a nested list. I don't know how to split the sentences into different lists on the empty row.

 sentences = []
    for row in text:
        sentences.append(list(row))
 print(sentences)

Any suggestions?

Body:
You can do something like

sentences = []
with open('my_file.csv', 'r') as R:
  curr = [] # store current sentence
  for row in R:
    if len(row) == 0:
      # empty line
      sentences.append(curr) # add current sentence to pool
      curr = [] # start a new sentence
      continue
    curr.append(row.strip().split()) # assuming no leading 1. etc.

I am using strip to remove empty spaces from the beginning/end of the line, and split to split a string (row) into list elements.


问:
How to test for booleans in javascript or jquery?
I need to test in JS if a variable is a boolean or not. It has four possible value TRUE, FALSE, "TRUE" and "FALSE".
I am using the following code but the thing is that it never goes to the else even if the "value" is some other string.

let value = "true";// could be true, false, "true", "false" or some other text string
if ($.type(new Boolean(value)) === "boolean") {
  $("input[value='" + value + "']").prop("checked", true);
} else {
  $("input[name=" + columnName + "]").val(value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

答:
You just need the typeof keyword:

let value = "true"; // could be true, false, "true", "false" or some other text string
var columnName = "";
if (typeof value === "boolean") {
  // $("input[value='" + value + "']").prop("checked", true);
  console.log("Yes");
} else {
  // $("input[name=" + columnName + "]").val(value);
  console.log("No");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Now the reason why it doesn't go is, it is stored as string. The typeof or whatever way it is, will report it as string and not boolean. You shouldn't use " quotes to represent boolean variables.

To achieve what you need, you need a condition like:

```<code>if (typeof value === "boolean" || value.toLowerCase() === "true" || value.toLowerCase() === "false")
</code>```

This will make it work for you.

Body:
You just need the typeof keyword:

let value = "true"; // could be true, false, "true", "false" or some other text string
var columnName = "";
if (typeof value === "boolean") {
  // $("input[value='" + value + "']").prop("checked", true);
  console.log("Yes");
} else {
  // $("input[name=" + columnName + "]").val(value);
  console.log("No");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Now the reason why it doesn't go is, it is stored as string. The typeof or whatever way it is, will report it as string and not boolean. You shouldn't use " quotes to represent boolean variables.

To achieve what you need, you need a condition like:

if (typeof value === "boolean" || value.toLowerCase() === "true" || value.toLowerCase() === "false")

This will make it work for you.


问:
My autowired DataSource is returning null in Spring, how come?
I'm trying to set my dataSource to get a connection but it is returning null on conn=dataSource.getConnection();. Here is the relevant code from my DAO:

```<code>@Autowired
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
@Override
    public Acronym findByAcronymId(int acronymId) {
        String sql = "SELECT * FROM acronym_table WHERE acronymId = ?";

        Connection conn = null;

        try {
            conn = dataSource.getConnection();
</code>```

Here is the database bean:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id = "dataSource"
    class = "org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/db_name?useSSL=false" />
        <property name="username" value="username" />
        <property name="password" value="password" />
    </bean>

</beans>
</code>```

Here's the acronym bean:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id = "acronymDAO" class ="com.user.dao.JdbcAcronymDAO">
        <property name = "dataSource" ref ="dataSource"/>
    </bean>

</beans>
</code>```

答: The problem was that I had an extra bean. Once I deleted the acronym bean and setup @Autowired it worked correctly</p>

Body:
I'm trying to set my dataSource to get a connection but it is returning null on conn=dataSource.getConnection();. Here is the relevant code from my DAO:

@Autowired
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
@Override
    public Acronym findByAcronymId(int acronymId) {
        String sql = "SELECT * FROM acronym_table WHERE acronymId = ?";

        Connection conn = null;

        try {
            conn = dataSource.getConnection();

Here is the database bean:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id = "dataSource"
    class = "org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/db_name?useSSL=false" />
        <property name="username" value="username" />
        <property name="password" value="password" />
    </bean>

</beans>

Here's the acronym bean:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id = "acronymDAO" class ="com.user.dao.JdbcAcronymDAO">
        <property name = "dataSource" ref ="dataSource"/>
    </bean>

</beans>


问:
Struts2+jsonplugin: response takes a long time to display in browser from remote server
Sending request to action using Ajax, the result type is json. Use a json plugin for struts2. The result is correct, but takes a very long time.

Below is the content of struts.xml:

```<code><package name="FoodCompositionSearchajax"  extends="json-default">
      <action name="addSearchCondition" class ="com.fmOnline.action.FmzxMenuCompositionSearchAction" enter code here
method="addSearchCondition">
          <result name="success" type="json">
           <param name="excludeProperties">
     showList\[\d+\]\.foodStr,showList\[\d+\]\.nourishStr,
     showList\[\d+\]\.searchFunction,showList\[\d+\]\.num1,
     showList\[\d+\]\.num2,showList\[\d+\]\.danwei,
     showList\[\d+\]\.nourishname,showList\[\d+\]\.resultmap,
     dataList, foodList, foodStr, map, nourishList, nourishStr,
     num1, num2, paramList, searchDes, searchFun
   </param>
          </result>
     </action>
 </package>
</code>```

The <param name="includeProperties"> does not work, so use <param name="excludeProperties"> instead.

The result json contains a list (showList, contains 2 String attributes, the number of elements varies from 1 to 6) and a String. I have alerted the result content from the javascript in the client page, and the <param name="excludeProperties"> works.

The json result is :
{"msg":null, "showList":[{"id":1, "searchDes":"淀粉中的蛋白质含量>=11"}, {"id":2,"searchDes":"豆类中的蛋白质含量>=11"}, {"id":3, "searchDes":"禽类中的蛋白质含量>=11"}]}

At first, I used <result type="json"/>. I though the cause of the long time may be a too large object. Then I tried to @JSON(serialize=false) to deserialize the get methods, so that these methods will not execute at the conversion process from java to json. Finally I used excludeProperties. They all succeed in returning smaller object but failed to shorten the time. The response time of a normal jsp page is good

Problem:

When running the project on the local host, the response time is short.

When running in the remote server, it takes above 10 seconds to response on the client side. Operating Database is really quick, it seems that it takes a long time to send the result from server to browser.

When the result is null, the response time is short, even from remote server.

How can I shorten the response time?

答: I replace jsonplugin with json-lib-2.3-jdk15.jar, and the problem has settled. Really appreciate your help~ So happy now O(∩_∩)O~</p>

Body:
Sending request to action using Ajax, the result type is json. Use a json plugin for struts2. The result is correct, but takes a very long time.

Below is the content of struts.xml:

<package name="FoodCompositionSearchajax"  extends="json-default">
      <action name="addSearchCondition" class ="com.fmOnline.action.FmzxMenuCompositionSearchAction" enter code here
method="addSearchCondition">
          <result name="success" type="json">
           <param name="excludeProperties">
     showList\[\d+\]\.foodStr,showList\[\d+\]\.nourishStr,
     showList\[\d+\]\.searchFunction,showList\[\d+\]\.num1,
     showList\[\d+\]\.num2,showList\[\d+\]\.danwei,
     showList\[\d+\]\.nourishname,showList\[\d+\]\.resultmap,
     dataList, foodList, foodStr, map, nourishList, nourishStr,
     num1, num2, paramList, searchDes, searchFun
   </param>
          </result>
     </action>
 </package>

The <param name="includeProperties"> does not work, so use <param name="excludeProperties"> instead.

The result json contains a list (showList, contains 2 String attributes, the number of elements varies from 1 to 6) and a String. I have alerted the result content from the javascript in the client page, and the <param name="excludeProperties"> works.

The json result is :
{"msg":null, "showList":[{"id":1, "searchDes":"淀粉中的蛋白质含量>=11"}, {"id":2,"searchDes":"豆类中的蛋白质含量>=11"}, {"id":3, "searchDes":"禽类中的蛋白质含量>=11"}]}

At first, I used <result type="json"/>. I though the cause of the long time may be a too large object. Then I tried to @JSON(serialize=false) to deserialize the get methods, so that these methods will not execute at the conversion process from java to json. Finally I used excludeProperties. They all succeed in returning smaller object but failed to shorten the time. The response time of a normal jsp page is good

Problem:

When running the project on the local host, the response time is short.

When running in the remote server, it takes above 10 seconds to response on the client side. Operating Database is really quick, it seems that it takes a long time to send the result from server to browser.

When the result is null, the response time is short, even from remote server.

How can I shorten the response time?


问:
How to pass prop to eventhandler?
I have 4 span with onClick={this.clickhandler}. Inside the clickhandler there is an audio which i'd like to play when clicked. The problem is, i want 4 different audio-urls inside the same clickhandler. How can i associate each span with an audio-string and pass it to the same eventhandler?

clickhander(e) {
    const audio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3');
    audio.play()
    console.dir(e.target)
}
render() {
    return(

Simon Game

                <Heart fill="#555"/>

                <Heart fill="#402" />

                <Heart fill="#f39" />

                <Heart fill="#29f" />

    )
}```
</div>
</div>
</p>

<p>EDIT: i tried the solutions below but i get this error:  The error you provided does not contain a stack trace.</p>

<p>this is my code now: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Home extends Component {

    constructor(props){
        super(props)
    }
    clickhander(e, url) {
        const str = url
        const audio = new Audio(String(str));
        audio.play()

    }
    render() {
        return(
            <div className="container">
                <h1 className="header">Simon Game</h1>
                <span  onClick={this.clickhander.bind(this, "https://s3.amazonaws.com/freecodecamp/simonSound1.mp3")}>
                    <Heart fill="#555"/>
                </span>
                <span onClick={this.clickhander}>
                    <Heart fill="#402" />
                </span>
                <span onClick={this.clickhander}>
                    <Heart fill="#f39" />
                </span>
                <span onClick={this.clickhander}>
                    <Heart fill="#29f" />
                </span>
            </div>
        )
    }
}

export default Home</code>```

答:
In React, try to think component-like.

app.js

```<code>class App extends Component {

  audioArr = ['link1', 'link2', 'link3']; // links to songs

  render() {
    return (
      <div className="App">
        {this.audioArr.map((link, i) => (
          <Player link={link} key={i} />
        ))}
      </div>
    )
  }
}
</code>```

Player.js

```<code>class Player extends Component {

  handleClick = () => {
    const audio = new Audio(this.props.link);
    audio.play();
  };

  render() {
    return (
      <div>
        <span onClick={this.handleClick}>
          <Heart fill="#29f" />
        </span>
      </div>
    );
  }
}
</code>```

Title: How to pass prop to eventhandler?

Body:
I have 4 span with onClick={this.clickhandler}. Inside the clickhandler there is an audio which i'd like to play when clicked. The problem is, i want 4 different audio-urls inside the same clickhandler. How can i associate each span with an audio-string and pass it to the same eventhandler?

clickhander(e) {
    const audio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3');
    audio.play()
    console.dir(e.target)
}
render() {
    return(

Simon Game

                <Heart fill="#555"/>

                <Heart fill="#402" />

                <Heart fill="#f39" />

                <Heart fill="#29f" />

    )
}

EDIT: i tried the solutions below but i get this error:  The error you provided does not contain a stack trace.

this is my code now:

class Home extends Component {

    constructor(props){
        super(props)
    }
    clickhander(e, url) {
        const str = url
        const audio = new Audio(String(str));
        audio.play()

    }
    render() {
        return(

Simon Game

                    <Heart fill="#555"/>

                    <Heart fill="#402" />

                    <Heart fill="#f39" />

                    <Heart fill="#29f" />

        )
    }
}

export default Home

Body:
In React, try to think component-like.

app.js

class App extends Component {

  audioArr = ['link1', 'link2', 'link3']; // links to songs

  render() {
    return (
      <div className="App">
        {this.audioArr.map((link, i) => (
          <Player link={link} key={i} />
        ))}
      </div>
    )
  }
}

Player.js

class Player extends Component {

  handleClick = () => {
    const audio = new Audio(this.props.link);
    audio.play();
  };

  render() {
    return (
      <div>
        <span onClick={this.handleClick}>
          <Heart fill="#29f" />
        </span>
      </div>
    );
  }
}


问:
Get All exceptions in Command Line Symfony 2
I have a command that runs with Cron, and i Want to create file with logs.
In that file i write the successfully log and I want to write also the exception logs and I want to see the logs to console, if i launch my command manually

I created the service like this link But I don't see any log and any error in my console

I don't Understand what i have to do after create the service

my command is Simple and extends ContainerAwareCommand

class CreateXmlCommand extends ContainerAwareCommand

```<code>{
    protected function configure()
    {
        $this
            ->setName('foo')
            );

    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        //stuff

    }
}
</code>```

I Want to get also FatalErrorException and write it in my file

答:
To catch fatals, etc... pre PHP7, you'll need to setup an error hander, to catch the errors, and throw an exception yourself. E.g.

```<code>function exception_error_handler($severity, $message, $file, $line)
{
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting
        return;
    }

    $message = sprintf('Error: %s, occured in (%s) on line (%s)', $message, $file, $line);

    throw new ErrorException($message, 0, $severity, $file, $line);
}
</code>```

Then once you have your function you need to register it

```<code>set_error_handler('exception_error_handler');
</code>```

Body:
I have a command that runs with Cron, and i Want to create file with logs.
In that file i write the successfully log and I want to write also the exception logs and I want to see the logs to console, if i launch my command manually

I created the service like this link But I don't see any log and any error in my console

I don't Understand what i have to do after create the service

my command is Simple and extends ContainerAwareCommand

class CreateXmlCommand extends ContainerAwareCommand

{
    protected function configure()
    {
        $this
            ->setName('foo')
            );

    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        //stuff

    }
}

I Want to get also FatalErrorException and write it in my file

Body:
To catch fatals, etc... pre PHP7, you'll need to setup an error hander, to catch the errors, and throw an exception yourself. E.g.

function exception_error_handler($severity, $message, $file, $line)
{
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting
        return;
    }

    $message = sprintf('Error: %s, occured in (%s) on line (%s)', $message, $file, $line);

    throw new ErrorException($message, 0, $severity, $file, $line);
}

Then once you have your function you need to register it

set_error_handler('exception_error_handler');


问:
transposing data with macro
I would like to transpose my data using a loop and not the typical transpose function so I don't have to merge the data with unused variables.

Data I have is the following:

```<code>df1 <- data.frame(ID=c(1:4), Amount=c(100, 150, 75, 50),
    Month=c("Jan", "Feb", "Mar", "Apr"))
</code>```

Which gives the following results:

```<code>ID Amount Month
1    100   Jan
2    150   Feb
3     75   Mar
4     50   Apr
</code>```

I would like the final results to be like this:

```<code>ID Amount Jan Feb Mar Apr
1    100   1   0   0   0
2    150   0   1   0   0
3     75   0   0   1   0
4     50   0   0   0   1
</code>```

I would know how to do this in SAS but couldn't find a solution with R.  Your help is appreciated.

答:
```<code>library('tidyr')
df1 <- data.frame(ID=c(1:4), Amount=c(100, 150, 75, 50),
                  Month=c("Jan", "Feb", "Mar", "Apr"))
df1$ID <- 1
df1 <- spread(df1 , Month, ID, fill=0)
df1
</code>```

will result in:

```<code>  Amount Apr Feb Jan Mar
1     50   1   0   0   0
2     75   0   0   0   1
3    100   0   0   1   0
4    150   0   1   0   0
</code>```

Title: transposing data with macro

Body:
I would like to transpose my data using a loop and not the typical transpose function so I don't have to merge the data with unused variables.

Data I have is the following:

df1 <- data.frame(ID=c(1:4), Amount=c(100, 150, 75, 50),
    Month=c("Jan", "Feb", "Mar", "Apr"))

Which gives the following results:

ID Amount Month
1    100   Jan
2    150   Feb
3     75   Mar
4     50   Apr

I would like the final results to be like this:

ID Amount Jan Feb Mar Apr
1    100   1   0   0   0
2    150   0   1   0   0
3     75   0   0   1   0
4     50   0   0   0   1

I would know how to do this in SAS but couldn't find a solution with R.  Your help is appreciated.

Body:
library('tidyr')
df1 <- data.frame(ID=c(1:4), Amount=c(100, 150, 75, 50),
                  Month=c("Jan", "Feb", "Mar", "Apr"))
df1$ID <- 1
df1 <- spread(df1 , Month, ID, fill=0)
df1

will result in:

  Amount Apr Feb Jan Mar
1     50   1   0   0   0
2     75   0   0   0   1
3    100   0   0   1   0
4    150   0   1   0   0


问:
NPM install gulp --save-dev error
I'm trying to get set up on a project with Gulp.js when I run the command:

```<code>npm install gulp --save-dev
</code>```

I get the errors:

```<code>npm WARN package.json htdocs@0.0.0 No repository field.
npm WARN package.json gulp-uglify@1.0.1 No README data
npm WARN package.json gulp@3.8.8 No README data
npm ERR! Error: EACCES, chown '/path/to/dir/htdocs/node_modules/gulp/package.json'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES, chown '/path/to/dir/htdocs/node_modules/gulp/package.json']
npm ERR!   stack: 'Error: EACCES, chown \'/path/to/dir/htdocs/node_modules/gulp/package.json\'\n    at Error (native)',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/path/to/dir/htdocs/node_modules/gulp/package.json',
npm ERR!   fstream_finish_call: 'chown',
npm ERR!   fstream_type: 'File',
npm ERR!   fstream_path: '/path/to/dir/htdocs/node_modules/gulp/package.json',
npm ERR!   fstream_class: 'FileWriter',
npm ERR!   fstream_stack:
npm ERR!    [ '/usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:308:19',
npm ERR!      '/usr/local/lib/node_modules/npm/node_modules/graceful-fs/polyfills.js:143:7',
npm ERR!      'Object.oncomplete (evalmachine.<anonymous>:93:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Linux 3.0.0-12-generic-pae
npm ERR! command "node" "/usr/local/bin/npm" "install" "gulp" "--save-dev"
npm ERR! cwd /path/to/dir/htdocs
npm ERR! node -v v0.13.0-pre
npm ERR! npm -v 1.4.26
npm ERR! path /path/to/dir/htdocs/node_modules/gulp/package.json
npm ERR! fstream_path /path/to/dir/htdocs/node_modules/gulp/package.json
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! fstream_finish_call chown
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! stack Error: EACCES, chown '/path/to/dir/htdocs/node_modules/gulp/package.json'
npm ERR! stack     at Error (native)
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:308:19
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/graceful-fs/polyfills.js:143:7
npm ERR! fstream_stack Object.oncomplete (evalmachine.<anonymous>:93:15)
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /path/to/dir/htdocs/npm-debug.log
npm ERR! not ok code 0
</code>```

Here is my package.json file

```<code>{
  "name": "htdocs",
  "version": "0.0.0",
  "description": "",
  "main": "gulpfile.js",
  "dependencies": {
    "gulp": "^3.8.8",
    "gulp-uglify": "1.0.1"
  },
  "devDependencies": {
    "gulp": "^3.8.8",
    "gulp-uglify": "1.0.1"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
</code>```

I found a few people with similar issues online and the fixes suggested running the command:

sudo chown -R whoami ~/.npm
  But this has not solved the issue in my case.

Does anyone have an idea what the cause of this could be and a solution?

答:
running
npm install npm@latest -g
and updating to the latest version solved the issue for me :)</p>

Title: NPM install gulp --save-dev error

Body:
I'm trying to get set up on a project with Gulp.js when I run the command:

npm install gulp --save-dev

I get the errors:

npm WARN package.json htdocs@0.0.0 No repository field.
npm WARN package.json gulp-uglify@1.0.1 No README data
npm WARN package.json gulp@3.8.8 No README data
npm ERR! Error: EACCES, chown '/path/to/dir/htdocs/node_modules/gulp/package.json'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES, chown '/path/to/dir/htdocs/node_modules/gulp/package.json']
npm ERR!   stack: 'Error: EACCES, chown \'/path/to/dir/htdocs/node_modules/gulp/package.json\'\n    at Error (native)',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/path/to/dir/htdocs/node_modules/gulp/package.json',
npm ERR!   fstream_finish_call: 'chown',
npm ERR!   fstream_type: 'File',
npm ERR!   fstream_path: '/path/to/dir/htdocs/node_modules/gulp/package.json',
npm ERR!   fstream_class: 'FileWriter',
npm ERR!   fstream_stack:
npm ERR!    [ '/usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:308:19',
npm ERR!      '/usr/local/lib/node_modules/npm/node_modules/graceful-fs/polyfills.js:143:7',
npm ERR!      'Object.oncomplete (evalmachine.<anonymous>:93:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Linux 3.0.0-12-generic-pae
npm ERR! command "node" "/usr/local/bin/npm" "install" "gulp" "--save-dev"
npm ERR! cwd /path/to/dir/htdocs
npm ERR! node -v v0.13.0-pre
npm ERR! npm -v 1.4.26
npm ERR! path /path/to/dir/htdocs/node_modules/gulp/package.json
npm ERR! fstream_path /path/to/dir/htdocs/node_modules/gulp/package.json
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! fstream_finish_call chown
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! stack Error: EACCES, chown '/path/to/dir/htdocs/node_modules/gulp/package.json'
npm ERR! stack     at Error (native)
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:308:19
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/graceful-fs/polyfills.js:143:7
npm ERR! fstream_stack Object.oncomplete (evalmachine.<anonymous>:93:15)
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /path/to/dir/htdocs/npm-debug.log
npm ERR! not ok code 0

Here is my package.json file

{
  "name": "htdocs",
  "version": "0.0.0",
  "description": "",
  "main": "gulpfile.js",
  "dependencies": {
    "gulp": "^3.8.8",
    "gulp-uglify": "1.0.1"
  },
  "devDependencies": {
    "gulp": "^3.8.8",
    "gulp-uglify": "1.0.1"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

I found a few people with similar issues online and the fixes suggested running the command:

sudo chown -R whoami ~/.npm
  But this has not solved the issue in my case.

Does anyone have an idea what the cause of this could be and a solution?


问:
Strange behavior of function Simd::Fill()
I use function Simd::Fill from Simd Library. And it works fine in the most cases. But there is a strange behavior sometimes. For example, in this case:

```<code>#include "Simd/SimdLib.hpp"

typedef Simd::View<Simd::Allocator> View;

View Create(size_t w, size_t h, uint8_t color)
{
    View image(w, h, View::Gray8);
    Simd::Fill(image, color);
    return image;
}

int main()
{
    View image;

    image = Create(200, 150, 127);
    image.Save("image.pgm");

    return 0;
}
</code>```

Saved "image.pgm":

There is a strange noise in the image. It is similar to memory corruption, but I can't find where is it. Could anybody help me?

答:
It seems that I found a mistake which leads to this behavior.
Assignment operator View& operator=(const View &view) of Simd::View class assigns only reference to other image. So your function Create() returns reference to local object. </p>

<p>In order to create copy of the Simd::View you have to use function Simd::Copy() or method Simd::View::Clone(). </p>

Body:
I use function Simd::Fill from Simd Library. And it works fine in the most cases. But there is a strange behavior sometimes. For example, in this case:

#include "Simd/SimdLib.hpp"

typedef Simd::View<Simd::Allocator> View;

View Create(size_t w, size_t h, uint8_t color)
{
    View image(w, h, View::Gray8);
    Simd::Fill(image, color);
    return image;
}

int main()
{
    View image;

    image = Create(200, 150, 127);
    image.Save("image.pgm");

    return 0;
}

Saved "image.pgm":

There is a strange noise in the image. It is similar to memory corruption, but I can't find where is it. Could anybody help me?

Body:
It seems that I found a mistake which leads to this behavior.
Assignment operator View& operator=(const View &view) of Simd::View class assigns only reference to other image. So your function Create() returns reference to local object.

In order to create copy of the Simd::View you have to use function Simd::Copy() or method Simd::View::Clone().


问:
Hamburger menu and app bar
I want to achieve layout simmilar to Groove application, where hamburger menu is on the left and appbar on the bottom. However, not all pages contains appbar.

I have an usercontrol called MainFrame which contains the hamburger menu and a navigation frame.

When page is loaded into the navigation frame, the AppBar overlays the HamburgerMenu. I could just offset the HamburgerMenu, but not all pages contains the AppBar, or the AppBar's height is different.

Is it possible to show the hamburger on top of appbar? Or do you have any other ideas?

答:
Use CommandBar instead of Page.BottomAppBar. Also, it is the recommended way for UWP by Microsoft.

You should use the AppBar only when you are upgrading a Universal
  Windows 8 app that uses the AppBar, and need to minimize changes. For
  new apps in Windows 10, we recommend using the CommandBar control
  instead.

Set the CommandBar in the content Grid of HamburgerMenu

Here is a sample code:

```<code><controls:HamburgerMenu>
    <!--  Items  -->
    <controls:HamburgerMenu.ItemsSource>
    </controls:HamburgerMenu.ItemsSource>
    <!--  Options  -->
    <controls:HamburgerMenu.OptionsItemsSource>
    </controls:HamburgerMenu.OptionsItemsSource>
    <!--  Content  -->
    <Grid x:Name="ContentGrid">
        <Frame Name="MainFrame"/>
        <CommandBar VerticalAlignment="Bottom"/>
    </Grid>
</controls:HamburgerMenu>
</code>```

Title: Hamburger menu and app bar

Body:
Use CommandBar instead of Page.BottomAppBar. Also, it is the recommended way for UWP by Microsoft.

You should use the AppBar only when you are upgrading a Universal
  Windows 8 app that uses the AppBar, and need to minimize changes. For
  new apps in Windows 10, we recommend using the CommandBar control
  instead.

Set the CommandBar in the content Grid of HamburgerMenu

Here is a sample code:

<controls:HamburgerMenu>
    <!--  Items  -->
    <controls:HamburgerMenu.ItemsSource>
    </controls:HamburgerMenu.ItemsSource>
    <!--  Options  -->
    <controls:HamburgerMenu.OptionsItemsSource>
    </controls:HamburgerMenu.OptionsItemsSource>
    <!--  Content  -->
    <Grid x:Name="ContentGrid">
        <Frame Name="MainFrame"/>
        <CommandBar VerticalAlignment="Bottom"/>
    </Grid>
</controls:HamburgerMenu>


问:
How can I remove the last character of a file in unix?
Say I have some arbitrary multi-line text file:

```<code>sometext
moretext
lastline
</code>```

How can I remove only the last character (the e, not the newline or null) of the file without making the text file invalid?

答:
Just a remark: sed will temporarily remove the file.
So if you are tailing the file, you'll get a "No such file or directory" warning until you reissue the tail command.</p>

Body:
Say I have some arbitrary multi-line text file:

sometext
moretext
lastline

How can I remove only the last character (the e, not the newline or null) of the file without making the text file invalid?


问:
Ruby : Getting error []': no implicit conversion of String into Integer (TypeError)
```<code>class LineAnalyzer
    @@highest_wf_count = 0
    @@highest_wf_words = Hash.new(0)

    def initialize(content, line_number)
      @content = content
      @line_number = line_number
      calculate_word_frequency(content)
    end

    def calculate_word_frequency(content)
        content.split.each do |word|
          @@highest_wf_words[word.downcase] +=1
        end
        @@highest_wf_words = @@highest_wf_words.sort_by{|k,v| -v}
    end
end

class Solution

    def initialize()
        @analyzers = Array.new
        @highest_count_words_across_lines = Array.new
    end
    def analyze_file()
        @line_number = 0
        File.foreach('test.txt') do |content|
          @line_number += 1
          @line = LineAnalyzer.new(content,@line_number)
          @analyzers.<<(@line)
        end
    end
end
</code>```

When trying to create LineAnalyzer object and passing values, getting this error in:

```<code>@line = LineAnalyzer.new(content,@line_number)
</code>```

This is what I getting:

```<code>Max-Word-Freq/module2_assignment.rb:34:in `calculate_word_frequency'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:25:in `initialize'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:68:in `new'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:68:in `block in analyze_file'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:66:in `foreach'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:66:in `analyze_file'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/solution.rb:10:in `<main>'
</code>```

答:
You have this error because you are trying to use an Array like a Hash.

On this line :

```<code> @@highest_wf_words = @@highest_wf_words.sort_by{|k,v| -v}
</code>```

In the first time @@highest_wf_words is indeed a Hash but the sort_by method is returning an Array. So when you use it again you have an error.

If you want to sort your hash by value you can do this :

```<code>@@highest_wf_words = Hash[@@highest_wf_words.sort]
# Or reverse it
@@highest_wf_words = Hash[@@highest_wf_words.sort.reverse]
</code>```

Look at this for further explanation : Hash::[]

Body:
class LineAnalyzer
    @@highest_wf_count = 0
    @@highest_wf_words = Hash.new(0)

    def initialize(content, line_number)
      @content = content
      @line_number = line_number
      calculate_word_frequency(content)
    end

    def calculate_word_frequency(content)
        content.split.each do |word|
          @@highest_wf_words[word.downcase] +=1
        end
        @@highest_wf_words = @@highest_wf_words.sort_by{|k,v| -v}
    end
end

class Solution

    def initialize()
        @analyzers = Array.new
        @highest_count_words_across_lines = Array.new
    end
    def analyze_file()
        @line_number = 0
        File.foreach('test.txt') do |content|
          @line_number += 1
          @line = LineAnalyzer.new(content,@line_number)
          @analyzers.<<(@line)
        end
    end
end

When trying to create LineAnalyzer object and passing values, getting this error in:

@line = LineAnalyzer.new(content,@line_number)

This is what I getting:

Max-Word-Freq/module2_assignment.rb:34:in `calculate_word_frequency'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:25:in `initialize'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:68:in `new'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:68:in `block in analyze_file'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:66:in `foreach'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:66:in `analyze_file'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/solution.rb:10:in `'

Body:
You have this error because you are trying to use an Array like a Hash.

On this line :

 @@highest_wf_words = @@highest_wf_words.sort_by{|k,v| -v}

In the first time @@highest_wf_words is indeed a Hash but the sort_by method is returning an Array. So when you use it again you have an error.

If you want to sort your hash by value you can do this :

@@highest_wf_words = Hash[@@highest_wf_words.sort]
# Or reverse it
@@highest_wf_words = Hash[@@highest_wf_words.sort.reverse]

Look at this for further explanation : Hash::[]


问:
The MongoDB PECL extension has not been installed or enabled codeigniter
Hi All i am trying to connect mongodb with php  codeigniter framework.

i have made changes in

php.in file   extension=php_mongodb.dll

and put file in xampp/php/ext/php_mongodb.dll

when i  load my php dashboard  i found there mongodb is install  and get this message.

but still i am facing issue there  The MongoDB PECL extension has not been installed or enabled

i have placed  Mongo_db.php in library folder and also mongo_db.php  in config folder.

How can i solve my problem.

i am using php 7 n xampp and mongo db install  in my machine 3.4 version

答:
It is possible that CodeIgniter does not work yet with the new "mongodb" extension that you have installed, but instead relies on the old "mongo" extension.

You can still find the latter online (http://pecl.php.net/mongo), but you should probably find a few to get CodeIgniter to use the new one that you have installed instead.


问:
iOS - How can I display an 'AirPlay' popup menu in Swift?
How can I display an AirPlay popup menu in my Swift project? (Many applications like Spotify can display one like below):

答:
After all it seems there is no easy and straightforward way to make a custom button display the system's Airplay menu.

However, @totiG pointer me to an interesting resource and I created a script that creates the standard Volume Control outside of the visible area of the screen a simulates a click on the Airplay button:

```<code>func showAirplay() {
    let rect = CGRect(x: -100, y: 0, width: 0, height: 0)
    let airplayVolume = MPVolumeView(frame: rect)
    airplayVolume.showsVolumeSlider = false
    self.view.addSubview(airplayVolume)
    for view: UIView in airplayVolume.subviews {
        if let button = view as? UIButton {
            button.sendActions(for: .touchUpInside)
            break
        }
    }
    airplayVolume.removeFromSuperview()
}
</code>```

After running this code the following popup menu appears:

Body:
After all it seems there is no easy and straightforward way to make a custom button display the system's Airplay menu.

However, @totiG pointer me to an interesting resource and I created a script that creates the standard Volume Control outside of the visible area of the screen a simulates a click on the Airplay button:

func showAirplay() {
    let rect = CGRect(x: -100, y: 0, width: 0, height: 0)
    let airplayVolume = MPVolumeView(frame: rect)
    airplayVolume.showsVolumeSlider = false
    self.view.addSubview(airplayVolume)
    for view: UIView in airplayVolume.subviews {
        if let button = view as? UIButton {
            button.sendActions(for: .touchUpInside)
            break
        }
    }
    airplayVolume.removeFromSuperview()
}

After running this code the following popup menu appears: