问:
React component rendered twice using server side rendering
I have an app where I configured server side rendering. Everything is working nice and my component is rendered on the server. The problem is that I get my component rendered twice on the screen. One comes from
<%- content %>
that I am using for server rendering and one comes from . I use webpack to make two bundles for my server and client. Why is this happening and how can I fix this?

views/index.ejs

```<code><body>
  <div id="app"></div>
  <div id="content"><%- content %></div>
  <script src="http://localhost:3001/bundle.js"></script>
</body>
</code>```

index.js

```<code>app.use(Express.static(path.join(__dirname, '../', 'dist')))

app.use(serverRenderer)
app.get('*', (req: Object, res: Object) => {
  res.render('index', {content: req.body})
})
</code>```

serverRender

```<code>import React from 'react'
import ReactDOM from 'react-dom/server'
import { match, RouterContext } from 'react-router'
import routes from '../client/routes.js'

async function render (component) {
  const content = ReactDOM.renderToString(component)
  return content
}

async function getMatchParams (routes, currentUrl) {
  return new Promise((resolve, reject) => {
    match({routes: routes, location: currentUrl}, (err, redirect, props) => {
      if (err) {
        return reject(err)
      }
      return resolve(props)
    })
  })
}

export default async(req, res, next) => {
  const renderProps = await getMatchParams(routes, req.url)
  if (renderProps) {
    const component = (
      <RouterContext {...renderProps} />
    )
    req.body = await render(component)
    next()
  }
}
</code>```

答:
Ok. I have found a problem. I was referring to the bundle and server rendered string with two separate
. Inside my app.js I was doing this

```<code>render(
    <Router history={browserHistory}>
      {routes}
    </Router>,
  document.getElementById('app')
)
</code>```

Thats why I should have been sending the string to the template like this.

```<code>app.use(Express.static(path.join(__dirname, '../', 'dist')))

app.use(serverRenderer)
app.get('*', (req: Object, res: Object) => {
  res.render('index', {app: req.body})
})
</code>```

And finally my views/index.js should look like this

```<code><body>
  <div id="app"><%- app %></div>
  <script src="http://localhost:3001/bundle.js"></script>
</body>
</code>```

Body:
I have an app where I configured server side rendering. Everything is working nice and my component is rendered on the server. The problem is that I get my component rendered twice on the screen. One comes from
<%- content %>
that I am using for server rendering and one comes from . I use webpack to make two bundles for my server and client. Why is this happening and how can I fix this?

views/index.ejs

<%- content %>

index.js

app.use(Express.static(path.join(__dirname, '../', 'dist')))

app.use(serverRenderer)
app.get('*', (req: Object, res: Object) => {
  res.render('index', {content: req.body})
})

serverRender

import React from 'react'
import ReactDOM from 'react-dom/server'
import { match, RouterContext } from 'react-router'
import routes from '../client/routes.js'

async function render (component) {
  const content = ReactDOM.renderToString(component)
  return content
}

async function getMatchParams (routes, currentUrl) {
  return new Promise((resolve, reject) => {
    match({routes: routes, location: currentUrl}, (err, redirect, props) => {
      if (err) {
        return reject(err)
      }
      return resolve(props)
    })
  })
}

export default async(req, res, next) => {
  const renderProps = await getMatchParams(routes, req.url)
  if (renderProps) {
    const component = (
      <RouterContext {...renderProps} />
    )
    req.body = await render(component)
    next()
  }
}

Body:
Ok. I have found a problem. I was referring to the bundle and server rendered string with two separate <div>. Inside my app.js I was doing this

render(
    <Router history={browserHistory}>
      {routes}
    </Router>,
  document.getElementById('app')
)

Thats why I should have been sending the string to the template like this.

app.use(Express.static(path.join(__dirname, '../', 'dist')))

app.use(serverRenderer)
app.get('*', (req: Object, res: Object) => {
  res.render('index', {app: req.body})
})

And finally my views/index.js should look like this

<body>
  <div id="app"><%- app %></div>
  <script src="http://localhost:3001/bundle.js"></script>
</body>


来源: stackexchange

问:
How to delete a file via PHP?
How do I delete a file from my server with PHP if the file is in another directory?

Here is my page layout:

projects/backend/removeProjectData.php (this file deletes all my entries for the database and should also delete the related file)

public_files/22.pdf (the place where the file is located.)

I'm using the unlink function:

unlink('../../public_files/' . $fileName);

But this always gives me an error that the file does not exist. Any ideas?

答:
AIO solution, handles everything, It's not my work but I just improved myself. Enjoy!

```<code>/**
 * Unlink a file, which handles symlinks.
 * @see https://github.com/luyadev/luya/blob/master/core/helpers/FileHelper.php
 * @param string $filename The file path to the file to delete.
 * @return boolean Whether the file has been removed or not.
 */
function unlinkFile ( $filename ) {
    // try to force symlinks
    if ( is_link ($filename) ) {
        $sym = @readlink ($filename);
        if ( $sym ) {
            return is_writable ($filename) && @unlink ($filename);
        }
    }

    // try to use real path
    if ( realpath ($filename) && realpath ($filename) !== $filename ) {
        return is_writable ($filename) && @unlink (realpath ($filename));
    }

    // default unlink
    return is_writable ($filename) && @unlink ($filename);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to delete a file via PHP?

Body:
AIO solution, handles everything, It's not my work but I just improved myself. Enjoy!

/**
 * Unlink a file, which handles symlinks.
 * @see https://github.com/luyadev/luya/blob/master/core/helpers/FileHelper.php
 * @param string $filename The file path to the file to delete.
 * @return boolean Whether the file has been removed or not.
 */
function unlinkFile ( $filename ) {
    // try to force symlinks
    if ( is_link ($filename) ) {
        $sym = @readlink ($filename);
        if ( $sym ) {
            return is_writable ($filename) && @unlink ($filename);
        }
    }

    // try to use real path
    if ( realpath ($filename) && realpath ($filename) !== $filename ) {
        return is_writable ($filename) && @unlink (realpath ($filename));
    }

    // default unlink
    return is_writable ($filename) && @unlink ($filename);
}

ContentLicense: CC BY-SA 4.0


问:
Displaying images from ImageField
I try to display the same image of a coin in 2 sections of my site (a list of articles and a gallery of coins). The only difference (I guess) is that from the articles page I call it by a foreign key while from the gallery I call it directly.

The image is displayed in the article list but not in the gallery.

Here is some code:

the models:

```<code># coinCollection/models.py:
class coin(models.Model):
    #...
    coin_thumbnail = models.ImageField(max_length=500, upload_to = join(MEDIA_IMAGES_DIR, MEDIA_COINS_DIR), verbose_name='Miniature')
    #...

# blog/models.py:
class article(models.Model):
    #...
    article_money = models.ForeignKey(coin,
        null = True,
        on_delete = models.SET_NULL,
        related_name="money"
    )
</code>```

the views:

```<code># coinCollection/views.py:
class coinGallery(ListView):
    model = coin
    template_name = 'coinsCollection/gallery.html'
    context_object_name = 'coins_list'

    def get_queryset(self):
        coin_list = coin.objects.values('id', 'coin_name', 'coin_millesime', 'coin_thumbnail').order_by('coin_name')

        paginator = Paginator(coin_list, 3) # Show n coins per page

        page = self.request.GET.get('page')
        try:
            coins = paginator.page(page)
        except PageNotAnInteger:
            coins = paginator.page(1)
        except EmptyPage:
            coins = paginator.page(paginator.num_pages)
        return coins

# blog/views.py
class IndexView(generic.ListView):
    template_name = 'blog/articles.html'
    context_object_name = 'article_list'

    def get_queryset(self):
        article_list = article.objects.order_by('-article_pub_date')
        paginator = Paginator(article_list, 3) # Show n articles per page

        page = self.request.GET.get('page')
        try:
            articles = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            articles = paginator.page(1)
        except EmptyPage:
            # If page is out of range, deliver last page of results.
            articles = paginator.page(paginator.num_pages)
        return articles
</code>```

and in the templates :

```<code># gallery.html (Not displayed, empty var)
<img class="img-responsive" src="{{ coin.coin_thumbnail.url }}" alt="{{ coin.coin_name }}">

# articles.html (Displayed correctly)
<img class="img-responsive" src="{{ article.article_money.coin_thumbnail.url }}">
</code>```

Thanks by advance for your help.

答: In the coinGallery view, you've converted the queryset to values(). This turns the ImageFieldFile object 'coin_thumbnail' into its string representation, i.e. 'myimage.jpg', and you can't use Django's convenience attribute .url with it. To use the .url attribute, just use coin.objects.order_by() instead of coin.objects.values().order_by(). Or if you prefer values then you'll need to join the MEDIA_URL to the coin_thumbnail file name to get the complete file path.

Title: Displaying images from ImageField

Body:
I try to display the same image of a coin in 2 sections of my site (a list of articles and a gallery of coins). The only difference (I guess) is that from the articles page I call it by a foreign key while from the gallery I call it directly.

The image is displayed in the article list but not in the gallery.

Here is some code:

the models:

# coinCollection/models.py:
class coin(models.Model):
    #...
    coin_thumbnail = models.ImageField(max_length=500, upload_to = join(MEDIA_IMAGES_DIR, MEDIA_COINS_DIR), verbose_name='Miniature')
    #...

# blog/models.py:
class article(models.Model):
    #...
    article_money = models.ForeignKey(coin,
        null = True,
        on_delete = models.SET_NULL,
        related_name="money"
    )

the views:

# coinCollection/views.py:
class coinGallery(ListView):
    model = coin
    template_name = 'coinsCollection/gallery.html'
    context_object_name = 'coins_list'

    def get_queryset(self):
        coin_list = coin.objects.values('id', 'coin_name', 'coin_millesime', 'coin_thumbnail').order_by('coin_name')

        paginator = Paginator(coin_list, 3) # Show n coins per page

        page = self.request.GET.get('page')
        try:
            coins = paginator.page(page)
        except PageNotAnInteger:
            coins = paginator.page(1)
        except EmptyPage:
            coins = paginator.page(paginator.num_pages)
        return coins

# blog/views.py
class IndexView(generic.ListView):
    template_name = 'blog/articles.html'
    context_object_name = 'article_list'

    def get_queryset(self):
        article_list = article.objects.order_by('-article_pub_date')
        paginator = Paginator(article_list, 3) # Show n articles per page

        page = self.request.GET.get('page')
        try:
            articles = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            articles = paginator.page(1)
        except EmptyPage:
            # If page is out of range, deliver last page of results.
            articles = paginator.page(paginator.num_pages)
        return articles

and in the templates :

# gallery.html (Not displayed, empty var)

# articles.html (Displayed correctly)

Thanks by advance for your help.


问:
Read a floating point matrix using Regular expressions
I am trying to read a matrix from a file using RegEx. The file consists of several strng, \n characteres, white spaces and floating point numbers. I would like to read only sets of three or more consecutive floating points. An exemple of code is as follow:

Data.txt

```<code>$Nodes
5
1 0 0 0
2 1 0 0
3 1 1 0
4 0 1 0
5 0.5 0.5 0
$EndNodes
$Values
5
1 1.5 3.6
2 1.5 3.4
3 1.5 3.3
4 1.5 3.5
5 1.5 3.1
$EndValues
</code>```

In my read_file.py, I have:

```<code>def read_file(filename):
    text = str()
    with open(filename) as file:
        lines = file.readlines()
        for line in lines:
            text += line
    return text
</code>```

The final output of my read_file functions is a big string containing the whole text, so I could use RegEx to find whatever I like all at once.
Well, I would like to read all the sets of three numbers (After $Nodes\n5 and before $EndNodes\n).

I tried many things, like re.compile(r'\$Nodes (.*)\$EndNodes') and many others combinations of characters, but nothing seems to work.

What I need, in the end, is something like:

```<code>list_of_nodes = [('1', '0', '0', '0'), ('2', '1', '0', '0'), ('3', '1', '1', '0'), ('4', '0', '1', '0'), ('5', '0.5', '0.5', '0')]
</code>```

Any help would be apreciated. Thanks in advance,

答:
You're really close. The regex you wrote would work with the re.DOTALL flag. In regex, . represents 'any character except newline'. When you use the re.DOTALL flag, . includes the newlines as well.

Demo

Body:
I am trying to read a matrix from a file using RegEx. The file consists of several strng, \n characteres, white spaces and floating point numbers. I would like to read only sets of three or more consecutive floating points. An exemple of code is as follow:

Data.txt

$Nodes
5
1 0 0 0
2 1 0 0
3 1 1 0
4 0 1 0
5 0.5 0.5 0
$EndNodes
$Values
5
1 1.5 3.6
2 1.5 3.4
3 1.5 3.3
4 1.5 3.5
5 1.5 3.1
$EndValues

In my read_file.py, I have:

def read_file(filename):
    text = str()
    with open(filename) as file:
        lines = file.readlines()
        for line in lines:
            text += line
    return text

The final output of my read_file functions is a big string containing the whole text, so I could use RegEx to find whatever I like all at once.
Well, I would like to read all the sets of three numbers (After $Nodes\n5 and before $EndNodes\n).

I tried many things, like re.compile(r'\$Nodes (.*)\$EndNodes') and many others combinations of characters, but nothing seems to work.

What I need, in the end, is something like:

list_of_nodes = [('1', '0', '0', '0'), ('2', '1', '0', '0'), ('3', '1', '1', '0'), ('4', '0', '1', '0'), ('5', '0.5', '0.5', '0')]

Any help would be apreciated. Thanks in advance,


问:
USB Barcode scanner research
I'm doing some feasibility research with regards to a (large) book cataloging project. Any help would w/r/t good sources of information would be appreciated but the things I would specifically like to know are:

1.)does python have any modules for use with barcode readers (preferably USB)? What other programs are available for reading barcode information?

2.)This may be better answered with a few sources of information, but what kinds of things should I look for in a barcode scanner, especially if I'm looking to scan, specifically, a lot of barcodes on books.

3.)This may also be better answered with a few sources of information, what kind of information is stored standard in a book's barcode.

I know this is relatively off-topic, but any help would be greatly appreciated.

答:
You don't need any - most USB barcode scanners emulate a keyboard - if you scan a barcode it simply sends a series of key presses representing the numbers (or text if it's a more advanced barcode encoding) encoded in the barcode.  Most scanners are pretty configurable so you could configure it to send a special character before the barcode data, then listen for key presses and if it matches that special character, then focus on the input field where you want the barcode data.

It depends a lot on what you're trying to do, the furniture where it's being done, etc.  I was involved in a reasonably large rollout of general purpose scanners (happened to be these) - it worked fine for what we were doing and there weren't any drivers to install or anything...the only thing that needed to be done was the stand that came with it was bolted to the desk next to the PC - and that wasn't our concern!

A typical book barcode encodes the book's ISBN.

ContentLicense: CC BY-SA 2.5

Title: USB Barcode scanner research


问:
If Textview is null or empty
I'm beginner in xamarin's projects. So please be patient with me. Ι want to check if textview is null or empty.I'm using this code but it doesnt work.</p>

```<code>TextView textview2 = FindViewById<TextView>(Resource.Id.textView2);
TextView textview1 = FindViewById<TextView>(Resource.Id.textView1);
if (textview1 != null)
{
 textview2.Text = "123";
}
else
{

}
</code>```

答:
I'd normally go;    </p>

```<code>if(textview1.getText().toString().length() > 0){...}
</code>```

Title: If Textview is null or empty

Body:
I'm beginner in xamarin's projects. So please be patient with me. Ι want to check if textview is null or empty.I'm using this code but it doesnt work.

TextView textview2 = FindViewById<TextView>(Resource.Id.textView2);
TextView textview1 = FindViewById<TextView>(Resource.Id.textView1);
if (textview1 != null)
{
 textview2.Text = "123";
}
else
{

}

Body:
I'd normally go;

if(textview1.getText().toString().length() > 0){...}


问:
NameError: name 'PlayerIG' is not defined
I have a problem here.

```<code>class Player:

    def __init__(self,name):
        self.armed = 0
        self.arms = 1
        self.bombs = 0
        self.exposed = 0
        self.foodDrink = 20
        self.gold = 350
        self.happy = 50
        self.heat = 0
        self.heatTier = 0
        self.month = 1
        self.name = name
        self.nameWait = 0
        self.path = 'None'
        self.poster = 5
        self.propa = 0
        self.raidPts = 0
        self.status = 'Citizen'
        self.successRiot = 0
        self.support = 0
        self.raidPts = 0
        self.triedVote = 0
# stuff, mainly for fixing variables down from here...
</code>```

Another, related block of code.

```<code>def nameType():
print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n')
CharName = input()
if CharName != '':
    if len(CharName) > 20:
        print('► The name is too long!')
        nameType()
    else:
        print('► Are you sure this is what you want as a name?\nIf so, type "yes".\nOtherwise, type "no".')
        confirmName = input()

        if confirmName == 'yes':
            PlayerIG = Player(CharName)
            print('► Crew Member: Thanks for travelling with us, and have a great time,',PlayerIG.name,'.')
            MainMenu()

        if confirmName == 'no':
            nameType()
        else:
            print('► Invalid Input!')
            nameType()
else:
    print('► Empty! Please type again.')
    nameType()
</code>```

And one last related one (there may be more).

```<code>def MainMenu():
    blankSmall()
    print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nMonth',PlayerIG.month,'\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
    blankSmall()
    print('► You can buy items at the store by typing "store",\nadd propaganda by typing "propa",\nmanage the party by typing "manage", or if you have at least 1 bomb and 5 armed supporters,\nyou can conduct a raid by typing "raid".\nWhen you are done for the month, type "end".\nIf you are at rank President, you can participate in an election with "vote".\nIf you are Chief of Revolution, you can conduct a riot with "riot".\nTo save the game and leave, type "save".')
Option = input()
# Again, more stuff down here that may be included...
</code>```

The problem is, when I load the main menu with MainMenu(), it raises this error:

```<code>Traceback (most recent call last):
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 791, in <module>
    TitleScreen()
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 144, in TitleScreen
    nameType()
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 168, in nameType
    MainMenu()
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 181, in MainMenu

 print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nMonth',PlayerIG.month,'\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
NameError: name 'PlayerIG' is not defined
</code>```

Is there any solution to this?

EDIT: The MainMenu() function was supposed to be indented, but the formatting was a bit stubborn.

答:
The line PlayerIG = Player(CharName) in the nameType() function defines a local variable.  You can't reference this outside that function.  This is like the following example:

```<code>>>> def foo():
...   x = 1
...
>>> foo()
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
</code>```

If you want it to be a global variable, you should declare it, like so:

```<code>>>> def foo():
...   global x
...   x = 1
...
>>> foo()
>>> x
1
</code>```

see also Short Description of the Scoping Rules?

Body:
I have a problem here.

class Player:

    def __init__(self,name):
        self.armed = 0
        self.arms = 1
        self.bombs = 0
        self.exposed = 0
        self.foodDrink = 20
        self.gold = 350
        self.happy = 50
        self.heat = 0
        self.heatTier = 0
        self.month = 1
        self.name = name
        self.nameWait = 0
        self.path = 'None'
        self.poster = 5
        self.propa = 0
        self.raidPts = 0
        self.status = 'Citizen'
        self.successRiot = 0
        self.support = 0
        self.raidPts = 0
        self.triedVote = 0
# stuff, mainly for fixing variables down from here...

Another, related block of code.

def nameType():
print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n')
CharName = input()
if CharName != '':
    if len(CharName) > 20:
        print('► The name is too long!')
        nameType()
    else:
        print('► Are you sure this is what you want as a name?\nIf so, type "yes".\nOtherwise, type "no".')
        confirmName = input()

        if confirmName == 'yes':
            PlayerIG = Player(CharName)
            print('► Crew Member: Thanks for travelling with us, and have a great time,',PlayerIG.name,'.')
            MainMenu()

        if confirmName == 'no':
            nameType()
        else:
            print('► Invalid Input!')
            nameType()
else:
    print('► Empty! Please type again.')
    nameType()

And one last related one (there may be more).

def MainMenu():
    blankSmall()
    print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nMonth',PlayerIG.month,'\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
    blankSmall()
    print('► You can buy items at the store by typing "store",\nadd propaganda by typing "propa",\nmanage the party by typing "manage", or if you have at least 1 bomb and 5 armed supporters,\nyou can conduct a raid by typing "raid".\nWhen you are done for the month, type "end".\nIf you are at rank President, you can participate in an election with "vote".\nIf you are Chief of Revolution, you can conduct a riot with "riot".\nTo save the game and leave, type "save".')
Option = input()
# Again, more stuff down here that may be included...

The problem is, when I load the main menu with MainMenu(), it raises this error:

Traceback (most recent call last):
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 791, in <module>
    TitleScreen()
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 144, in TitleScreen
    nameType()
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 168, in nameType
    MainMenu()
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 181, in MainMenu

 print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nMonth',PlayerIG.month,'\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
NameError: name 'PlayerIG' is not defined

Is there any solution to this?

EDIT: The MainMenu() function was supposed to be indented, but the formatting was a bit stubborn.

Body:
The line PlayerIG = Player(CharName) in the nameType() function defines a local variable.  You can't reference this outside that function.  This is like the following example:

>>> def foo():
...   x = 1
...
>>> foo()
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

If you want it to be a global variable, you should declare it, like so:

>>> def foo():
...   global x
...   x = 1
...
>>> foo()
>>> x
1

see also Short Description of the Scoping Rules?


问:
How to get max and min values of an Array of Tuples
Say I have a List of Tuples of Integers

```<code>var i = Array(1->3, 5->9, 15->18)
</code>```

How can I return a Tuple of the highest and lowest values from the above?

So for the above input, 1-> 18 should be returned as 1 is the lowest and 18 is the highest value. Here's the skeleton of the function that takes an Array of Tuples and returns the highest & the lowest values as a Tuple.

```<code>    def returnHighest(i: Array[(Int, Int)]): (Int, Int)={

      ....

  }
</code>```

答:
You could use foldLeft, but you need to be careful about the start value. What if the array is empty ?</p>

```<code>val res4 = Array(1->3, 5->9, 15->18)
res4.foldLeft(res4(0))({
    case (acc, i) =>
      Math.min(acc._1, i._1) -> Math.max(acc._2, i._2)
  })
res6: (Int, Int) = (1, 18)
</code>```

Body:
Say I have a List of Tuples of Integers

var i = Array(1->3, 5->9, 15->18)

How can I return a Tuple of the highest and lowest values from the above?

So for the above input, 1-> 18 should be returned as 1 is the lowest and 18 is the highest value. Here's the skeleton of the function that takes an Array of Tuples and returns the highest & the lowest values as a Tuple.

    def returnHighest(i: Array[(Int, Int)]): (Int, Int)={

      ....

  }

Body:
You could use foldLeft, but you need to be careful about the start value. What if the array is empty ?

val res4 = Array(1->3, 5->9, 15->18)
res4.foldLeft(res4(0))({
    case (acc, i) =>
      Math.min(acc._1, i._1) -> Math.max(acc._2, i._2)
  })
res6: (Int, Int) = (1, 18)


问:
Azure Data Factory Copy
I have a Azure Data Factory Copy Activity within a pipeline. The copy activity is working - but the data is copied multiple times. My data source is an Azure  NoSQL DB. How do I configure the Copy Activity to Not Recopy a record?

Here is my Activity

```<code>{
  "name": "Copy Usage Session Data",
  "properties":
  {
    "description": "",
    "activities":
    [
      {
        "type": "Copy",
        "typeProperties":
        {
          "source": {"type": "DocumentDbCollectionSource"},
          "sink":
          {
            "type": "SqlSink",
            "writeBatchSize": 0,
            "writeBatchTimeout": "05:00:00",
            "sliceIdentifierColumnName": "InstallationSliceIdentifier"
          },
          "translator":
          {
            "type": "TabularTranslator",
            "ColumnMappings": "machineKey: machineKey, product: product, softwareVersion: softwareVersion, id: DocumentDBId"
          }

        },
        "inputs": [{"name": "Machine Registration Input Data"}],
        "outputs": [{"name": "Machine Registration Output Data"}],
        "policy":
        {
          "timeout": "01:00:00",
          "concurrency": 1,
          "executionPriorityOrder": "OldestFirst"
        },
        "scheduler":
        {
          "frequency": "Hour",
          "interval": 1
        },
        "name": "Machine Registration Data To History",
        "description": "Copy Machine Registration Data To SQL Server DB Activity"
      },
      {
        "type": "Copy",
        "typeProperties":
        {
          "source": {"type": "DocumentDbCollectionSource"},
          "sink":
          {
            "type": "SqlSink",
            "writeBatchSize": 0,
            "writeBatchTimeout": "05:00:00",
            "sliceIdentifierColumnName": "UsageSessionSliceIdentifier"
          },
          "translator":
          {
            "type": "TabularTranslator",
            "ColumnMappings": "id: usageSessionId, usageInstallationId: usageInstallationId, startTime: startTime, stopTime: stopTime, currentVersion: currentVersion"
          }
        },
        "inputs": [{"name": "Usage Session Input Data"}],
        "outputs": [{"name": "Usage Session Output Data"}],
        "policy":
        {
          "timeout": "01:00:00",
          "concurrency": 2,
          "executionPriorityOrder": "OldestFirst"
        },
        "scheduler":
        {
          "frequency": "Hour",
          "interval": 1
        },
        "name": "Usage Session Data To History",
        "description": "Copy Usage Session Data To SQL Server DB Activity"
      }
    ],
    "start": "2017-05-29T16:15:00Z",
    "end": "2500-01-01T00:00:00Z",
    "isPaused": false,
    "pipelineMode": "Scheduled"
  }
}
</code>```

答: You can use the query with created/modified date (it should exists in your table) and only pick the records for current date. This will be provided by slice start or end date and that way you can read only newly created records on daily basis.</p>

Title: Azure Data Factory Copy

Body:
I have a Azure Data Factory Copy Activity within a pipeline. The copy activity is working - but the data is copied multiple times. My data source is an Azure  NoSQL DB. How do I configure the Copy Activity to Not Recopy a record?

Here is my Activity

{
  "name": "Copy Usage Session Data",
  "properties":
  {
    "description": "",
    "activities":
    [
      {
        "type": "Copy",
        "typeProperties":
        {
          "source": {"type": "DocumentDbCollectionSource"},
          "sink":
          {
            "type": "SqlSink",
            "writeBatchSize": 0,
            "writeBatchTimeout": "05:00:00",
            "sliceIdentifierColumnName": "InstallationSliceIdentifier"
          },
          "translator":
          {
            "type": "TabularTranslator",
            "ColumnMappings": "machineKey: machineKey, product: product, softwareVersion: softwareVersion, id: DocumentDBId"
          }

        },
        "inputs": [{"name": "Machine Registration Input Data"}],
        "outputs": [{"name": "Machine Registration Output Data"}],
        "policy":
        {
          "timeout": "01:00:00",
          "concurrency": 1,
          "executionPriorityOrder": "OldestFirst"
        },
        "scheduler":
        {
          "frequency": "Hour",
          "interval": 1
        },
        "name": "Machine Registration Data To History",
        "description": "Copy Machine Registration Data To SQL Server DB Activity"
      },
      {
        "type": "Copy",
        "typeProperties":
        {
          "source": {"type": "DocumentDbCollectionSource"},
          "sink":
          {
            "type": "SqlSink",
            "writeBatchSize": 0,
            "writeBatchTimeout": "05:00:00",
            "sliceIdentifierColumnName": "UsageSessionSliceIdentifier"
          },
          "translator":
          {
            "type": "TabularTranslator",
            "ColumnMappings": "id: usageSessionId, usageInstallationId: usageInstallationId, startTime: startTime, stopTime: stopTime, currentVersion: currentVersion"
          }
        },
        "inputs": [{"name": "Usage Session Input Data"}],
        "outputs": [{"name": "Usage Session Output Data"}],
        "policy":
        {
          "timeout": "01:00:00",
          "concurrency": 2,
          "executionPriorityOrder": "OldestFirst"
        },
        "scheduler":
        {
          "frequency": "Hour",
          "interval": 1
        },
        "name": "Usage Session Data To History",
        "description": "Copy Usage Session Data To SQL Server DB Activity"
      }
    ],
    "start": "2017-05-29T16:15:00Z",
    "end": "2500-01-01T00:00:00Z",
    "isPaused": false,
    "pipelineMode": "Scheduled"
  }
}


问:
Java Swing JMenu Mnemonic
I have a menu that I created using JMenu. I want to assign a shortcut key Alt-F to this menu. I used setMnemonic('F') to do that, but the menu does not recognise the mnemonic.

What is the best way to troubleshoot or debug this problem ? I find that setting a break point does not help that much.

Thank you.

Code Snippet:

```<code>//higher up in variable declaration
/** Menus on the menu bar */
private JMenu uiFindMnu           = new JMenu("Find");
...
//inside the constructor
// set mnemonic for the Find menu
uiFindMnu.setMnemonic('F');
</code>```

答:
Inside of a class constructor (extending JFrame):

```<code>JMenu helpmenu = new JMenu("File");
helpmenu.setMnemonic('F');
JMenuBar menubar = new JMenuBar();
menubar.add(helpmenu);
setJMenuBar(menubar);
</code>```

That worked fine for me.  You'll have to give some more details about your code in order for me to give a better answer.  As far as troubleshooting SWING or any application GUI, one of the best recommendations I can give is to create the simplest possible scenario.  I keep a bare-bones JFrame template around that I can throw simple code like this inside for testing.  Once you know it works in the simplest scenario you can step back to your project and discover what other portion of your GUI is causing a conflict with this functionality.

Just out of curiosity, you don't happen to have a local variable called 'uiFindMnu' in your Constructor that is hiding your class variable, do you?  I'd double check to make sure that the variable that you are calling setMnemonic() on is the one that is added to your MenuBar (and actually displayed).

Title: Java Swing JMenu Mnemonic

Body:
I have a menu that I created using JMenu. I want to assign a shortcut key Alt-F to this menu. I used setMnemonic('F') to do that, but the menu does not recognise the mnemonic.

What is the best way to troubleshoot or debug this problem ? I find that setting a break point does not help that much.

Thank you.

Code Snippet:

//higher up in variable declaration
/** Menus on the menu bar */
private JMenu uiFindMnu           = new JMenu("Find");
...
//inside the constructor
// set mnemonic for the Find menu
uiFindMnu.setMnemonic('F');

Body:
Inside of a class constructor (extending JFrame):

JMenu helpmenu = new JMenu("File");
helpmenu.setMnemonic('F');
JMenuBar menubar = new JMenuBar();
menubar.add(helpmenu);
setJMenuBar(menubar);

That worked fine for me.  You'll have to give some more details about your code in order for me to give a better answer.  As far as troubleshooting SWING or any application GUI, one of the best recommendations I can give is to create the simplest possible scenario.  I keep a bare-bones JFrame template around that I can throw simple code like this inside for testing.  Once you know it works in the simplest scenario you can step back to your project and discover what other portion of your GUI is causing a conflict with this functionality.

Just out of curiosity, you don't happen to have a local variable called 'uiFindMnu' in your Constructor that is hiding your class variable, do you?  I'd double check to make sure that the variable that you are calling setMnemonic() on is the one that is added to your MenuBar (and actually displayed).


问:
Write to textbox during animation
I have 4 pictures that are faded in (when I click space or mouse). But I want to add a text field to every picture and ask my students what is it that is faded in next? The first picture fades in, the studens say "Oh it is a TV" and now I want to write TV into the textbox and continue with the next picture.

Problem is, that I cannot click into the textfield I added, since as soon as I click my mouse the next picutre fades out. I already check a lot of forums but coult not find anything. Anyone who can help me with this?

答: You would have to set that text box (pre-written) as an object, setting it to fade-in like you're fading in your photos. You can't type text when the PPT is in presentation mode.</p>

Title: Write to textbox during animation


问:
How to take an input that is equal to 10 and perform a function that says awesome to the screen
I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.</p>

```<code>    <!DOCTYPE html>
    <html>

    <head>
        <title>Fizzbuzz Input Field</title>
        <script src="scripts.js"></script>
    </head>

    <body>
        <form>
            <input type="number" id="userInput"></input>
            <button onclick="fizzBuzz()">Go</button>
        </form>
    </body>

    </html>

    window.onload = function() {
        alert("Page is loaded");
    };

    var fizzBuzz = function() {
    var userInput = document.getElementById("userInput");
        fizzBuzz.onclick = function() {
        if(userInput.value == 10) {
            document.write("awesome");
        };
        };
    }
</code>```

答:
I don't have any idea how you want the awesome to be displayed. Made it an alert. Have fun.

```

Body:
I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.

    <!DOCTYPE html>

        <title>Fizzbuzz Input Field</title>

        <form>
            <input type="number" id="userInput"></input>
            <button onclick="fizzBuzz()">Go</button>
        </form>

    window.onload = function() {
        alert("Page is loaded");
    };

    var fizzBuzz = function() {
    var userInput = document.getElementById("userInput");
        fizzBuzz.onclick = function() {
        if(userInput.value == 10) {
            document.write("awesome");
        };
        };
    }

Body:
I don't have any idea how you want the awesome to be displayed. Made it an alert. Have fun.

<script>
function fizzBuzz() {
var fizzBuzz = document.getElementById("userInput").value;
if(fizzBuzz != 10){
 alert('Number is not equal to ten!');
 }else {
     alert('awesome');
    }

}
</script>


问:
SetInterval/SetTimeout with Countdown Display
I want to have a function set to run at an interval

```<code>setInterval(function, 360000);
</code>```

When it's called, it will load some info from Ajax/Flask, but won't refresh or reload the page.

How can I display a countdown in a div that shows time remaining until the function/interval is next triggered?

答:
Instead of using a very long timer (six minutes in the code you listed), use a much shorter timer, e.g. a one second timer. Update your div each time that timer fires, and keep track of how many times it gets called. For example:

```<code>var secondsBetweenActions = 360;
var secondsRemaining = secondsBetweenActions;
setInterval( function() {
    updateStatus( secondsRemaining );
    secondsRemaining--;
    if( secondsRemaining <= 0 ) {
        doAction();
        secondsRemaining = secondsBetweenActions;
    }
}, 1000 );
</code>```

Now you just need to implement updateStatus() which should display secondsRemaining in your status div using jQuery, and doAction() which does whatever you need to do.

Body:
I want to have a function set to run at an interval

setInterval(function, 360000);

When it's called, it will load some info from Ajax/Flask, but won't refresh or reload the page.

How can I display a countdown in a div that shows time remaining until the function/interval is next triggered?

Body:
Instead of using a very long timer (six minutes in the code you listed), use a much shorter timer, e.g. a one second timer. Update your div each time that timer fires, and keep track of how many times it gets called. For example:

var secondsBetweenActions = 360;
var secondsRemaining = secondsBetweenActions;
setInterval( function() {
    updateStatus( secondsRemaining );
    secondsRemaining--;
    if( secondsRemaining <= 0 ) {
        doAction();
        secondsRemaining = secondsBetweenActions;
    }
}, 1000 );

Now you just need to implement updateStatus() which should display secondsRemaining in your status div using jQuery, and doAction() which does whatever you need to do.


问:
Facebook 'Like' button on an ecommerce site
I'm looking to add the 'Like' button on my ecommerce site. The problem I'm facing is figuring out how to have each individual page have its own Like accessibility. Meaning, if a user clicks on Like for one individual product, I don't want the Like to show up for other products. It should be on a per product basis.

How does one configure the Like button in this case, to individualize each item with its own Likes?

Do I need to use FBML or can it be done with the iframe embed?

答:
Yes it can be done with FB iframe code, you just need to write in the unique URL for each product into the code for each page.

So you need to assemble:

```<code><iframe src="http://www.facebook.com/widgets/like.php?href=http://www.example.com/UNIQUE-URL" scrolling="no" frameborder="0" style="border:none; width:450px; height:80px"></iframe>
</code>```

where example.com is replaced with your site and UNIQUE-URL is replaced with the URL for that product. So your page template would use something like:

```<code><iframe src="http://www.facebook.com/widgets/like.php?href=http://www.example.com/products.php?pid=<?php print $pid ?>" scrolling="no" frameborder="0" style="border:none; width:450px; height:80px"></iframe>
</code>```

Body:
Yes it can be done with FB iframe code, you just need to write in the unique URL for each product into the code for each page.

So you need to assemble:

<iframe src="http://www.facebook.com/widgets/like.php?href=http://www.example.com/UNIQUE-URL" scrolling="no" frameborder="0" style="border:none; width:450px; height:80px"></iframe>

where example.com is replaced with your site and UNIQUE-URL is replaced with the URL for that product. So your page template would use something like:

<iframe src="http://www.facebook.com/widgets/like.php?href=http://www.example.com/products.php?pid=<?php print $pid ?>" scrolling="no" frameborder="0" style="border:none; width:450px; height:80px"></iframe>


问:
Inquiry in Bootstrapping
I made a bootstrap class which holds the redirecting and getting the parameters from the URL. </p>

```<code>class Bootstrap
{
    private $controller;
    private $action;
    private $request;

    public function __construct($request){
        $this->request = $request;
        if ($this->request['controller'] == '') {
            $this->controller = 'home';
        } else {
            $this->controller = $this->request['controller'];
        }

        if ($this->request['action'] == '') {
            $this->action = 'index';
        } else {
            $this->action = $this->request['action'];
        }
        echo $this->controller;
    }
}
</code>```

<p>I've changed my domain from localhost to php.dev. Now the problem is that whenever i enter something in the url it echo only the "index" or the action and even I put something in the action it still echo "index".  For example: I've entered php.dev/users/ it should echo the word "users" the controller. Here's my .htaccess file: </p>

```<code>Options +FollowSymLinks
RewriteEngine on
RewriteRule ^([a-zA-Z)]*)/?([a-zA-Z]*)?/?([a-zA-z)-9]*)?/?$ index.php?controller=$1&action=$2&id=$3 [NC,L]
</code>```

答:
Try this rule:

```<code>RewriteRule ^([^/]+)(/([^/]+)(/([^/]+))?)?/?$ index.php?controller=$1&action=$3&id=$5 [NC,QSA,L]
</code>```

I used it in my project, it works as it should. If the problem persists, make sure that $request is filled correctly when passing it to the class.

Title: Inquiry in Bootstrapping

Body:
I made a bootstrap class which holds the redirecting and getting the parameters from the URL.

class Bootstrap
{
    private $controller;
    private $action;
    private $request;

    public function __construct($request){
        $this->request = $request;
        if ($this->request['controller'] == '') {
            $this->controller = 'home';
        } else {
            $this->controller = $this->request['controller'];
        }

        if ($this->request['action'] == '') {
            $this->action = 'index';
        } else {
            $this->action = $this->request['action'];
        }
        echo $this->controller;
    }
}

I've changed my domain from localhost to php.dev. Now the problem is that whenever i enter something in the url it echo only the "index" or the action and even I put something in the action it still echo "index".  For example: I've entered php.dev/users/ it should echo the word "users" the controller. Here's my .htaccess file:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^([a-zA-Z)]*)/?([a-zA-Z]*)?/?([a-zA-z)-9]*)?/?$ index.php?controller=$1&action=$2&id=$3 [NC,L]

Body:
Try this rule:

RewriteRule ^([^/]+)(/([^/]+)(/([^/]+))?)?/?$ index.php?controller=$1&action=$3&id=$5 [NC,QSA,L]

I used it in my project, it works as it should. If the problem persists, make sure that $request is filled correctly when passing it to the class.


问:
join 2 RDDs using scala
I have two RDDs

The first one (productID,category)

The second one (customerID,productID,quantity)

How can I make output looks like (customerID,category,quantity)?

The logic is to replace each productID of second rdd with corresponding category of first rdd.

I would like to use scala for the solution

答:
It seems that you have two case classes for your two rdds

```<code>case class Products(productId:String, category:String)
case class Customer(customerId:String, productId:String, quantity:Int)
</code>```

You have two rdds as

```<code>val rdd1 = sc.parallelize(Seq(
  Products("product1", "category1"),
  Products("product2", "category2"),
  Products("product3", "category3"),
  Products("product4", "category4")
))
val rdd2 = sc.parallelize(Seq(
  Customer("customer1", "product1", 5),
  Customer("customer1", "product2", 6),
  Customer("customer2", "product3", 2),
  Customer("customer2", "product4", 9)
))
</code>```

You can simply join the two rdds with productId but before joining them you will have to created pairRDD with productId as key.

```<code>rdd1.map(prod => (prod.productId, prod))
rdd2.map(customer => (customer.productId, customer))
</code>```

Final step is a simple join and select the values you want.

```<code>rdd1.join(rdd2).map(x => (x._2._2.customerId, x._2._1.category, x._2._2.quantity))
</code>```

I hope this helps

Title: join 2 RDDs using scala

Body:
It seems that you have two case classes for your two rdds

case class Products(productId:String, category:String)
case class Customer(customerId:String, productId:String, quantity:Int)

You have two rdds as

val rdd1 = sc.parallelize(Seq(
  Products("product1", "category1"),
  Products("product2", "category2"),
  Products("product3", "category3"),
  Products("product4", "category4")
))
val rdd2 = sc.parallelize(Seq(
  Customer("customer1", "product1", 5),
  Customer("customer1", "product2", 6),
  Customer("customer2", "product3", 2),
  Customer("customer2", "product4", 9)
))

You can simply join the two rdds with productId but before joining them you will have to created pairRDD with productId as key.

rdd1.map(prod => (prod.productId, prod))
rdd2.map(customer => (customer.productId, customer))

Final step is a simple join and select the values you want.

rdd1.join(rdd2).map(x => (x._2._2.customerId, x._2._1.category, x._2._2.quantity))

I hope this helps


问:
Benchmark of HowTo: Reading Data
I'm using tensorflow 0.10 and I was benchmarking the examples found in the official HowTo on reading data.  This HowTo illustrates different methods to move data to tensorflow, using the same MNIST example.

I was surprised by the results and I was wondering if anyone has enough low-level understanding to explain what is happening.

In the HowTo there are basically 3 methods to read in data:

Feeding: building the mini-batch in python and passing it with sess.run(..., feed_dict={x: mini_batch})

Reading from files: use tf operations to open the files and create mini-batches.  (Bypass handling data in python.)

Preloaded data: load all the data in either a single tf variable or constant and use tf functions to break that up in mini-batches.  The variable or constant is pinned to the cpu, not gpu.

The scripts I used to run my benchmarks are found within tensorflow:

Feeding: examples/tutorials/mnist/fully_connected_feed.py

Reading from files: examples/how_tos/reading_data/convert_to_records.py and examples/how_tos/reading_data/fully_connected_reader.py

Preloaded data (constant): examples/how_tos/reading_data/fully_connected_preloaded.py

Preloaded data (variable): examples/how_tos/reading_data/fully_connected_preloaded_var.py

I ran those scripts unmodified, except for the last two because they crash --for version 0.10 at least-- unless I add an extra sess.run(tf.initialize_local_variables()).

Main Question

The time to execute 100 mini-batches of 100 examples running on a GTX1060:

Feeding: ~0.001 s

Reading from files: ~0.010 s

Preloaded data (constant): ~0.010 s

Preloaded data (variable): ~0.010 s

Those results are quite surprising to me.  I would have expected Feeding to be the slowest since it does almost everything in python, while the other methods use lower-level tensorflow/C++ to carry similar operations.   It is the complete opposite of what I expected.   Does anyone understand what is going on?

Secondary question

I have access to another machine which has a Titan X and older NVidia drivers.  The relative results were roughly in line with the above, except for Preloaded data (constant) which was catastrophically slow, taking many seconds for a single mini-batch.

Is this some known issue that performance can vary greatly with hardware/drivers?

答:
The main question is that why the example with the preloaded data (constant)
 examples/how_tos/reading_data/fully_connected_preloaded.py is significantly slower than other data loading example codes when using GPU.

I had the same problem, that fully_connected_preloaded.py is unexpectedly slow on my Titan X. The problem was that the whole dataset was pre-loaded on CPU, not GPU.

First, let me share my initial attempts. I applied the following performance tips by Yaroslav.

set capacity=55000 for tf.train.slice_input_producer.(55000 is the size of MNIST training set in my case)

set num_threads=5 for tf.train.batch.

set capacity=500 for tf.train.batch.

put time.sleep(10) after tf.train.start_queue_runners.

However, the average speed per each batch stays the same. I tried timeline visualization for profiling, and still got QueueDequeueManyV2 dominating.

The problem was the line 65 of fully_connected_preloaded.py.  The following code loads entire dataset to CPU, still providing a bottleneck for CPU-GPU data transmission.

```<code>with tf.device('/cpu:0'):
    input_images = tf.constant(data_sets.train.images)
    input_labels = tf.constant(data_sets.train.labels)
</code>```

Hence, I switched the device allocation.

```<code>with tf.device('/gpu:0')
</code>```

Then I got x100 speed-up per each batch.

Note:

This was possible because Titan X has enough memory space to preload entire dataset.

In the original code(fully_connected_preloaded.py), the comment in the line 64 says "rest of pipeline is CPU-only". I am not sure about what this comment intended.

Title: Benchmark of HowTo: Reading Data

Body:
The main question is that why the example with the preloaded data (constant)
 examples/how_tos/reading_data/fully_connected_preloaded.py is significantly slower than other data loading example codes when using GPU.

I had the same problem, that fully_connected_preloaded.py is unexpectedly slow on my Titan X. The problem was that the whole dataset was pre-loaded on CPU, not GPU.

First, let me share my initial attempts. I applied the following performance tips by Yaroslav.

set capacity=55000 for tf.train.slice_input_producer.(55000 is the size of MNIST training set in my case)

set num_threads=5 for tf.train.batch.

set capacity=500 for tf.train.batch.

put time.sleep(10) after tf.train.start_queue_runners.

However, the average speed per each batch stays the same. I tried timeline visualization for profiling, and still got QueueDequeueManyV2 dominating.

The problem was the line 65 of fully_connected_preloaded.py.  The following code loads entire dataset to CPU, still providing a bottleneck for CPU-GPU data transmission.

with tf.device('/cpu:0'):
    input_images = tf.constant(data_sets.train.images)
    input_labels = tf.constant(data_sets.train.labels)

Hence, I switched the device allocation.

with tf.device('/gpu:0')

Then I got x100 speed-up per each batch.

Note:

This was possible because Titan X has enough memory space to preload entire dataset.

In the original code(fully_connected_preloaded.py), the comment in the line 64 says "rest of pipeline is CPU-only". I am not sure about what this comment intended.


问:
Fill JComboBox after changing another JComboBox
I have a class

```<code>    public class Speciality {
    String specName;
    String eduProgram; }
</code>```

and a TreeMap Map<String, ArrayList<Speciality>> treeMap = new TreeMap<String, ArrayList<Speciality>>(); where String is the name of faculty.

My 1st JComboBox comprises of names of faculties (so they're equal to keys in my Map) and in my BoxActionListener I need to fill my 2nd JComboBox with the array of specNames.

Here you can see what I actually need, but ofc it doesn't word (because I cast String[] to String)

```<code>boxSpeciality.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for(int i = 0; i < treeMap.size(); i++){
                    Object key = treeMap.keySet().toArray(new Object[treeMap.size()])[i];
                    ArrayList<Speciality> value = treeMap.get(key);

                    if(key == boxFaculty.getSelectedItem()){
                        boxSpeciality.setModel(new DefaultComboBoxModel((String[]) value.get(i).specName));
                    }
                }
            }
        });
</code>```

答:
As I understand, your combobox boxFaculty shows the keys of treeMap which are faculty names and your combobox boxSpeciality should show the specialities of each faculty ( which is one of the values of the treeMap ).

If you want the boxSpeciality to be populated based on selection of boxFaculty, you should write an actionListener on boxFaculty.

Another thing to note is do not set a new DefaultComboboxModel everytime in the action listener. Set one when you defined the combobox and update its elements in the action listener.

You can do something like below:

```<code>DefaultComboBoxModel<Speciality> specialityModel = new DefaultComboBoxModel<Speciality>();
boxSpeciality.setModel( specialityModel );
boxFaculty.addActionListener( new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        Object obj = boxFaculty.getSelectedItem();
        if ( obj != null )
        {
           ArrayList<Speciality> specialities = treeMap.get( obj );
           specialityModel.removeAllElements();
           for ( Speciality speciality : specialities )
           {
              specialityModel.addElement( speciality );
           }
        }

    }

});
</code>```

This will update the boxSpeciality box everytime you select an item in boxFaculty.

Body:
I have a class

    public class Speciality {
    String specName;
    String eduProgram; }

and a TreeMap Map<String, ArrayList<Speciality>> treeMap = new TreeMap<String, ArrayList<Speciality>>(); where String is the name of faculty.

My 1st JComboBox comprises of names of faculties (so they're equal to keys in my Map) and in my BoxActionListener I need to fill my 2nd JComboBox with the array of specNames.

Here you can see what I actually need, but ofc it doesn't word (because I cast String[] to String)

boxSpeciality.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for(int i = 0; i < treeMap.size(); i++){
                    Object key = treeMap.keySet().toArray(new Object[treeMap.size()])[i];
                    ArrayList<Speciality> value = treeMap.get(key);

                    if(key == boxFaculty.getSelectedItem()){
                        boxSpeciality.setModel(new DefaultComboBoxModel((String[]) value.get(i).specName));
                    }
                }
            }
        });

Body:
As I understand, your combobox boxFaculty shows the keys of treeMap which are faculty names and your combobox boxSpeciality should show the specialities of each faculty ( which is one of the values of the treeMap ).

If you want the boxSpeciality to be populated based on selection of boxFaculty, you should write an actionListener on boxFaculty.

Another thing to note is do not set a new DefaultComboboxModel everytime in the action listener. Set one when you defined the combobox and update its elements in the action listener.

You can do something like below:

DefaultComboBoxModel<Speciality> specialityModel = new DefaultComboBoxModel<Speciality>();
boxSpeciality.setModel( specialityModel );
boxFaculty.addActionListener( new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        Object obj = boxFaculty.getSelectedItem();
        if ( obj != null )
        {
           ArrayList<Speciality> specialities = treeMap.get( obj );
           specialityModel.removeAllElements();
           for ( Speciality speciality : specialities )
           {
              specialityModel.addElement( speciality );
           }
        }

    }

});

This will update the boxSpeciality box everytime you select an item in boxFaculty.


问:
Meteor - React - Stripe: how to import Stripe
In a Meteor/React app I need to import Stripe from mrgalaxy:stripe. I tried:

```<code>import { Stripe }  from 'meteor/mrgalaxy:stripe';
</code>```

but it returns:

```<code>TypeError: Cannot read property 'setPublishableKey' of undefined
</code>```

In the server folder I created stripe.js file where added the following:

```<code>import { Meteor } from 'meteor/meteor';
import { Stripe }  from 'meteor/mrgalaxy:stripe';

Meteor.startup(function(){
  Stripe.setPublishableKey(Meteor.settings.public.StripePub);
});
</code>```

答: What helped me was adding this package "stripe": "^4.9.0" into package.json in addition to mrgalaxy:stripe in .meteor/packages</p>

Body:
In a Meteor/React app I need to import Stripe from mrgalaxy:stripe. I tried:

import { Stripe }  from 'meteor/mrgalaxy:stripe';

but it returns:

TypeError: Cannot read property 'setPublishableKey' of undefined

In the server folder I created stripe.js file where added the following:

import { Meteor } from 'meteor/meteor';
import { Stripe }  from 'meteor/mrgalaxy:stripe';

Meteor.startup(function(){
  Stripe.setPublishableKey(Meteor.settings.public.StripePub);
});


问:
Adding a lightbox using Bootstrap
I'm trying to add a lightbox using bootstrap, but when I click on the link to the lightbox nothing happends.

My HTML code is as follows:

```<code> <head>
  <link href="css/bootstrap-lightbox.css" rel="stylesheet" type="text/css"/>
  <link href ="css/bootstrap.css" rel="stylesheet" type="text/css" />
  <link href ="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
  <title>Bootstrap RC1</title>
</code>```

```<code><div class="container">

    <div class="row">

        <div class="col-lg-12">`

            <h2>Bootstrap Lightbox - Creativity Tuts</h2>

            <div id="demolightbox" class="lightbox fade hide" tabindex="-1" role="dialog" aria-hidden="true">
                    <div class="lightbox-content">
                        <img src="images/beautiful-image.jpg">
                        <div class="lightbox-caption"><p>This is my background image</p></div>
                    </div>
            </div>
                <a data-toggle="lightbox" href='#demolightbox'><p>Open lightbox</p></a>
        </div>
    </div>
</div>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery-2.0.3.min.js"></script>
<script src="js/bootstrap-lightbox.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</code>```

答:
Try This </p>

```<code><html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-lightbox/0.7.0/bootstrap-lightbox.css"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-lightbox/0.7.0/bootstrap-lightbox.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-lightbox/0.7.0/bootstrap-lightbox.min.css"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-lightbox/0.7.0/bootstrap-lightbox.min.js"></script>

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

</head>
<body>

<div class="container">

    <div class="row">

        <div class="span12">`

            <h2>Bootstrap Lightbox - Creativity Tuts</h2>

            <div id="demolightbox" class="lightbox fade hide" tabindex="-1" role="dialog" aria-hidden="true">
                    <div class="lightbox-content">
                        <img src="img_fjords.jpg"/>
                        <div class="lightbox-caption">
                          <p>This is my background image</p>
                        </div>
                    </div>
            </div>
                <a data-toggle="lightbox" href="#demolightbox" class="span2 thumbnail">
                  <p>Open lightbox</p>
                  <img src="img_fjords.jpg"/>
                </a>

        </div>
    </div>
</div>

</body>

</html>
</code>```

Title: Adding a lightbox using Bootstrap

Body:
I'm trying to add a lightbox using bootstrap, but when I click on the link to the lightbox nothing happends.

My HTML code is as follows:

  <link href="css/bootstrap-lightbox.css" rel="stylesheet" type="text/css"/>
  <link href ="css/bootstrap.css" rel="stylesheet" type="text/css" />
  <link href ="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
  <title>Bootstrap RC1</title>

`

Bootstrap Lightbox - Creativity Tuts

This is my background image

Open lightbox

Body:
Try This

<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-lightbox/0.7.0/bootstrap-lightbox.css"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-lightbox/0.7.0/bootstrap-lightbox.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-lightbox/0.7.0/bootstrap-lightbox.min.css"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-lightbox/0.7.0/bootstrap-lightbox.min.js"></script>

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

</head>
<body>

<div class="container">

    <div class="row">

        <div class="span12">`

            <h2>Bootstrap Lightbox - Creativity Tuts</h2>

            <div id="demolightbox" class="lightbox fade hide" tabindex="-1" role="dialog" aria-hidden="true">
                    <div class="lightbox-content">
                        <img src="img_fjords.jpg"/>
                        <div class="lightbox-caption">
                          <p>This is my background image</p>
                        </div>
                    </div>
            </div>
                <a data-toggle="lightbox" href="#demolightbox" class="span2 thumbnail">
                  <p>Open lightbox</p>
                  <img src="img_fjords.jpg"/>
                </a>

        </div>
    </div>
</div>

</body>

</html>


答: Are you making a python web-app or a client application? Unless you're looking for specialized bar code scanning functionality it doesn't really matter since the input from the scanner appears like keyboard entry (sometimes prefixed with a special input character), so you just have to have a way of listening to the keyboard input and catching that special character.</p>

Title: USB Barcode scanner research

Body:
I'm doing some feasibility research with regards to a (large) book cataloging project. Any help would w/r/t good sources of information would be appreciated but the things I would specifically like to know are:

1.)does python have any modules for use with barcode readers (preferably USB)? What other programs are available for reading barcode information?

2.)This may be better answered with a few sources of information, but what kinds of things should I look for in a barcode scanner, especially if I'm looking to scan, specifically, a lot of barcodes on books.

3.)This may also be better answered with a few sources of information, what kind of information is stored standard in a book's barcode.

I know this is relatively off-topic, but any help would be greatly appreciated.


问:
String replacement combinations with fixed parts
Let's say I have the following string abcixigea and I want to replace the first 'i', 'e' and the second 'a' with '1', '3' and '4', getting all the combinations with those "progressive" replacement.

So, I need to get:

abc1xigea

abcixig3a

abcixig34

abc1xige4

...and so on.

I tried with itertools.product following this question python string replacement, all possible combinations #2 but the result I get is not exactly what I need and I can see why.

However I'm stuck on trying with combinations and keeping parts of the string fixed (changing just some chars as explained above).

答:
```<code>from itertools import product

s = "abc{}xig{}{}"

for combo in product(("i", 1), ("e", 3), ("a", 4)):
    print(s.format(*combo))
</code>```

produces

```<code>abcixigea
abcixige4
abcixig3a
abcixig34
abc1xigea
abc1xige4
abc1xig3a
abc1xig34
</code>```

Edit: in a more general way, you want something like:

```<code>from itertools import product

def find_nth(s, char, n):
    """
    Return the offset of the nth occurrence of char in s,
      or -1 on failure
    """
    assert len(char) == 1
    offs = -1
    for _ in range(n):
        offs = s.find(char, offs + 1)
        if offs == -1:
            break
    return offs

def gen_replacements(base_string, *replacement_values):
    """
    Generate all string combinations from base_string
      by replacing some characters according to replacement_values

    Each replacement_value is a tuple of
      (original_char, occurrence, replacement_char)
    """
    assert len(replacement_values) > 0
    # find location of each character to be replaced
    replacement_offsets = [
        (find_nth(base_string, orig, occ), orig, occ, (orig, repl))
        for orig,occ,repl in replacement_values
    ]
    # put them in ascending order
    replacement_offsets.sort()
    # make sure all replacements are actually possible
    if replacement_offsets[0][0] == -1:
        raise ValueError("'{}' occurs less than {} times".format(replacement_offsets[0][1], replacement_offsets[0][2]))
    # create format string and argument list
    args = []
    for i, (offs, _, _, arg) in enumerate(replacement_offsets):
        # we are replacing one char with two, so we have to
        # increase the offset of each replacement by
        # the number of replacements already made
        base_string = base_string[:offs + i] + "{}" + base_string[offs + i + 1:]
        args.append(arg)
    # ... and we feed that into the original code from above:
    for combo in product(*args):
        yield base_string.format(*combo)

def main():
    s = "abcixigea"

    for result in gen_replacements(s, ("i", 1, "1"), ("e", 1, "3"), ("a", 2, "4")):
        print(result)

if __name__ == "__main__":
    main()
</code>```

which produces exactly the same output as above.

Body:
from itertools import product

s = "abc{}xig{}{}"

for combo in product(("i", 1), ("e", 3), ("a", 4)):
    print(s.format(*combo))

produces

abcixigea
abcixige4
abcixig3a
abcixig34
abc1xigea
abc1xige4
abc1xig3a
abc1xig34

Edit: in a more general way, you want something like:

from itertools import product

def find_nth(s, char, n):
    """
    Return the offset of the nth occurrence of char in s,
      or -1 on failure
    """
    assert len(char) == 1
    offs = -1
    for _ in range(n):
        offs = s.find(char, offs + 1)
        if offs == -1:
            break
    return offs

def gen_replacements(base_string, *replacement_values):
    """
    Generate all string combinations from base_string
      by replacing some characters according to replacement_values

    Each replacement_value is a tuple of
      (original_char, occurrence, replacement_char)
    """
    assert len(replacement_values) > 0
    # find location of each character to be replaced
    replacement_offsets = [
        (find_nth(base_string, orig, occ), orig, occ, (orig, repl))
        for orig,occ,repl in replacement_values
    ]
    # put them in ascending order
    replacement_offsets.sort()
    # make sure all replacements are actually possible
    if replacement_offsets[0][0] == -1:
        raise ValueError("'{}' occurs less than {} times".format(replacement_offsets[0][1], replacement_offsets[0][2]))
    # create format string and argument list
    args = []
    for i, (offs, _, _, arg) in enumerate(replacement_offsets):
        # we are replacing one char with two, so we have to
        # increase the offset of each replacement by
        # the number of replacements already made
        base_string = base_string[:offs + i] + "{}" + base_string[offs + i + 1:]
        args.append(arg)
    # ... and we feed that into the original code from above:
    for combo in product(*args):
        yield base_string.format(*combo)

def main():
    s = "abcixigea"

    for result in gen_replacements(s, ("i", 1, "1"), ("e", 1, "3"), ("a", 2, "4")):
        print(result)

if __name__ == "__main__":
    main()

which produces exactly the same output as above.


问:
PHP: How to activate class "active" in pagination, If $_GET['page']==$pagenumber
This is my pagination code:

```<code><?php
   while($pagenumber != $totalpages)
     {
        echo"<a href='?page=" . ++$pagenumber. "' >" . $pagenumber. "</a>     ";
     }
 ?>
</code>```

The above code will look like this in normal html:

```<code><a href="?page=1">1</a>
<a href="?page=2">2</a>
</code>```

I want to add class="active" with this condition

```<code>If ($_GET['page'] == " . $pagenumber . ")
echo "class="active" ";
</code>```

I do not know, how to insert if statement inside echo command.

`

答:
I think this might help:</p>

```<code>if ($_GET['page'] == $pagenumber) echo "<a href='?page=$pagenumber' class='active'>$pagenumber</a>";
</code>```

Body:
This is my pagination code:

<?php
   while($pagenumber != $totalpages)
     {
        echo"" . $pagenumber. "     ";
     }
 ?>

The above code will look like this in normal html:

1
2

I want to add class="active" with this condition

If ($_GET['page'] == " . $pagenumber . ")
echo "class="active" ";

I do not know, how to insert if statement inside echo command.

`

Body:
I think this might help:

if ($_GET['page'] == $pagenumber) echo "<a href='?page=$pagenumber' class='active'>$pagenumber</a>";


问:
How to make UIImage round
I am trying to make the annotation.image round. But I don't know how. How would i go about making a UIImage round.

```<code> //Customize Annotation
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let annotationIdentifier = "Identifier"

    var annotationView: MKAnnotationView! = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)

    if annotationView != nil {
        annotationView.annotation = annotation
    } else {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)

        annotationView.image = profileImage.image

        annotationView.canShowCallout = true
        annotationView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)

        annotationView.autoresizesSubviews = true
        annotationView.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) as UIView
    }

      return annotationView
}
</code>```

}

Currently looks like this on a map

答:
Try this method:   </p>

```<code>func getRoundedImage(originalImage: UIImage,view: UIView,radius:CGFloat,borderWidth:CGFloat) -> UIImage?{
        UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0)
        let path = UIBezierPath(roundedRect: view.bounds.insetBy(dx: borderWidth / 2, dy: borderWidth / 2), cornerRadius: radius)
        let context = UIGraphicsGetCurrentContext()
        context!.saveGState()
        path.addClip()
        originalImage.draw(in: view.bounds)
        UIColor.gray.setStroke()
        path.lineWidth = borderWidth
        path.stroke()
        let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return roundedImage

    }
</code>```

Title: How to make UIImage round

Body:
I am trying to make the annotation.image round. But I don't know how. How would i go about making a UIImage round.

 //Customize Annotation
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let annotationIdentifier = "Identifier"

    var annotationView: MKAnnotationView! = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)

    if annotationView != nil {
        annotationView.annotation = annotation
    } else {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)

        annotationView.image = profileImage.image

        annotationView.canShowCallout = true
        annotationView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)

        annotationView.autoresizesSubviews = true
        annotationView.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) as UIView
    }

      return annotationView
}

}

Currently looks like this on a map

Body:
Try this method:

func getRoundedImage(originalImage: UIImage,view: UIView,radius:CGFloat,borderWidth:CGFloat) -> UIImage?{
        UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0)
        let path = UIBezierPath(roundedRect: view.bounds.insetBy(dx: borderWidth / 2, dy: borderWidth / 2), cornerRadius: radius)
        let context = UIGraphicsGetCurrentContext()
        context!.saveGState()
        path.addClip()
        originalImage.draw(in: view.bounds)
        UIColor.gray.setStroke()
        path.lineWidth = borderWidth
        path.stroke()
        let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return roundedImage

    }


问:
RecyclerView in Fragment is sometimes empty on BottomNavigationView item touch
My RecyclerView in Fragment (FrameLayout) is sometimes empty on BottomNavigationView item touch (sometimes you can touch 5x and it's not empty but then it's empty again until the next touch).

YouTuberFragment

```<code>public class YouTuberFragment extends Fragment {

    private List<YouTuber> youtuber;

    private class GetYouTuber extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                InputStream inputStream = getActivity().getAssets().open("youtuber.json");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder total = new StringBuilder();
                String line;

                while ((line = bufferedReader.readLine()) != null) total.append(line);

                String m = total.toString();
                JSONObject jsonObject = new JSONObject(m);
                JSONArray jsonYouTuberArray = jsonObject.getJSONArray("youtuber");

                int youTubersCount = 0;
                if (jsonYouTuberArray != null) youTubersCount = jsonYouTuberArray.length();

                for (int i = 0; i < youTubersCount; i++) {
                    JSONObject jsonYouTuberObject = jsonYouTuberArray.getJSONObject(i);

                    YouTuber youTuber = new YouTuber(
                            jsonYouTuberObject.getString("name"),
                            jsonYouTuberObject.getString("role"),
                            jsonYouTuberObject.getString("picture"),
                            jsonYouTuberObject.getString("episodes"),
                            jsonYouTuberObject.getString("youtube")
                    );

                    youtuber.add(youTuber);
                }
            } catch (JSONException | IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }

    public YouTuberFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_youtuber, container, false);

        LinearLayoutManager llm = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        youtuber = new ArrayList<>();
        RVAdapter adapter = new RVAdapter(youtuber, getContext());

        new YouTuberFragment.GetYouTuber().execute();

        RecyclerView rv = (RecyclerView) v.findViewById(R.id.rv);
        rv.setLayoutManager(llm);
        rv.setHasFixedSize(true);
        rv.setAdapter(adapter);

        return v;
    }

}
</code>```

RVAdapter

```<code>class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {

    private final Context context;
    private Resources res;
    private List<YouTuber> youTuber;
    RVAdapter(List<YouTuber> youTuber, Context context){
        this.youTuber = youTuber;
        this.context = context;
    }

    static class PersonViewHolder extends RecyclerView.ViewHolder {
        CardView cv;
        ImageView ytPicture;
        TextView ytName;
        TextView ytRole;
        TextView ytEpisodes;
        Button ytYoutube;

        PersonViewHolder(View itemView) {
            super(itemView);

            cv = (CardView) itemView.findViewById(R.id.cv);
            ytPicture = (ImageView) itemView.findViewById(R.id.yt_picture);
            ytName = (TextView) itemView.findViewById(R.id.yt_name);
            ytRole = (TextView) itemView.findViewById(R.id.yt_role);
            ytEpisodes = (TextView) itemView.findViewById(R.id.yt_episodes);
            ytYoutube = (Button) itemView.findViewById(R.id.yt_youtube);
        }
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_youtuber, viewGroup, false);
        res = v.getResources();
        PersonViewHolder pvh = new PersonViewHolder(v);
        return pvh;
    }

    @Override
    public void onBindViewHolder(final PersonViewHolder personViewHolder, final int i) {
        personViewHolder.ytPicture.setImageResource(res.getIdentifier(youTuber.get(i).picture, "drawable", BuildConfig.APPLICATION_ID));
        personViewHolder.ytName.setText(youTuber.get(i).name);
        personViewHolder.ytRole.setText(youTuber.get(i).role);
        personViewHolder.ytEpisodes.setText(res.getString(R.string.yt_episodes, youTuber.get(i).episodes));
        personViewHolder.ytYoutube.setText(youTuber.get(i).youtube);

        personViewHolder.ytYoutube.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri uri = Uri.parse("https://" + youTuber.get(i).youtube);

                Intent youtube_url = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(youtube_url);
            }
        });
    }

    @Override
    public int getItemCount() {
        return youTuber.size();
    }
}
</code>```

答: It could be that you are running a different thread to gather your data while your adapter initialization is being ran on the main thread and is being rendered before your data can be retrieved. Have you tried rotating the device if it is blank?</p>

Body:
My RecyclerView in Fragment (FrameLayout) is sometimes empty on BottomNavigationView item touch (sometimes you can touch 5x and it's not empty but then it's empty again until the next touch).

YouTuberFragment

public class YouTuberFragment extends Fragment {

    private List<YouTuber> youtuber;

    private class GetYouTuber extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                InputStream inputStream = getActivity().getAssets().open("youtuber.json");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder total = new StringBuilder();
                String line;

                while ((line = bufferedReader.readLine()) != null) total.append(line);

                String m = total.toString();
                JSONObject jsonObject = new JSONObject(m);
                JSONArray jsonYouTuberArray = jsonObject.getJSONArray("youtuber");

                int youTubersCount = 0;
                if (jsonYouTuberArray != null) youTubersCount = jsonYouTuberArray.length();

                for (int i = 0; i < youTubersCount; i++) {
                    JSONObject jsonYouTuberObject = jsonYouTuberArray.getJSONObject(i);

                    YouTuber youTuber = new YouTuber(
                            jsonYouTuberObject.getString("name"),
                            jsonYouTuberObject.getString("role"),
                            jsonYouTuberObject.getString("picture"),
                            jsonYouTuberObject.getString("episodes"),
                            jsonYouTuberObject.getString("youtube")
                    );

                    youtuber.add(youTuber);
                }
            } catch (JSONException | IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }

    public YouTuberFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_youtuber, container, false);

        LinearLayoutManager llm = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        youtuber = new ArrayList<>();
        RVAdapter adapter = new RVAdapter(youtuber, getContext());

        new YouTuberFragment.GetYouTuber().execute();

        RecyclerView rv = (RecyclerView) v.findViewById(R.id.rv);
        rv.setLayoutManager(llm);
        rv.setHasFixedSize(true);
        rv.setAdapter(adapter);

        return v;
    }

}

RVAdapter

class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {

    private final Context context;
    private Resources res;
    private List<YouTuber> youTuber;
    RVAdapter(List<YouTuber> youTuber, Context context){
        this.youTuber = youTuber;
        this.context = context;
    }

    static class PersonViewHolder extends RecyclerView.ViewHolder {
        CardView cv;
        ImageView ytPicture;
        TextView ytName;
        TextView ytRole;
        TextView ytEpisodes;
        Button ytYoutube;

        PersonViewHolder(View itemView) {
            super(itemView);

            cv = (CardView) itemView.findViewById(R.id.cv);
            ytPicture = (ImageView) itemView.findViewById(R.id.yt_picture);
            ytName = (TextView) itemView.findViewById(R.id.yt_name);
            ytRole = (TextView) itemView.findViewById(R.id.yt_role);
            ytEpisodes = (TextView) itemView.findViewById(R.id.yt_episodes);
            ytYoutube = (Button) itemView.findViewById(R.id.yt_youtube);
        }
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_youtuber, viewGroup, false);
        res = v.getResources();
        PersonViewHolder pvh = new PersonViewHolder(v);
        return pvh;
    }

    @Override
    public void onBindViewHolder(final PersonViewHolder personViewHolder, final int i) {
        personViewHolder.ytPicture.setImageResource(res.getIdentifier(youTuber.get(i).picture, "drawable", BuildConfig.APPLICATION_ID));
        personViewHolder.ytName.setText(youTuber.get(i).name);
        personViewHolder.ytRole.setText(youTuber.get(i).role);
        personViewHolder.ytEpisodes.setText(res.getString(R.string.yt_episodes, youTuber.get(i).episodes));
        personViewHolder.ytYoutube.setText(youTuber.get(i).youtube);

        personViewHolder.ytYoutube.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri uri = Uri.parse("https://" + youTuber.get(i).youtube);

                Intent youtube_url = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(youtube_url);
            }
        });
    }

    @Override
    public int getItemCount() {
        return youTuber.size();
    }
}


问:
Differences in print output/format
New to python and trying to figure out why the following 2 lists generate different output formats

```<code>n=5
mylist = "*" * n
print(mylist)
mylist = ["\*", "\*", "\*", "\*", "\*"]
print(mylist)
</code>```

Output:

*****
['\*', '\*', '\*', '\*', '\*']
```

答:
"*" * 5 gives you a string of length 5.

["*"] * 5 gives you a list of five strings of length 1.

In both of these cases, the result has the same type as the "input," just five times longer.

Title: Differences in print output/format

Body:
New to python and trying to figure out why the following 2 lists generate different output formats

n=5
mylist = "*" * n
print(mylist)
mylist = ["\*", "\*", "\*", "\*", "\*"]
print(mylist)

Output:

*****
['\*', '\*', '\*', '\*', '\*']


问:
Nginx location not work on digital-ocean
I created two node.js instance on DigitalOcean's Ubuntu machine.
Both listen to localhost, with different ports.
Then test by curl http:\localhost:${port}.  Both worked.

Then I added them to  /etc/nginx/site-available/default

```<code>location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            #try_files $uri $uri/ =404;
            proxy_pass http://localhost:8837;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
}

location /app {
            proxy_pass http://localhost:9837;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
}
</code>```

Only  http://${ip_address}:${port}/  worked.

http://${ip_address}:${port}/app  return
"Cannot GET /app"

I used express in node.js  is it the problem come from?

答:
I don't know where is wrong, here is what I found:

If remove express  from node.js  and listen port like this:

```<code>var http = require('http');
http.createServer(function (req, res) {
  ...
}).listen(8001, 'localhost');
</code>```

The /app worked,  no error happen.
If use express like this:

```<code>const app = express();
app.listen(8001, 'localhost', function() {
   ...
});
</code>```

/app will return error.

To resolve this problem I open another port that create another configuration by copy /etc/nginx/sites-available/default ,then link it to /etc/nginx/sites-enabled
sudo ln -s /etc/nginx/sites-available/default2 /etc/nginx/sites-enabled/
and change the port in server{}

Body:
I created two node.js instance on DigitalOcean's Ubuntu machine.
Both listen to localhost, with different ports.
Then test by curl http:\localhost:${port}.  Both worked.

Then I added them to  /etc/nginx/site-available/default

location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            #try_files $uri $uri/ =404;
            proxy_pass http://localhost:8837;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
}

location /app {
            proxy_pass http://localhost:9837;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
}

Only  http://${ip_address}:${port}/  worked.

http://${ip_address}:${port}/app  return
"Cannot GET /app"

I used express in node.js  is it the problem come from?

Body:
I don't know where is wrong, here is what I found:

If remove express  from node.js  and listen port like this:

var http = require('http');
http.createServer(function (req, res) {
  ...
}).listen(8001, 'localhost');

The /app worked,  no error happen.
If use express like this:

const app = express();
app.listen(8001, 'localhost', function() {
   ...
});

/app will return error.

To resolve this problem I open another port that create another configuration by copy /etc/nginx/sites-available/default ,then link it to /etc/nginx/sites-enabled
sudo ln -s /etc/nginx/sites-available/default2 /etc/nginx/sites-enabled/
and change the port in server{}


问:
I can't run my winform application om startup?
I added :

```<code>RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("My Application", Application.ExecutablePath.ToString());
</code>```

But my application doesn't run on startup , i also set :

```<code><requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</code>```

in app.manifest

And my Registry :

Please help me !

答:
Kinda weird when nobody has answered this question.

Application.ExecutablePath will return incorrect result in some cases, one of them is "#" sign in path.

Change

```<code>rkApp.SetValue("My Application", Application.ExecutablePath.ToString());
</code>```

To

```<code>rkApp.SetValue("My Application", Application.StartupPath + @"\" + Process.GetCurrentProcess().ProcessName + ".exe");
</code>```

Also remember to change all remaining paths if exist.

Body:
I added :

RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("My Application", Application.ExecutablePath.ToString());

But my application doesn't run on startup , i also set :

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

in app.manifest

And my Registry :

Please help me !

Body:
Kinda weird when nobody has answered this question.

Application.ExecutablePath will return incorrect result in some cases, one of them is "#" sign in path.

Change

rkApp.SetValue("My Application", Application.ExecutablePath.ToString());

To

rkApp.SetValue("My Application", Application.StartupPath + @"\" + Process.GetCurrentProcess().ProcessName + ".exe");

Also remember to change all remaining paths if exist.


答:
Your first variable is a string and the second is a list.

When you do "*" and multiply it by n you multiply that character n times and it returns a string.

The second one you declared as a list and is thus, printed as a list.

Title: Differences in print output/format


问:
setInterval to display div if ajax returns data
I'm trying to simulate a homemade push notification using setInterval but not sure how to do this. The ajax request works just fine at displaying messages. This is not the problem. I'm trying to display a separate notification in the section style='notification'.

Ajax snippet

```<code>  setInterval(function(){
 $.ajaxSetup({
     cache:false,
     type: "GET",
    url: "log.php",
    data: data,
 });
      $('#displayMessage').load('log.php');

     //display div notification if return data
     //document.getElementById('notification').style.display = 'block';

}, 3000);
</code>```

markup

```<code>   <section style='display:none;' id='notification' class="notif notif-notice alert  alert-dismissable">
      <h6 class="notif-title">Congratulations!
      <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
      </h6>
      <p>You have just received a new message</p>
    </section>
</code>```

答:
Javascript's .load() method has an optional argument that is a function to do after the load is completed. It would look like this:</p>

```<code>$('#displayMessage').load('log.php', function(){
    $('#notification').show();
});
</code>```

Body:
I'm trying to simulate a homemade push notification using setInterval but not sure how to do this. The ajax request works just fine at displaying messages. This is not the problem. I'm trying to display a separate notification in the section style='notification'.

Ajax snippet

  setInterval(function(){
 $.ajaxSetup({
     cache:false,
     type: "GET",
    url: "log.php",
    data: data,
 });
      $('#displayMessage').load('log.php');

     //display div notification if return data
     //document.getElementById('notification').style.display = 'block';

}, 3000);

markup

Congratulations!
      ×

You have just received a new message

Body:
Javascript's .load() method has an optional argument that is a function to do after the load is completed. It would look like this:

$('#displayMessage').load('log.php', function(){
    $('#notification').show();
});


问:
Where can I find a bit shifting guide for C?
I have looked at What are bitwise shift (bit-shift) operators and how do they work?, but I still find the concept of bit shifting difficult to understand.

Can someone point me in the direction of a more basic guide to bit shifting in C? I expect it will be something really long since it will need to cover the whole subject.

I am learning the The C Programming Language (AKA K&R), and that is what this is for, so I can do the exercises. I understand the basics, but I still cannot do correct bit shift operations.

Here are the exercises from K&R that have stumped me

Exercise 2-6: Write a function setbits(x, p, n, y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

Exercise 2-7: Write a function invert(x, p, n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged.

Exercise 2-8: Write a function rightrot(x, n) that returns the value of the integer x rotated to the right by n bit positions

Exercise 2-9: In a two's complement number system, x &= (x-1) deletes the rightmost 1-bit in x. Explain why, and use this observation to write a faster version of bitcount.

These are exercises from the k&R (the C programming language) book. It's the best C book there is, but I am having trouble understanding bit shifting, so I am having problems with these exercises.

答: If you have the money (and the time), grab a copy of Hacker's Delight (by Henry S. Warren). It is probably the best bit shifting guide around. It will take you through simple shifts (and other manipulation techniques) all the way through Gray codes and more...</p>

OwnerDisplayName: angie

LastEditorDisplayName: Rich B

OwnerDisplayName: Jamie