def test_multiple_elements(self):
        """Test the anysotropic case in multiple element."""
        p = (6, 6)
        is_inner = False
        crazy_mesh = CrazyMesh(2, (8, 5),  ((-1, 1), (-1, 1)), curvature=0.1)

        func_space_2_lobatto = FunctionSpace(crazy_mesh, '2-lobatto', p, is_inner)
        func_space_1_lobatto = FunctionSpace(crazy_mesh, '1-lobatto', p, is_inner)
        func_space_1_lobatto.dof_map.continous_dof = True

        def diffusion_11(x, y): return 4 * np.ones(np.shape(x))

        def diffusion_12(x, y): return 3 * np.ones(np.shape(x))

        def diffusion_22(x, y): return 5 * np.ones(np.shape(x))

        def source(x, y):
            return -36 * np.pi ** 2 * np.sin(2 * np.pi * x) * np.sin(2 * np.pi * y) + 24 * np.pi ** 2 * np.cos(2 * np.pi * x) * np.cos(2 * np.pi * y)

        # mesh function to inject the anisotropic tensor
        mesh_k = MeshFunction(crazy_mesh)
        mesh_k.continous_tensor = [diffusion_11, diffusion_12, diffusion_22]

        # definition of the basis functions
        basis_1 = BasisForm(func_space_1_lobatto)
        basis_1.quad_grid = 'gauss'
        basis_2 = BasisForm(func_space_2_lobatto)
        basis_2.quad_grid = 'gauss'

        # solution form
        phi_2 = Form(func_space_2_lobatto)
        phi_2.basis.quad_grid = 'gauss'

        form_source = Form(func_space_2_lobatto)
        form_source.discretize(source, ('gauss', 30))
        # find inner product
        M_1k = inner(basis_1, basis_1, mesh_k)
        N_2 = inner(d(basis_1), basis_2)
        M_2 = inner(basis_2, basis_2)
        # assemble
        M_1k = assemble(M_1k, func_space_1_lobatto)
        N_2 = assemble(N_2, (func_space_1_lobatto, func_space_2_lobatto))
        M_2 = assemble(M_2, func_space_2_lobatto)

        lhs = sparse.bmat([[M_1k, N_2], [N_2.transpose(), None]]).tocsc()
        rhs_source = (form_source.cochain @ M_2)[:, np.newaxis]
        rhs_zeros = np.zeros(lhs.shape[0] - np.size(rhs_source))[:, np.newaxis]
        rhs = np.vstack((rhs_zeros, rhs_source))

        solution = sparse.linalg.spsolve(lhs, rhs)
        phi_2.cochain = solution[-func_space_2_lobatto.num_dof:]

        # sample the solution
        xi = eta = np.linspace(-1, 1, 200)
        phi_2.reconstruct(xi, eta)
        (x, y), data = phi_2.export_to_plot()
        plt.contourf(x, y, data)
        plt.show()
        print("max value {0} \nmin value {1}" .format(np.max(data), np.min(data)))
        npt.assert_array_almost_equal(self.solution(x, y), data, decimal=2)
Exemplo n.º 2
0
def multiple_element():
    mesh = CrazyMesh(2, (5, 7), ((-1, 1), (-1, 1)), curvature=0.3)
    p = 10, 10
    func_space_vort = FunctionSpace(mesh, '0-ext_gauss', (p[0] - 1, p[1] - 1), is_inner=False)
    func_space_outer_vel = FunctionSpace(
        mesh, '1-total_ext_gauss', (p[0], p[1]), is_inner=False)
    # func_space_outer_vel = FunctionSpace(
    #     mesh, '1-gauss', (p[0], p[1]), is_inner=False)
    func_space_inner_vel = FunctionSpace(mesh, '1-lobatto', p, is_inner=True)
    func_space_inner_vel.dof_map.continous_dof = True
    func_space_source = FunctionSpace(mesh, '2-lobatto', p, is_inner=True)

    basis_vort = BasisForm(func_space_vort)
    basis_vel_in = BasisForm(func_space_inner_vel)
    basis_vel_in.quad_grid = 'lobatto'
    basis_vel_out = BasisForm(func_space_outer_vel)
    basis_vel_out.quad_grid = 'lobatto'
    basis_2 = BasisForm(func_space_source)

    psi = Form(func_space_vort)
    u_in = Form(func_space_inner_vel)
    source = Form(func_space_source)
    source.discretize(ffun)

    M_1 = inner(basis_vel_in, basis_vel_in)
    E_21_in = d(func_space_inner_vel)
    W_02 = basis_2.wedged(basis_vort)
    W_02_E21 = np.transpose(W_02 @ E_21_in)

    M_1 = assemble(M_1, (func_space_inner_vel, func_space_inner_vel))
    print(np.shape(M_1))
    W_02_E21 = assemble(W_02_E21, (func_space_inner_vel, func_space_vort))
    print(np.shape(W_02_E21))
    W_02 = assemble(W_02, (func_space_source, func_space_vort))

    lhs = spr.bmat([[M_1, W_02_E21], [W_02_E21.transpose(), None]])
    print(np.shape(lhs))
    rhs = np.zeros(np.shape(lhs)[0])
    rhs[-func_space_source.num_dof:] = W_02 @ source.cochain

    solution = spr.linalg.spsolve(lhs.tocsc(), rhs)
    u_in.cochain = solution[:func_space_inner_vel.num_dof]
    cochian_psi = np.zeros(func_space_vort.num_dof)
    cochian_psi[:func_space_vort.num_internal_dof] = solution[-func_space_vort.num_internal_dof:]
    psi.cochain = cochian_psi

    xi = eta = np.linspace(-1, 1, 40)
    u_in.reconstruct(xi, eta)
    (x, y), u_x, u_y = u_in.export_to_plot()
    plt.contourf(x, y, u_x)
    plt.colorbar()
    plt.title("u_x inner")
    plt.show()
    psi.reconstruct(xi, eta)
    (x, y), psi_value = psi.export_to_plot()
    plt.contourf(x, y, psi_value)
    plt.title("psi outer"
              )
    plt.colorbar()
    plt.show()
    def test_single_element(self):
        """Test the anysotropic case in a single element."""
        dim = 2
        elements_layout = (1, 1)
        bounds_domain = ((-1, 1), (-1, 1))
        curvature = 0.1

        p = (20, 20)
        is_inner = False

        crazy_mesh = CrazyMesh(dim, elements_layout, bounds_domain, curvature)

        func_space_2_lobatto = FunctionSpace(crazy_mesh, '2-lobatto', p, is_inner)
        func_space_1_lobatto = FunctionSpace(crazy_mesh, '1-lobatto', p, is_inner)

        def diffusion_11(x, y): return 4 * np.ones(np.shape(x))

        def diffusion_12(x, y): return 3 * np.ones(np.shape(x))

        def diffusion_22(x, y): return 5 * np.ones(np.shape(x))

        mesh_k = MeshFunction(crazy_mesh)
        mesh_k.continous_tensor = [diffusion_11, diffusion_12, diffusion_22]

        basis_1 = BasisForm(func_space_1_lobatto)
        basis_1.quad_grid = 'gauss'
        basis_2 = BasisForm(func_space_2_lobatto)
        basis_2.quad_grid = 'gauss'

        phi_2 = Form(func_space_2_lobatto)
        phi_2.basis.quad_grid = 'gauss'

        M_1k = inner(basis_1, basis_1, mesh_k)

        N_2 = inner(basis_2, d(basis_1))

        def source(x, y):
            return -36 * np.pi ** 2 * np.sin(2 * np.pi * x) * np.sin(2 * np.pi * y) + 24 * np.pi ** 2 * np.cos(2 * np.pi * x) * np.cos(2 * np.pi * y)

        form_source = Form(func_space_2_lobatto)
        form_source.discretize(source)

        M_2 = inner(basis_2, basis_2)

        lhs = np.vstack((np.hstack((M_1k[:, :, 0], N_2[:, :, 0])), np.hstack(
            (np.transpose(N_2[:, :, 0]), np.zeros((np.shape(N_2)[1], np.shape(N_2)[1]))))))

        rhs = np.zeros((np.shape(lhs)[0], 1))
        rhs[-np.shape(M_2)[0]:] = form_source.cochain @ M_2

        phi_2.cochain = np.linalg.solve(lhs, rhs)[-phi_2.basis.num_basis:].flatten()
        xi = eta = np.linspace(-1, 1, 200)
        phi_2.reconstruct(xi, eta)
        (x, y), data = phi_2.export_to_plot()
        print("max value {0} \nmin value {1}" .format(np.max(data), np.min(data)))
        npt.assert_array_almost_equal(self.solution(x, y), data, decimal=2)
Exemplo n.º 4
0
def hodge_from_func_space(function_space, extend):
    """Calculate the hodge matrix  from the function space."""
    dual_space = DualSpace(function_space, extend)
    dual_form = Form(dual_space)
    form = Form(function_space)
    wedge_prod = form.basis.wedged(dual_form.basis)
    inner_prod = inner(dual_form.basis, dual_form.basis)
    inverse_inner = inv(np.rollaxis(inner_prod, 2, 0))
    hodge_matrix = np.tensordot(inverse_inner, wedge_prod, axes=((2), (0)))
    hodge_matrix = np.moveaxis(hodge_matrix, 0, -1)
    return hodge_matrix
Exemplo n.º 5
0
def form(request):
    if request.method == 'POST':
        form = Form(request.POST)
        if form.is_valid():
            return render_to_response('form.html', {'m': 'woo hoo'})
    else:
        form = Form()

    return render_to_response('form.html', {
        'form': form,
    })
Exemplo n.º 6
0
    def test_discretize_lobatto(self):
        """Test the discretize method of the 2 - forms."""
        my_mesh = CrazyMesh(2, (2, 2), ((-1, 1), (-1, 1)), curvature=0)
        p_int_0 = 2
        for p in range(3, 8):
            filename = 'discrete_2_form_p' + \
                str(p) + '_p_int' + str(p_int_0) + '.dat'
            directory = os.getcwd() + '/src/tests/test_discrete_2_form/'
            func_space = FunctionSpace(my_mesh, '2-lobatto', p)
            form = Form(func_space)
            form.discretize(paraboloid, ('gauss', p_int_0))
            cochain_ref = np.loadtxt(directory + filename, delimiter=',')
            npt.assert_array_almost_equal(form.cochain_local,
                                          cochain_ref,
                                          decimal=4)
        p = 5
        for p_int in range(2, 6):
            filename = 'discrete_2_form_p' + \
                str(p) + '_p_int' + str(p_int_0) + '.dat'
            directory = os.getcwd() + '/src/tests/test_discrete_2_form/'
            func_space = FunctionSpace(my_mesh, '2-lobatto', p)
            form = Form(func_space)
            form.discretize(paraboloid, ('gauss', p_int_0))
            cochain_ref = np.loadtxt(directory + filename, delimiter=',')
            npt.assert_array_almost_equal(form.cochain_local,
                                          cochain_ref,
                                          decimal=4)

        p = 6
        p_int = 5
        filename_1 = 'discrete_2_form_p' + \
            str(p) + '_p_int' + str(p_int) + '_el_57.dat'
        directory = os.getcwd() + '/src/tests/test_discrete_2_form/'
        mesh_1 = CrazyMesh(2, (5, 7), ((-1, 1), (-1, 1)), curvature=0)
        func_space = FunctionSpace(mesh_1, '2-lobatto', p)
        form = Form(func_space)
        form.discretize(paraboloid, ('gauss', p_int))
        cochain_ref_1 = np.loadtxt(directory + filename_1, delimiter=',')
        npt.assert_array_almost_equal(form.cochain_local, cochain_ref_1)

        mesh_2 = CrazyMesh(2, (5, 7), ((-1, 1), (-1, 1)), curvature=0.2)
        filename_2 = 'discrete_2_form_p' + \
            str(p) + '_p_int' + str(p_int) + '_el_57_cc2.dat'
        directory = os.getcwd() + '/src/tests/test_discrete_2_form/'
        func_space = FunctionSpace(mesh_2, '2-lobatto', p)
        form = Form(func_space)
        form.discretize(paraboloid, ('gauss', p_int))
        cochain_ref_2 = np.loadtxt(directory + filename_2, delimiter=',')
        npt.assert_array_almost_equal(form.cochain_local, cochain_ref_2)
Exemplo n.º 7
0
    def test_project_lobatto(self):
        directory = 'src/tests/test_form_2/'
        x_ref = np.loadtxt(directory + 'x_lobatto_n3-2_p20-20_c3_xieta_30.dat',
                           delimiter=',')
        y_ref = np.loadtxt(directory + 'y_lobatto_n3-2_p20-20_c3_xieta_30.dat',
                           delimiter=',')
        data_ref = np.loadtxt(directory +
                              'data_lobatto_n3-2_p20-20_c3_xieta_30.dat',
                              delimiter=',')

        def ffun(x, y):
            return np.sin(np.pi * x) * np.sin(np.pi * y)

        p = (20, 20)
        n = (3, 2)
        mesh = CrazyMesh(2, n, ((-1, 1), (-1, 1)), 0.3)
        xi = eta = np.linspace(-1, 1, 30)

        func_space = FunctionSpace(mesh, '2-lobatto', p)
        form_2 = Form(func_space)
        form_2.discretize(ffun)
        form_2.reconstruct(xi, eta)
        (x, y), data = form_2.export_to_plot()
        npt.assert_array_almost_equal(x_ref, x)
        npt.assert_array_almost_equal(y_ref, y)
        npt.assert_array_almost_equal(data_ref, data)
Exemplo n.º 8
0
def login():
    fields = []
    fields.append(
        Field(name="email",
              title="Email",
              the_type='email',
              identifier='email',
              placeholder="Email"))
    fields.append(
        Field(name='password',
              title="Password",
              the_type="password",
              identifier='password',
              placeholder='Password'))
    title = "Login "
    form = Form(fields=fields, title=title)
    if request.method == 'GET':
        return render_template('login.html', login_form=form)
    try:
        user = User.get_by_id(request.form['email'])
        if user:
            if user.password == request.form['password']:
                print "pop"

                return logged_in(user)
            else:
                form.error = "User or Password was Incorrect"
                return render_template('login.html', login_form=form)
        else:
            form.error = "User or Password was Incorrect"
            return render_template('login.html', login_form=form)
    except KeyError as err:
        form.error = "Email or Password Was Not Filled Out Correctly"
        return render_template('login.html', login_form=form)
Exemplo n.º 9
0
    def test_visulalization_extended_gauss_e10_inner(self):
        def pfun(x, y):
            return np.sin(np.pi * x) * np.sin(np.pi * y)

        p = (10, 10)
        n = (20, 20)

        mesh = CrazyMesh(2, n, ((-1, 1), (-1, 1)), 0.3)
        func_space_extGau = FunctionSpace(mesh, '0-ext_gauss', p)

        form_0_extG = Form(func_space_extGau)
        form_0_extG.discretize(self.pfun)

        xi = eta = np.linspace(-1, 1, 10)
        form_0_extG.reconstruct(xi, eta)
        (x, y), data = form_0_extG.export_to_plot()
        plt.contourf(x, y, data)
        plt.title('reduced extended_gauss 0-form')
        plt.colorbar()
        plt.show()

        form_1 = d(form_0_extG)
        form_1.reconstruct(xi, eta)
        (x, y), data_dx, data_dy = form_1.export_to_plot()
        ufun_x, ufun_y = self.ufun()
        plt.contourf(x, y, data_dx)
        plt.title('extended_gauss 1-form dx')
        plt.colorbar()
        plt.show()
        #
        plt.contourf(x, y, data_dy)
        plt.title('extended_gauss 1-form dy')
        plt.colorbar()
        plt.show()
        print(np.min(data_dy))
Exemplo n.º 10
0
def detect():
    form = Form(request.form)
    if request.method == 'POST':  #and form.validate():
        test_values = np.array([
            [
                form.pregnancies.data, form.glucose.data,
                form.bloodPressure.data, form.skinThickness.data,
                form.insulin.data, form.bmi.data,
                form.diabetesPedigreeFunction.data, form.age.data
            ],
        ],
                               dtype=np.float32)
        result = restore_model(test_values)
        print("************")
        if (result):
            result = "Time to go Sugar Free"
        else:
            result = "Time for dessert"
    else:
        result = None
    iframe = 'details.html'

    return render_template('detect.html',
                           form=form,
                           result=result,
                           iframe=iframe)
Exemplo n.º 11
0
    def test_visulization_lobato_e10_inner(self):
        def pfun(x, y):
            return np.sin(np.pi * x) * np.sin(np.pi * y)

        p = (20, 20)
        n = (2, 2)
        mesh = CrazyMesh(2, n, ((-1, 1), (-1, 1)), 0.2)
        xi = eta = np.linspace(-1, 1, 100)

        func_space = FunctionSpace(mesh, '0-lobatto', p)
        form_0 = Form(func_space)
        form_0.discretize(pfun)
        form_0.reconstruct(xi, eta)
        (x, y), data = form_0.export_to_plot()
        plt.contourf(x, y, data)
        plt.title('reduced lobatto 0-form')
        plt.colorbar()
        plt.show()

        form_1 = d(form_0)

        form_1.reconstruct(xi, eta)
        (x, y), data_dx, data_dy = form_1.export_to_plot()

        plt.contourf(x, y, data_dx)
        plt.title('lobatto 1-form dx')
        plt.colorbar()
        # plt.show()

        plt.contourf(x, y, data_dy)
        plt.title('lobatto 1-form dy')
        plt.colorbar()
        # plt.show()
        print(np.min(data_dy))
Exemplo n.º 12
0
    def main(self, message='', **kwargs):
        store = filedict_con(cfg.store_file, 'sys')

        defaults = {'wan_admin': "''",
                    'wan_ssh': "''",
                    'lan_ssh': "''",
                    }
        for k,c in defaults.items():
            if not k in kwargs:
                try:
                    kwargs[k] = store[k]
                except KeyError:
                    exec("if not '%(k)s' in kwargs: store['%(k)s'] = kwargs['%(k)s'] = %(c)s" % {'k':k, 'c':c})

        form = Form(title=_("Accessing the %s" % cfg.box_name), 
                        action="/sys/config/wan", 
                        name="admin_wan_form",
                        message=message )
        form.html(self.help())
        if cfg.users.expert():
            form.checkbox(_("Allow access to Plinth from WAN"), name="wan_admin", checked=kwargs['wan_admin'])
            form.checkbox(_("Allow SSH access from LAN"), name="lan_ssh", checked=kwargs['lan_ssh'])
            form.checkbox(_("Allow SSH access from WAN"), name="wan_ssh", checked=kwargs['wan_ssh'])
        form.submit(_("Submit"))
        return form.render()
Exemplo n.º 13
0
    def _upload_file(self, image=False, show_filename=True):
        import os
        import Image
        if image:
            from forms import ImageUploadForm as Form
        else:
            from forms import FileUploadForm as Form
        from uliweb.utils.image import thumbnail_image, fix_filename
        from uliweb import json_dumps

        File = get_model('forumattachment')

        forum_id = request.GET.get('forum_id')
        slug = request.GET.get('slug')
        form = Form()
        suffix = date.now().strftime('_%Y_%m_%d')
        if request.method == 'GET':
            form.bind({'is_thumbnail': True})
            return {'form': form}
        else:
            flag = form.validate(request.values, request.files)
            if flag:
                f = form.data['filedata']
                _f = os.path.basename(f['filename'])
                #文件格式为forum/<forum_id>/<filename_yyyy_mm_dd>
                filename = fix_filename('forum/%s/%s' % (forum_id, _f), suffix)
                if image:
                    filename = functions.save_file(filename, f['file'])
                    if form.data['is_thumbnail']:
                        #process thumbnail
                        rfilename, thumbnail = thumbnail_image(
                            functions.get_filename(filename, filesystem=True),
                            filename,
                            settings.get_var('PARA/FORUM_THUMBNAIL_SIZE'))
                        _file = functions.get_href(thumbnail)
                    else:
                        _file = functions.get_href(filename)
                    name = functions.get_href(filename)
                else:
                    filename = functions.save_file(filename, f['file'])
                    name = form.data['title']
                    if not name:
                        name = _f
                    _file = functions.get_href(filename, alt=name)
                ff = File(slug=slug, file_name=filename, name=name)
                ff.save()
                name = json_dumps(name, unicode=True)
                if show_filename:
                    fargs = '||%s' % name[1:-1]
                else:
                    fargs = ''
                return '''<script type="text/javascript">
var url='%s%s';
setTimeout(function(){callback(url);},100);
</script>
''' % (_file, fargs)
            else:
                return {'form': form}
Exemplo n.º 14
0
def index():
    form = Form()
    if request.method == 'POST' and form.validate():
        email = request.form['email']
        # Check that email does not already exist (not a great query, but works)
        if not db.session.query(Subscriber).filter(
                Subscriber.email == email).count():
            subscriber = Subscriber(email=email, confirmed=False)
            db.session.add(subscriber)
            db.session.commit()

            token = generate_confirmation_token(subscriber.email)
            confirm_url = url_for('confirm_email', token=token, _external=True)
            html = render_template('emails/subscribers.html',
                                   confirm_url=confirm_url,
                                   token_time_limit=TOKEN_EXPIRATION_MINUTES)
            subject = "Please confirm your subscription to analyseether.com"
            send_email(subscriber.email, subject, html)

            message = Markup("Thank you for subscribing, we have sent you \
                                              a verification email.")
            flash(message)

            return redirect(url_for('index', _anchor='signUpForm'))

        else:  # The subscriber email exists in the database
            subscriber = Subscriber.query.filter_by(email=email).first_or_404()

            if subscriber.confirmed:  # the subscriber has confirmed his email
                message_email_already_verified = Markup(
                    'This email has already been verified')
                flash(message_email_already_verified)
            else:  # resent the confirmation email
                token = generate_confirmation_token(subscriber.email)
                confirm_url = url_for('confirm_email',
                                      token=token,
                                      _external=True)
                html = render_template(
                    'emails/subscribers.html',
                    confirm_url=confirm_url,
                    token_time_limit=TOKEN_EXPIRATION_MINUTES)
                subject = "Please confirm your subscription to analyseether.com"
                send_email(subscriber.email, subject, html)

                message_token_resent = Markup(
                    'Email exists, we have resent you \
                                              a verification email.')
                flash(message_token_resent)
            return redirect(url_for('index', _anchor='signUpForm'))
    elif request.method == 'POST' and not form.validate():
        for field, errors in form.errors.items():
            for error in errors:
                message_validation_error = Markup(error)
                flash(message_validation_error)
        return redirect(url_for('index', _anchor='signUpForm'))

    return render_template('index.html', form=form)
Exemplo n.º 15
0
    def main(self, message='', **kwargs):
        sys_store = filedict_con(cfg.store_file, 'sys')
        defaults = {
            'time_zone': "slurp('/etc/timezone').rstrip()",
            'hostname': "gethostname()",
        }
        for k, c in defaults.items():
            if not k in kwargs:
                try:
                    kwargs[k] = sys_store[k]
                except KeyError:
                    exec(
                        "if not '%(k)s' in kwargs: sys_store['%(k)s'] = kwargs['%(k)s'] = %(c)s"
                        % {
                            'k': k,
                            'c': c
                        })

        ## Get the list of supported timezones and the index in that list of the current one
        module_file = __file__
        if module_file.endswith(".pyc"):
            module_file = module_file[:-1]
        time_zones = json.loads(
            slurp(
                os.path.join(os.path.dirname(os.path.realpath(module_file)),
                             "time_zones")))
        for i in range(len(time_zones)):
            if kwargs['time_zone'] == time_zones[i]:
                time_zone_id = i
                break

        ## A little sanity checking.  Make sure the current timezone is in the list.
        try:
            cfg.log('kwargs tz: %s, from_table: %s' %
                    (kwargs['time_zone'], time_zones[time_zone_id]))
        except NameError:
            cfg.log.critical("Unknown Time Zone: %s" % kwargs['time_zone'])
            raise cherrypy.HTTPError(
                500, "Unknown Time Zone: %s" % kwargs['time_zone'])

        ## And now, the form.
        form = Form(title=_("General Config"),
                    action="/sys/config/general/index",
                    name="config_general_form",
                    message=message)
        form.html(self.help())
        form.dropdown(_("Time Zone"),
                      name="time_zone",
                      vals=time_zones,
                      select=time_zone_id)
        form.html(
            "<p>Your hostname is the local name by which other machines on your LAN can reach you.</p>"
        )
        form.text_input('Hostname', name='hostname', value=kwargs['hostname'])
        form.submit(_("Submit"))
        return form.render()
Exemplo n.º 16
0
 def test_local_to_global_cochain(self):
     # TODO: currently not supported px != py
     """Test local to global mapping of cochians."""
     mesh = CrazyMesh(2, (2, 2), ((-1, 1), (-1, 1)), curvature=0.3)
     cases = ['2-lobatto', '2-gauss']
     p = 2, 3
     for form_case in cases:
         func_space = FunctionSpace(mesh, form_case, p)
         form_2 = Form(func_space)
         form_2.discretize(paraboloid)
Exemplo n.º 17
0
def _get_forms_with_variant(lemma_subdict, postag, prefix=''):

    result = []

    variants = [
        "0", "1", "2", "3", "4", "5", "6", "7", "C", "X", "Y", "Z", "V", "B"
    ]

    for variant in variants:
        word = lemma_subdict.get(postag + variant)
        if word is not None:
            result.append(Form(word, variant, prefix, False))

        new_postag = postag + variant + DIACRITIC_POSTAG
        word = lemma_subdict.get(new_postag)
        if word is not None:
            result.append(Form(word, variant, prefix, True))

    return result
Exemplo n.º 18
0
def categories_edit(category_id):
    try:
        category = Category.find_by_id(category_id)
        if category:
            if request.method == 'GET':
                category_dict = category.__dict__
                form = Form(category_dict, form_fields)
                return render_template('category/edit.html',
                                       form=form,
                                       category_id=category_id,
                                       success=True)
            elif request.method == 'POST':
                form = Form(request.form, form_fields)
                if form.validate():
                    values = form.named_values()
                    category.from_dict(values)
                    category.save()
                    miner = miner_cls(category)
                    miners[category_id] = miner
                    miner.start()
                    return redirect(url_for('categories'))
                else:
                    return render_template('category/edit.html',
                                           form=form,
                                           category_id=category_id,
                                           success=True)
            elif request.method == 'DELETE':
                if category_id in miners:
                    miner = miners[category_id]
                    miner.stop()
                    del miners[category_id]
                    Category.delete(category_id)
                    return 'Category {} deleted.'.format(category_id), 200
                else:
                    return 'Category {} not present on miner.'.format(
                        category_id), 400
            else:
                return 'Unsupported request method.', 400
        else:
            return 'Category {} not found.'.format(category_id), 400
    except ValueError, e:
        print e
        return '{} is not a valid category id.'.format(category_id), 400
Exemplo n.º 19
0
def thanks():
    form = Form()

    na = request.args.get('name').split(",")

    xa = list(map(float, na))
    # 'icon': 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
    #          'lat': 37.4419,
    #          'lng': -122.1419,
    #          'infobox': "<b>Hello World</b>"

    mrks = marker()
    if form.validate_on_submit():
        ad = adfco(xa)
        cr = form.fb.data
        mr = {
            'icon':
            'http://maps.google.com/mapfiles/kml/paddle/grn-circle.png',
            'lat':
            xa[0] + 0.000019,
            'lng':
            xa[1] + .000019,
            'infobox':
            'warning this site is well known for <b>' + cr + '</b><br>' + ad
        }
        mrks.append(mr)
        # original database not updated

    warns = ['<b>WARNING YOU ARE WITHIN THRESHOLD RANGE OF THESE AREAS</b>']
    for m in mrks:
        d = distance(*xa, m['lat'], m['lng']) * 1000  # 1000x = into meters
        if d <= 1000:
            warns.append(str(m['infobox']))

    INFO = "<B>KEEP WALKIN ,YOU'RE IN SAFE REGION</B>"
    if len(warns) > 1:
        INFO = '<br><br><hr>'.join(warns)
    mymap = Map(
        identifier="view-side",
        varname="mymap",
        style="height:75%;width:100%;margin:0;",
        lat=na[0],
        lng=na[1],
        zoom=15,
        markers=[{
            'icon':
            'http://maps.google.com/mapfiles/kml/paddle/grn-circle.png',
            'lat': na[0],
            'lng': na[1],
            'infobox': INFO
        }] + mrks)
    return render_template('wc.html', mymap=mymap, form=form)


#see 57
Exemplo n.º 20
0
 def test_l2_norm(self):
     p = (10, 10)
     n = (10, 10)
     mesh = CrazyMesh(2, n, ((0, 1), (0, 1)), 0.1)
     func_space = FunctionSpace(mesh, '1-lobatto', p)
     form_1 = Form(func_space)
     form_1.discretize((self.ufun_x, self.ufun_y))
     # print("chochain : \n", form_1.chochain)
     error_global, error_local = form_1.l_2_norm((self.ufun_x, self.ufun_y))
     self.assertLess(error_global, 4 * 10**(-12))
     self.assertLess(error_local, 4 * 10**(-10))
Exemplo n.º 21
0
def index():
    form = Form()
    if form.validate_on_submit():
        name = form.name.data
        email = form.email.data
        mobile = form.mobile.data
        new_list = DB(name, email, mobile)
        db.session.add(new_list)
        db.session.commit()
        return redirect(url_for('container_details'))
    return render_template('home.html', form=form)
Exemplo n.º 22
0
 def main(self, msg=''):
     users = cfg.users.keys()
     add_form = Form(title=_("Edit or Delete User"), action="/sys/users/edit", message=msg)
     add_form.html('<span class="indent"><strong>Delete</strong><br /></span>')
     for uname in sorted(users.keys()):
         add_form.html('<span class="indent">&nbsp;&nbsp;%s&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' % 
                       add_form.get_checkbox(name=uname) +
                       '<a href="/sys/users/edit?username=%s">%s (%s)</a><br /></span>' % 
                       (uname, users[uname]['name'], uname))
     add_form.submit(label=_("Delete User"), name="delete")
     return add_form.render()
Exemplo n.º 23
0
 def test_lobatto_projection(self):
     p = (10, 10)
     n = (5, 6)
     mesh = CrazyMesh(2, n, ((-1, 1), (-1, 1)), 0.3)
     func_space = FunctionSpace(mesh, '0-lobatto', p)
     form_0 = Form(func_space)
     form_0.discretize(self.pfun)
     xi = eta = np.linspace(-1, 1, 20)
     form_0.reconstruct(xi, eta)
     (x, y), data = form_0.export_to_plot()
     npt.assert_array_almost_equal(self.pfun(x, y), data)
Exemplo n.º 24
0
def hodge_from_form(form, extend):
    """Calculate the hodge matrix and resulting form."""
    dual_space = DualSpace(form.function_space, extend)
    dual_form = Form(dual_space)
    wedge_prod = form.basis.wedged(dual_form.basis)
    inner_prod = inner(dual_form.basis, dual_form.basis)
    inverse_inner = inv(np.rollaxis(inner_prod, 2, 0))
    hodge_matrix = np.tensordot(inverse_inner, wedge_prod, axes=((2), (0)))
    dual_form.cochain_local = np.einsum('kij,jk->ik', hodge_matrix,
                                        form.cochain_local)
    hodge_matrix = np.moveaxis(hodge_matrix, 0, -1)
    return dual_form, hodge_matrix
Exemplo n.º 25
0
 def test_projection_gauss(self):
     p = (10, 10)
     n = (5, 6)
     mesh = CrazyMesh(2, n, ((-1, 1), (-1, 1)), 0.1)
     func_space = FunctionSpace(mesh, '1-gauss', p)
     form_1 = Form(func_space)
     form_1.discretize((self.ufun_x, self.ufun_y))
     xi = eta = np.linspace(-1, 1, 40)
     form_1.reconstruct(xi, eta)
     (x, y), data_dx, data_dy = form_1.export_to_plot()
     npt.assert_array_almost_equal(self.ufun_x(x, y), data_dx, decimal=4)
     npt.assert_array_almost_equal(self.ufun_y(x, y), data_dy, decimal=4)
Exemplo n.º 26
0
 def test_discretize_simple(self):
     """Simple discretization of 0 forms."""
     p_s = [(2, 2)]
     n = (2, 2)
     for p in p_s:
         mesh = CrazyMesh(2, n, ((-1, 1), (-1, 1)), 0.0)
         func_space = FunctionSpace(mesh, '0-lobatto', p)
         form_0 = Form(func_space)
         form_0.discretize(self.pfun)
         # values at x = +- 0.5 and y = +- 0.5
         ref_value = np.array((1, -1, -1, 1))
         npt.assert_array_almost_equal(ref_value, form_0.cochain_local[4])
Exemplo n.º 27
0
def _add(request, template_name='s/_add.html'):
    form = Form(request.POST or None)
    username = request.session['username']
    print username
    if form.is_valid():
        print form
        form.save()
        return redirect('_list')

    return render(request, template_name, {'form': form,
                                           'username': username,
                                           'var3': 'active',
                                           })
Exemplo n.º 28
0
def _edit(request, pk, template_name='s/_add.html'):
    username = request.session['username']
    deps = get_object_or_404(, pk=pk)
    form = Form(request.POST or None, instance=deps)
    if form.is_valid():
        form.save()
        return redirect('_list')

    return render(request, template_name, {'form': form,
                                           'username': username,
                                           'var3': 'active',
                                           'deps': deps,
                                           })
def index():
    form = Form()
    if form.validate_on_submit():
        weather = weather_api(form.zip.data)
        nec = {
            'description': weather['weather'][0]['description'],
            'temp': weather['main']['temp'],
            'temp_min': weather['main']['temp_min'],
            'temp_max': weather['main']['temp_max'],
            'name': weather['name']
        }
        return render_template('home.html', nec=nec)
    return render_template('home.html', form=form)
Exemplo n.º 30
0
 def main(self, username='', name='', email='', message=None, *args, **kwargs):
     form = Form(title="Add User", 
                     action="/sys/users/add/index", 
                     onsubmit="return md5ify('add_user_form', 'password')", 
                     name="add_user_form",
                     message=message)
     form.text = '<script type="text/javascript" src="/static/js/md5.js"></script>\n'+form.text
     form.text_input(_("Username"), name="username", value=username)
     form.text_input(_("Full name"), name="name", value=name)
     form.text_input(_("Email"), name="email", value=email)
     form.text_input(_("Password"), name="password")
     form.text_input(name="md5_password", type="hidden")
     form.submit(label=_("Create User"), name="create")
     return form.render()