text:
Q: How to bind to a property of type dynamic? public interface IClassA
{
    string Description { get; set; }
    // more IClassA specific definitions
}

public interface IClassB
{
    string Description { get; set; }
    // more IClassB specific definitions
}

public class ClassA : IClassA
{
    public string Description { get; set; }
}

public class ClassB : IClassB
{
    public string Description { get; set; }
}

This is the very simplified code. All classes lack of INotifyPropertyChanged implementations for simplicity. Just watch all the code as if it was properly implementend.
Putting Description into a base interface for IClassA and IClassB can't be considered, yet, so I was curious about dynamic properties bound via data binding in WPF. This is, what I have tried:
public class CustomClass
{
    public dynamic Instance { get; set; }

    // passed instance is a ClassA or ClassB object
    public CustomClass(dynamic instance)
    {
        Instance = instance;
    }
}

My Xaml contains a TextBlock, which has its DataContext set to a CutomClass object. If I change the Instance property's type to e.g. IClassA and fill it properly, everything works as expected. Not with dynamic though.
<TextBlock Text="{Binding Instance.Description}" />

The Xaml Designer/ReSharper in VS2012 tells me:Cannot resolve property 'Description' in data context of type 'object'.
Though CodeInstance is described as type of dynamic. But the code compiled, so I thought that just might be a design-time issue. But the TextBlock remains empty.
I might misunderstand the principle dynamic in this case, I don't know. So the lack of search results by using Google might be caused by not exactly knowing what to search for.

A: You can bind to a dynamic property the same way as any property. So your problem must be manifesting somewhere else, or ReSharper is giving yet another unhelpful error, (hate that program)
Dynamic binding Example:
Xaml:
<Window x:Class="WpfApplication7.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="104" Width="223" Name="UI">
    <StackPanel DataContext="{Binding ElementName=UI}">
        <TextBlock Text="{Binding MyProperty}" />
        <TextBlock Text="{Binding MyObject.MyProperty}" />
    </StackPanel>
</Window>

Code:
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        MyProperty = "Hello";
        MyObject = new ObjectTest { MyProperty = "Hello" };
    }

    private dynamic myVar;
    public dynamic MyProperty
    {
        get { return myVar; }
        set { myVar = value; NotifyPropertyChanged("MyProperty"); }
    }

    private dynamic myObject;
    public dynamic MyObject
    {
        get { return myObject; }
        set { myObject = value; NotifyPropertyChanged("MyObject"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string p)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(p));
        }
    }
}

public class ObjectTest
{
    public string MyProperty { get; set; }
}

Result:


text:
Q: Application of the Hadamard three-line theorem without an a-priori upper bound The Hadamard three-line theorem states:

Let $f: \mathbb R + i(0,1) \to \mathbb C$ and $M_y := \sup_{x \in
> \mathbb R} |f(x + iy)|$. If

*

*f is analytic on $\mathbb R + i(0,1)$ and continuous on $\mathbb R + i[0,1]$,

*$\sup_{y \in (0,1)} M_y < B$ for some $B > 0$ fixed,
then $M_y \leq M_0^{1-y} M_1^y$.

Q: Is it possible to relax the second condition to $M_y < \frac{B}{(y(1-y))^n}$ for some $n \in \mathbb N$.
My thoughts:
The supremum is still bounded on every subset, $\sup_{y \in (\epsilon,1-\epsilon)} M_y < \infty$ for any $\epsilon > 0$ fixed.
Is it possible to estimate $M_y$ close to the boundary by $M_0$ and $M_1$?
This is related to the question whether $y \mapsto M_y$ is continuous. This is certainly not true for any analytic function, e.g. $f(z) = e^{iz}$ satisfies $M_0 = 1$ by $M_y = \infty$ for any $y>0$ fixed.
However, we additionally have the property that $M_y < \infty$ for any $y>0$. Then, it seems obvious that $\lim_{y \searrow 0} M_y = M_0$ (at least no counter-example comes to my mind). But I am unsure how this can be proven.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Odoo _check_concurrency never triggered? With our team, we would like to implement a feature where the user is warned whenever the record he/she is updating have also been updated by one of his collegue since he/she opened the record.
We dug into the source code because we did not find any official documentation, only some module that did not fit our Odoo version (11).
We found in the file /odoo/odoo/models.py the method def _check_concurrency(self): with the following code:
    @api.multi
    def _check_concurrency(self):
        if not (self._log_access and self._context.get(self.CONCURRENCY_CHECK_FIELD)):
            return
        check_clause = "(id = %s AND %s < COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp)"
        for sub_ids in self._cr.split_for_in_conditions(self.ids):
            nclauses = 0
            params = []
            for id in sub_ids:
                id_ref = "%s,%s" % (self._name, id)
                update_date = self._context[self.CONCURRENCY_CHECK_FIELD].pop(id_ref, None)
                if update_date:
                    nclauses += 1
                    params.extend([id, update_date])
            if not nclauses:
                continue
            query = "SELECT id FROM %s WHERE %s" % (self._table, " OR ".join([check_clause] * nclauses))
            self._cr.execute(query, tuple(params))
            res = self._cr.fetchone()
            if res:
                # mention the first one only to keep the error message readable
                raise ValidationError(_('A document was modified since you last viewed it (%s:%d)') % (self._description, res[0]))

=> This method is called before any "write". It compares :

*

*the __last_update value of the record at the time of write

*with a value of __last_update get from the context, which therefore should have been set in the context beforehand
PROBLEM
We did not find anywhere in the code (python or javascript) the value set in the context => NOTHING HAPPENS ! THe function returns from the beginning.
When we tried to hardcode it in the context, the function check_concurrency seems to work properly.
QUESTION
Does anyone one know where the __last_update is set or SHOULD BE set in the context ? And how ?
I would e.g. imagine setting it somehow when clicking on edit button of a record ??? Or at read time ??

A: CONCURRENCY_CHECK_FIELD = '__last_update'

concurrency field is a dynamic field which computing method defined dynamically and also you can see this is updated by
last_modified_name = 'compute_concurrency_field_with_access' or last_modified_name = 'compute_concurrency_field' according to access and later added to the class. Following functions will take part in the workaround.
@api.model
    def _add_magic_fields(self):
        """ Introduce magic fields on the current class

        * id is a "normal" field (with a specific getter)
        * create_uid, create_date, write_uid and write_date have become
          "normal" fields
        * $CONCURRENCY_CHECK_FIELD is a computed field with its computing
          method defined dynamically. Uses ``str(datetime.datetime.utcnow())``
          to get the same structure as the previous
          ``(now() at time zone 'UTC')::timestamp``::

              # select (now() at time zone 'UTC')::timestamp;
                        timezone
              ----------------------------
               2013-06-18 08:30:37.292809

              >>> str(datetime.datetime.utcnow())
              '2013-06-18 08:31:32.821177'
        """
        def add(name, field):
            """ add ``field`` with the given ``name`` if it does not exist yet """
            if name not in self._fields:
                self._add_field(name, field)

        # cyclic import
        from . import fields

        # this field 'id' must override any other column or field
        self._add_field('id', fields.Id(automatic=True))

        add('display_name', fields.Char(string='Display Name', automatic=True,
            compute='_compute_display_name'))

        if self._log_access:
            add('create_uid', fields.Many2one('res.users', string='Created by', automatic=True))
            add('create_date', fields.Datetime(string='Created on', automatic=True))
            add('write_uid', fields.Many2one('res.users', string='Last Updated by', automatic=True))
            add('write_date', fields.Datetime(string='Last Updated on', automatic=True))
            last_modified_name = 'compute_concurrency_field_with_access'
        else:
            last_modified_name = 'compute_concurrency_field'

        # this field must override any other column or field
        self._add_field(self.CONCURRENCY_CHECK_FIELD, fields.Datetime(
            string='Last Modified on', compute=last_modified_name, automatic=True))

    def compute_concurrency_field(self):
        for record in self:
            record[self.CONCURRENCY_CHECK_FIELD] = odoo.fields.Datetime.now()

    @api.depends('create_date', 'write_date')
    def compute_concurrency_field_with_access(self):
        for record in self:
            record[self.CONCURRENCY_CHECK_FIELD] = \
                record.write_date or record.create_date or odoo.fields.Datetime.now()


text:
Q: How to implement Hammer.js for the swipe event for devices without mouse How can I implement Hammer.js to catch only swipeLeft and swipeRight events on devices without mouse?
In the source code of hammer.js I found that a var INPUT_TYPE_MOUSE = 'mouse'; exists. In the documentation I did not find how to disable it with the options.
Have I to disable all recognizers in a preset if I only want to use the swipe recognizer?
 preset: [
// RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
[RotateRecognizer, { enable: false }],
[PinchRecognizer, { enable: false }, ['rotate']],
[SwipeRecognizer,{ direction: DIRECTION_HORIZONTAL }],
[PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']],
[TapRecognizer],
[TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']],
[PressRecognizer]
],

How can I do this by the options?

A: To use only Swipe recognizer you can do this:
var mc = new Hammer.Manager(element, managerOptions);
mc.add(new Hammer.Swipe(recognizerOptions));
mc.on('swipeleft', leftSwipeHandler);
mc.on('swiperight', rightSwipeHandler);

It's described in More Control Section in documentation.
This will recognize swipe not only in touch devices but also in those that use mouse. I don't know how to disable firing this event in mouse devices. But I think that after event's been fired you can check in handler function what kind of pointer caused the event. Use event's pointerType property for that purpose:
var leftSwipeHandler = function (event) {
  if (event.pointerType === 'mouse')
    return;
  // some more code
}

If you use jquery plugin then this property is in gesture object: event.gesture.pointerType.


text:
Q: Mount nginx configuration files inside docker container I would like to mount nginx.conf and default.conf to an nginx running container.
docker run --detach --tty --interactive --publish=8081:80
-v $(pwd)/app:/var/www/
-v $(pwd)/configurations/nginx.conf:/etc/nginx/nginx.conf
-v $(pwd)/configurations/default.conf:/etc/nginx/sites-enabled/default.conf
--name="my_container" my:dev

I have got a 404 error and when I logged into the docker container I found that the app directory was mount but the default.conf was the default one.
This is default.conf file:
server {

    root /var/www;
    index index.html index.htm index.php;

    server_name localhost;

    location / {
        try_files $uri $uri/ /index.php?$query_string =404;
    }

    location ~ \.php$ {

                fastcgi_split_path_info ^(.+\.php)(/.+)$;

                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;

                fastcgi_buffer_size 128k;
                fastcgi_buffers 256 16k;
                fastcgi_busy_buffers_size 256k;
                fastcgi_temp_file_write_size 256k;
                fastcgi_read_timeout 240;

    }

}


text:
Q: Getting error "Can only apply 'exp' function to dimensionless quantities", Not sure how to fix this I have been working on converting some MatLab code over to python for one of my professors (not an assignment just working on putting together some stuff) and I am stuck on this one part.
When I run the code I am getting UnitTypeError: "Can only apply 'exp' function to dimensionless quantities", all of the methods I have tried to fix this won't work. I imagine the error is caused by the linspace command but am not sure. Any help with this would be great.
here is the line
IM0 = ((2*h*c**2)/(l**5))/(np.exp(h*c/( h*c/(k*T1*l)))-1)
with the constants being from astropy
h = const.h;
c = const.c;
k = const.k_B;
l = np.linspace(0, 1.5e-6, 1500);
T1 = 3750

A: The astropy constants are instances of classes.  Try extracting the "value" for each before using them as an argument to np.exp():
import astropy.constants as const
import numpy as np

h = const.h.value
c = const.c.value
k = const.k_B.value
l = np.linspace(0, 1.5e-6, 1500);
T1 = 3750
IM0 = ((2*h*c**2)/(l**5))/(np.exp(h*c/( h*c/(k*T1*l)))-1)

However please note there are numerical problems with IM0.  The denominator is zero over all l.

A: The accepted answer is fine and works so far as you're confident that the bare values you're using are in the correct dimensions.  But in general using .value and throwing away the units information can be potentially dangerous--using Quantities with units ensures that all your calculations are being done with compatible units.
Let's look at just the exponent in your exponential, which normally should be a dimensionless quantity.
First note that all the constants you're using from Astropy have units:
>>> from astropy.constants import h, c, k_B
>>> h
<<class 'astropy.constants.codata2018.CODATA2018'> name='Planck constant' value=6.62607015e-34 uncertainty=0.0 unit='J s' reference='CODATA 2018'>
>>> c
<<class 'astropy.constants.codata2018.CODATA2018'> name='Speed of light in vacuum' value=299792458.0 uncertainty=0.0 unit='m / s' reference='CODATA 2018'>
>>> k_B
<<class 'astropy.constants.codata2018.CODATA2018'> name='Boltzmann constant' value=1.380649e-23 uncertainty=0.0 unit='J / K' reference='CODATA 2018'>

You then declared some unitless values and mixed them in with those:
>>> T1 = 3750
>>> l = np.linspace(0, 1.5e-6, 1500)
>>> h*c/(h*c/(k_B*T1*l))
/home/embray/.virtualenvs/astropy/lib/python3.6/site-packages/astropy/units/quantity.py:481: RuntimeWarning: divide by zero encountered in true_divide
  result = super().__array_ufunc__(function, method, *arrays, **kwargs)
<Quantity [0.00000000e+00, 5.18088768e-29, 1.03617754e-28, ...,
           7.75578885e-26, 7.76096974e-26, 7.76615063e-26] J / K>

Giving a result in joules per kelvin, from k_B which needs to be canceled out with some values in the correct unit.  I'm guessing T1 is supposed to be temperature in Kelvin (I'm not sure about l but let's say it's a thermodynamic beta in J-1 though you should double-check whatever units this value is supposed to be in).
So what you probably want to do is declare these values with appropriate units (as an aside, you can avoid the annoying divide-by-zero by defining some epsilon and using that as the start of your range):
>>> from astropy import units as u
>>> eps = np.finfo(float).eps
>>> T1 = 3750 * u.K
>>> l = np.linspace(eps, 1.5e-6, 1500) * (u.J**-1)

Now your exponent is properly a dimensionless quantity:
>>> h*c/(h*c/(k_B*T1*l))
<Quantity [1.14962123e-35, 5.18088882e-29, 1.03617765e-28, ...,
           7.75578885e-26, 7.76096974e-26, 7.76615063e-26]>
>>> np.exp(h*c/(h*c/(k_B*T1*l)))
<Quantity [1., 1., 1., ..., 1., 1., 1.]>

(In this case the dimensionless values were all so close to zero that the exponents round to 1--if this is not correct then you'll want to check some of my assumptions about your units).
In any case, this is how the library is intended to be used, and the error you're getting is a deliberate safecheck against your assumptions.
Update: I saw in your other question that you gave some more context to your problem, in particular specifying that l are wavelengths in meters (this was my first guess but I wasn't sure based on the equation you gave).
Actually you can avoid directly using h and c in your Plank equation by taking advantage of equivalencies.  Here you can define l as wavelengths in meters:
>>> l = np.linspace(eps, 1.5e-6, 1500) * u.m

and convert this directly to spectral energy:
>>> E = l.to(u.J, equivalencies=u.spectral())
>>> E
<Quantity [8.94615682e-10, 1.98512112e-16, 9.92560670e-17, ...,
           1.32606651e-19, 1.32518128e-19, 1.32429724e-19] J>

Then write the exponent in your Plank's law equation like:
>>> np.exp(E / (k_B * T1))
/home/embray/.virtualenvs/astropy/lib/python3.6/site-packages/astropy/units/quantity.py:481: RuntimeWarning: overflow encountered in exp
  result = super().__array_ufunc__(function, method, *arrays, **kwargs)
<Quantity [        inf,         inf,         inf, ..., 12.95190431,
           12.92977839, 12.90771972]>

(here it gives some infinities near low wavelengths, but you can avoid this by clipping to a larger lower bound).


text:
Q: How to set Image instead of text in ListView with Section Header part in Android I want to set Image in Header of ListView Section instead of text. I use ListView with section and in header part I want to set Image so how can I do this?

A: If your're talking about sectioning in listviews like in preferences you can try this tutoeial
http://bartinger.at/listview-with-sectionsseparators/
but instead of use my section xml make your own with an imageview


text:
Q: Read Text File; Copy Non-Indented Text Line; Replace Beginning of Indented Lines with Said Text I have a text file I want to manipulate the text in.  An example portion of the file is below.  I want to read the first non-indented line and insert that text at the beginning of all the following indented lines below.  However, as you can see from the example portion (the file is 12k lines long with each section being of varying length), eventually the indented lines stop, there is a blank line, and then a new non-indented string that I would want inserted at the beginning of the next set of indented lines.  The indent as well as white-space between text are all currently tabs, however, could easily be replaced throughout the document with something like "|".
So....file example before modification:
SOME_LINE_OF_TEXT
    Interface   Status  Protocol    Description
    Vl1 up  up
    Gi0/1   admin down  down
    Gi0/2   admin down  down
    Gi0/3   admin down  down
    Gi0/4   admin down  down
    Gi0/5   admin down  down
    Gi0/6   admin down  down
    Gi0/7   admin down  down
    Gi0/8   admin down  down
    Gi0/9   admin down  down
    Gi0/10  admin down  down
    Gi0/11  admin down  down
    Gi0/12  admin down  down
    Gi0/13  admin down  down
    Gi0/14  admin down  down
    Gi0/15  admin down  down
    Gi0/16  admin down  down
    Gi0/17  admin down  down
    Gi0/18  admin down  down
    Gi0/19  admin down  down
    Gi0/20  admin down  down
    Gi0/21  admin down  down
    Gi0/22  admin down  down
    Gi0/23  admin down  down
    Gi0/24  admin down  down
    Gi0/25  admin down  down
    Gi0/26  admin down  down
    Gi0/27  admin down  down
    Gi0/28  up  up  Node Name

SOME_OTHER_DIFFERENT_LINE_OF_TEXT
    Interface   Status  Protocol    Description
    Vl1 up  up
    Gi0/1   down    down    Noce Name
    Gi0/2   admin down  down
    Gi0/3   admin down  down
    Gi0/4   admin down  down
    Gi0/5   admin down  down
    Gi0/6   admin down  down
    Gi0/7   admin down  down
    Gi0/8   admin down  down
    Gi0/9   admin down  down
    Gi0/10  admin down  down
    Gi0/11  admin down  down
    Gi0/12  admin down  down
    Gi0/13  admin down  down
    Gi0/14  admin down  down
    Gi0/15  admin down  down
    Gi0/16  admin down  down
    Gi0/17  admin down  down
    Gi0/18  admin down  down
    Gi0/19  admin down  down
    Gi0/20  admin down  down
    Gi0/21  admin down  down
    Gi0/22  admin down  down
    Gi0/23  up  up  Node Name
    Gi0/24  up  up  Node Name
    Gi0/25  admin down  down
    Gi0/26  admin down  down
    Gi0/27  admin down  down
    Gi0/28  up  up  Node Name

Desired End Result:
SOME_LINE_OF_TEXT
SOME_LINE_OF_TEXT   Interface   Status  Protocol    Description
SOME_LINE_OF_TEXT   Vl1 up  up
SOME_LINE_OF_TEXT   Gi0/1   admin down  down
SOME_LINE_OF_TEXT   Gi0/2   admin down  down
SOME_LINE_OF_TEXT   Gi0/3   admin down  down
SOME_LINE_OF_TEXT   Gi0/4   admin down  down
SOME_LINE_OF_TEXT   Gi0/5   admin down  down
SOME_LINE_OF_TEXT   Gi0/6   admin down  down
SOME_LINE_OF_TEXT   Gi0/7   admin down  down
SOME_LINE_OF_TEXT   Gi0/8   admin down  down
SOME_LINE_OF_TEXT   Gi0/9   admin down  down
SOME_LINE_OF_TEXT   Gi0/10  admin down  down
SOME_LINE_OF_TEXT   Gi0/11  admin down  down
SOME_LINE_OF_TEXT   Gi0/12  admin down  down
SOME_LINE_OF_TEXT   Gi0/13  admin down  down
SOME_LINE_OF_TEXT   Gi0/14  admin down  down
SOME_LINE_OF_TEXT   Gi0/15  admin down  down
SOME_LINE_OF_TEXT   Gi0/16  admin down  down
SOME_LINE_OF_TEXT   Gi0/17  admin down  down
SOME_LINE_OF_TEXT   Gi0/18  admin down  down
SOME_LINE_OF_TEXT   Gi0/19  admin down  down
SOME_LINE_OF_TEXT   Gi0/20  admin down  down
SOME_LINE_OF_TEXT   Gi0/21  admin down  down
SOME_LINE_OF_TEXT   Gi0/22  admin down  down
SOME_LINE_OF_TEXT   Gi0/23  admin down  down
SOME_LINE_OF_TEXT   Gi0/24  admin down  down
SOME_LINE_OF_TEXT   Gi0/25  admin down  down
SOME_LINE_OF_TEXT   Gi0/26  admin down  down
SOME_LINE_OF_TEXT   Gi0/27  admin down  down
SOME_LINE_OF_TEXT   Gi0/28  up  up  Node Name

SOME_OTHER_DIFFERENT_LINE_OF_TEXT
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Interface   Status  Protocol    Description
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Vl1 up  up
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/1   down    down    Noce Name
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/2   admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/3   admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/4   admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/5   admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/6   admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/7   admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/8   admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/9   admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/10  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/11  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/12  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/13  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/14  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/15  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/16  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/17  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/18  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/19  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/20  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/21  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/22  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/23  up  up  Node Name
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/24  up  up  Node Name
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/25  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/26  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/27  admin down  down
SOME_OTHER_DIFFERENT_LINE_OF_TEXT   Gi0/28  up  up  Node Name

I am currently doing a manual find and replace thought Notepad++, however, with 12k lines, that is going to take more time than I would rather spend on this.

A: Possible solution:

awk '{ if (/^[A-Z]/) { p=$0; print } else if (/^$/) { print "" } else { print p$0 } }' /path/to/file

If a line starts with a non-whitespace value, save and print it, otherwise prepend the line with last stored value.


text:
Q: Angular js How to pass parameters to $location.path() and use this in $routeProvider for routing On button click I have code to navigate.

$s.onClick = function (pageObj) {
     $location.path('/Next');
}

Here param pageObj is object containing link (ex: http://sample..), title and other key values. Now I want to pass link, title as params to $location.path so I tried with

$location.path('/Next/' + pageObj.link + '/' + pageObj.title)

Here link, title params I want to use in next page. pageObj.link is again http so the complete routing url will be invalid to navigate.
Here is the code for routing

angularModule.config(function ($routeProvider) {
$routeProvider
    .when('/', {
        templateUrl: '/www/temp/Main.html',
        controller: 'MainController'
    })
    .when('/Next', {

        templateUrl: '/www/temp/Select.html',
        controller: 'SelectController'

    })
});

how to check for params and navigate to Next page with those params. I do not want those params to be shown in the url.

A: Since you don't want the parameters to appear in the URL, the absolute easiest way is to use the $rootScope like this:
First Page
$rootScope.routeParams.link = "/my/link/here";
$rootScope.routerParams.title = "My page title here";

Second Page
$scope.link = $rootScope.routerParams.link;
$scope.title = $rootScope.routerParams.title;

Note
You'll need to define the $rootScope.routeParams object in your app.config, similar to this:
app.config(function($rootScope) {
    $rootScope.routeParams = {
        link: null,
        title: null
    }
});

You'll also need to inject $rootScope into each controller where you reference it, similar to this:
app.controller('FirstPage_Ctrl', function($scope, $rootScope) {
    $rootScope.routeParams.link = "/my/link/here";
    $rootScope.routerParams.title = "My page title here";
});


text:
Q: C# MVC 4 ViewModel not accepting null DateTime I'm in a bit of trouble here learning C# and mvc4.
The Problem occurs in the Filter part of my application.
I have an ViewModel that grabs the list of "Listar_Produtos" of the database, and some fields for searching options.
What I intend to do is make the filter accept any field, even if it's null values. Because i'll make the filter based on these paramters.
I Have an Viewmodel:
using Foolproof;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Ecommerce.Models.Repository
{
    public class Produto_Repository
    {
        public class Index_Listar_Produtos
        {
            public List<Listar_Produto> Index_List_Produto { get; set; }

            [Display(Name = "Data de Cadastro Inicial")]
            [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
            public Nullable<DateTime> CadastroInicialData { get; set; }

            [Display(Name = "Data de Cadastro Final")]
            [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
            [GreaterThanOrEqualTo("CadastroInicialData", ErrorMessage = "\"Data Inicial\", deve ser maior que \"Data Final\"")]
            public Nullable<DateTime> CadastroFinalData { get; set; }
        }
    }
}

And I have the following View:

    @Html.LabelFor(Model => Model.CadastroInicialData)

    @Html.TextBoxFor(Model => Model.CadastroInicialData, "{0:dd/MM/yyyy}")
    @Html.ValidationMessageFor(Model => Model.CadastroInicialData)

    @Html.LabelFor(Model => Model.CadastroFinalData)

    @Html.TextBoxFor(Model => Model.CadastroFinalData, "{0:dd/MM/yyyy}")
    @Html.ValidationMessageFor(Model => Model.CadastroFinalData)

In my Controller I have:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Filtro(Produto_Repository.Index_Listar_Produtos ViewModel)
{
    if (!ModelState.IsValid)
    {
        Produto_Repository.Index_Listar_Produtos Model_list = Produto_Repository.GetProdutoByAll();
        ViewModel.Index_List_Produto = Model_list.Index_List_Produto;
        return View("Index", ViewModel);
    }
}

Where "Produto_Repository.GetProdutoByAll();" returns the list of "Produtos" again.
The code works fine and well if I provide dates in the form. The dates are in "pt-BR" format: 23/03/2013.
But if I provide nothing in the Fields (both Datefields in my View), than the "if(!ModelState.IsValid)" returns true and enters the "if", because both "CadastroInicialData" and "CadastroFinalData" comes with null values
The desired behavior is that the ViewModel could accept null or empty values that are granted by "Nullable" or "DateTime?".
I Tryed to insert values to the nullable date fields doing the following:
if (ViewModel.CadastroInicialData == null)
    ViewModel.CadastroInicialData = Convert.ToDateTime("01/01/2013");
if (ViewModel.CadastroFinalData == null)
    ViewModel.CadastroFinalData = Convert.ToDateTime("01/01/2013");

But now the ViewModel returns the following error:
"is an invalid date format"
One note is that i'm using the following 'solution' for converting datetimes for pt-BR dateformat on the following question:
Format datetime in asp.net mvc 4
How I make the ViewModel accept null values when the text fields are not filled with dates?
I'm kinda confused here. I apreciate any help ! Thanks !

A: You can add another properties to your Model class, then use them to determine if the value is null or not. Also implement them in your view. See below code:
Model
public class Index_Listar_Produtos
{
    public List<Listar_Produto> Index_List_Produto { get; set; }

    [Display(Name = "Data de Cadastro Inicial")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public Nullable<DateTime> CadastroInicialData { get; set; }

    [Display(Name = "Data de Cadastro Final")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    [GreaterThanOrEqualTo("CadastroInicialData", ErrorMessage = "\"Data Inicial\", deve ser maior que \"Data Final\"")]
    public Nullable<DateTime> CadastroFinalData { get; set; }

    public string GetStringTypeCadastroInicialData
    {
        get { return CadastroInicialData != null ? CadastroInicialData.Value.ToShortDateString() : DateTime.MinValue.ToShortDateString()(Or empty string ); }
    }

    public string GetStringTypeCadastroFinalData
    {
        get { return CadastroInicialData != null ? CadastroFinalData.Value.ToShortDateString() : DateTime.Now.ToShortDateString(); }
    }

}

View

    @Html.LabelFor(Model => Model.GetStringTypeCadastroInicialData)

    @Html.TextBoxFor(Model => Model.GetStringTypeCadastroInicialData)
    @Html.ValidationMessageFor(Model => Model.GetStringTypeCadastroInicialData)

    @Html.LabelFor(Model => Model.GetStringTypeCadastroFinalData)

    @Html.TextBoxFor(Model => Model.GetStringTypeCadastroFinalData)
    @Html.ValidationMessageFor(Model => Model.GetStringTypeCadastroFinalData)

A: Instead of
public Nullable<DateTime> CadastroInicialData { get; set; }

try
public DateTime? CadastroInicialData { get; set; }

and then to see if it has a value, you can do:
if (CadastroInicialData.HasValue)
{
    // do your processing here
}

A: Your model state is failing because of the GreaterThan data annotation on your second nullable DateTime value.  null is not greater than null, so it is failing.  You will either need to modify the GreaterThan data annotation to not compare if the values if they are null or remove that data annotation and do the comparison yourself.  An example could be:
if(model.CadastroInicialData.HasValue() && model.CadastroFinalData.HasValue() && model.CadastroInicialData.Value > model.CadastroFinalData.Value){
    ModelState.AddModelError("CadastroInicialData", "CadastroInicialData must be less than CadastroFinalData");
}

if(!modelState.IsValid()){
   Produto_Repository.Index_Listar_Produtos Model_list = Produto_Repository.GetProdutoByAll();
   ViewModel.Index_List_Produto = Model_list.Index_List_Produto;
   return View("Index", ViewModel);
}

A: Instead of using Convert.ToDateTime use DateTime.TryParseExact, and you can specify format and culture. The below code should work and fix the errors:
if (ViewModel.CadastroInicialData == null)
    ViewModel.CadastroInicialData = DateTime.TryParseExact(text, "MM/dd/yyyy",
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out "01/01/2013");
if (ViewModel.CadastroFinalData == null)
    ViewModel.CadastroFinalData = DateTime.TryParseExact(text, "MM/dd/yyyy",
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out "01/01/2013");


text:
Q: How to notate the universal quantifier when applied to an equation? So I have an equation with infinite regular solutions. Let's say this equation is $$\sin^{-1}(0)=\pi n$$ where $n$ is any integer. How do I express this formally using the universal quantifier?
Do I say

*

*$\forall n\in\mathbb Z: \sin^{-1}(0)=\pi n$

*$\sin^{-1}(0)=\forall n\in\mathbb Z:\pi n$

*$\sin^{-1}(0)=\pi n, \forall n\in\mathbb Z$
Or is there a more aesthetic way to express this?
In other words, by convention, where am I supposed to put the universal quantifier when an equality sign is involved?

A: Using natural language (like you did in the first paragraph of your question) is a very common, and in many cases, the preferred way of writing a quantification.
But there are occasions where using symbols is preferable. Formal definitions of formulas usually dictate that the quantifier must come first, i.e.
$$
  \forall x \in X: f(x) = g(x).
$$
If you work with formulas in logic or model theory, this is the only way.
Outside of this context, it can be more pleasant to put the formula up-front, and most people would find
$$
  f(x) = g(x) \qquad \forall x \in X
$$
acceptable as well. It is generally a bad idea to mix quantifiers before and after the formula, though, because there is no convention in which order they apply (and $\forall$ and $\exists$ cannot be interchanged in general).
Your second option really makes no sense at all because it looks like $\sin^{-1}(0)$ is somehow equal to the "statement" $\forall n \in \mathbb Z : \pi n$ (which isn't even a statement because $\pi n$ isn't).

A: $$\sin(x)=0\iff\exists\ n\in\mathbb Z:x=n\pi.$$

A:
$$\sin^{-1}(0)=\pi n$$ where $n$ is any integer

*

*If you accept that $\sin^{-1}(0)$ is just the single value $0$ (as
pointed out in the comments), then technically $$\forall
n{\in}\mathbb Z\:\:\sin^{-1}(0)=\pi n$$ is false, but $$\exists
n{\in}\mathbb Z\:\:\sin^{-1}(0)=\pi n$$ is true.

*Both these statements (which I think you, in trying to convey that every integer multiple of $\pi$ is a solution of $\sin\theta,$ actually meant) are false!
$$\forall\theta{\in}\mathbb R\,\Big(\quad\forall n{\in}\mathbb Z\quad
\big(\sin\theta=0 \implies \theta=\pi n\big)\quad\Big)$$
$$\forall\theta{\in}\mathbb R\,\Big(\quad\sin\theta=0 \implies \big(\forall n{\in}\mathbb Z\quad\theta=\pi n\big)\quad\Big)$$

*These statements are all true (the last one vacuously true):
$$\forall\theta{\in}\mathbb R\,\Big(\quad\exists n{\in}\mathbb Z\quad
\big(\sin\theta=0 \iff \theta=\pi n\big)\quad\Big)$$
$$\forall\theta{\in}\mathbb R\,\Big(\quad\sin\theta=0 \iff \big(\exists
n{\in}\mathbb Z\quad\theta=\pi n\big)\quad\Big)$$
$$\forall\theta{\in}\mathbb R\,\Big(\quad\forall n{\in}\mathbb Z\quad \big(\theta=\pi n \implies \sin\theta=0\big)\quad\Big)$$
$$\forall\theta{\in}\mathbb R\,\Big(\quad\big(\forall n{\in}\mathbb Z\quad\theta=\pi n\big) \implies \sin\theta=0\quad\Big)$$

*

*$\forall n\in\mathbb Z: \sin^{-1}(0)=\pi n$

The colon ("such that") is, at best, unnecessary.

*$\sin^{-1}(0)=\forall n\in\mathbb Z:\pi n$

Syntactically very wrong.

*$\sin^{-1}(0)=\pi n, \forall n\in\mathbb Z$

Syntactically wrong because in symbolic logic, quantifiers are always in front of the formula. Even in natural language (e.g., English), when there are multiple quantifiers, placing one or all of them behind the formula is called hanging the quantifier; to prevent scope ambiguities, avoid this practice.


text:
Q: Extract content between tag I need to replace all tags in a XML formatted string with a white space. For example, after replacement, <student x = 100>Nick Miles</student> would become  Nick Miles  with two whitespace around Nick Miles.
I have tried str.replaceAll("<ref.*?>", " ") and str.replaceAll(</ref>, " ").
It works for most cases. However, if there is no > following ref, the content in the text would be eliminated. I know is about greedy qualifier, but I just fail to fix it. Could some please propose a possible solution?

A: Why use the greedy quantifier at all? You want exactly the opposite: for the regex to stop matching .* once the first > is encountered. That's what a lazy quantifier is for. Just replace + with ? and you're done.


text:
Q: How to maintain SoftKeyboard AND Refresh Layouts in Android When the device rotates, I have different layouts based on portrait/landscape.  So I can't put this line in manifest:
android:configChanges="orientation|screenSize|keyboardHidden"

However, if the user is in a EditText field and the keyboard is out, and text is filled in that field, and then they rotate device, keyboard hides and text is lost (frustrating to user).
Is there a proper way to handle this situation?

A: Why couldn't you use android:configChanges and then override the onConfigurationChanged and then store whatever is in the EditText in a temp variable, call you UI initialization method (take out the findViewById from onCreate and put it in a seperate method), and then set the EditText to the temp variable.
Here is a sample of something I did for buttons
@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
    setContentView(R.layout.main);
    Log.i("configChange", "configChange");
    String tmp = connect.getText().toString();
    boolean onTmp = on.isEnabled();
    boolean offTmp = off.isEnabled();
    boolean connTmp = reconnect.isEnabled();
    InitializeUI();
    connect.setText(tmp);
    on.setEnabled(onTmp);
    off.setEnabled(offTmp);
    reconnect.setEnabled(connTmp);
}


text:
Q: How to get the stage width of a loaded SWF I'm loading an SWF that displays a slideshow of images into another stage. When I use stage.stageHeight or stage.stageWidth inside the loaded SWF I get the width and height of the stage that loaded the SWF instead of the loaded SWF stage.
My question is, how do I get the width and hight of a loaded SWF from within the loaded SWF itself and not the main stage?

A: The only way I see is to read the swf metadata. You can use com.senocular.utils.SWFReader for this:
package
{
import com.senocular.utils.SWFReader;

import flash.display.Sprite;
import flash.events.KeyboardEvent;

[SWF(width="800", height="200", backgroundColor="0x8B8B8B")]
public class astest extends Sprite
{
    public function astest()
    {
        stage.addEventListener(KeyboardEvent.KEY_UP, onKb);
    }

    protected function onKb(event:KeyboardEvent):void
    {
        var swf:SWFReader = new SWFReader(root.loaderInfo.bytes);

        trace("swf.width: "+swf.width);
        trace("swf.height: "+swf.height);
    }

}
}

output:
swf.width: 800
swf.height: 200

Be sure to pass the loaderInfo of the loaded swf file rather than the loader.

A: The loaded swf's LoaderInfo height and width will give the original stage size. That data isn't available until the swf is done loading though, so you should wait for the LoaderInfo instance to dispatch Event.COMPLETE before accessing them or it will throw an error.


text:
Q: How can I shuffle a range of numbers and then split it into subarrays of a certain length? Suppose I have a range 1:N, I want to shuffle the range into a random order and then split the resulting shuffled array into subarrays that are at most 128 elements long. How can I do this?
This question is based by one that appeared on the JuliaLang slack channel.

A: The function shuffle from the Random standard library can be used to shuffle a container into random order:
julia> using Random: shuffle

julia> shuffle(1:10)
10-element Array{Int64,1}:
  6
  9
  3
  2
 10
  1
  8
  7
  5
  4

The function Iterators.partition from Julia's Base can be used to iterate over an iterable in chunks of a fixed length:
julia> using Base.Iterators: partition

julia> partition(1:20, 7)
Base.Iterators.PartitionIterator{UnitRange{Int64}}(1:20, 7)

However, partition returns a lazy iterator by default so if we want to materialize the actual result, we'll need to collect it:
julia> collect(partition(1:20, 7))
3-element Array{UnitRange{Int64},1}:
 1:7
 8:14
 15:20

Putting this all together, we have
julia> using Random: shuffle

julia> using Base.Iterators: partition

julia> shuffle_partition(N; chunk_size=128) = (collect ∘ partition)(shuffle(1:N), chunk_size)
shuffle_partition (generic function with 1 method)

julia> shuffle_partition(503)
4-element Array{SubArray{Int64,1,Array{Int64,1},Tuple{UnitRange{Int64}},true},1}:
 [313, 51, 117, 373, 381, 340, 342, 415, 423, 453  …  201, 178, 167, 242, 2, 76, 146, 439, 363, 448]
 [115, 121, 306, 440, 295, 181, 30, 280, 388, 227  …  362, 39, 317, 171, 55, 214, 261, 251, 96, 9]
 [486, 248, 161, 319, 325, 176, 80, 369, 434, 209  …  442, 350, 273, 419, 130, 305, 192, 482, 265, 234]
 [460, 31, 400, 466, 220, 447, 119, 446, 198, 141  …  226, 438, 74, 152, 203, 303, 378, 231, 458, 194]

julia> length.(ans)
4-element Array{Int64,1}:
 128
 128
 128
 119

This answer is based on the answer found on Slack.

A: using Iterators:
I think the most simple is using randperm (if the values are between 1 and N), so
using Base.Iterators: partition
using Random: randperm

N = 513
k = 128

collect(partition(randperm(N), k))

should work.

A: parts = view.(Ref(shuffle(1:N)),(i:min(i+k-1, N) for i in 1:k:N))

This assumes N is the number of elements and parition size is k. The obtained result is a list of views (hence shuffled 1:N is stored only once in the memory). Note how Ref is used to avoid vectorization over the shuffled list.
Sample test code:
julia> using Random

julia> N, k = 20, 4;

julia> parts = view.(Ref(shuffle(1:N)),(i:min(i+k-1, N) for i in 1:k:N))
5-element Array{SubArray{Int64,1,Array{Int64,1},Tuple{UnitRange{Int64}},true},1}:
 [18, 15, 1, 6]
 [10, 20, 4, 14]
 [17, 9, 19, 16]
 [5, 8, 12, 3]
 [11, 13, 2, 7]


text:
Q: Most Efficient way to enumerate all registry keys I am using following function to enumerate all registry keys for a particular key and subkey in a vector and return it.
But this code seems to run very slow for large Key Values, like for above 200000+ keys, it takes more than 5 minutes to complete.
Just want to know how can I make it more efficient.
vector<string> CRegistryAPI::EnumKeys(HKEY RootKey, string SubKey)
{
    DWORD keyLen = 255;
    int index = 0;
    int ret = 0;
    PFILETIME lastWrite = 0;
    HKEY hKey = 0;
    char keyName[255];
    vector<string> keyList;

    if (RegOpenKeyExA(RootKey, SubKey.c_str(), 0, KEY_ENUMERATE_SUB_KEYS,&hKey) != ERROR_SUCCESS)
        return keyList;
    do
    {
        ret = RegEnumKeyExA(hKey, index, keyName, &keyLen, 0, 0, 0, lastWrite);
        if (ret == ERROR_SUCCESS)
        {
            keyList.push_back(keyName);
        }
        index ++;
        keyLen = 255;
    }
    while (ret == ERROR_SUCCESS);

    if (hKey != NULL)
        RegCloseKey(hKey);

    return keyList;
}

Any help is appreciated. Thanks.

A: One optimization you can do is use RegQueryInfoKey() to query information about a given key before then enumerating its contents. For instance, you can preallocate your vector's capacity so it does not have to be reallocated multiple times during the enumeration:
RegQueryInfoKey(hKey, 0, 0, 0, 0, 0, 0, &dwNumValues, 0, 0, 0, 0);
keyList.reserve(keyList.size()+dwNumValues);

Also, your enumeration is not ensuring your buffer is null-terminated when pushing it into the vector. Even if it were, your way of pushing currently requires std::string to calculate the buffer length each time. You should instead use the buffer length that is returned to you:
keyList.push_back(string(keyName, keyLen));


text:
Q: Dynamically created form successfully routes to controller but not posting AJAX data When a new product form is loaded in to the user's screen, everything loads in successfully in regards to HTML,CSS and event broadcasting etc. However when a user clicks 'buy now' on this dynamically added product I get an error in the UserController function that it posts to. It's as if the data isn't even being sent at all.
Here is my event listener on client side where form is added
var productToAdd="
" +
                    "

" +
                    "
" +
                    "
" + newProductData.title.toUpperCase() + "
" +
                    "
PRICE PER UNIT: " +
                    "
" + newProductData.price + "
" +
                    " EXENS
" +
                    "
" +
                    "QUANTITY:
" + newProductData.quantity + "
" +
                    "
" +
                    "SELLER:
" + newProductData.seller + "
" +
                    "
" +
                    "PRICE:
" + newProductData.price * newProductData.quantity + "
" +
                    "
" +
                    "<form class='buy-product-form' action='/UoE/buy-product/" + newProductData.id + "' method='POST'>"  +
                    "<input type='hidden' name='_token' value='" + add_csrf + "'>" +
                    "<button class='pull-right btn btn-primary'>BUY NOW</button>" +
                    "</form>" +
                    "
" +
                    "
";

                $('.content').append(productToAdd);

Here is the AJAX function when the button gets pressed. Note that this works for every product that is loaded in when the page loads
$('form.buy-product-form').on('submit', (function (e) {
                e.preventDefault();
                var product_id = $(this).closest('.product').attr("id");
                var element = $(this).closest('.product');
                $.ajax({
                    url: $(this).attr('action'),
                    type: 'POST',
                    data: {'id': product_id},
                    dataType: 'json',
                    success: function (data) {
                        if(data.valid_funds) {
                            updateSideBarContent(data.player_capital, data.total_price, data.player_utility,
                                data.marginal_utility, data.purchases);
                        }else {
                            window.alert("You do not have enough funds!");
                        }
                    },
                    error: function () {
                            window.alert("Error, product may no longer exist. Transaction cancelled!");
                            $(element).css('background-color', 'red');
                            $(element).fadeout("100", removeElement(element));
                    }
                });
            }));

I get a user controller error

ErrorException in UserController.php line 279:
Trying to get property 'quantity_available' of non-object

Here is my user controller code
public function buyProduct(Request $request){
        $product_id = $request->id;
        $player = Player::where('user_id', Auth::user()->id)->first();
        $product = Product::where('id', $product_id)->first();

        $totalPrice = $product->quantity_available * $product->price;
}


text:
Q: Show div after scrolled back to the top I want to show a Top-Bar, when the user scrolled back to top of the site.
So e.g. the user scrolls down for a minimum of a 300-400px and then when he scrolls back up again to maybe around 100px (left to the top of the site) the bar should toggle / show up.
Thanks for your help! :)

A: You can add an event listener to document to check when a user scrolls down the page. Once they hit a preset breakpoint, you can remove a hidden class from your navbar element, like so:
var breakpoint = 400;
var navbar = $('.nav-bar');
$(document).scroll(function(){
    if($(this).scrollTop() >= breakpoint) {
        navbar.removeClass('hidden', 500);
    }
});

If your navbar is fixed, you can also check a boolean variable to see if the user has scrolled past the breakpoint, and then set it to true. If they scroll up past the breakpoint, you can then show the navbar, like so:
var breakpoint = 400;
var scrolledPastBreakpoint = false;
var navbar = $('.nav-bar');
$(document).scroll(function(){
    if($(this).scrollTop() >= breakpoint) {
        scrolledPastBreakpoint = true;
    };
    if($(this).scrollTop() < breakpoint && scrolledPastBreakpoint) {
        navbar.removeClass('hidden', 500);
    };
});


text:
Q: Project Euler #5 php doubt! problem euler #5
i found the solution but i don't know why this first code is faster (i put 14 in order to try to make more clear the code) the only difference is that i eliminate the for i wrote for a huge if
if($num%14==0 && $num%13==0 &&$num%12==0 &&$num%11==0 &&$num%10==0 && $num%9==0 && $num%8==0 && $num%7==0 && $num%6==0 && $num%5==0 && $num%4==0 && $num%3==0 && $num%2==0 && $num%1==0){
    $notFound=0;
}

why is this second code hugely more slow than the first one? With the for it suppose to be faster. is the same in another languages???
$notFound=0;
for ( $i=14; $i>=2 && notFound==0; $i--){
    if($num%$i!=0){
        $notFound=1;
    }
}

A: for ( $i=14; $i>=2 && notFound==0; $i--){
should be
for ( $i=14; $i>=2 && $notFound==0; $i--){

A: I would go from the smallest to the largest number. Because if a number is divisible by 14 it is also divisible by 2.
$notFound = 0;
for ($i=2; $i<=14; $i++) {
    if ($num % $i !== 0) {
        $notFound = 1;
        break;
    }
}

By doing this you can exclude the numbers as early as possible.

A: I think this is due to the interpreter overhead with PHP (with it having to parse and execute the for loop).

A: The second code sample is simply performing more operations than the first, so I'd expect it to be slower.  In this situation, you'd find that whilst offering poorer performance, a for loop offers significantly better readability and maintainability.


text:
Q: How to set "columnWeights" and "rowWeights" for a GridBagLayout in NetBeans? Apologies if I'm missing something silly... but I'm experimenting with NetBean's WYSIWYG Swing GUI builder, and am having some issues with GridBagLayout.
When writing a Swing application from scratch, I'll typically establish the column and row weights in one fell swoop at the time I first declare the layout.  Something like this:
final JPanel myContainer = new JPanel();
GridBagLayout gbl = new GridBagLayout();
gbl.columnWeights = new double[]{0.0f, 0.0f, 1.0f};
gbl.rowWeights = new double[]{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
myContainer.setLayout(gbl);

However, when using the NetBeans WYSIWYG builder, I haven't found a clean way to access my GridBayLayout's "columnWeights" and "rowWeights" member variables.  How do developers go about doing this with the NetBeans builder?

A: Have a look at NetBeans 7, they've just overhauled the GridBagLayout Designer.

A: Wow, not a lot of NetBeans-love here on StackOverflow, compared to the "Eclipse" tag!  At any rate, after spending a full day crawling through various discussion boards and talking with more experienced users... it's apparent that NetBeans' WYSIWYG Swing builder simply doesn't expose these two GridBagLayout attributes.  Moreover, the GridBagLayout object is entirely encapsulated within an automatically-generated code block, so any custom code added there will be overwritten.
The closest thing to an "answer" is that rather than applying weight values to all columns or rows... you can instead set a column or row's weight by setting those values on any random component within each column or row.
In the case of my code snippet above... I had a bunch of small components on the left-hand side of the panel, and one really big component on the right that I wanted to fill all that space.  Just setting "weightx" and "weighty" to "1.0" for that component, while keeping it at "0.0" for all the other components, achieved the same result.


text:
Q: Akka FSM vs Storm for media content rendering application I have actor system with data flow route depending on passed data.

Now I want to extract common pieces of code from actors and introduce states.
Like if I want to build video with audio - then either on "ffmpeg" state  I have to wait for both messages from "PhantomJS" and "Audio", and on Amazon S3 -"PhantomJS" and "FFMPEG" arrived. But for other data sets (just video or just audio) it can simply pass through. States may be governed by several actors.
In the very past I worked with OSWorkflow project, which seems to be dead now. I looked at Akka FSM and Twitter Storm, both seem to solve my problem, but perhaps I need some opinions.

A: Not sure what you are actually asking for but to me ..
In a storm like environment these sources like Video, Preview, Audio could act as a Spout subscribed to a message queue like Kafka or kestrel. PhantomJS on the other hand could play the role of a Bolt subscribed to different spouts (Video, Preview). Same goes with the other components (ffmpeg, S3).

I have to wait for both messages from "PhantomJS" and "Audio", and on
  Amazon S3 -"PhantomJS" and "FFMPEG" arrived.

Is this a kind of stream joining you are looking for ? Check out this doc that says

A streaming join combines two or more data streams together based on some common field. Whereas a normal database join has finite input and clear semantics for a join, a streaming join has infinite input and unclear semantics for what a join should be.

Storm trident also provides a very efficient ways of merging . Its as simple as topology.merge(stream1, stream2, stream3);
You could probably look futher on this, hope this helps


text:
Q: What does the number following fieldWeight mean in Solr debug explain? When I read the debug explain in Solr, there is one number following "fieldWeight in", like:
<str name="2531072">
3.1245635 = (MATCH) weight(

title:epic in 111
) [DefaultSimilarity], result of:
      3.1245635 =

fieldWeight in 111
, product of:
        1.0 = tf(freq=1.0), with freq of:
          1.0 = termFreq=1.0
        6.249127 = idf(docFreq=4, maxDocs=952)
        0.5 = fieldNorm

(doc=111)
</str>

I wonder what that bold number means, how does solr get that number?
I can understand freq, docFeq, maxDoc termFreq, but only confused by this number.

A: This number is the internal id of the document and doesn't affect the score. It's only a debugging info. The mailing list of Lucene gives this information.


text:
Q: Unable to add dialog when press my own softkeyboard key I get the following android exception when I try to open a dialog. when i am press my own SoftKeyboard key how can I fix this problem?
BadTokenException: Unable to add window -- token null is not for an application
com.example.android.softkeyboard.SoftKeyboard.diqalog(SoftKeyboard.java:759)
com.example.android.softkeyboard.SoftKeyboard.onKey(SoftKeyboard.java:526)
android.inputmethodservice.KeyboardView.onModifiedTouchEvent(KeyboardView.java:1252)

A: First of all, you cannot present a dialog from a remote service, you can only do so from within a running Activity, that's why you're getting a BadTokenException. But there are solutions to this problem:
1) Present an Activity with Theme.Dialog theme:
<activity
      android:name="com.srgtuszy.activity"
      android:theme="@android:style/Theme.Dialog"
      />

And start the activity as a new task:
Intent intent = new Intent(context, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

This way, you'll get an activity which will look just like a dialog.
2) Present an empty and transparent Activity and show an AlertDialog from within the activity
Declare and start the activity in manifest just as before, but use a transparent theme:
  <style name="Theme.Transparent" parent="android:Theme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
  </style>

In the activity, override the onCreate() method and don's call setContentView() and present the AlertDialog:
@Override
protected void onCreate(Bundle savedInstanceState)
{
     super.onCreate(savedInstanceState);
     Context context = this;
     AlertDialog.Builder dialog = new AlertDialog.Builder(context);
     dialog.setTitle("Hello!");
     dialog.show();
}

This is a more hacky approach, but in this way you can show a dialog to the user without dismissing the input method, you can use to to present edit options for instance.
If you just want to notify the user about a certain event, consider using Notifications, they won't distract the user and pollute the UI.


text:
Q: Is there a reason to have different files or entities with same name in FPGA project? In FPGA projects, the files are usually named after the entity they contain. I am trying to figure out these things:

*

*Is it a good practice to have multiple entities in same file?

*What if entity and architecture are to be kept in different files? What should the files be named in that case?

*Can there be multiple files or entities that have same name where the ports of the entity can be different? Is this acceptable for simulation and synthesis purpose?

A:
Is it a good practice to have multiple entities in same file?

Generally not, unless they're very closely related and will never need to be used separately. Very rare IME.

What if entity and architecture are to be kept in different files? What should the files be named in that case?

I have done some projects like that. It becomes useful if some of the code is being generated by a higher-level tool. I simply called the entity file module.vhd and the architecture file module_a.vhd.

Can there be multiple files or entities that have same name where the ports of the entity can be different? Is this acceptable for simulation and synthesis purpose?

An entity is pretty much defined by its interface, so giving entities with two different interfaces the same name can only be confusing.
It's more common to have a common entity, but two or more architectures for simulation/synthesis.


text:
Q: Влияют ли sleep() или wait() в момент вызова, на флаг isInterrupted() или нет? Если я приостанавливаю поток при помощи методов sleep() или wait(), флаг isInterrupted() в этот момент меняется или нет?

A: Флаг не меняется, но если в момент sleep или wait вызвать метод interrupt(), то ожидание прервется и будет выброшено исключение InterruptedException.


text:
Q: Exception in thread "main" java.lang.NullPointerException. While OneToOne association in Hibernet 21:20:26,958  INFO Version:15 - Hibernate Annotations 3.2.0.GA
21:20:26,976  INFO Environment:500 - Hibernate 3.2.1
21:20:26,981  INFO Environment:533 - hibernate.properties not found
21:20:26,983  INFO Environment:667 - Bytecode provider name : cglib
21:20:26,987  INFO Environment:584 - using JDK 1.4 java.sql.Timestamp handling
21:20:27,065  INFO Configuration:1423 - configuring from resource: hibernate.cfg.xml
21:20:27,066  INFO Configuration:1400 - Configuration resource: hibernate.cfg.xml
21:20:27,229  INFO Configuration:1538 - Configured SessionFactory: null
21:20:27,247  INFO Dialect:151 - Using dialect: org.hibernate.dialect.MySQLDialect
21:20:27,318  INFO AnnotationBinder:387 - Binding entity from annotated class: com.project1.model.CompanyDetails
21:20:27,343  INFO EntityBinder:340 - Bind entity com.project1.model.CompanyDetails on table TAB_COMPANY_DETAILS
21:20:27,413  INFO AnnotationBinder:387 - Binding entity from annotated class: com.project1.model.CompanyCategory
21:20:27,416  INFO EntityBinder:340 - Bind entity com.project1.model.CompanyCategory on table TAB_COMPANY_CATEGORY
21:20:27,419  INFO AnnotationBinder:387 - Binding entity from annotated class: com.project1.model.CompanySector
21:20:27,420  INFO EntityBinder:340 - Bind entity com.project1.model.CompanySector on table TAB_COMPANY_SECTOR
21:20:27,426  INFO AnnotationBinder:387 - Binding entity from annotated class: com.project1.model.CompanyType
21:20:27,427  INFO EntityBinder:340 - Bind entity com.project1.model.CompanyType on table TAB_COMPANY_TYPE
21:20:27,430  INFO AnnotationBinder:387 - Binding entity from annotated class: com.project1.model.Country
21:20:27,430  INFO EntityBinder:340 - Bind entity com.project1.model.Country on table TAB_COUNTRY
Exception in thread "main" java.lang.NullPointerException
    at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:135)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1127)
    at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:296)
    at org.hibernate.cfg.Configuration.generateDropSchemaScript(Configuration.java:756)
    at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:93)
    at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:61)
    at com.project1.model.TestCompanyDetails.main(TestCompanyDetails.java:32)


text:
Q: Codeigniter session error in Redis using PHP 7.0 I am using CI version 3.0.3, PHP version 7.0, Redis and MariaDB. When I store session data in the Database, there are no errors. But if I switch to Redis, I get an error every time session tries to regenerate via session_regenerate_id, in my case every 300 sec. But if I refresh the page again, Redis get updated and page loads without errors.

A PHP Error was encountered
Severity: 4096
Message: session_regenerate_id(): Failed to create(read) session ID: user
  (path: tcp://localhost:6379?auth=xxxx)
Filename: Session/Session.php
Line Number: 625

A: This is a php / memcached bug related.
Work around:
class MemcachedSession extends SessionHandler { public function read($session_id) { return (string)parent::read($session_id); } }

$sess = new MemcachedSession(); session_set_save_handler($sess, true);

session_start(); $_SESSION['value'] = session_id(); session_regenerate_id(); ?>

A: Please refer https://github.com/bcit-ci/CodeIgniter/commit/79b8a086187f199bb708bd56477850fbf1dd9e91 for the fix on CI 3.0.3
CI 3.0.4 will ship with the update for PHP 7 out of the box.
Thanks to https://github.com/narfbg


text:
Q: Regular Expression: Matches some characters or no character I expected a string to be either "abc", "adc" or "ac". How to say that in regular expression?

A: You could use the | (OR) operator like so:
abc|adc|ac

It is equivalent to saying Select abc or adc or ac
You can use tools like RegExr or Regex101 to test your RegEx
Live Demo on Regex101

There is also a clever to do it, that is shorter. Since all 3 strings start with an a, the first part of the RegEx will be a. They all end in a c, so the last part will be a c.
Now the middle letter is either a b or d. You could use (b|d), or you can use the shorter [bd] (it means the same thing). You can use the ? to state that the middle letter is optional.
So your full RegEx will be:
a[bd]?c

Live Demo on Regex101

A: You can do the simple way:
abc|adc|ac

or the more 'advanced' way:
a[bd]?c

Both should Work.


text:
Q: How can I exempt images from Rails cache-busting? I've implemented this solution to help prevent browser page caching, based on the question How to prevent browser page caching in Rails:
def set_cache_buster
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
end

While this certainly work, it feels a bit like killing an ant with a sledgehammer; everything is prevent from caching, including images (e.g., a hamburger icon, or other small images like that). When navigating from page to page, this results in unsightly flashes of empty content while these images are reloaded.
Is there a way that I can prevent general caching, but exempt certain assets?

A: Sorry for miss on tags, but as i see nginx can be a perfect answer to it - just serve static content (images/css/etc) with nginx and pass all other requests to backend (ruby)


text:
Q: Definition A.3.1.5 of Higher Topos Theory I am now reading the book Higher Topos Theory. In A.3.1.5, it gives the definition
of a $\mathbf{S}$-enriched model category, where $\mathbf{S}$ is a monoidal model category. But in the book model structures are introduced only on $\mathsf{Set}$-enriched categories.

So, what does a model structure on a $\mathbf{S}$-enriched category mean?

Is it supposed to be that $\mathbf{S}$ obtains a forgetful functor to $\mathsf{Set}$, and the model structure is defined on the category with respect to the $\mathsf{Set}$ enrichment, or is it something else?

A: Your guess is correct, indeed. In general, given any monoidal category $(\mathbf V, \otimes, 1)$, and any $\mathbf V$-enriched category $\mathbf C$, one can always consider the underlying category $\mathbf C_0$ as the ($\mathbf{Set}$-)category having as objects the same objects as $\mathbf C$, and as hom-sets
$$
\mathbf C_0(x,y):= \mathbf V(1,\mathbf{Hom}_{\mathbf C}(x,y))
$$
You can easily work out how to define composition, after checking that $\mathbf V(1,-)$ is a lax monoidal functor, as pointed out by Denis in the comments.
Now, if $\mathbf S$ is a monoidal model category, and $\mathbf A$ is a $\mathbf S$-enriched category, "equipping $\mathbf A$ with a model structure" just means "equipping $\mathbf A_0$ with a model structure", whereas to talk about a $\mathbf S$-enriched model category one requires the two extra conditions spelled out in HTT A.3.1.5.


text:
Q: Como puedo ordenar la tabla donde se muestran los post de forma numérica? Tengo una tabla de custom post type que muestra unos campos personalizados y me gustaría poder organizar de mayor a menor la tabla cuando pincho en el nombre del campo, tal y como hace wordpress por defecto con la fecha de creación del post. Lo que tengo son 2 campos numéricos. Y lo cierto es que me reoriganiza, pero no lo hace bien. Y en la url parece indicarse bien.
¿Cual puede ser el problema?
function sortable_channel_columns_list( $columns ){

    return wp_parse_args( array(
        'channel_views'             => '_numb_views_field',
        'channel_spectators'  => '_numb_spectators_field'
    ), $columns );
}
add_filter('manage_edit-channel_sortable_columns', 'sortable_channel_columns_list');

He tomado como ejemplo a seguir:
https://rudrastyh.com/wordpress/sortable-date-user-registered-column.html

A: //Hacemos que sea organizable los siguientes campos del listado al hacer click sobre los nombres de los campos
function sortable_channel_columns_list( $columns ){
    $arrParams = array(
        'channel_views'             => '_numb_views_field',
        'channel_spectators'    => '_numb_spectators_field'
    );

    return wp_parse_args( $arrParams, $columns );
}
add_filter('manage_edit-channel_sortable_columns', 'sortable_channel_columns_list');

//Interceptamos la query e indicamos por que campos queremos que ordene
function audience_orderby_meta( $query ) {
    if( ! is_admin() )
        return;

    $orderby = $query->get( 'orderby' );

    if ( $query->is_main_query() && ( $orderby = $query->get( 'orderby' ) ) ){
        switch( $orderby ) {
      case '_numb_views_field':
                $query->set('meta_key','_numb_views_field');
                $query->set('orderby','meta_value_num');
      break;
            case '_numb_spectators_field':
                $query->set('meta_key','_numb_spectators_field');
                $query->set('orderby','meta_value_num'); // or meta_value for strings
            break;
        }
    }
}
add_action( 'pre_get_posts', 'audience_orderby_meta', 1 );


text:
Q: work with a variable which content are a form elements in jquery I have a form seems like this:
<form id="form1">

       aaa: <input id="aaa" name="aaa" type="text" />
       bbb: <input id="bbb" name="aaa" type="text" />
       ccc: <input id="ccc" name="aaa" type="text" />

       ddd: <input id="ddd" name="aaa" type="text" />

</form>

So, in jquery I took the 'form1' element and put it into a variable and passed it into a function parameter:
$.function({
   var temp = $("#form1");
   foo(temp);
});

And then, the function foo is inside other script and I need find the id 'ddd', for example. How can I do it?
foo = function(dataform)
{
   dataform.$("#ddd").val() ?????
};

thanks a lot.

A: have you been trying element.find(); or element.children();
sample:
foo = function(dataform, inside)
{
   var element_you_want = dataform.children(inside);
};

foo($("#form1"), "#ddd");

A: Firstly, $.function is not part of the jQuery API and will be undefined. I suspect you want to use the ready event which is typically done like this:
$(document).ready(function ({
    var temp = $("#form1");
    foo(temp);
});

Secondly, $.$ is also not part of the jQuery API and so dataform.$("#ddd") will be also undefined. Since you're trying to find a descendant element (and not a direct child element), I would recommend the find method:
foo = function(dataform) {
   dataform.find("#ddd").val() //?????
};

Also, as an aside, in the above code you are not doing anything with the value of #ddd so there won't be any discernible actions visible on the page when it successfully executes.
Finally, assuming your markup is valid and each id attribute is unique, using .find to find an element by id is less efficient than simply searching by id (i.e., $('#ddd').val()). Mind you, this obviously defeats the purpose of passing $("#form1") as a function parameter but it's more efficient (in terms of querying the DOM) and it makes me wonder what you are trying to accomplish. If you can update your question with the overall goal, we may be able to better assist you.

A: Working jsFiddle Demo
There is no need to define many fynctions. Add a button to your page:
<input type="button" id="check" value="Check Values" />

And attach an event (for example click) to it:
$('#check').on('click', function () {
    // do stuff
});

Now, you can get the other elements and check their value.
Also you need to wait for document ready (to ensure your elements are loaded in browser):
$(function () {
    $('#check').on('click', function () {
        var ddd = $('#ddd').val();

        alert(ddd);
    });
});


text:
Q: Swipe to delete UITableViewCell very difficult to trigger So I have a table view and I'd like the user to be able to swipe left to reveal a delete button, identically to how it works in the mail app. My issue is not that I can't get this to work - it does, I can swipe the row left, it reveals a delete button, and the user can click it to delete the cell (I do this by implementing editingStyleForRowAtIndexPath). My issue is that the swipe that is required is extremely insensitive. You have to swipe very fast and perfectly horizontally. It is not nearly as smooth as the swiping in mail. Is this just the way it is or am I overlooking something?
I thought maybe the views in the cell were blocking the swipe gesture somehow, but I went into the xib and set everything to hidden and it still is extremely difficult to swipe. The other thing I tried was to add my own swipe gesture recognizer to trigger the delete show. I tried adding it to the cell (that didn't work), to the table view (nope), and I also tried adding a clear colored UIView as a frontmost subview and putting it on that, but still no. Any ideas?
EDIT:
I just created a new project to test the responsiveness of the editing style delete feature - very very simple table view just to see how it works. It is MUCH easier to swipe than the cell in my actual project. There aren't many differences between my test project and my actual one: actual loads a xib on cellForRowAtIndexPath while in test project it uses default styled cell, actual project has imageviews and uilabels within cell while test project is just a uilabel... what could be making it so unresponsive?

A: It turns out there was a competing gesture recognizer hidden in a superclass I was completely oblivious to. Once I realized that, it was easily solved by disabling the other recognizer for that screen (although I believe there would be a more correct way of doing it by setting gesture recognizer priorities). Anyway, if you are having similar issues - really strange/ unexpected behavior from a UIGestureRecognizer - I would ensure there is no other gesture recognizer interfering.

A: You could try to "roll your own". In the built-in UITableView, we are probably responding to a leftward swipe gesture recognizer (the gesture for which, as you say, must be quick and very horizontal in order to recognized). The way this works in Mail, on the other hand, is that the cell contents actually contains a UIScrollView, capable of being scrolled horizontally only - and that is what you are doing when you slide left, just dragging as you would with any scroll view. (That's why you can peek at the Delete button and then drag the message back to the right.)


text:
Q: Would codes after try and except be executed? Let's say a code like this
try:
    objectToBeUsed = func1()
except:
    objectToBeUsed = false

nextValue = func2(objectToBeUsed)

Would the last line be executed, whether exception is caught or not? Do I need to use finally here?

A: Yes, it will be executed.
However, that's probably exactly why it's a bad idea to use  a bare except with no specificed exception classes to catch.  It's rare that you want to keep blithely going along in the case of any exception.  The exception could be a KeyboardInterrupt, for instance.
You catch the specific exceptions that indicate situations where you actually do want to set objectToBeUsed = False, and let other exceptions propagate up if you can't handle them.

A: finally is usually used to execute clean up code, whether an exception has been raised or not. If I understand correctly, calling func2() is part of your normal program flow and is not considered clean up. So you should not use finally in this case.
Read more about python exception handling here: https://docs.python.org/2/tutorial/errors.html


text:
Q: calling method from alertdialog onclick event within ui thread I am having an issue calling a method within an OnClick event of an AlertDialog that's within a RunOnUiThread.
The logic below is that ProgressDialog displays while the applyUpdate() method is executing. The method returns 0 if the the download has failed or is still in progress. The user is given the choice to restart or continue the download.
The issue is that when Restart is selected the AlertDialog remains on the screen (with the button clicked).
Is the doDownload() starting before the dialog dismisses, is it a threading issue, or something else?
public void doApply(View view){
    progressDialog = ProgressDialog.show(UpdateForm.this, "", "Applying update...");

    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            try{
                applyUpdate = nnEngine.applyUpdate();
            } catch (Exception e) {
                // Handle exception
            }

            // Check update result.
            progressDialog.dismiss();
            switch (applyUpdate) {
// Other cases removed.....
                case 0:
                    // Download in progress or failed.
                    AlertDialog.Builder inprogDlg = new AlertDialog.Builder(UpdateForm.this);
                    inprogDlg.setTitle("Download in progress or failed.");

                    inprogDlg.setPositiveButton("Continue download", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        // Wrong button may be displayed.
                        notifyUser(null, checkDownloadButton);
                    }
                });

                inprogDlg.setNegativeButton("Restart download", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        doDownload(getWindow().getDecorView().findViewById(android.R.id.content));
                    }
                });

                inprogDlg.create().show();
                break;
            }
        }
    });
}


text:
Q: using exceptions and writing data to files in python 3 here what I need to do:
Your program must raise an exception if the user chooses any item not on the menu
presented. Along with raising an exception, write the code to handle this exception.
Ask the user for a value to convert.Your program must raise and exception, and handle the exception, if an input
errors occurs
Perform the conversion and write the original value, the original unit, the
converted value, and the converted unit to an output file named
conversions.txt.
Repeat steps a and b 10 times (in a loop).
heres my code:
#imports

import os

# global variables
mile_choice = 1
gallon_choice = 2
pound_choice = 3
inch_choice = 4
fah_choice = 5
quit_choice = 6

mainfile = open('conversions.txt', 'w')

# intro and global name variable

name = input ('what is your name? ')
print()
print('hello',name,', today we will be doing\
some standard to metric conversions.')

#define main function
def main():

    choice = 0

    while choice != quit_choice:

             display_menu()

             print()
             choice = int(input('Please enter a number 1 - 6 : '))\

             if choice == mile_choice:
                    print()
                    miletokm()

             elif choice == gallon_choice:
                    print()
                    galtolit()

             elif choice == pound_choice:
                    print()
                    poundstokg()

             elif choice == inch_choice:
                    print()
                    inchtocm()

             elif choice == fah_choice:
                    print()
                    fahtocel()

             elif choice == quit_choice:
                    print()
                    print('Exiting the program.')

#define functions
def display_menu():
    print()
    print('          Menu          ')
    print()
    print('Press 1 for Miles to Kilometers')
    print()
    print('Press 2 for Gallons to Liters')
    print()
    print('Press 3 for Pounds to Kilograms')
    print()
    print('Press 4 for Inches to Centimeters')
    print()
    print('Press 5 for Fahrenhiet to Celisus')
    print()
    print('To exit please enter 6 ')

def miletokm():
     invalid_attempts = 0

 #while loop for invalid input limited to 3

    while invalid_attempts < 3 and invalid_attempts >= 0:
        print()
        mile = float(input('how many miles would you\
 like to convert to kilometers? '))
        mainfile.write(str(mile) + '\n')

 # if statement to determine weather to proceed with conversation
 # valid input = conversion
 # invalid input =  return with + 1 to invalid_attempt count

    if mile >= 0 :

        print()
        mile_conv = mile * 1.6
        print('that would be:', format(mile_conv, '.2f'), 'kilometers.')
        print()
        mainfile.write(str(mile_conv) + '\n')
        return mile

    else:

        print()
        print ('invalid input')
        print()
        invalid_attempts += 1

I left out the other conversion def. to help keep it shorter.
I am having problems with the exception part first and for most.
I have tried various things but I cant figure out how to write out the code correctly
I know how to define a value error for a number entered outside of the menu range
I don't understand how to write the units along with the data entered to the file.
The way I Have it now, it is not writing any information to mainfile.
I also feel like my code is very sloppy written. I have no idea because my professor refuses to help me.
I know that's alot to run through but i really have no where else to turn. I don't understand how I should structure the code and how to effectively accomplish what I need done.
what I have read covers the basis of this but I have no examples to look at other than very simple simple examples that deal with strictly one thing.

A: You could try something like... (from http://docs.python.org/2/tutorial/errors.html#exceptions)
>>> while True:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break
...     except ValueError:
...         print "Oops!  That was no valid number.  Try again..."
...

A: You're on the right track. First thing that you need to do is to handle better the value for choice that the user gives you. Check what happens if they give you 9 or 'foo'.
Next, you should do the same for every value received in your functions that convert units. For that, you use try/except as @bitfish showed you (except that you use input instead of raw_input).

A: *

*close the files you open (mainfile.close())

*doing this elif choice == quit_choice: inside of this while choice != quit_choice makes no sense

*use '\n' to skip lines (print('\n') is the same than print() two times

there are many ways to solve such a problem, white the experience you'll acquire you'll find more elegant ones, but this one is already ok.


text:
Q: How do I display contents of a file where PATH environment changes are made? Say I change the $PATH environment variable. If I'm asked to display the contents of the file where this change happened, how would I do this?

A: This isn't possible. There isn't any way to find out where environment variable changes came from, after the fact.
You could insert some echo commands which would display the name of the file as changes are being made, but the changes are not tracked, with respect to which file made a particular change.


text:
Q: Differential algebraicity and transcendence degree The question that was left unanswered during a lecture was

For a differential field $K$ and $x$ an element of a differential field extension of $K$, is it necessarily the case that for any element $x$ that is
differentially algebraic over $K$, $K\langle x\rangle $ has finite transcendence degree over $K?$ Is the converse true as well?

Definitions I'm working with:
$x$ is differentially algebraic over $K$ if $P(x) = 0$ for some $P \in K\{X\}^{\neq}$
If $S$ is a subset of $K$ which is algebraically independent over $k$, and if the cardinality of $S$ is greatest among all such subsets, then we call this cardinality the transcendence degree of $K$ over $k$.
And $K\langle y \rangle$ is just $K(x, x', x'')$
My intuition is that the answer is yes to both, but I don't see a rigorous way to prove it. Any help would be appreciated.


text:
Q: How do I connect four 2D grid points with a smooth curve in C# and give the x and y location back at a certain time? So I'm trying to connect four grid points with x and y values together with a smooth curve. Given a parameter 'time' I want to receive the x and y locations of the point on the curve at that time.
I've tried multiple options like quadratic bezier curves and such but can't seem to figure it out.
There's no need to visualize it in Unity, wpf or any other way.  I don't need a draw method or anything like that. I simply need the position value of the point in the curve.
This is the sort of curve I am looking for:

Thank you in advance for helping me!

A: Simple approach is using Catmull-Rom splines.
Example of implementation
Some more variants
Note that parameter t varies from 0 to 1 at every point-point interval, so you can map your "position" onto corresponding interval. For example, if position varies from 0 to 1, mutliply it by 3. Integer part of result is interval number, fractional part - parameter t at this interval.


text:
Q: Indexing a list of dictionaries for a relating value I have a 4 dictionaries which have been defined into a list
dict1 = {'A':'B'}
dict2 = {'C':'D'}
dict3 = {'E':'F'}
dict4 = {'G':'H'}

list = [dict1, dict2, dict3, dict4]

value = 'D'

print (the relating value to D)

using the list of dictionaries I would like to index it for the relating value of D (which is 'C').
is this possible?
note: the list doesn't have to be used, the program just needs to find the relating value of C by going through the 4 dictionaries in one way or another.
Thanks!

A: You have a list of dictionaries. A straightforward way would be to loop over the list, and search for desired value using -

dict.iteritems()

which iterates over the dictionary and returns the 'key':'value' pair as a tuple (key,value). So all thats left to do is search for a desired value and return the associated key. Here is a quick code I tried. Also this should work for dictionaries with any number of key value pairs (I hope).
dict1 = {'A':'B'}
dict2 = {'C':'D'}
dict3 = {'E':'F'}
dict4 = {'G':'H'}

list = [dict1, dict2, dict3, dict4]

def find_in_dict(dictx,search_parameter):
    for x,y in dictx.iteritems():
        if y == search_parameter:
            return x

for i in range(list.__len__()):
    my_key = find_in_dict(list[i], "D")
    print my_key or "No key found"

On a different note, such a usage of dictionaries is little awkward for me, as it defeats the purpose of having a KEY as an index for an associated VALUE. But anyway, its just my opinion and I am not aware of your use case. Hope it helps.


text:
Q: External hard drive disappears even during file operation I have a Western Digital Green 2TB SATA disk in an ICY BOX IB-368STU3-B box connected via USB 3.0.
At a certain moment, the disk is not available anymore (and the blue LED on the back of the box shut down).
See dmesg log:
[418367.616545] usb 7-2: new SuperSpeed USB device number 2 using xhci_hcd
[418367.633699] usb 7-2: New USB device found, idVendor=05e3, idProduct=0731
[418367.633709] usb 7-2: New USB device strings: Mfr=3, Product=4, SerialNumber=5
[418367.633715] usb 7-2: Product: USB 3.0 Mass Storage Device
[418367.633720] usb 7-2: Manufacturer: Raid Sonic
[418367.633725] usb 7-2: SerialNumber: 0000000000000806
[418372.632296] usb 7-2: Set SEL for device-initiated U1 failed.
[418376.219833] usb-storage 7-2:1.0: USB Mass Storage device detected
[418376.220738] scsi2 : usb-storage 7-2:1.0
[418376.222967] usbcore: registered new interface driver usb-storage
[418377.221322] scsi 2:0:0:0: Direct-Access     WDC WD20 EZRX-00D8PB0     80.0 PQ: 0 ANSI: 0
[418377.222015] sd 2:0:0:0: Attached scsi generic sg2 type 0
[418377.222420] sd 2:0:0:0: [sdc] 3907029164 512-byte logical blocks: (2.00 TB/1.81 TiB)
[418377.223166] sd 2:0:0:0: [sdc] Write Protect is off
[418377.223175] sd 2:0:0:0: [sdc] Mode Sense: 03 00 00 00
[418377.223924] sd 2:0:0:0: [sdc] No Caching mode page found
[418377.223933] sd 2:0:0:0: [sdc] Assuming drive cache: write through
[418377.226889] sd 2:0:0:0: [sdc] No Caching mode page found
[418377.226904] sd 2:0:0:0: [sdc] Assuming drive cache: write through
[418377.255267]  sdc: sdc1
[418377.258061] sd 2:0:0:0: [sdc] No Caching mode page found
[418377.258072] sd 2:0:0:0: [sdc] Assuming drive cache: write through
[418377.258080] sd 2:0:0:0: [sdc] Attached SCSI disk
[418378.570903] EXT4-fs (sdc1): recovery complete
[418378.571188] EXT4-fs (sdc1): mounted filesystem with ordered data mode. Opts: (null)
[427069.908051] xhci_hcd 0000:01:00.0: Timeout while waiting for address device command
[427070.165440] xhci_hcd 0000:01:00.0: Stopped the command ring failed, maybe the host is dead
[427070.165440] xhci_hcd 0000:01:00.0: Abort command ring failed
[427082.535178] xhci_hcd 0000:01:00.0: HC died; cleaning up
[427082.535232] usb 6-1: USB disconnect, device number 2
[427082.536024] [sched_delayed] sched: RT throttling activated
[427082.536122] usb 7-2: USB disconnect, device number 0
[427082.940059] usb 7-2: device not accepting address 2, error -22
[427082.940172] sd 2:0:0:0: Device offlined - not ready after error recovery

I exchanged it with another box (same but a new one), same effect.
I changed the DD in it with a Seagate Green 2TB, same effect.
I tested on 2 USB3 ports, 2 USB2 ports, another laptop, Ubuntu (the distro currently running my laptops), Debian stable (to test another kernel) and Sysrescue, same effect.
The first time, it stopped while I was doing an rsync on it, so it was in activity (I copied 1TB of data on it) and all of a sudden, I received errors Input/Output errors and /dev/sdc1 not existing anymore.
Any idea what it could be?
Thanks for the help!
Best regards,
Raph

A: Well I would have said that it looks like a bad usb controller based on those messages, but if you have tested it in multiple controllers that rules that out.  The other two possibilities are the cable, and the enclosure.  Try another cable, and if you can, remove the drive from the usb enclosure, and connect it directly to a sata port.


text:
Q: Parsing string to date in d3.js I am trying to parse a date string using d3.js. The format is like "2012-11-02T08:32:55-04:00"
You can see the console output below.
Relavent API is here.
D3 parser is stricter, as explains the doc. But, I was expecting '%Y-%m-%dT%H:%M:%SZ' as the format string. Which returns null. Any help appreciated.
Thanks.
format = d3.time.format('%Y-%m-%dT%H:%M:%SZ')
%Y-%m-%dT%H:%M:%SZ
format.parse("2012-11-02T08:32:55-04:00");
null
format.parse("2011-07-01T19:15:28Z");
Fri Jul 01 2011 19:15:28 GMT-0400 (EDT)
format = d3.time.format('%Y-%m-%dT%H:%M:%S%Z')
%Y-%m-%dT%H:%M:%S%Z
format.parse("2011-07-01T19:15:28Z");
null
format.parse("2012-11-02T08:32:55-04:00");
null

A: According to that API:

The following directives are not yet supported for parsing:
  %j - day of the year.
  %U - week number of the year.
  %w - weekday number.
  %W - week number of the year.
%Z - time zone offset, such as "-0700".
  %% - a literal "%" character.

So you may be out of luck unless you remove the -[time_zone] part of the date.

A: This is no longer the case. Time zones were included in version 3.3.x of d3js.
d3js pull request: https://github.com/mbostock/d3/pull/1495


text: Q: Radiation attenuation parameters for beta and gamma rays I know that to describe the attenuation radiation undergoes while passing through a material, we use the areal density (which is basically the penetration depth * density of the material) for beta electrons and then the photon attenuation coefficient for photons. My question is why can't we use areal density for photons as well? Is it because they are very penetrating and thus the penetration depth would be too big? Or maybe because since they have no mass they are just slowed down but do not really "bump" into the material's electrons to lose their energy?


text:
Q: How to automatically logout user from Guacamole Webpage I've been running Apache Guacamole for a few days now and I'm just testing around with it (latest version of server and webclient). A user X logs in and automatically connects to a machine with the RDP connection assigned to him. Now I come along and edit the user, insofar that I remove the connection assigned to him again. Means, the user X has now no more connections assigned to him. Now I kill the existing RDP connection of user X.
My problem:
It doesn't matter what I do. I can disable the login for user X, I can set the password to expired, I can set a new password or anything else. The user simply remains logged into the web client. The problem is that I just can't get the user logged out. Yes, I get the RDP connection capped, but that's it.
Now I would like to try to automate the whole thing via the API. But for that, it would be more "convenient" if I have a single user list that doesn't keep changing. I would like to be able to say via the API "Log out user X and kill his existing connections, change the password to a new password and end". Yes, I can of course set the api-session-timeout value in the guacamole.properties, however this will then apply to all users. If I set the value too low, it will be annoying for the users to have to log in all the time. If I set it too long, the user X can't be used during this time (so I can't assign connections to the user, because the "previous" user could still be logged in and I don't want to give him access to the next assigned connection).
So, my question is simply:
How do I get the user logged out of the web browser. I can of course delete the user and recreate it. That would work, of course. But can't I just say delete the user's auth token? Unfortunately, I also can't find any information about where the created tokens are stored at all. What I could read from the code so far is only that the tokens are temporary. Where they are stored (probably only in memory, because temporary?) I couldn't really find out. Otherwise I would just say "delete the token of the logged in user". But I can't find anything about that.
Does anyone here have any ideas?
Has anyone maybe already automated this, if so, did you delete and recreate the user each time?

*

*Link to the guacamole web client source code: https://github.com/apache/guacamole-client

*Link to the guacamole server source code: https://github.com/apache/guacamole-server
I am grateful for any help.

A: You can send an API request to kill the active connection:
https://github.com/ridvanaltun/guacamole-rest-api-documentation/blob/master/docs/CONNECTIONS.md#kill-connections


text:
Q: Signal Analysis in Octave Dears,
I would like to ask you for help. Since I do not have a signal pkg in Matlab I tried to run the script with Octave. Unfortunately, I am struggling with optimization. Code crashed with the [Horizontal_Peaks_ROI_3, Loc1_ROI_3] = findpeaks(double(line_image_ROI_3(i).ESF), 'MinPeakDistance',8); Do you have any idea, where I did mistake, please?
Here you are my minimal reproducible example:
line_image_ROI_3 = struct('ESF', zeros(0),'LSF',zeros(0), 'Peaks',zeros(1,2), 'Valleys',zeros(1,2));
mass_center_ROI_3 = zeros(1,size(cropped_image_Horizontal_ROI_3,1));
pixel_position_ROI_3 = 1:size(cropped_image_Horizontal_ROI_3,1);
i=1;j=1;
Max_Peaks=zeros(1,12);
for i = 1 :StepWidth:size(cropped_image_Horizontal_ROI_3,1)
    %get the column_ROI_3 of the image
    line_image_ROI_3(i).ESF = cropped_image_Horizontal_ROI_3(:,i)';
    SignalROI3(j,:)=cropped_image_Horizontal_ROI_3(:,i)'
    subplot(4,5,j+3)
    plot(line_image_ROI_3(i).ESF);
    axis tight;
    hold on;
    [Horizontal_Peaks_ROI_3, Loc1_ROI_3] = findpeaks(double(line_image_ROI_3(i).ESF), 'MinPeakDistance',8);
    line_image_ROI_3(j).Peaks=[Loc1_ROI_3', Horizontal_Peaks_ROI_3'];

    plot(Loc1_ROI_3,Horizontal_Peaks_ROI_3,'or');
    Max_Avg_V_ROI_3(j)=mean(Horizontal_Peaks_ROI_3);
    x1_ROI_3=[0 length(line_image_ROI_3(i).ESF)];
    y1_ROI_3=[Max_Avg_V_ROI_3(j) Max_Avg_V_ROI_3(j)];
    plot(x1_ROI_3,y1_ROI_3,'--g'); % Average Max

Thank you in advance.