问:
Listbox extending off the page
I have a listbox inside of a stack panel inside of a border in a silverlight application and when ever I add anything to the listbox it increases in height so the scrollbar is never used and it extends beyond the boundaries of the border element. I have tried explicitly setting the height attribute of the listbox, the border and the stack panel and it still goes beyond this.

Here is my code:

```<code><Border x:Name="articlePane">
                <StackPanel>
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top">
                        <Button Content="Latest" MouseEnter="HandleRollInAnimation" MouseLeave="HandleRollOutAnimation" />
                        <Button Content="Pending" MouseEnter="HandleRollInAnimation" MouseLeave="HandleRollOutAnimation" />
                        <Button Content="Done" MouseEnter="HandleRollInAnimation" MouseLeave="HandleRollOutAnimation" />
                    </StackPanel>
                    <ListBox x:Name="articleList" Margin="5" Background="Transparent" ItemsSource="{Binding}"
                             ScrollViewer.VerticalScrollBarVisibility="Visible">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Vertical" VerticalAlignment="Top" HorizontalAlignment="Center">
                                    <Image x:Name="articleImage" />
                                    <TextBlock x:Name="articleTitle" Text="{Binding Path=Title}" FontSize="18" FontWeight="Bold"
                                               Margin="5"/>
                                    <TextBlock x:Name="articleDate" Text="{Binding Path=Date}" FontSize="14" Foreground="Gray"
                                               Margin="5"/>
                                </StackPanel>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </StackPanel>
            </Border>
</code>```

答: I have a feeling that the StackPanel just keeps on adding height forever. I think in this instance you'd be better off with a Grid layout within your Border. Put the Button StackPanel in one height defined row, and the ListBox in an autosizing * height row. This way Grid will stick within the confines of your form.</p>

Title: Listbox extending off the page

Body:
I have a listbox inside of a stack panel inside of a border in a silverlight application and when ever I add anything to the listbox it increases in height so the scrollbar is never used and it extends beyond the boundaries of the border element. I have tried explicitly setting the height attribute of the listbox, the border and the stack panel and it still goes beyond this.

Here is my code:

<Border x:Name="articlePane">
                <StackPanel>
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top">
                        <Button Content="Latest" MouseEnter="HandleRollInAnimation" MouseLeave="HandleRollOutAnimation" />
                        <Button Content="Pending" MouseEnter="HandleRollInAnimation" MouseLeave="HandleRollOutAnimation" />
                        <Button Content="Done" MouseEnter="HandleRollInAnimation" MouseLeave="HandleRollOutAnimation" />
                    </StackPanel>
                    <ListBox x:Name="articleList" Margin="5" Background="Transparent" ItemsSource="{Binding}"
                             ScrollViewer.VerticalScrollBarVisibility="Visible">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Vertical" VerticalAlignment="Top" HorizontalAlignment="Center">
                                    <Image x:Name="articleImage" />
                                    <TextBlock x:Name="articleTitle" Text="{Binding Path=Title}" FontSize="18" FontWeight="Bold"
                                               Margin="5"/>
                                    <TextBlock x:Name="articleDate" Text="{Binding Path=Date}" FontSize="14" Foreground="Gray"
                                               Margin="5"/>
                                </StackPanel>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </StackPanel>
            </Border>


来源: stackexchange

问:
Jelastic Nginx http to https redirect
I have an account in Jelastic and I want to force my site to work only over https. I've created environment nginx + php with nginx balancer and enabled Jelastic SSL (as it described here).

Whenever I tried to setup 301 redirect from http to https with no luck. Using mod_rewrite didn't work for me, the only thing I've got is a loop redirect. Google didn't help.

I really need advise. Any additional info will be provided.

Thanks in advance.

答:
Всем привет) With domain ssl this variant works just fine</p>

```<code>if ( $scheme = "http" ) { rewrite ^(.*)$    https://$host$1 last; }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jelastic Nginx http to https redirect

Body:
Всем привет) With domain ssl this variant works just fine

if ( $scheme = "http" ) { rewrite ^(.*)$    https://$host$1 last; }


问:
ProgrammingError: can't adapt type 'seniat.url' - Odoo v8 to Odoo v10 community
I have this wizard class:

```<code>from odoo import fields, models, api

class WizardUrlSeniat(models.TransientModel):

_name = "wizard.seniat.url"

url1 = fields.Char(
    string='URL1', size=255, required=True, readonly=False,
    default=lambda s: s._get_url1(),
    help='In this field enter the URL from Seniat for search the'
    ' fiscal information from partner')
url2 = fields.Char(
    string='URL2', size=255, required=True, readonly=False,
    default=lambda s: s._get_url2(),
    help='In this field enter the URL from Seniat for search the'
    ' retention rate from partner (RIF)')
url3 = fields.Char(
    string='URL3', size=255, required=True, readonly=False,
    default=lambda s: s._get_url3(),
    help='In this field enter the URL from Seniat for search the'
    ' retention rate from partner (CI or Passport)')

@api.multi
def _get_url(self):
    """ Get seniat web page
    """
    url = self.env['seniat.url']
    url_ids = url.search([])
    if len(url_ids) > 1:
        url.unlink.self.env.url_ids[1:]
    url_obj = self.env['seniat.url'].browse(url_ids)
    return url_obj
@api.multi
def _get_url1(self):
    url_obj = self._get_url()
    return url_obj.name

@api.multi
def _get_url2(self):
    url_obj = self._get_url()
    return url_obj.url_seniat

@api.multi
def _get_url3(self):
    url_obj = self._get_url()
    return url_obj.url_seniat2

@api.multi
def update_url(self):
    for url in self:
        url_obj = self._get_url()
        url_obj.write(
            {'name': url.url1,
             'url_seniat': url.url2,
             'url_seniat2': url.url3
        })
    return {}
</code>```

Every time I try this, I receive this error:

```<code>Traceback (most recent call last):
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 638, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 675, in dispatch
result = self._call_function(**self.params)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 331, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/service/model.py", line 119, in wrapper
return f(dbname, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 324, in checked_call
result = self.endpoint(*a, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 933, in __call__
return self.method(*args, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 504, in response_wrap
response = f(*args, **kw)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 862, in call_kw
return self._call_kw(model, method, args, kwargs)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 854, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 679, in call_kw
return call_kw_model(method, model, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 664, in call_kw_model
result = method(recs, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 1101, in default_get
defaults[name] = field.default(self)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/wizard/wizard_url_seniat.py", line 41, in <lambda>
default=lambda s: s._get_url3(),
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/wizard/wizard_url_seniat.py", line 70, in _get_url3
return url_obj.url_seniat2
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/fields.py", line 860, in __get__
self.determine_value(record)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/fields.py", line 960, in determine_value
record._prefetch_field(self)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 3044, in _prefetch_field
result = records.read([f.name for f in fs], load='_classic_write')
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 2984, in read
self._read_from_database(stored, inherited)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 3112, in _read_from_database
cr.execute(query_str, params)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/sql_db.py", line 141, in wrapper
return f(self, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/sql_db.py", line 218, in execute
res = self._obj.execute(query, params)
File "/home/kristian/.virtualenvs/odoov10/local/lib/python2.7/site-packages/psycopg2/extensions.py", line 129, in getquoted
pobjs = [adapt(o) for o in self._seq]
ProgrammingError: can't adapt type 'seniat.url'
</code>```

The error comes on _get_url method.

I think the problem is that I call seniat_url which is a class, then it should parse it, looking for a string, which should be Char field containing a name or an url.

But I'm pretty confused, because url_ids = url.search([]) should look for it, but at the same time, I already did url = self.env['seniat.url'], so I don't know if the order is wrong, because seniat.url is the model, so, if I work on it with url_ids it already has seniat.url as class, so it's useless.

By the way, this is from a mirgation I'm doing, the original wizard looked like this:

```<code>class WizardUrlSeniat(osv.osv_memory):

def _get_url(self, cr, uid, ids, context=None):
    """ Get seniat web page
    """
    url = self.pool.get('seniat.url')
    url_ids = url.search(cr, uid, [])
    if len(url_ids) > 1:
        url.unlink(cr, uid, url_ids[1:])
    url_obj = url.browse(cr, uid, url_ids, context=None)[0]
    return url_obj

def _get_url1(self, cr, uid, ids, context=None):
    url_obj = self._get_url(cr, uid, ids, context)
    return url_obj.name

def _get_url2(self, cr, uid, ids, context=None):
    url_obj = self._get_url(cr, uid, ids, context)
    return url_obj.url_seniat

def _get_url3(self, cr, uid, ids, context=None):
    url_obj = self._get_url(cr, uid, ids, context)
    return url_obj.url_seniat2

def update_url(self, cr, uid, ids, context=None):
    data = self.pool.get('wizard.seniat.url').read(cr, uid, ids)[0]
    url_obj = self._get_url(cr, uid, ids, context)
    url_obj.write(
        {'name': data['url1'],
         'url_seniat': data['url2'],
         'url_seniat2': data['url3']})
    return {}

_name = "wizard.seniat.url"
_columns = {
    'url1': fields.char(
        string='URL1', size=255, required=True, readonly=False,
        default=lambda s: s._get_url1(),
        help='In this field enter the URL from Seniat for search the'
        ' fiscal information from partner'),
    'url2': fields.char(
        string='URL2', size=255, required=True, readonly=False,
        default=lambda s: s._get_url2(),
        help='In this field enter the URL from Seniat for search the'
        ' retention rate from partner (RIF)'),
    'url3': fields.char(
        string='URL3', size=255, required=True, readonly=False,
        default=lambda s: s._get_url3(),
        help='In this field enter the URL from Seniat for search the'
        ' retention rate from partner (CI or Passport)'),
}

WizardUrlSeniat()
</code>```

Any ideas?

If You need more info, please let me know.

Thanks.

答:
There is one Issue in _get_url method.

In odoo API search method is returning Browse records and it is called RecordSet.

url_ids = url.search([])

In above search line odoo will return url Browse records.

```<code>@api.multi
def _get_url(self):
    """ Get seniat web page
    """
    url_obj = self.env['seniat.url']
    urls = url_obj.search([])
    if len(urls) > 1:
        urls[1:].unlink()
    return urls
</code>```

When you call above method then you will get url browse record.

If you need list of ids then you need to use ids property.

Ex: urls.ids()

This may help you.

Body:
I have this wizard class:

from odoo import fields, models, api

class WizardUrlSeniat(models.TransientModel):

_name = "wizard.seniat.url"

url1 = fields.Char(
    string='URL1', size=255, required=True, readonly=False,
    default=lambda s: s._get_url1(),
    help='In this field enter the URL from Seniat for search the'
    ' fiscal information from partner')
url2 = fields.Char(
    string='URL2', size=255, required=True, readonly=False,
    default=lambda s: s._get_url2(),
    help='In this field enter the URL from Seniat for search the'
    ' retention rate from partner (RIF)')
url3 = fields.Char(
    string='URL3', size=255, required=True, readonly=False,
    default=lambda s: s._get_url3(),
    help='In this field enter the URL from Seniat for search the'
    ' retention rate from partner (CI or Passport)')

@api.multi
def _get_url(self):
    """ Get seniat web page
    """
    url = self.env['seniat.url']
    url_ids = url.search([])
    if len(url_ids) > 1:
        url.unlink.self.env.url_ids[1:]
    url_obj = self.env['seniat.url'].browse(url_ids)
    return url_obj
@api.multi
def _get_url1(self):
    url_obj = self._get_url()
    return url_obj.name

@api.multi
def _get_url2(self):
    url_obj = self._get_url()
    return url_obj.url_seniat

@api.multi
def _get_url3(self):
    url_obj = self._get_url()
    return url_obj.url_seniat2

@api.multi
def update_url(self):
    for url in self:
        url_obj = self._get_url()
        url_obj.write(
            {'name': url.url1,
             'url_seniat': url.url2,
             'url_seniat2': url.url3
        })
    return {}

Every time I try this, I receive this error:

Traceback (most recent call last):
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 638, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 675, in dispatch
result = self._call_function(**self.params)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 331, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/service/model.py", line 119, in wrapper
return f(dbname, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 324, in checked_call
result = self.endpoint(*a, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 933, in __call__
return self.method(*args, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 504, in response_wrap
response = f(*args, **kw)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 862, in call_kw
return self._call_kw(model, method, args, kwargs)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 854, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 679, in call_kw
return call_kw_model(method, model, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 664, in call_kw_model
result = method(recs, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 1101, in default_get
defaults[name] = field.default(self)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/wizard/wizard_url_seniat.py", line 41, in <lambda>
default=lambda s: s._get_url3(),
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/wizard/wizard_url_seniat.py", line 70, in _get_url3
return url_obj.url_seniat2
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/fields.py", line 860, in __get__
self.determine_value(record)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/fields.py", line 960, in determine_value
record._prefetch_field(self)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 3044, in _prefetch_field
result = records.read([f.name for f in fs], load='_classic_write')
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 2984, in read
self._read_from_database(stored, inherited)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 3112, in _read_from_database
cr.execute(query_str, params)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/sql_db.py", line 141, in wrapper
return f(self, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/sql_db.py", line 218, in execute
res = self._obj.execute(query, params)
File "/home/kristian/.virtualenvs/odoov10/local/lib/python2.7/site-packages/psycopg2/extensions.py", line 129, in getquoted
pobjs = [adapt(o) for o in self._seq]
ProgrammingError: can't adapt type 'seniat.url'

The error comes on _get_url method.

I think the problem is that I call seniat_url which is a class, then it should parse it, looking for a string, which should be Char field containing a name or an url.

But I'm pretty confused, because url_ids = url.search([]) should look for it, but at the same time, I already did url = self.env['seniat.url'], so I don't know if the order is wrong, because seniat.url is the model, so, if I work on it with url_ids it already has seniat.url as class, so it's useless.

By the way, this is from a mirgation I'm doing, the original wizard looked like this:

class WizardUrlSeniat(osv.osv_memory):

def _get_url(self, cr, uid, ids, context=None):
    """ Get seniat web page
    """
    url = self.pool.get('seniat.url')
    url_ids = url.search(cr, uid, [])
    if len(url_ids) > 1:
        url.unlink(cr, uid, url_ids[1:])
    url_obj = url.browse(cr, uid, url_ids, context=None)[0]
    return url_obj

def _get_url1(self, cr, uid, ids, context=None):
    url_obj = self._get_url(cr, uid, ids, context)
    return url_obj.name

def _get_url2(self, cr, uid, ids, context=None):
    url_obj = self._get_url(cr, uid, ids, context)
    return url_obj.url_seniat

def _get_url3(self, cr, uid, ids, context=None):
    url_obj = self._get_url(cr, uid, ids, context)
    return url_obj.url_seniat2

def update_url(self, cr, uid, ids, context=None):
    data = self.pool.get('wizard.seniat.url').read(cr, uid, ids)[0]
    url_obj = self._get_url(cr, uid, ids, context)
    url_obj.write(
        {'name': data['url1'],
         'url_seniat': data['url2'],
         'url_seniat2': data['url3']})
    return {}

_name = "wizard.seniat.url"
_columns = {
    'url1': fields.char(
        string='URL1', size=255, required=True, readonly=False,
        default=lambda s: s._get_url1(),
        help='In this field enter the URL from Seniat for search the'
        ' fiscal information from partner'),
    'url2': fields.char(
        string='URL2', size=255, required=True, readonly=False,
        default=lambda s: s._get_url2(),
        help='In this field enter the URL from Seniat for search the'
        ' retention rate from partner (RIF)'),
    'url3': fields.char(
        string='URL3', size=255, required=True, readonly=False,
        default=lambda s: s._get_url3(),
        help='In this field enter the URL from Seniat for search the'
        ' retention rate from partner (CI or Passport)'),
}

WizardUrlSeniat()

Any ideas?

If You need more info, please let me know.

Thanks.

Body:
There is one Issue in _get_url method.

In odoo API search method is returning Browse records and it is called RecordSet.

url_ids = url.search([])

In above search line odoo will return url Browse records.

@api.multi
def _get_url(self):
    """ Get seniat web page
    """
    url_obj = self.env['seniat.url']
    urls = url_obj.search([])
    if len(urls) > 1:
        urls[1:].unlink()
    return urls

When you call above method then you will get url browse record.

If you need list of ids then you need to use ids property.

Ex: urls.ids()

This may help you.


问:
How to make links active with jquery in rails
I'm trying get some active links in my navbar and failing big time, what im doing wrong?

HTML:

```<code><div class="navbar-links text-center hidden-xs hidden-sm">
  <%= link_to "HOME", "#one", class: "navbar-links link-home" %>
  <%= link_to "FEATURES", "#features-container", class: "navbar-link link-home" %>
  <%= link_to "TEMPLATES", "#templates", class: "navbar-links link-home" %>
  <%= link_to "CONTACT", "#map", class: "navbar-links link-home" %>
</div>
</code>```

CSS:

```<code>.active-link {
  color: #C99D9A;
  transition: all 0.3s ease;
  opacity: 80%;
  border-bottom: 3px solid #C99D9A;
}
</code>```

JQUERY:

```<code>$('.navbar-links a').on('click', function(){
  $('this').removeClass('.active-link');
  $(this).addClass('.active-link');
});
</code>```

答:
You need to take a way the two dots(.) in removeClass and addClass. Following Jquery document: .removeClass( [className ] )

```<code>$('this').removeClass('active-link');
$(this).addClass('active-link');
</code>```

Body:
I'm trying get some active links in my navbar and failing big time, what im doing wrong?

HTML:

  <%= link_to "HOME", "#one", class: "navbar-links link-home" %>
  <%= link_to "FEATURES", "#features-container", class: "navbar-link link-home" %>
  <%= link_to "TEMPLATES", "#templates", class: "navbar-links link-home" %>
  <%= link_to "CONTACT", "#map", class: "navbar-links link-home" %>

CSS:

.active-link {
  color: #C99D9A;
  transition: all 0.3s ease;
  opacity: 80%;
  border-bottom: 3px solid #C99D9A;
}

JQUERY:

$('.navbar-links a').on('click', function(){
  $('this').removeClass('.active-link');
  $(this).addClass('.active-link');
});

Body:
You need to take a way the two dots(.) in removeClass and addClass. Following Jquery document: .removeClass( [className ] )

$('this').removeClass('active-link');
$(this).addClass('active-link');


问:
Endpoints discovery for headless services on Kubernetes
I have a cluster of MongoDB instances exposed with a headless service

```<code>k get svc
NAME         CLUSTER-IP   EXTERNAL-IP   PORT(S)          AGE
hello        10.0.0.90    <nodes>       8080:32361/TCP   7h
kubernetes   10.0.0.1     <none>        443/TCP          7h
mongo        None         <none>        27017/TCP        7h
</code>```

So there are multiple MongoDB endpoints:

```<code>k get ep
NAME         ENDPOINTS                           AGE
hello        172.17.0.4:8080                     7h
kubernetes   10.0.2.15:8443                      7h
mongo        172.17.0.5:27017,172.17.0.6:27017   7h
</code>```

How can my other service (called hello) can find 1 IP or 1 DNS entry to talk to ? How would it be possible to discover that list of IPs efficiently?

In the case of Mongo, would it be possible to automatically find the Primary replica (or a writable / readable one) ?

答:
Services should be reachable through their DNS name. In your case "mongo" or "mongo.my-namespace" if you assigned a namespace. You should also check if you have "spec.clusterIP=None" set in your deployment file. If that would be case you are telling kubernetes that you don't want to use the standard way of service discovery and will provide your own.

There are multiple standard ways to expose services:

You can add a fixed internal cluster IP for the service using "spec.clusterIP" field.

Add a "NodePort" type to your service. This allows you to define a port that is available on each node. So when you have a load balancer in front of the service you can forward to this port on each node.

More info can be found at k8s docs

Body:
I have a cluster of MongoDB instances exposed with a headless service

k get svc
NAME         CLUSTER-IP   EXTERNAL-IP   PORT(S)          AGE
hello        10.0.0.90    <nodes>       8080:32361/TCP   7h
kubernetes   10.0.0.1     <none>        443/TCP          7h
mongo        None         <none>        27017/TCP        7h

So there are multiple MongoDB endpoints:

k get ep
NAME         ENDPOINTS                           AGE
hello        172.17.0.4:8080                     7h
kubernetes   10.0.2.15:8443                      7h
mongo        172.17.0.5:27017,172.17.0.6:27017   7h

How can my other service (called hello) can find 1 IP or 1 DNS entry to talk to ? How would it be possible to discover that list of IPs efficiently?

In the case of Mongo, would it be possible to automatically find the Primary replica (or a writable / readable one) ?


问:
sum rows in a nested list in R
I have a nested list coming out of a program its length is 100. I need to sum all elements of first row and all elements of 2nd row. Here a a small reproducible example. What I need is sum of 1+3+5+7= 16 and sum of 2+4+6+8= 20 as a vector or matrix. </p>

```<code> l1<-as.matrix(c(1,2))
 l2<-as.matrix(c(3,4))
 l3<-as.matrix(c(5,6))
 l4<-as.matrix(c(7,8))
 ll1<-list(l1,l2)
 ll2<-list(l3,l4)
 lll<-list(ll1,ll2)

   lll
 [[1]]
 [[1]][[1]]
      [,1]
 [1,]    1
 [2,]    2

 [[1]][[2]]
      [,1]
 [1,]    3
 [2,]    4

 [[2]]
 [[2]][[1]]
      [,1]
 [1,]    5
 [2,]    6

 [[2]][[2]]
      [,1]
 [1,]    7
 [2,]    8
</code>```

答:
We can do this with base R by removing the nested list to a single list using do.call(c then cbind the elements of the list and get the rowSums

```<code>rowSums(do.call(cbind, do.call(c, lll)))
#[1] 16 20
</code>```

Or otherwise we can unlist, create a matrix with 2 columns, and get the colSums

```<code>colSums(matrix(unlist(lll), ncol=2, byrow=TRUE))
#[1] 16 20
</code>```

Title: sum rows in a nested list in R

Body:
I have a nested list coming out of a program its length is 100. I need to sum all elements of first row and all elements of 2nd row. Here a a small reproducible example. What I need is sum of 1+3+5+7= 16 and sum of 2+4+6+8= 20 as a vector or matrix.

 l1<-as.matrix(c(1,2))
 l2<-as.matrix(c(3,4))
 l3<-as.matrix(c(5,6))
 l4<-as.matrix(c(7,8))
 ll1<-list(l1,l2)
 ll2<-list(l3,l4)
 lll<-list(ll1,ll2)

   lll
 [[1]]
 [[1]][[1]]
      [,1]
 [1,]    1
 [2,]    2

 [[1]][[2]]
      [,1]
 [1,]    3
 [2,]    4

 [[2]]
 [[2]][[1]]
      [,1]
 [1,]    5
 [2,]    6

 [[2]][[2]]
      [,1]
 [1,]    7
 [2,]    8

Body:
We can do this with base R by removing the nested list to a single list using do.call(c then cbind the elements of the list and get the rowSums

rowSums(do.call(cbind, do.call(c, lll)))
#[1] 16 20

Or otherwise we can unlist, create a matrix with 2 columns, and get the colSums

colSums(matrix(unlist(lll), ncol=2, byrow=TRUE))
#[1] 16 20


问:
How to send a message to a client using WampSharp?
Is it possible to do this way:
WampSharp client app connects to a WampSharp Server, then this server sends message/call client's function?</p>

答:
The client can subscribe to a topic and then you can publish to this topic, specifying in the publish options' eligible property the session id of the client.

For functions this is more tricky - you would need to register the procedure with a unique name which depends on the client's session id and then call it from the server side.


答:
Make sure the database charset/collation is UTF-8

On the page you insert these russian characters ( the form, textarea ), make sure the encoding is UTF-8, by setting Content-Type to text/html; charset=utf-8. Enter in russian text directly to the form input.

On the processing page that handles this form, which inserts it into the database, make sure to do SET NAMES utf8 so it's stored as UTF-8 before you insert the data, in a separate query beforehand.

When you render the content from the database in a view, make sure the Content-Type is text/html; charset=utf-8.

Make sure that the content-type is not windows-1251 or iso-8859-1/latin1. Make sure the database charset/collation is NOT ISO-8859-1/Latin1.

ContentLicense: CC BY-SA 2.5

Title: MySQL - Russian characters display incorectly

Body:
I have to make an russian version of a website, but I can't find out, how to insert russian characters into Database.

I tryed almost every possible coding, but it only shows:

???????? ?????????? ??????? ??????? ? ????? ?? ????????????? ? ???????, ??????? ????? ??????? ???????? ????? .??? ??????????? ???????? ????? ?? ????? ?????????? ? ????? ????????.
??????????? ?????? ?? ???????? ????? ?? 20 ???????. ???????? ??? ?? ??????????? ?????????????? ????? ? ????????????? ??????? ??????. ? ???????, ? ??????? ? ?.?.

ContentLicense: CC BY-SA 4.0


问:
Java: array initialize in shorthand cannot assign to an object
```<code>Integer i1 = 1;
Integer i2 = 2;

Number arr1[] = {i1, i2};
</code>```

as we already know, {i1, i2} is shorthand for new Number[]{i1, i2}

but when declare in this way:

```<code>Object o = {i1, i2};   //error
</code>```

I got a compile error:
Type mismatch: cannot convert from Integer[] to Object

On the other hand,

```<code>Object arr1 = new Number[]{i1, i2};
</code>```

Isn't it means, that the array can be convert to Object.

And if I write in this way:

```<code>Number arr2[] = {i1, i2};
Object obj = arr2;
</code>```

It's also okay.

So, the problem i want to consult is, why did I got the compile error.
Or the eclipse gave me an mistake error message ,for '{i1, i2}' in the expression 'Object o = {i1, i2};' is not an array?

答:
{..} is a syntactic sugar for declaring an array type and initializing it.

In your Object o = {i1, i2}, you didn't specify that it is an array type (because you omitted []), so the compiler does not even know that it is an array i.e. it treats that it is a single object and throws error.

```<code>Object o = {i1, i2}; // This is NOT an array type

Object[] o = {i1, i2}; //This represents an array
</code>```

But, once you have got an array object created (i.e., either with new operator specifying the size or by using the above syntactic sugar), you will have an array object which you can assign it to an Object type as shown below:

```<code>Number arr1[] = {i1, i2};//arr1 created & initialized
Object obj1 = arr1;//arr1 can now be assigned to Object type

Number arr2[] = new Number[2];//arr2 created (initialized values to null)
Object obj2 = arr2;//arr2 can now be assigned to Object type
</code>```

Body:
Integer i1 = 1;
Integer i2 = 2;

Number arr1[] = {i1, i2};

as we already know, {i1, i2} is shorthand for new Number[]{i1, i2}

but when declare in this way:

Object o = {i1, i2};   //error

I got a compile error:
Type mismatch: cannot convert from Integer[] to Object

On the other hand,

Object arr1 = new Number[]{i1, i2};

Isn't it means, that the array can be convert to Object.

And if I write in this way:

Number arr2[] = {i1, i2};
Object obj = arr2;

It's also okay.

So, the problem i want to consult is, why did I got the compile error.
Or the eclipse gave me an mistake error message ,for '{i1, i2}' in the expression 'Object o = {i1, i2};' is not an array?

Body:
{..} is a syntactic sugar for declaring an array type and initializing it.

In your Object o = {i1, i2}, you didn't specify that it is an array type (because you omitted []), so the compiler does not even know that it is an array i.e. it treats that it is a single object and throws error.

Object o = {i1, i2}; // This is NOT an array type

Object[] o = {i1, i2}; //This represents an array

But, once you have got an array object created (i.e., either with new operator specifying the size or by using the above syntactic sugar), you will have an array object which you can assign it to an Object type as shown below:

Number arr1[] = {i1, i2};//arr1 created & initialized
Object obj1 = arr1;//arr1 can now be assigned to Object type

Number arr2[] = new Number[2];//arr2 created (initialized values to null)
Object obj2 = arr2;//arr2 can now be assigned to Object type


问:
Declaring Global Array in PHP
I'm trying to declare a global array and put data in it with a function.

It works only if the global variable is a string but not if it's an array:

```<code>$data = iterate("USER361");
print_r($data);

function iterate($username)
{
    global $gv_array;

    $sql = "select * from account where sponsor = '$username'";
    $result = mysql_query($sql);
        while($row = mysql_fetch_array($result))
        {
            $this_user = $row['username'];
            $this_name = $row['full_name'];
            $this_tier = $row['tier'];

            $my_array = array("username"=>$this_user,"name"=>$this_name,"tier"=>$this_tier);
            array_push($gv_array[],$my_array);

            iterate($row['username']);
        }

}//end of iterate
</code>```

The error I get is:

PHP Warning:  array_push() expects parameter 1 to be array, null given in /var/www/html/inc/code.php on line 29

答:
if $gv_array it's an array then the problem is here array_push($gv_array[],$my_array); remove the square brackets.

```<code>array_push($gv_array,$my_array);
</code>```

Title: Declaring Global Array in PHP

Body:
I'm trying to declare a global array and put data in it with a function.

It works only if the global variable is a string but not if it's an array:

$data = iterate("USER361");
print_r($data);

function iterate($username)
{
    global $gv_array;

    $sql = "select * from account where sponsor = '$username'";
    $result = mysql_query($sql);
        while($row = mysql_fetch_array($result))
        {
            $this_user = $row['username'];
            $this_name = $row['full_name'];
            $this_tier = $row['tier'];

            $my_array = array("username"=>$this_user,"name"=>$this_name,"tier"=>$this_tier);
            array_push($gv_array[],$my_array);

            iterate($row['username']);
        }

}//end of iterate

The error I get is:

PHP Warning:  array_push() expects parameter 1 to be array, null given in /var/www/html/inc/code.php on line 29

Body:
if $gv_array it's an array then the problem is here array_push($gv_array[],$my_array); remove the square brackets.

array_push($gv_array,$my_array);


问:
How to access data effectively in JSON PHP
How do I get the data under [t]?

JSON data:

```<code>$array=  json_decode($json);
echo "```";
print_r($array[something blah blah]);
echo "```"
</code>```

答:
Either you convert the json object to an array, or access it as an object:</p>

```<code>$json->manga[0]->t;
</code>```

Body:
How do I get the data under [t]?

JSON data:

$array=  json_decode($json);
echo "
";
print_r($array[something blah blah]);
echo "
"

Body:
Either you convert the json object to an array, or access it as an object:

$json->manga[0]->t;


问:
How do I restore the default settings or use a UI tool for git diff?
I am using ubuntu 14.04 and before pushing the code, I used to run command git diff so that I can know what changes I made in the code.

Then someone told me, I should use meld for resolving merge confilcts.

I am not able to resolve any conflicts nor able to use git diff anymore, because meld is too complicated.
So I want to restore back the old git diff.

I am getting this error when I do git diff.

```<code>Usage:
  meld                        Start with an empty window
  meld <file|dir>             Start a version control comparison
  meld <file> <file> [<file>] Start a 2- or 3-way file comparison
  meld <dir> <dir> [<dir>]    Start a 2- or 3-way directory comparison
  meld <file> <dir>           Start a comparison between file and dir/file

meld: error: too many arguments (wanted 0-3, got 7)
external diff died, stopping at app/Plugin/Community/Controller/CommunitiesContr
</code>```

All I want to see is the difference of code edited by me from the original, so that I can verify the changes before pushing.

答:
have you tried git difftool?

```<code>git difftool --tool=meld yourfile
</code>```

I found an answer here that describes how to configure difftool to use meld as default tool.

In short:

Open your git configuration file (usually ~/.gitconfig on linux)

and enter the following sections:

```<code>[diff]
  tool = meld
[difftool]
  prompt = false
[difftool "meld"]
  cmd = meld "$LOCAL" "$REMOTE"
</code>```

Now you can call git difftool yourfile

The link above also describes how to configure meld as default merge tool.

Body:
I am using ubuntu 14.04 and before pushing the code, I used to run command git diff so that I can know what changes I made in the code.

Then someone told me, I should use meld for resolving merge confilcts.

I am not able to resolve any conflicts nor able to use git diff anymore, because meld is too complicated.
So I want to restore back the old git diff.

I am getting this error when I do git diff.

Usage:
  meld                        Start with an empty window
  meld <file|dir>             Start a version control comparison
  meld <file> <file> [<file>] Start a 2- or 3-way file comparison
  meld <dir> <dir> [<dir>]    Start a 2- or 3-way directory comparison
  meld <file> <dir>           Start a comparison between file and dir/file

meld: error: too many arguments (wanted 0-3, got 7)
external diff died, stopping at app/Plugin/Community/Controller/CommunitiesContr

All I want to see is the difference of code edited by me from the original, so that I can verify the changes before pushing.

Body:
have you tried git difftool?

git difftool --tool=meld yourfile

I found an answer here that describes how to configure difftool to use meld as default tool.

In short:

Open your git configuration file (usually ~/.gitconfig on linux)

and enter the following sections:

[diff]
  tool = meld
[difftool]
  prompt = false
[difftool "meld"]
  cmd = meld "$LOCAL" "$REMOTE"

Now you can call git difftool yourfile

The link above also describes how to configure meld as default merge tool.


问:
Looking for S#arp Architecture usage without ASP.net MVC issues or gotchas
I am exploring technologies and libraries before I get started on a new project.  One that has really caught my eye is the S#arp Architecture library for ASP.net MVC.  However, I have already decide that the bulk of my web application will use Visual Web GUI as the front end, leaving only a small separate customer facing web component that will be developed in ASP.net MVC.  Bearing this in mind, based on the experiences of those of you who have a good familiarity with S#harp Architecture, or may have attempted a similar solution using S#harp, are there any issues or gotchas I should be aware of before I begin? I have also had a look at Castle Active Record, and Fluent NHibernate usage as possible options, but find myself leaning towards S#arp.

My most major goal in choosing a library are to get my data access set up using the repository pattern as quickly as possible.

答:
We have implemented a ASP.NET standard project using the S#harp framework without any problems. I would strongly recommend you start coding from the Services layer and leave no logic in your codebehind aspx files. We do also make big efforts to avoid having logic in Controllers as we saw them as codebehinds files and try to put all the system logic in the services.

Just make sure you plug all necesarry in your global asax file and you should have no problem at all. If you are using NHibernate, Fluent, Service Injection and DDD is really easy to make it work with old asp.net web application.


问:
Add value of playing cards - with pointers and structures
I'm going through some c programming questions and I'm currently stuck on a pointer related question

Q: Write a function that takes the values of a two-card blackjack HAND as input, and returns the point total of the hand. The value
 of the cards '2' through '9' is equal to their face value, the cards 'T', 'K', 'Q', 'J' are worth 10 points and the ace ('A') is worth 11 points
 unless it comes with another ace, then that second ace is worth 1 point. The program should be able to catch incorrect input.

Examples:
Enter cards: A Q
 The score is 21

Enter cards: A A
 The score is 12

I've tackled this question before, but this time I'd have to use pointers which I'm still fairly new towards. Getting card values and calculating cards must be done in one function. Here's what i have so far:

```<code>#include <stdio.h>
#define HAND 2
struct player_hand
{
     char card1;
     char card2;
};

void getHandValue(struct player_hand * hnd_ptr, char size, char size2)
{
    int first_card;
    int second_card;

    //get cards from user
    scanf("%c %c",&hnd_ptr->card1, &hnd_ptr->card2);
    printf("Enter Cards: %c %c", &hnd_ptr->card1, &hnd_ptr->card2);

    //check value of first card in hand
    if(hnd_ptr->card1<='9' && hnd_ptr->card1>='2')
    {
        first_card=(int)hnd_ptr->card1 -48;

    }
    //check for special cards: king, queen, jack, ten
    else if(hnd_ptr->card1=='T'||hnd_ptr->card1=='K'||hnd_ptr->card1=='Q'||hnd_ptr->card1=='J')
    {
        first_card=10;
    }
    //if first card is Ace
    else if(hnd_ptr->card1=='A')
    {
        first_card=11;
    }
    else
    {
        //card not valid
        printf("Not a valid card: %c",hnd_ptr->card1);
        return;
    }

    //check value of 2nd card
    if(hnd_ptr->card2<='9' && hnd_ptr->card2>='2')
    {
        second_card=(int)hnd_ptr->card2 -48;

    }
    //if 2nd card is a special kind
    else if(hnd_ptr->card2=='T'||hnd_ptr->card2=='K'||hnd_ptr->card2=='Q'||hnd_ptr->card2=='J')
    {
        second_card=10;
    }
    //if 2nd card is Ace
    else if(hnd_ptr->card2=='A')
    {
        if(hnd_ptr->card1=='A')
        second_card=1;
        else
        second_card=11;
    }
    else
    {
        //if 2nd card not valid
        printf("Not a valid card: %c",hnd_ptr->card2);
        return;
    }

    add cards
    printf("\nThe total card value is: %d",first_card+second_card);

}

//call function, test if works
//calling it wrong?
int main(void)
{
    struct player_hand hnd [HAND]  =  { {'A', 'A'}};
    getHandValue (hnd, HAND);
    return;
}
</code>```

答:
You're not passing the address of hnd to the function getHandValue(). To do this you have to pass the address using the & operator getHandValue(&hnd).

You're also not initializing struct player_hand hnd correctly. There's one set of {} too many.

Body:
I'm going through some c programming questions and I'm currently stuck on a pointer related question

Q: Write a function that takes the values of a two-card blackjack HAND as input, and returns the point total of the hand. The value
 of the cards '2' through '9' is equal to their face value, the cards 'T', 'K', 'Q', 'J' are worth 10 points and the ace ('A') is worth 11 points
 unless it comes with another ace, then that second ace is worth 1 point. The program should be able to catch incorrect input.

Examples:
Enter cards: A Q
 The score is 21

Enter cards: A A
 The score is 12

I've tackled this question before, but this time I'd have to use pointers which I'm still fairly new towards. Getting card values and calculating cards must be done in one function. Here's what i have so far:

#include <stdio.h>
#define HAND 2
struct player_hand
{
     char card1;
     char card2;
};

void getHandValue(struct player_hand * hnd_ptr, char size, char size2)
{
    int first_card;
    int second_card;

    //get cards from user
    scanf("%c %c",&hnd_ptr->card1, &hnd_ptr->card2);
    printf("Enter Cards: %c %c", &hnd_ptr->card1, &hnd_ptr->card2);

    //check value of first card in hand
    if(hnd_ptr->card1<='9' && hnd_ptr->card1>='2')
    {
        first_card=(int)hnd_ptr->card1 -48;

    }
    //check for special cards: king, queen, jack, ten
    else if(hnd_ptr->card1=='T'||hnd_ptr->card1=='K'||hnd_ptr->card1=='Q'||hnd_ptr->card1=='J')
    {
        first_card=10;
    }
    //if first card is Ace
    else if(hnd_ptr->card1=='A')
    {
        first_card=11;
    }
    else
    {
        //card not valid
        printf("Not a valid card: %c",hnd_ptr->card1);
        return;
    }

    //check value of 2nd card
    if(hnd_ptr->card2<='9' && hnd_ptr->card2>='2')
    {
        second_card=(int)hnd_ptr->card2 -48;

    }
    //if 2nd card is a special kind
    else if(hnd_ptr->card2=='T'||hnd_ptr->card2=='K'||hnd_ptr->card2=='Q'||hnd_ptr->card2=='J')
    {
        second_card=10;
    }
    //if 2nd card is Ace
    else if(hnd_ptr->card2=='A')
    {
        if(hnd_ptr->card1=='A')
        second_card=1;
        else
        second_card=11;
    }
    else
    {
        //if 2nd card not valid
        printf("Not a valid card: %c",hnd_ptr->card2);
        return;
    }

    add cards
    printf("\nThe total card value is: %d",first_card+second_card);

}

//call function, test if works
//calling it wrong?
int main(void)
{
    struct player_hand hnd [HAND]  =  { {'A', 'A'}};
    getHandValue (hnd, HAND);
    return;
}


答:
Here's an edited version of your main() code that works, just some minor edits to how your pointer is set up.

```<code>// main
int main(void)
{
    // minor edits to fix the code here
    struct player_hand hnd = {'A', 'A'};
    struct player_hand *hndPtr = &hnd;

    getHandValue (hndPtr);
    return 0;
}
</code>```

Title: Add value of playing cards - with pointers and structures

Body:
Here's an edited version of your main() code that works, just some minor edits to how your pointer is set up.

// main
int main(void)
{
    // minor edits to fix the code here
    struct player_hand hnd = {'A', 'A'};
    struct player_hand *hndPtr = &hnd;

    getHandValue (hndPtr);
    return 0;
}


问:
cycling star-field animation
I made this star-field animation in javascript. I'm just not sure the best way to make it cycle the same animation from the other side. I like to get the stars to scroll across from one side of the canvas to the other.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
stars = [];
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getSpeed(depth) {
  switch (depth / 2) {
    case 0:
      return 6;
    case 1:
      return 5;
    case 2:
      return 4;
    case 3:
      return 3;
    case 4:
      return 2;
    case 5:
      return 1;
  }
}
var i;
for (i = 0; i < 2000; i++) {
  var star = {
    x: 0,
    y: 0,
    z: 0,
    v: 0
  };
  star.x = getRandomInt(0, 500);
  star.y = getRandomInt(0, 500);
  star.z = getRandomInt(0, 5) * 2;
  star.v = getSpeed(star.z);
  stars.push(star);
}

function animation() {
  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, 500, 500);

  // populates space with stars
  for (i = 0; i < 2000; i++) {
    ctx.fillStyle = "rgb(" + (256 / stars[i].z) + "," + (256 / stars[i].z) + "," + (256 / stars[i].z) + ")";
    ctx.fillRect(stars[i].x, stars[i].y, 2, 2);
    stars[i].x += stars[i].v;
  }

  setTimeout(animation, 33);
}
animation();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas"></canvas></code>```

答:
you can see that the stars go both ways by adding the new property d (direction) and the direction changes when the stars reach to the end of the screen...

<!DOCTYPE html>

<canvas id="myCanvas"></canvas>

```

Title: cycling star-field animation

Body:
I made this star-field animation in javascript. I'm just not sure the best way to make it cycle the same animation from the other side. I like to get the stars to scroll across from one side of the canvas to the other.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
stars = [];
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getSpeed(depth) {
  switch (depth / 2) {
    case 0:
      return 6;
    case 1:
      return 5;
    case 2:
      return 4;
    case 3:
      return 3;
    case 4:
      return 2;
    case 5:
      return 1;
  }
}
var i;
for (i = 0; i < 2000; i++) {
  var star = {
    x: 0,
    y: 0,
    z: 0,
    v: 0
  };
  star.x = getRandomInt(0, 500);
  star.y = getRandomInt(0, 500);
  star.z = getRandomInt(0, 5) * 2;
  star.v = getSpeed(star.z);
  stars.push(star);
}

function animation() {
  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, 500, 500);

  // populates space with stars
  for (i = 0; i < 2000; i++) {
    ctx.fillStyle = "rgb(" + (256 / stars[i].z) + "," + (256 / stars[i].z) + "," + (256 / stars[i].z) + ")";
    ctx.fillRect(stars[i].x, stars[i].y, 2, 2);
    stars[i].x += stars[i].v;
  }

  setTimeout(animation, 33);
}
animation();

<canvas id="myCanvas"></canvas>

Body:
you can see that the stars go both ways by adding the new property d (direction) and the direction changes when the stars reach to the end of the screen...

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas"></canvas>
<script>

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
stars = [];
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getSpeed( depth)
{
     switch(depth/2)
     {
       case 0:
         return 6;
       case 1:
         return 5;
       case 2:
         return 4;
       case 3:
         return 3;
       case 4:
         return 2;
       case 5:
         return 1;
     }
}
var i;
for (i = 0; i < 2000; i++) {
  var star= { x: 0, y: 0, z: 0, v: 0 };
  star.x = getRandomInt(0, 500);
  star.y = getRandomInt(0, 500);
  star.z = getRandomInt(0, 5) * 2;
  star.v = getSpeed(star.z);
  star.d = 1;
  stars.push(star);
}

function animation () {
  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, 500, 500);

  // populates space with stars
  for (i = 0; i < 2000; i++) {
  ctx.fillStyle = "rgb(" + (256 / stars[i].z) + "," + (256 / stars[i].z) + "," + (256 / stars[i].z) + ")";
  ctx.fillRect(stars[i].x, stars[i].y, 2, 2);
  if(stars[i].x>=500)stars[i].d=-1;
  if(stars[i].x<=0)stars[i].d=1;
  stars[i].x += stars[i].v * stars[i].d;
 }

   setTimeout(animation, 33);
}
animation ();

</script>
</body>
</html>


问:
Vaadin 8: Widgetset not compiling com.vaadin.terminal.gwt.DefaultWidgetSet not found in project
I am trying to implement a Vaadin 8 framework project (8.0.5) but I can't get the widgetset to compile.

Using Glassfish 4 (alternatively, tried on Wildfly) DB: ObjectDB. I do have the charts and Timeline addon (Licensed). Theme compiles fine, using eclipse Vaadin plugin. WAR deploys fine.

After bringing up glassfish, tried accessing the UI - MyAppWidgetset.nocache.js not found error.

At this point tried compiling the widgetset Build failure with error com.vaadin.terminal.gwt.DefaultWidgetSet not found in project.

pom.xml reflects the same error at <execution> element.

Tried the fowllowing:

Added: @WidgetSet annotation to the MainUI class. Then added a gwt.xml class in ../resources/{package-folder structure} found on Vaadin forum:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.7.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/1.7.0/distro-source/core/src/gwt-module.dtd">
<module>
    <inherits name="com.vaadin.addon.charts.Widgetset" />
    <inherits name="com.vaadin.addon.timeline.gwt.TimelineWidgetSet" />
    <inherits name="com.vaadin.DefaultWidgetSet" />
</module>
</code>```

I manually tried adding:

```<code><inherits name="com.vaadin.terminal.gwt.DefaultWidgetSet" />
</code>```

But as soon as I save, Eclipse editor deletes that row. Is that supposed to happen? Tried adding from an external editor, but it gets deleted as soon as I open it in Eclipse.

After selectivly adding dependencies, the problem seems to be with charts.
Apparently, Adding Vaadin Charts dependency is causing the compilation to fail.
But I do have the license key in my root folder.

```<code>    <dependency>
        <groupId>com.vaadin.addon</groupId>
        <artifactId>vaadin-charts</artifactId>
        <version>2.0.0</version>
    </dependency>
</code>```

答:
So I was doing 2 things wrong:

The location of the license file. A per the Demo code on github, it was in the root folder of the project. It has to be under \Users\(username) Directory.

Vaadin 8 works with Charts 4.0 and not earlier versions.

Body:
I am trying to implement a Vaadin 8 framework project (8.0.5) but I can't get the widgetset to compile.

Using Glassfish 4 (alternatively, tried on Wildfly) DB: ObjectDB. I do have the charts and Timeline addon (Licensed). Theme compiles fine, using eclipse Vaadin plugin. WAR deploys fine.

After bringing up glassfish, tried accessing the UI - MyAppWidgetset.nocache.js not found error.

At this point tried compiling the widgetset Build failure with error com.vaadin.terminal.gwt.DefaultWidgetSet not found in project.

pom.xml reflects the same error at <execution> element.

Tried the fowllowing:

Added: @WidgetSet annotation to the MainUI class. Then added a gwt.xml class in ../resources/{package-folder structure} found on Vaadin forum:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.7.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/1.7.0/distro-source/core/src/gwt-module.dtd">
<module>
    <inherits name="com.vaadin.addon.charts.Widgetset" />
    <inherits name="com.vaadin.addon.timeline.gwt.TimelineWidgetSet" />
    <inherits name="com.vaadin.DefaultWidgetSet" />
</module>

I manually tried adding:

<inherits name="com.vaadin.terminal.gwt.DefaultWidgetSet" />

But as soon as I save, Eclipse editor deletes that row. Is that supposed to happen? Tried adding from an external editor, but it gets deleted as soon as I open it in Eclipse.

After selectivly adding dependencies, the problem seems to be with charts.
Apparently, Adding Vaadin Charts dependency is causing the compilation to fail.
But I do have the license key in my root folder.

    <dependency>
        <groupId>com.vaadin.addon</groupId>
        <artifactId>vaadin-charts</artifactId>
        <version>2.0.0</version>
    </dependency>


问:
Testing a rake task in rspec (and cucumber)
I'm new to Ruby, and I've been trying to learn Rake, RSpec, and Cucumber.  I found some code that will help me test my Rake tasks, but I'm having trouble getting it to work.  I was told here: http://blog.codahale.com/2007/12/20/rake-vs-rspec-fight/ to drop this:

```<code>def describe_rake_task(task_name, filename, &block)
  require "rake"

  describe "Rake task #{task_name}" do
    attr_reader :task

    before(:all) do
      @rake = Rake::Application.new
      Rake.application = @rake
      load filename
      @task = Rake::Task[task_name]
    end

    after(:all) do
      Rake.application = nil
    end

    def invoke!
      for action in task.instance_eval { @actions }
        instance_eval(&action)
      end
    end

    instance_eval(&block)
  end
end
</code>```

into my spec_helper.rb file.

I've managed to take this code out and run it in my cucumber steps like this:

```<code>When /^I run the update_installers task$/ do
 @rake = Rake::Application.new
 Rake.application = @rake
 load "lib/tasks/rakefile.rb"
 @task = Rake::Task["update_installers"]

 for action in @task.instance_eval { @actions }
  instance_eval(&action)
 end

 instance_eval(&block)

 Rake.application = nil
end
</code>```

but when I try to get things working in rspec, I get the following error.

ArgumentError in 'Rake task
  install_grapevine should install to
  the mygrapevine directory'

wrong number of arguments (1 for 2)
  /spec/spec_helper.rb: 21:in instance_eval'
  /spec/spec_helper.rb: 21:inblock in invoke!'
  /spec/spec_helper.rb: 20:in each'
  /spec/spec_helper.rb: 20:ininvoke!'
  /spec/tasks/rakefile_spec.rb:12:in `block (2 levels) in
  '

Unfortunately, I've got just under a week of ruby under by belt, so the metaprogramming stuff is over my head.  Could anyone point me in the right direction?

答:
This works for me: (Rails3/ Ruby 1.9.2)

```<code>When /^the system does it's automated tasks$/ do
  require "rake"
  @rake = Rake::Application.new
  Rake.application = @rake
  Rake.application.rake_require "tasks/cron"
  Rake::Task.define_task(:environment)
  @rake['cron'].invoke
end
</code>```

Substitute your rake task name here and also note that your require may be "lib/tasks/cron" if you don't have the lib folder in your load path.

I agree that you should only do minimal work in the Rake task and push the rest to models for ease of testing. That being said I think it's important to ensure that the code is ACTUALLY run in my cron tasks during my integration tests so I think very mild testing of the rake tasks is justified.

Body:
I'm new to Ruby, and I've been trying to learn Rake, RSpec, and Cucumber.  I found some code that will help me test my Rake tasks, but I'm having trouble getting it to work.  I was told here: http://blog.codahale.com/2007/12/20/rake-vs-rspec-fight/ to drop this:

def describe_rake_task(task_name, filename, &block)
  require "rake"

  describe "Rake task #{task_name}" do
    attr_reader :task

    before(:all) do
      @rake = Rake::Application.new
      Rake.application = @rake
      load filename
      @task = Rake::Task[task_name]
    end

    after(:all) do
      Rake.application = nil
    end

    def invoke!
      for action in task.instance_eval { @actions }
        instance_eval(&action)
      end
    end

    instance_eval(&block)
  end
end

into my spec_helper.rb file.

I've managed to take this code out and run it in my cucumber steps like this:

When /^I run the update_installers task$/ do
 @rake = Rake::Application.new
 Rake.application = @rake
 load "lib/tasks/rakefile.rb"
 @task = Rake::Task["update_installers"]

 for action in @task.instance_eval { @actions }
  instance_eval(&action)
 end

 instance_eval(&block)

 Rake.application = nil
end

but when I try to get things working in rspec, I get the following error.

ArgumentError in 'Rake task
  install_grapevine should install to
  the mygrapevine directory'

wrong number of arguments (1 for 2)
  /spec/spec_helper.rb: 21:in instance_eval'
  /spec/spec_helper.rb: 21:inblock in invoke!'
  /spec/spec_helper.rb: 20:in each'
  /spec/spec_helper.rb: 20:ininvoke!'
  /spec/tasks/rakefile_spec.rb:12:in `block (2 levels) in
  '

Unfortunately, I've got just under a week of ruby under by belt, so the metaprogramming stuff is over my head.  Could anyone point me in the right direction?

Body:
This works for me: (Rails3/ Ruby 1.9.2)

When /^the system does it's automated tasks$/ do
  require "rake"
  @rake = Rake::Application.new
  Rake.application = @rake
  Rake.application.rake_require "tasks/cron"
  Rake::Task.define_task(:environment)
  @rake['cron'].invoke
end

Substitute your rake task name here and also note that your require may be "lib/tasks/cron" if you don't have the lib folder in your load path.

I agree that you should only do minimal work in the Rake task and push the rest to models for ease of testing. That being said I think it's important to ensure that the code is ACTUALLY run in my cron tasks during my integration tests so I think very mild testing of the rake tasks is justified.


问:
Eclipse Mars not running after installing Lombok
i Need to use project Lombok into my spring based application. I am using eclipse Marc with Spring Tool Suit Plugin, when i try to install lombok jar it executed well and install the lombok to eclipse i-e adding lombok jar statement into eclipse.ini file and adding jar to root folder of eclipse but after this eclipse stop working means when i restart eclipse it does not start. just shows the eclipse launching screen and quickly hide that,
can anyone help me on that.
Thanks in advance.</p>

答:
Can you try this

go to eclipse.ini and edit and project clean

```<code>Eclipse.app/Contents/Eclipse/eclipse.ini.

-vmargs
-javaagent:lombok.jar
</code>```

Body:
Can you try this

go to eclipse.ini and edit and project clean

Eclipse.app/Contents/Eclipse/eclipse.ini.

-vmargs
-javaagent:lombok.jar


问:
compare multiple strings in foreach
I am making some programming for a hotel. They want an email receipt if a booking has been made.

I am working with a razor mergefield called: @GuaranteePolicy

A guest can book 1 or multiple rooms. If there is booked multiple rooms, the GuaranteePolicy has to be set on each room. But if the GuaranteePolicy is the same on each room, I have to print the GuaranteePolicy in the footer.

So as I see it I have to compare all the GuaranteePolicy mergefields in each room, and see if they consist of the same text? That I do not know how to solve.

I loop through the multiple rooms, and print if the GuaranteePolicy is different. That is working fine:

```<code>@if (!string.IsNullOrWhiteSpace(room.GuaranteePolicy))
{
    <tr>
        <th>
            <span><strong>GuaranteePolicy:</strong></span>
        </th>
    </tr>
    <tr>
        <th>
            <span>@room.GuaranteePolicy</span>
        </th>
    </tr>
}
</code>```

But how can I compare the text in multiple room.GuaranteePolicy and check if the text in each room is the same?

```<code> @if (room.GuaranteePolicy == ? )
{
    <tr>
        <th>
            <span>@room.GuaranteePolicy</span>
        </th>
    </tr>
    <tr>
         <th>
            <span>@room.GuaranteePolicy</span>
         </th>
    </tr>
}
</code>```

答:
In the controller make a function that check if all the rooms have the same Policy and assign a property in the model to true or false  :

```<code>public class RoomsModel{
public bool SamePolicy ...
public .......  Rooms ...
}
</code>```

Then check if this property true in the cshtml

```<code>if(Model.SamePolicy){
<footer>....
 }
</code>```

Title: compare multiple strings in foreach

Body:
I am making some programming for a hotel. They want an email receipt if a booking has been made.

I am working with a razor mergefield called: @GuaranteePolicy

A guest can book 1 or multiple rooms. If there is booked multiple rooms, the GuaranteePolicy has to be set on each room. But if the GuaranteePolicy is the same on each room, I have to print the GuaranteePolicy in the footer.

So as I see it I have to compare all the GuaranteePolicy mergefields in each room, and see if they consist of the same text? That I do not know how to solve.

I loop through the multiple rooms, and print if the GuaranteePolicy is different. That is working fine:

@if (!string.IsNullOrWhiteSpace(room.GuaranteePolicy))
{

            GuaranteePolicy:

            @room.GuaranteePolicy

}

But how can I compare the text in multiple room.GuaranteePolicy and check if the text in each room is the same?

 @if (room.GuaranteePolicy == ? )
{

            @room.GuaranteePolicy

            @room.GuaranteePolicy

}

Body:
In the controller make a function that check if all the rooms have the same Policy and assign a property in the model to true or false  :

public class RoomsModel{
public bool SamePolicy ...
public .......  Rooms ...
}

Then check if this property true in the cshtml

if(Model.SamePolicy){
<footer>....
 }


问:
PHP Error in my Server
Hey Guys I have this Java code in ANdroid studio:

```<code>private void loginUser(){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    boolean success = jsonResponse.getBoolean("success");
                    if (success) {
                        launchHomeScreen();
                        pd.dismiss();
                        Toast.makeText(LoginActivity.this,"Welcome back " + username,Toast.LENGTH_LONG).show();
                    }
                    else {
                        loginButton.setBackgroundColor(0x73000000);
                        Toast.makeText(LoginActivity.this,"Try again later!",Toast.LENGTH_LONG).show();
                        pd.dismiss();
                    }
                }
                catch (JSONException e) {
                    loginButton.setBackgroundColor(0x73000000);
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this,e.toString(),Toast.LENGTH_LONG).show();
                    pd.dismiss();
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loginButton.setBackgroundColor(0x73000000);
                Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                pd.dismiss();
            }
        }){
    @Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<>();
        params.put(KEY_USERNAME,username);
        params.put(KEY_PASSWORD,password);
        return params;
    }

};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
</code>```

}

And this at my Server as php code:

```<code><?php
$con = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];

$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUsername, $colPassword);

$response = array();
$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    if (password_verify($password, $colPassword)) {
        $response["success"] = true;
    }
}
header('Content-Type: application/json');
echo json_encode($response);
</code>```

?>

And that's the Error I get from my Server:

[29-Mar-2017 18:24:46 UTC] PHP Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement in /home/u371648055/public_html/login.php on line 11

SO I don't understand what's wrong in my Code. I know that the Javacode is correct....so....it's the phpcode..but what?

MY MySQL Database:

For the problem with the password = 0
Here is that what I send to Server:

```<code>private void registerUser(){
    pd = ProgressDialog.show(RegisterActivity.this, "", "Loading...");
    StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");
                        if (success) {
                            launchHomeScreen();
                            pd.dismiss();
                        }
                        else {
                            Toast.makeText(RegisterActivity.this,"Try again later!",Toast.LENGTH_LONG).show();
                            pd.dismiss();
                            Intent loginActivity = new Intent (RegisterActivity.this,LoginActivity.class);
                            RegisterActivity.this.startActivity(loginActivity);
                            finish();
                        }
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                        pd.dismiss();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(RegisterActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    pd.dismiss();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<>();
            params.put(KEY_USERNAME,username);
            params.put(KEY_PASSWORD,password);
            params.put(KEY_MOBILENUMBER,mobileNumber);
            params.put(KEY_EMAIL, email);
            return params;
        }

    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
</code>```

}
ANd that's the register php code:

```<code><?php
$connect = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];
$mobilenumber = $_POST["mobilenumber"];
$email = $_POST["email"];

registerUser();

function registerUser() {
    global $connect, $username, $password, $mobilenumber, $email;
    $statement = mysqli_prepare($connect, "INSERT INTO user (username, password, mobilenumber, email) VALUES (?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "siss", $username, $password, $mobilenumber, $email);
    mysqli_stmt_execute($statement);
    mysqli_stmt_close($statement);

}
</code>```

How I get the $password:

```<code>public class RegisterActivity extends AppCompatActivity {

   public static final String KEY_PASSWORD = "password";
   private String password;

  //When clicking the Regsiter-Button:
   pwd = (EditText) findViewById(R.id.editText2);
   password = pwd.getText().toString().trim();
   registerUser();
}
</code>```

答:
Well, most of the answers are correct here and I see your comment.

If you look into the password column, all the rows have the same value 'zero'. Possibly when you debug, you'll find that the password value that you send as post data is inconsistent with the password value for the corresponding row in the database.

Also note that passwords should not be of type int, and that varchar serves better as a password. Try keeping the same password in both your request and the row in the database.
Additionally, post here the value that you are sending from Android, and also that of the password_verify() function if your problem remains.

Title: PHP Error in my Server

Body:
Hey Guys I have this Java code in ANdroid studio:

private void loginUser(){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    boolean success = jsonResponse.getBoolean("success");
                    if (success) {
                        launchHomeScreen();
                        pd.dismiss();
                        Toast.makeText(LoginActivity.this,"Welcome back " + username,Toast.LENGTH_LONG).show();
                    }
                    else {
                        loginButton.setBackgroundColor(0x73000000);
                        Toast.makeText(LoginActivity.this,"Try again later!",Toast.LENGTH_LONG).show();
                        pd.dismiss();
                    }
                }
                catch (JSONException e) {
                    loginButton.setBackgroundColor(0x73000000);
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this,e.toString(),Toast.LENGTH_LONG).show();
                    pd.dismiss();
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loginButton.setBackgroundColor(0x73000000);
                Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                pd.dismiss();
            }
        }){
    @Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<>();
        params.put(KEY_USERNAME,username);
        params.put(KEY_PASSWORD,password);
        return params;
    }

};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

}

And this at my Server as php code:

<?php
$con = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];

$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUsername, $colPassword);

$response = array();
$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    if (password_verify($password, $colPassword)) {
        $response["success"] = true;
    }
}
header('Content-Type: application/json');
echo json_encode($response);

?>

And that's the Error I get from my Server:

[29-Mar-2017 18:24:46 UTC] PHP Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement in /home/u371648055/public_html/login.php on line 11

SO I don't understand what's wrong in my Code. I know that the Javacode is correct....so....it's the phpcode..but what?

MY MySQL Database:

For the problem with the password = 0
Here is that what I send to Server:

private void registerUser(){
    pd = ProgressDialog.show(RegisterActivity.this, "", "Loading...");
    StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");
                        if (success) {
                            launchHomeScreen();
                            pd.dismiss();
                        }
                        else {
                            Toast.makeText(RegisterActivity.this,"Try again later!",Toast.LENGTH_LONG).show();
                            pd.dismiss();
                            Intent loginActivity = new Intent (RegisterActivity.this,LoginActivity.class);
                            RegisterActivity.this.startActivity(loginActivity);
                            finish();
                        }
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                        pd.dismiss();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(RegisterActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    pd.dismiss();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<>();
            params.put(KEY_USERNAME,username);
            params.put(KEY_PASSWORD,password);
            params.put(KEY_MOBILENUMBER,mobileNumber);
            params.put(KEY_EMAIL, email);
            return params;
        }

    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

}
ANd that's the register php code:

<?php
$connect = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];
$mobilenumber = $_POST["mobilenumber"];
$email = $_POST["email"];

registerUser();

function registerUser() {
    global $connect, $username, $password, $mobilenumber, $email;
    $statement = mysqli_prepare($connect, "INSERT INTO user (username, password, mobilenumber, email) VALUES (?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "siss", $username, $password, $mobilenumber, $email);
    mysqli_stmt_execute($statement);
    mysqli_stmt_close($statement);

}

How I get the $password:

public class RegisterActivity extends AppCompatActivity {

   public static final String KEY_PASSWORD = "password";
   private String password;

  //When clicking the Regsiter-Button:
   pwd = (EditText) findViewById(R.id.editText2);
   password = pwd.getText().toString().trim();
   registerUser();
}


问:
Passing spinner values to async task as an parameter
I am new to android. I need to pass values from the spinner to asynctask as an parameter and till now I am successful in showing the results in spinner successfully.  Now i need to pass the selected value from the spinner to another activity on a button click (as an parameter to asynctask). Below is the code. Thanks in advance.

BackgroundFetchWorker.java:

```<code>public class BackgroundFetchWorker extends AsyncTask<String,Void,String> {
String json_string;
ProgressDialog progressDialog;
Context context;

BackgroundFetchWorker(Context ctx)
{
    context = ctx;
}

@Override
protected String doInBackground(String... params) {
    String type2 = params[0];
    String student_fetch_url = "http://pseudoattendance.pe.hu/studentFetch.php";
    if (type2.equals("fetchSubject")) {
        try {
            String semester = params[1];
            String stream = params[2];

            URL url = new URL(student_fetch_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoOutput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("semester", "UTF-8") + "=" + URLEncoder.encode(semester, "UTF-8")
                    + URLEncoder.encode("stream","UTF-8")+"="+URLEncoder.encode(stream,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String result = " ";
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();

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

    }
    return null;
}
@Override
protected void onPreExecute() {

    progressDialog = new ProgressDialog(context);
    progressDialog.setTitle("Fetching Data....");
    progressDialog.setMessage("This may take a while..");
    progressDialog.show();
}

@Override
protected void onPostExecute(String result) {

    progressDialog.dismiss();
    String s = result.trim();
    if(s.equals("{\"result\":[]}")){
        Toast.makeText(context, "ERROR OCCURED", Toast.LENGTH_SHORT).show();
    }
    else {
        json_string = result;
        Intent i = new Intent(context, TakeAttendanceActivity.class);
        i.putExtra("studentdata", json_string);
        context.startActivity(i);
        Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();
    }

}
@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
</code>```

}

FacultyWelcomeActivity.java:

```<code>public class FacultyWelcomeActivity extends AppCompatActivity  implements Spinner.OnItemSelectedListener{
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;

//Declaring an Spinner
private Spinner spinner;
private Spinner spinner1;

//An ArrayList for Spinner Items
private ArrayList<String> students;
private ArrayList<String> stream;

//JSON Array
private JSONArray result;
private JSONArray result1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_faculty_welcome);
    //Initializing the ArrayList
    students = new ArrayList<String>();
    stream = new ArrayList<String>();
    //Initializing Spinner
    spinner = (Spinner) findViewById(R.id.spinner);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String semesters= parent.getItemAtPosition(position).toString();

            String stream= parent.getItemAtPosition(position).toString();

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
    spinner1 = (Spinner) findViewById(R.id.spinner1);

    //Adding an Item Selected Listener to our Spinner
    //As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener

    getData();
    getData1();

    listView = (ListView) findViewById(R.id.lectureList);

    contactAdapter = new ContactAdapter(this, R.layout.rowlayout);
    listView.setAdapter(contactAdapter);
    JSON_STRING = getIntent().getExtras().getString("JSON Data");

    try {
        jsonObject = new JSONObject(JSON_STRING);
        jsonArray = jsonObject.getJSONArray("result");
        int count = 0;
        String sub1, sub2, sub3, sub4;
        while (count < jsonArray.length()) {
            JSONObject JO = jsonArray.getJSONObject(count);

            sub1 = JO.getString("fname");
            sub2 = JO.getString("lname");
            sub3 = JO.getString("id");
            sub4 = JO.getString("email");

            Contacts contacts = new Contacts(sub1, sub2, sub3, sub4);
            contactAdapter.add(contacts);
            count++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
    public void fetchSubject(View view) {
        String type2 = "fetchSubject";
        String spinnerdata = spinner.getSelectedItem().toString();
        String spinner1data = spinner1.getSelectedItem().toString();
        BackgroundFetchWorker background = new BackgroundFetchWorker(this);
        background.execute(type2,spinnerdata,spinner1data);
    }

private void getData1(){

    StringRequest stringRequest = new StringRequest(Config2.DATA_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);

                        //Storing the Array of JSON String to our JSON Array
                        result1 = j.getJSONArray(Config2.JSON_ARRAY);
                        getStudents1(result1);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(stringRequest);
}

private void getData(){

    StringRequest stringRequest = new StringRequest(Config.DATA_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);
                        result = j.getJSONArray(Config.JSON_ARRAY);
                        getStudents(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(stringRequest);
}

private void getStudents(JSONArray j){

    for(int i=0;i<j.length();i++){
        try {
            //Getting json object
            JSONObject json = j.getJSONObject(i);

            students.add(json.getString(Config.TAG_SEMESTER));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    spinner.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}

private void getStudents1(JSONArray j){
    //Traversing through all the items in the json array
    for(int i=0;i<j.length();i++){
        try {
            //Getting json object
            JSONObject json = j.getJSONObject(i);

            //Adding the name of the student to array list
            stream.add(json.getString(Config2.TAG_STREAM));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    spinner1.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, stream));
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    //check which spinner triggered the listener
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}}
</code>```

答:
You are passing parameters to doInBackground() this way:

```<code> background.execute("your string");
</code>```

Now the string "your string" will be the parameter within doInBackground() callback:

```<code>@Override
protected String doInBackground(String... params) {
    String type2 = params[0]; // type2 == "your string"
    ...
}
</code>```

See docs for more info.

Body:
I am new to android. I need to pass values from the spinner to asynctask as an parameter and till now I am successful in showing the results in spinner successfully.  Now i need to pass the selected value from the spinner to another activity on a button click (as an parameter to asynctask). Below is the code. Thanks in advance.

BackgroundFetchWorker.java:

public class BackgroundFetchWorker extends AsyncTask<String,Void,String> {
String json_string;
ProgressDialog progressDialog;
Context context;

BackgroundFetchWorker(Context ctx)
{
    context = ctx;
}

@Override
protected String doInBackground(String... params) {
    String type2 = params[0];
    String student_fetch_url = "http://pseudoattendance.pe.hu/studentFetch.php";
    if (type2.equals("fetchSubject")) {
        try {
            String semester = params[1];
            String stream = params[2];

            URL url = new URL(student_fetch_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoOutput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("semester", "UTF-8") + "=" + URLEncoder.encode(semester, "UTF-8")
                    + URLEncoder.encode("stream","UTF-8")+"="+URLEncoder.encode(stream,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String result = " ";
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();

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

    }
    return null;
}
@Override
protected void onPreExecute() {

    progressDialog = new ProgressDialog(context);
    progressDialog.setTitle("Fetching Data....");
    progressDialog.setMessage("This may take a while..");
    progressDialog.show();
}

@Override
protected void onPostExecute(String result) {

    progressDialog.dismiss();
    String s = result.trim();
    if(s.equals("{\"result\":[]}")){
        Toast.makeText(context, "ERROR OCCURED", Toast.LENGTH_SHORT).show();
    }
    else {
        json_string = result;
        Intent i = new Intent(context, TakeAttendanceActivity.class);
        i.putExtra("studentdata", json_string);
        context.startActivity(i);
        Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();
    }

}
@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

}

FacultyWelcomeActivity.java:

public class FacultyWelcomeActivity extends AppCompatActivity  implements Spinner.OnItemSelectedListener{
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;

//Declaring an Spinner
private Spinner spinner;
private Spinner spinner1;

//An ArrayList for Spinner Items
private ArrayList<String> students;
private ArrayList<String> stream;

//JSON Array
private JSONArray result;
private JSONArray result1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_faculty_welcome);
    //Initializing the ArrayList
    students = new ArrayList<String>();
    stream = new ArrayList<String>();
    //Initializing Spinner
    spinner = (Spinner) findViewById(R.id.spinner);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String semesters= parent.getItemAtPosition(position).toString();

            String stream= parent.getItemAtPosition(position).toString();

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
    spinner1 = (Spinner) findViewById(R.id.spinner1);

    //Adding an Item Selected Listener to our Spinner
    //As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener

    getData();
    getData1();

    listView = (ListView) findViewById(R.id.lectureList);

    contactAdapter = new ContactAdapter(this, R.layout.rowlayout);
    listView.setAdapter(contactAdapter);
    JSON_STRING = getIntent().getExtras().getString("JSON Data");

    try {
        jsonObject = new JSONObject(JSON_STRING);
        jsonArray = jsonObject.getJSONArray("result");
        int count = 0;
        String sub1, sub2, sub3, sub4;
        while (count < jsonArray.length()) {
            JSONObject JO = jsonArray.getJSONObject(count);

            sub1 = JO.getString("fname");
            sub2 = JO.getString("lname");
            sub3 = JO.getString("id");
            sub4 = JO.getString("email");

            Contacts contacts = new Contacts(sub1, sub2, sub3, sub4);
            contactAdapter.add(contacts);
            count++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
    public void fetchSubject(View view) {
        String type2 = "fetchSubject";
        String spinnerdata = spinner.getSelectedItem().toString();
        String spinner1data = spinner1.getSelectedItem().toString();
        BackgroundFetchWorker background = new BackgroundFetchWorker(this);
        background.execute(type2,spinnerdata,spinner1data);
    }

private void getData1(){

    StringRequest stringRequest = new StringRequest(Config2.DATA_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);

                        //Storing the Array of JSON String to our JSON Array
                        result1 = j.getJSONArray(Config2.JSON_ARRAY);
                        getStudents1(result1);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(stringRequest);
}

private void getData(){

    StringRequest stringRequest = new StringRequest(Config.DATA_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);
                        result = j.getJSONArray(Config.JSON_ARRAY);
                        getStudents(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(stringRequest);
}

private void getStudents(JSONArray j){

    for(int i=0;i<j.length();i++){
        try {
            //Getting json object
            JSONObject json = j.getJSONObject(i);

            students.add(json.getString(Config.TAG_SEMESTER));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    spinner.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}

private void getStudents1(JSONArray j){
    //Traversing through all the items in the json array
    for(int i=0;i<j.length();i++){
        try {
            //Getting json object
            JSONObject json = j.getJSONObject(i);

            //Adding the name of the student to array list
            stream.add(json.getString(Config2.TAG_STREAM));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    spinner1.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, stream));
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    //check which spinner triggered the listener
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}}

Body:
You are passing parameters to doInBackground() this way:

 background.execute("your string");

Now the string "your string" will be the parameter within doInBackground() callback:

@Override
protected String doInBackground(String... params) {
    String type2 = params[0]; // type2 == "your string"
    ...
}

See docs for more info.