repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
bionikspoon/Codewars-Challenges
python/8kyu/basic_subclasses/solution.py
Python
mit
277
0.00722
from main import * class Human(object): pass class Man(Human): pass class Woman(Human): pass def God(): adam, eve = Man(), Woman() return [adam, eve] paradise = God() test.assert_equals(True, isins
tance(p
aradise[0], Man), "First object are a man")
vgrem/SharePointOnline-REST-Python-Client
office365/sharepoint/field_collection.py
Python
mit
1,572
0.003817
from office365.runtime.client_object_collection import ClientObjectCollection from office365.runtime.client_query import CreateEntityQuery from office365.runtime.resource_path_service_operation import ResourcePathServiceOperation from office365.sharepoint.field import Field class FieldCollection(ClientObjectCollectio...
def __init__(self, context, resource_path=None): super(FieldCollection, self).__init__(context, Field, resource_path) def add(
self, field_creation_information): """Adds a field to the field collection.""" field = Field(self.context) self.add_child(field) qry = CreateEntityQuery(self, field_creation_information, field) self.context.add_query(qry) return field def get_by_id(self, _id): ...
himanshu-setia/keystone
keystone/contrib/ec2/controllers.py
Python
apache-2.0
18,637
0
# Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
his is similar with # other programming language libraries, JAVA for example.
signer = ec2_utils.Ec2Signer(creds_ref['secret']) signature = signer.generate(credentials) if utils.auth_str_equal(credentials['signature'], signature): return True raise exception.Unauthorized( ...
openqt/algorithms
leetcode/python/lc124-binary-tree-maximum-path-sum.py
Python
gpl-3.0
1,352
0.010355
# coding=utf-8 import unittest """124. Binary Tree Maximum Path Sum https://leetcode.com/problems/binary-tree-maximum-path-sum/description/ Given a **non-empty** binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along ...
,9,20,null,null,15,7] -10 / \ 9 **20** **/ \** **15 7** **Output:** 42 Similar Questions: Path Sum (path-sum) Sum Root to Leaf Numbers (sum-root-to-leaf-numbers) Path Sum IV (path-sum-iv) Longest Univalue Path (longest-univalue-path) """ # Def...
self.right = None class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ def test(self): pass if __name__ == "__main__": unittest.main()
hanlind/nova
nova/tests/unit/virt/xenapi/image/test_glance.py
Python
apache-2.0
10,892
0.000092
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
'endpoint': 'http://localhost:9292', 'sr_path': '/fake/sr/path', 'api_version': 2, 'extra_headers': {'
X-Auth-Token': 'foobar', 'X-Roles': '', 'X-Tenant-Id': 'project', 'X-User-Id': 'user', 'X-Identity-Status': 'Confirmed'}} def _get_download_params(self): params = self._ge...
WebCampZg/conference-web
project/sitemaps.py
Python
bsd-3-clause
869
0
from django.contrib import sitemaps from django.contrib.sitemaps import GenericSitemap from django.urls import reverse from blog.models import Post from talks.models import Talk from pages.models import Page class StaticViewSitemap(sitemaps.Sitemap): priority = 0.8 changefreq = 'weekly' def items(self):...
rn [ 'ui_index', 'blog_list_posts', 'talks_list_talks', ] def location(self, item
): return reverse(item) sitemaps = { 'static': StaticViewSitemap, 'pages': GenericSitemap({ 'queryset': Page.objects.filter(published=True), }), 'news': GenericSitemap({ 'queryset': Post.objects.none(), 'date_field': 'updated_at', }), 'talks': GenericSitemap({ ...
pygamebrasil/pygame-site
src/app/contents/models.py
Python
mit
969
0
# coding: utf-8 from app import db class Content(db.Model): __tablename__ = "contents" session = db.session data = db.Column(db.Text()) _type = db.Column(db.String(80), primary_key=True) def __init__(self, data, type):
self.data = data self._type = type def to_dict(sel
f): return{ "data": self.data, "_type": self._type, } @classmethod def make_commit(cls): cls.session.commit() @classmethod def get_contents(cls): return cls.session.query(cls).all() @classmethod def get_content_by_type(cls, _type): ...
davelab6/fontbakery
tools/fontbakery-crawl.py
Python
apache-2.0
4,997
0.0002
#!/usr/bin/env python # coding: utf-8 # Copyright 2013 The Font Bakery Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LIC...
directory CRAWLER_TIMEOUT = 60 class cd(object): def
__init__(self, new_path): self.new_path = new_path def __enter__(self): self.saved_path = os.getcwd() os.chdir(self.new_path) def __exit__(self, etype, value, traceback): os.chdir(self.saved_path) class RunCrawlerCommand(object): def __init__(self, cmd, **kwargs): ...
PaloAltoNetworks-BD/autofocus-client-library
autofocus/gsrt_config.py
Python
isc
6,385
0.003602
import os # maintain python 2.7 compatibility for time being. GSRTConfig is a dependency on everything else, # including ow-swagger-library, which supports both python2 and python3. I think we should # stop supporting 2.x if needed, but since many people outside GSRT are still just beginning # to transition to python3...
Y={some apikey} """ def __init__(self, config_section, defaults=None, config_path=None, secrets_dir=None, throw_exception=False, allow_no_value=True): """ Config files will be checked in /etc/panw be default. If a PANW_CONFIG env exists, it will pull the path from there...
setting that will work without colliding in an environment variable Settings and sections should be lower_case_underscore """ if defaults is None: defaults = {} if not secrets_dir and 'SECRETS_DIR' in os.environ: secrets_dir = os.environ.get("SECRETS_DIR") ...
ska-sa/purr
Purr/Plugins/local_pychart/afm/NewCenturySchlbk_Bold.py
Python
gpl-2.0
1,509
0.014579
# AFM font NewCenturySchlbk-Bold (path: /usr/share/fonts/afms/adobe/pncb8a.afm). # Derived from Ghostscript distribution. # Go to www.cs.wisc.edu/~ghost to get the Ghostcript source code. from . import dir dir.afm["NewCenturySchlbk-Bold"] = ( 500, 5
00, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 287, 296, 333, 574, 574, 833, 852, 241, 389, 389, 500, 606, 278, 333, 278, 278, 574, 574, 574, 574, 574, 574, 574, 574, 574, 574, 278, 278, 606, 606, 606, 500, 747, 7...
70, 444, 648, 815, 722, 981, 833, 833, 759, 833, 815, 667, 722, 833, 759, 981, 722, 722, 667, 389, 606, 389, 606, 500, 241, 611, 648, 556, 667, 574, 389, 611, 685, 370, 352, 667, 352, 963, 685, 611, 667, 648, 519, 500, 426, 685, 611, 889, 611, 611, 537, 389, 606, 389, 606, 500, 500, 500, 500, 500, 500, 500, 500, 500, 5...
cylc/cylc
tests/integration/utils/test_utils.py
Python
gpl-3.0
1,647
0
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. # Copyright (C) NIWA & British Crown (Met Office) & Contributors. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licen...
1) assert not path1.exists() @pytest.mark.asyncio async def test_poll_file(tmp_path): """It sh
ould return if the condition is met.""" path = tmp_path / 'file' await _poll_file(path, exists=False) path.touch() await _poll_file(path, exists=True)
inveniosoftware/invenio-upgrader
invenio_upgrader/upgrades/__init__.py
Python
gpl-2.0
812
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014, 2015 CERN. # # Invenio is free software; you can redistribute it
and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of #...
ICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Implement upgrade recipes."""
slek120/phys534
HW4/194287.admin.extreme.uic.edu/spectral_function.py
Python
gpl-3.0
895
0.037989
from scipy import * from scipy.integrate import simps import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def Compute_Aw(om, DOS, Sig, ommesh, delta=0.1j): Aw = zeros(len(om)) for i in range(len(om)): DMFTW = DOS / (om[i] - Sig[i] - ommesh + delta) Aw[i] = simps(-1.*DMFTW.imag/pi, omme...
ommesh = DOSfile[:,0] # 2nd column as DOS DOS = DOSfile[:,1] # Normalize DOS = DOS / simps(DOS, ommesh) # Load Sig Sigfile = loadtxt('Sig.out') # 1st column as frequencies om = Sigfile[:,0] # 2nd, 3rd column as self energy Sig = Sigfile[:,1] + 1j * Sigfile[:,2] Aw = Compute_Aw(om, DOS, Sig, omm...
omega)$') plt.xlabel('$\omega$') plt.savefig('Aw_U6.eps')
gedman4b/MachineLearning
Python/perceptron.py
Python
gpl-3.0
1,711
0.003507
import numpy as py class Perceptron(object): """Perceptron classifier. Parameters ------------- eta : float Learning rate (between 0.0 and 1.0) n_iter : int Passes over the training dataset. Attributes ----------- w_ : 1d...
alues. Returns --------
- self : object """ self.w_ = np.zeros(1 + X.shape[1]) self.errors_ = [] for _ in range(self.n_iter): errors = 0 for xi, target in zip(X, y): update = self.eta * (target - self.predict(xi)) self.w_[1:] += upda...
KrzysztofStachanczyk/Sensors-WWW-website
www/env/lib/python2.7/site-packages/django/templatetags/static.py
Python
gpl-3.0
4,391
0.000228
from django import template from django.apps import apps from django.utils.encoding import ir
i_to_uri from django.utils.six.moves.urllib.parse import urljoin register = template.Library() class PrefixNode(template.Node): def __repr__(self): return "<PrefixNode for %r
>" % self.name def __init__(self, varname=None, name=None): if name is None: raise template.TemplateSyntaxError( "Prefix nodes must be given a name to return.") self.varname = varname self.name = name @classmethod def handle_token(cls, parser, token, nam...
eicher31/compassion-switzerland
mis_builder_spn_event_info/models/__init__.py
Python
agpl-3.0
33
0
fr
om . import mis_spn_e
vent_info
alabid/pycrunchbase
src/pycrunchbase/resource/ipo.py
Python
mit
1,557
0
import six from .node import Node from .utils import parse_date @six.python_2_unicode_compatible class IPO(Node): """Represents an IPO on CrunchBase""" KNOWN_RELATIONSHIPS = [ 'funded_company', 'stock_exchange', 'images',
'videos', 'news', ] KNOWN_PROPERTIES
= [ "api_path", "web_path", "went_public_on", "went_public_on_trust_code", "stock_exchange_symbol", "stock_symbol", "shares_sold", "opening_share_price", "opening_share_price_currency_code", "opening_share_price_usd", "opening_valua...
anhstudios/swganh
data/scripts/templates/object/ship/shared_droid_fighter_tier2.py
Python
mit
416
0.050481
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE D
OCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Ship() result.template = "object/ship/shared_droid_fighter_tier2.iff" result.attribute_template_id = -1 result.stfName("","") #### BEGIN MODIFICATIONS #### #### END MODIFICAT
IONS #### return result
anditakaesar/aoms
aomswork/migrations/0001_initial.py
Python
mit
3,902
0.003332
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-07-14 03:53 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
imary_key=True, serialize=False, verbose_name='ID')), ('create_date', models.DateTimeField(auto_now_add=True)), ('update_date', models.DateTimeField(auto_now=True)), ], options={ 'ordering': ('-create_date',), }, ), migr...
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create_date', models.DateTimeField(auto_now_add=True)), ('update_date', models.DateTimeField(auto_now=True)), ('order', models.ForeignKey(on_delete=django.db.models.deleti...
willingc/portal
systers_portal/common/tests/test_views.py
Python
gpl-2.0
995
0
from django.core.urlresolvers import reverse from django.test import TestCase, Client class CommonViewsTestCase(TestCase): def setUp(self): self.client = Client() def test_index_page(self): """Test index/landing page""" index_url = reverse('index') response = self.client.get(i...
.get(contact_url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'common/contact.html') def test_about_us_page(self): """Test about us page""" about_us_url = reverse('about-us') res
ponse = self.client.get(about_us_url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'common/about_us.html')
cedriclaunay/gaffer
python/Gaffer/GraphComponentPath.py
Python
bsd-3-clause
3,167
0.029365
########################################################################## # # Copyright (c) 2012, John Haddon. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of so...
Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENT...
lmazuel/azure-sdk-for-python
azure-mgmt-resource/azure/mgmt/resource/policy/v2016_12_01/models/__init__.py
Python
mit
914
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project ro
ot for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .policy_definition import PolicyDefinition from .policy_assi...
ent_paged import PolicyAssignmentPaged from .policy_client_enums import ( PolicyType, PolicyMode, ) __all__ = [ 'PolicyDefinition', 'PolicyAssignment', 'PolicyDefinitionPaged', 'PolicyAssignmentPaged', 'PolicyType', 'PolicyMode', ]
quattor/aquilon
tests/broker/test_constraints_network.py
Python
apache-2.0
7,564
0.001058
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2013,2014,2015,2016,2017 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You ...
ning permissions and # limitations under the License. import unittest if __name__ == "__main__": import utils utils.import_depends() from brokertest import TestBrokerCommand class TestNetworkConstraints(TestBrokerCommand): def test_100_add_testnet(self): self.net.allocate_network(self, "bunker_...
", "ut") self.net.allocate_network(self, "bunker_mismatch2", 24, "unknown", "bunker", "bucket1.ut") def test_110_mismatch_1(self): # Rack is bunkerized, network is not net = self.net["bunker_mismatch1"] ip = net.usable[0] self.dsdb_expect_ad...
calculquebec/python-lustre-utils
lustre_util/lustre_ost.py
Python
apache-2.0
6,149
0.014637
# Copyright (c) 2014 . All rights reserved. # Use of this source code is governed by the APACHE 2.0 license that can be # found in the LICENSE file. # Author: Frederick Lefebre <frederick.lefebvre@calculquebec.ca> from __future__ import division import os import sys import glob import copy from lustre import lustre c...
en(line) == 0 or line.startswith('') : continue if not line.strip() : continue line_parts = line.split() #If a line begins with a
number, we assume we are in a section #and we store in the appropriate array if line[0].isdigit() : #print "Ligne({0}): {1}".format(len(line),line) #Build an array with the data from this section if sectionNo...
benjello/openfisca-france
openfisca_france/scripts/merge_ipp_tax_and_benefit_tables_with_parameters.py
Python
agpl-3.0
22,397
0.006035
#! /usr/bin/env python # -*- coding: utf-8 -*- """Merge YAML files of IPP tax and benefit tables with OpenFisca parameters to generate new parameters.""" import argparse import collections import datetime import logging import os import sys import xml.etree.ElementTree as etree from biryani import strings import ya...
= parser.parse_args() logging.basicConfig(level = logging.DEBUG if args.verbose else logging.WARNING, stream = sys
.stdout) file_system_encoding = sys.getfilesystemencoding() original_element_tree = etree.parse(args.origin) original_root_element = original_element_tree.getroot() # Apply translations to original parameters. with open(args.param_translations) as param_translations_file: param_translatio...
hermes47/QUACCS_2.0_Shython
py2/scan_dihedral.py
Python
mit
6,460
0.010372
#!/usr/bin/env python import sys import string import subprocess #---------------------------------------------------------------------- # Define some handy functions #---------------------------------------------------------------------- def get_contents(file): f = open(file,'r') fc = f.readlines() f.clo...
range(0,nsteps[0]): # for first dihedral, set new value to initial + step number*step size newvalue0 = values[0] + float(i0)*stepsizes[0] gzmat[lines[0]] = diheds[0] + "= " + str(newvalue0) + "\n" new_gzmat_file = base + "_" + str(i0).zfill(3) + ".gzmat" new_pdb_file = base + "_...
cess = subprocess.Popen("babel -igzmat {0} -opdb {1}".format(new_gzmat_file, new_pdb_file).split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) process.communicate() else: for i1 in range(0,nsteps[1]): # for second dihedral, set...
huchoi/edx-platform
lms/djangoapps/courseware/tests/test_tabs.py
Python
agpl-3.0
4,042
0.002227
""" Test cases for tabs. """ from mock import MagicMock, Mock, patch from courseware.courses import get_course_by_id from courseware.views import get_static_tab_contents from django.test.utils import override_settings from django.core.urlresolvers import reverse from student.tests.factories import UserFactory from x...
LESTORE) class StaticTabDateTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase): """Test cases for Static Tab Da
tes.""" def setUp(self): self.course = CourseFactory.create() self.page = ItemFactory.create( category="static_tab", parent_location=self.course.location, data="OOGIE BLOOGIE", display_name="new_tab" ) self.toy_course_key = SlashSeparatedCourseKey('edX', 'toy...
akamai-open/NetStorageKit-Python
setup.py
Python
apache-2.0
1,203
0.014131
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.rst', 'r') as f: readme = f.read() setup ( name = 'netstorageapi', version = '1.2.13', description = 'Akamai Netstorage API for Python', long_description = readme, namespace_packages=['akamai'], package...
m/akamai/NetStorageKit-Python', license='Apache 2.0', keywords='netstorage akamai open api', classifie
rs=[ 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Pyt...
phil-mansfield/gotetra
python/gtet.py
Python
mit
3,817
0.006026
import array import struct import numpy as np class File(object): def __init__(self, file_name): """ Reads a gotetra grid file located at file_name. Returns an object with various header fields along with a grid of positions ordered according to their positions in the ICs. Data gri...
count_width. x_origin - Position of the "lowest" corner of the bounding box around
x positions in the file in comoving Mpc/h. Will always be within the simulation domain. x_span - Displacement vector from the "lowest" to "highest" corner of the position bounding box in comoving Mpc/h. v_origin - Same as x_origin...
nikhila05/pietrack
project/urls.py
Python
mit
4,015
0.01071
from django.conf.urls import url from views import * urlpatterns = [ url(r'^create/$', create_project, name='create_project'), url(r'^list/$', list_of_projects, name='list_of_projects'), url(r'^(?P<slug>[-\w]+)/$', project_detail, name='project_detail'), url(r'^delete/(?P<id>[0-9]+)/$', delete_proje...
/priority/(?P<priority_slug>[a-zA-Z0-9-]+)/edit/$', priority_edit, name='priority_edit'), url(r'^(?P<slug>[-\w]+)/settings/priority/(?P<priority_slug>[a-zA-Z0-9-]+)/delete/$', priority_delete, name='priority_delete'), # severity url(r'^(?P<slug>[-\w]+)/settings/severities/$', severities, name='severities')...
ttings/severity/create/$', severity_create, name='severity_create'), url(r'^(?P<slug>[-\w]+)/settings/severity/(?P<severity_slug>[a-zA-Z0-9-]+)/edit/$', severity_edit, name='severity_edit'), url(r'^(?P<slug>[-\w]+)/settings/severity/(?P<severity_slug>[a-zA-Z0-9-]+)/delete/$', severity_delete, name='severity_del...
lampmantech/trytond_scenari
src/behaving/trytond/steps/dsl.py
Python
gpl-2.0
11,405
0.003507
# -*- mode: python; py-indent-offset: 4; coding: utf-8-unix; encoding: utf-8 -*- """ This is the advanced syntax for behave testing. This is from OpenERPScenario and may fail, as is not properly ported to Tryton yet. It could be that there's a lot in here that is unused and cleaned out. Or, it just needs some TLC by ...
value = int(value) elif field_type == 'float': value = float(value) elif field_type == 'numeric': # guessing value = Decimal(value) elif field_type == 'date': value = time.strftime(value) value = datetime.date(*map(int,value....
ue.split('-'))) res[key] = value return res # regexp @step('/^having:?$/') @step('having') def impl_having(ctx): config = ctx.oProteusConfig assert ctx.table, "please supply a table of values" assert ctx.search_model_name, 'cannot use "having" step without a previous step setting a model' ...
NERC-CEH/jules-jasmin
majic/joj/websetup_jules_parameters.py
Python
gpl-2.0
10,957
0.002555
""" # Majic # Copyright (C) 2014 CEH # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This pr...
TY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 5...
rom joj.model import NamelistFile, Namelist, Parameter log = logging.getLogger(__name__) class JulesParameterParser(object): """ Parser for the Jules documentation Parses the html namelist parameters into the database objects """ # regular expression for integers _RE_INTEGER = "([+\-]?\d+)" ...
apophys/freeipa
ipaserver/plugins/schema.py
Python
gpl-3.0
24,409
0.000082
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # import importlib import itertools import sys import six import hashlib from .baseldap import LDAPObject from ipalib import errors from ipalib.crud import PKQuery, Retrieve, Search from ipalib.frontend import Command, Local, Method, Object from ip...
raise errors.NotFound( reason=_("%(pkey)s: %(oname)s not found") % { 'pkey': name, 'oname': self.name, } ) def _search(self, **kwargs): for cmd in self.api.Command(): if not isinstance(cmd, Local): yield cmd @register() cla...
ommand_show(metaobject_show): __doc__ = _("Display information about a command.") @register() class command_find(metaobject_find): __doc__ = _("Search for commands.") @register() class command_defaults(PKQuery): NO_CLI = True takes_options = ( Str('params*'), Dict('kw?'), ) ...
jeffreyzzh/MYZXcrawler
MYZXcrawler/MYZXcrawler/regex_expression.py
Python
mit
287
0.038869
import re """ batch sub \s """ sub_s = re.compile('[ \t\n\x0B\f\r]{2,}') """ wang yi ne
ws's regex expressions """ wy_regex_doc_id = re.compile('(\w+)\.html') wy_regex_time = re.compile('\d{4}-\d{1,2}-\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2}') wy_regex_source = re.compile('来源:\s+(.*?)
$')
sergiocorreia/panflute
docs/source/_static/toc.py
Python
bsd-3-clause
612
0.001634
""" Add table
of contents at the beginning; uses optional metadata value 'toc-depth' """ from panflute import * def prepare(doc): doc.toc = BulletList() doc.depth = int(doc.get_metadata('toc-depth', default=1)) def action(elem, doc): if isinstance(elem, Header) and elem.level <= doc.depth: ite
m = ListItem(Plain(*elem.content)) doc.toc.content.append(item) def finalize(doc): doc.content.insert(0, doc.toc) del doc.toc, doc.depth def main(doc=None): return run_filter(action, prepare=prepare, finalize=finalize, doc=doc) if __name__ == '__main__': main()
ghallsimpsons/farxiv
farxiv/views.py
Python
unlicense
1,516
0.011214
from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import TemplateView from farxiv.forms import * class Index(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(TemplateView, self).get_context_data(**kwargs) ...
text = super(TemplateView, self).get_context_data(**kwargs) context['form'] = FarticleForm(instance=self.request.user) return context class ViewFarticle(TemplateView): template_name='view.html' def get_context_data(self, **kwargs): context = super(TemplateView, self).get_context_data(**...
] = farticle.title if farticle.render_type=="quick": # Does this actually work? Doubt it... template_name='view.html' farticle = QuickFarticle.objects.get(id = farticle_id) context['steps'] = farticle.steps context['problems'] = farticle.problems ...
mikemcdaid/getonupband
sites/all/themes/getonupband/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
Python
gpl-2.0
48,784
0.006191
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This module helps emulate Visual Studio 2008 behavior on top of other build systems, primarily ninja. """ import os import re import subprocess im...
for include in all_system_includes]) if any(['$' in include for include in expanded_system_includes]): # Some path relies on target-specific variables, bail. return None # Remove system includes
shared by all targets from the targets. for config in configs: includes = config.get('msvs_system_include_dirs', []) if includes: # Don't insert a msvs_system_include_dirs key if not needed. # This must check the unexpanded includes list: new_includes = [i for i in includes if i not in all_...
kamidox/weixin_producthunt
productporter/fixtures/tags.py
Python
bsd-2-clause
652
0
# -*- coding: utf-8 -*- """ productporter.fixtures.tags ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The fixtures module for our t
ags. :copyright: (c) 2014 by the ProductPorter Team. :license: BSD, see LICENSE for more details. """ from collections import OrderedDict fixture = OrderedDict(( ('iOS', { 'description': 'iOS application' }), ('Android', { 'description': 'Android application' }), ('Web',...
'description': 'Web application' }), ('Development', { 'description': 'Development tools' }), ('Design', { 'description': 'Design patterns and tools' }), ))
noironetworks/neutron
neutron/plugins/ml2/drivers/openvswitch/agent/openflow/native/br_phys.py
Python
apache-2.0
2,806
0.000713
# Copyright (C) 2014,2015 VA Linux Systems Japan K.K. # Copyright (C) 2014,2015 YAMAMOTO Takashi <yamamoto at valinux co jp> # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of t...
lf._get_dp() match = self._local_vlan_match(ofp, ofpp, port, lvid) if segmentation_id is None: actions = [ofpp.OFPActionPopVlan()] else: vlan_vid = segmentation_i
d | ofp.OFPVID_PRESENT actions = [ofpp.OFPActionSetField(vlan_vid=vlan_vid)] actions += [ofpp.OFPActionOutput(ofp.OFPP_NORMAL, 0)] self.install_apply_actions(table_id=table_id, priority=4, match=match, ...
pikeszfish/Leetcode.py
leetcode.py/LengthofLastWord.py
Python
mit
232
0.008621
cla
ss Solution: # @param s, a string # @return an integer def lengthOfLastWord(self, s): s = s.strip().split(' ')[-1].strip(',') return len(s) a = Solution()
print a.lengthOfLastWord("Hello World")
josealberto4444/ApodNasaBot
api.py
Python
agpl-3.0
5,412
0.003698
# Copyright © 2019 José Alberto Orejuela García (josealberto4444) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versio...
ix typos (they seem to write the HTML by hand, yes). explanation = explanation.replace('\n', ' ') # Delete all newlines. explanation = re.sub('\s+', ' ', explanation).strip() # Substitute repeated spaces and strips the ones at the beginning and the end of the string. explanation = re.sub(r'<a([^...
nge relative paths to absolute. return explanation def save_explanation(self, explanation): with open(self.filename + '.html', 'wt') as f: f.write(explanation) def explanation(self): filename = self.filename + '.html' if os.path.exists(filename): with op...
Haikson/virtenviro
virtenviro/content/admin.py
Python
apache-2.0
5,341
0.001685
#~*~ coding: utf-8 ~*~ from django.contrib import admin from django.forms import CheckboxSelectMultiple from django import forms from django.conf import settings from virtenviro.content.models import * class TemplateAdmin(admin.ModelAdmin): search_fields = ['title', 'filename'] class ContentAdminForm(forms.Mode...
'/static/filebrowser/js/FB_CKEditor.js', '/static/js/ckeditor.js', ) css = {'all': ('/static/css/ckeditor.css',), } except AttributeError: pass class TagInline(admin.StackedInline): model = Tag.content.through extra = 3 c...
_display = ('title', 'parent', 'language') #list_editable = ('parent',) list_filter = ('language',) formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, } search_fields = ['title', ] inlines = [TagInline,] form = ContentAdminForm def save_model(se...
rwisecar/data-structures
setup.py
Python
mit
582
0
"""Se
tup file for data structures/ linkedlist file.""" from setuptools import setup setup( name="linked_list", description="A project to create and instantiate linked lists.", versio
n=0.1, author="Reggie & Rachael", author_email="rachael.wisecarver@gmail.com", license="MIT", py_modules=['linked_list'], package_dir={'': 'src'}, install_requires=[], extras_require={'test': ['pytest', 'pytest-watch', 'pytest-cov', 'tox']}, # entry_points={ # 'console_scripts': ...
winsvega/solidity
test/formal/shl_workaround_8.py
Python
gpl-3.0
487
0.008214
from rule import Rule from opcodes import * """ Shift left worka
round that Solidity implements due to a bug in Boost. """ rule = Rule() n_bits = 8 bigint_bits = 16 # Input vars X = BitVec('X', n_b
its) A = BitVec('A', n_bits) B = BitVec('B', bigint_bits) # Compute workaround workaround = Int2BV( BV2Int( (Int2BV(BV2Int(X), bigint_bits) << Int2BV(BV2Int(A), bigint_bits)) & Int2BV(BV2Int(Int2BV(IntVal(-1), n_bits)), bigint_bits) ), n_bits ) rule.check(workaround, SHL(A, X))
bheklilr/lather_ui
setup.py
Python
gpl-3.0
897
0
import sys from setuptools import setup, find_packages version = '0.1.0' requirements = ['lxml'] if sys.version_info.major >= 3: requirements.append('suds-py3') else: requirements.append('suds') setup( name="lather_ui", version=version, author="Adam Clemons", author_email="adam@adamclmns.com...
['docs', 'tests']), entry_points={ 'gui_scripts': [ 'LatherUI=lather_ui.__main__:main' ] }, install_requires=requirements, license='GPL', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Programming Language :: Python :: 3', 'Natural Language ...
ware Development :: Testing', 'Topic :: Utilities' ], )
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/operations/_service_endpoint_policy_definitions_operations.py
Python
mit
24,235
0.00524
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class ServiceEndpointPolicyDefinitionsOperations(object): """ServiceEndpointPolicyDefinitionsOperations operations. You shou...
:ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2019_06_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model...
armorunicorn/price_forecast
price_interface/global_fun.py
Python
gpl-3.0
1,096
0.001845
import os import urllib.request from flask import current_app def download_img(comm): print(os.getcwd()) url_list = comm.pics img_dir_path = os.path.join(current_app.config.get("IMAGE_FOLDER", ""), comm.market + comm.idInMarket) # 创建图片目录 if not os.path.exists(img_dir_path): os.mkdir(img_
dir_path) new_list = list() for url in url_list: tmp = url.split("/") file_name = tmp[len(tmp) - 1] img_file_path = os.path.join(img_dir_path, file_name) print(img_file_path) if not os.path.exists(img_file_path): img_url = "http:" + url.replace("/n5/", "/n1/")...
f.close() except: print("download error") file_name = img_url new_list.append(file_name) comm.pics = new_list print(new_list) try: comm.update(pics=new_list) except Exception as e: print(e)
jurcicek/extended-hidden-vector-state-parser
svc/ui/cdc/treedist.py
Python
gpl-2.0
23,841
0.002726
# SVC library - usefull Python routines and classes # Copyright (C) 2006-2008 Jan Svec, honza.svec@gmail.com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, o...
out.append('D,"%s",' % a)
else: out.append('S,"%s","%s"' % (a, b)) out = ':'.join(out) fw.write(out + '\n') fw.write('</PATH>\n') i += 1 fw.write('</SPEAKER>\n') fw.write('</SYSTEM>\n') def forestProcessor(self, forest1...
9seconds/iblocklist2ipset
tests/test_networks.py
Python
mit
2,438
0
# -*- coding: utf-8 -*- # a hack for pytest to allow imports if __package__ is None: import sys import os.path sys.path[0:0] = [ os.path.dirname( # project_root os.path.dirname( # tests os.path.abspath(__file__) # this file )...
_NETWORK
S)
javrasya/django-river
river/core/workflowregistry.py
Python
bsd-3-clause
418
0
class WorkflowRegistry(object): def __init__(self): self.workflows = {} self.class_index = {} def add(self, name, cls): self.workflows[id(cls)] = s
elf
.workflows.get(id(cls), set()) self.workflows[id(cls)].add(name) self.class_index[id(cls)] = cls def get_class_fields(self, model): return self.workflows[id(model)] workflow_registry = WorkflowRegistry()
htygithub/bokeh
bokeh/server/protocol/messages/push_doc.py
Python
bsd-3-clause
847
0.005903
''' ''' from __future__ import absolute_import, print_function from ...exceptions import ProtocolError from ..message import Message from . import register import logging log = logging.getLogger(__name__) @register class push_doc_1(Message): ''' ''' msgtype = 'PUSH-DOC' revis
ion = 1 def __init__(self, header, metadata, content): super(push_doc_1, self).__i
nit__(header, metadata, content) @classmethod def create(cls, document, **metadata): ''' ''' header = cls.create_header() content = { 'doc' : document.to_json() } msg = cls(header, metadata, content) return msg def push_to_document(self, doc): if...
SrNetoChan/QGIS
python/plugins/processing/algs/gdal/ExecuteSql.py
Python
gpl-2.0
4,791
0.002296
# -*- coding: utf-8 -*- """ *************************************************************************** ExecuteSql.py --------------------- Date : November 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com **************************...
f.setOutputValue(self.OUTPUT, outFile) output, outputFormat = GdalUtils.ogrConnectionStringAndFormat(outFile, context) if not sql: raise QgsProcessingException( self.tr('Empty SQL. Please enter valid SQL expression and try again.')) arguments = [] arguments...
pend('-sql') arguments.append(sql) dialect = self.dialects[self.parameterAsEnum(parameters, self.DIALECT, context)][1] if dialect: arguments.append('-dialect') arguments.append(dialect) if options: arguments.append(options) if outputFormat: ...
aviarypl/mozilla-l10n-addons-server
src/olympia/amo/management/commands/generate_jsi18n_files.py
Python
bsd-3-clause
909
0
# -*- coding: utf-8 -*- import os from django.conf import settings from django.core.management.base import BaseCommand from django.http import HttpRequest from django.utils import translation from django.utils.encoding import force_text from django.views.i18n import javascript_catalog class Command(BaseCommand): ...
database up yet. def handle(self, *args, **options): fake_request = HttpRequest() f
or lang in settings.AMO_LANGUAGES: filename = os.path.join( settings.STATICFILES_DIRS[0], 'js', 'i18n', '%s.js' % lang) with translation.override(lang): response = javascript_catalog(fake_request) with open(filename, 'w') as f: ...
alobbs/ansible
test/units/vars/test_variable_manager.py
Python
gpl-3.0
5,400
0.001296
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
dict(foo="bar") mock_play.get_roles.return_value = [] mock_play.
get_vars_files.return_value = [] v = VariableManager() self.assertEqual(v.get_vars(loader=fake_loader, play=mock_play, use_cache=False).get("foo"), "bar") def test_variable_manager_play_vars_files(self): fake_loader = DictDataLoader({ "/path/to/somefile.yml": """ ...
chrinide/optunity
bin/examples/python/sobol_vs_uniform.py
Python
bsd-3-clause
960
0
# In this example we will show the difference between a 2-d Sobol sequence # and sampling uniformly at random in 2 dimensions. # The Sobol sequence has far lower discrepancy, i.e., the generated samples # are spread out better in the sampling space. # # This example requires matplotlib to generate figures. import matp...
es) # generate uniform points x1_random = [random.random() for _ in range(num_pts)] x2_random = [random.random() for _ in range(num_pts)] # plot results plt.figure(1) plt.plot(x1_sobol, x2_sobol, 'o') plt.title('Sobol sequence') plt.draw() plt.figure(2) plt.plot(x1_random, x
2_random, 'ro') plt.title('Uniform random samples') plt.show()
ptracton/wb_soc_template
tools/mem_to_bram.py
Python
mit
4,165
0.003842
#! /usr/bin/env python3 """ mem_to_bram.py Converts a verilog mem file to init statements for 4 BRAMs arranged as a word """ import argparse import sys if __name__ == "__main__": parser = argparse.ArgumentParser( description='Split MEM file into BRAM init statements') parser.add_argument("-D", "--...
sys.exit(-1) address = 0 init_number = 0 bank_number = 0 bram0_init_string = "defparam testbench.dut.rom0.ram0.bank{bank_number}.ram0.INIT_"
bram1_init_string = "defparam testbench.dut.rom0.ram0.bank{bank_number}.ram1.INIT_" bram2_init_string = "defparam testbench.dut.rom0.ram0.bank{bank_number}.ram2.INIT_" bram3_init_string = "defparam testbench.dut.rom0.ram0.bank{bank_number}.ram3.INIT_" index = 0 bram0_init = [] bram1_init = [] ...
cschenck/blender_sim
fluid_sim_deps/blender-2.69/2.69/scripts/startup/bl_ui/properties_render_layer.py
Python
gpl-3.0
5,639
0.000532
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
if self.layout_type in {'DEFAULT', 'COMPACT'}: layout.label(layer.name, icon_value=icon, translate=False) layout.prop(layer, "use", text="", index=index) elif self.layout_type in {'GRID'}: layout.alignment = 'CENTER' layout.label("", icon_value=icon) class RE...
el, Panel): bl_label = "Layer List" bl_options = {'HIDE_HEADER'} COMPAT_ENGINES = {'BLENDER_RENDER'} def draw(self, context): layout = self.layout scene = context.scene rd = scene.render row = layout.row() row.template_list("RENDERLAYER_UL_renderlayers", "", rd...
danielpontello/beatfever-legacy
FileParser.py
Python
mit
4,395
0.042776
# This is a separate module for parser functions to be added. # This is being created as static, so only one parser exists for the whole game. from nota import Nota from timingpoint import TimingPoint from tools import * import random import math def get_Name (osufile): Splitlines = osufile.split('\n') for Line in ...
params[1]) meter = int(params[2]) sampleType = int(params[3]) sampleSet = int(params[4]) volume = int(params[5]) inherited = int(param
s[6]) kiai = int(params[7]) newPoint = TimingPoint(offset, mpb, meter, sampleType, sampleSet, volume, inherited, kiai) TimingPoints.append(newPoint) return TimingPoints def get_NoteList (osufile, sprites, screen_width, screen_height, bpm): NoteList = [] SplitLines = [] #This function returns a list...
gitpython-developers/GitPython
git/objects/submodule/util.py
Python
bsd-3-clause
3,358
0.003574
import git from git.exc import InvalidGitRepositoryError from git.config import GitConfigParser from io import BytesIO import weakref # typing ----------------------------------------------------------------------- from typing import Any, Sequence, TYPE_CHECKING, Union from git.types import PathLike if TYPE_CHECKI...
r_files, BytesIO) sm = self._smref() if sm is not None: index = self._index if index is None: index = sm.repo.index # END handle index index.add([sm.k_
modules_file], write=self._auto_write) sm._clear_cache() # END handle weakref #} END interface #{ Overridden Methods def write(self) -> None: # type: ignore[override] rval: None = super(SubmoduleConfigParser, self).write() self.flush_to_index() return rval ...
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/reportlab/graphics/samples/__init__.py
Python
gpl-3.0
69
0.014493
__doc__="""Example dr
awings to review, used in autoge
nerated docs"""
finnurtorfa/aflafrettir.is
app/auth/forms.py
Python
mit
484
0.016632
#pylint: disable-msg=R0903 from flask_wtf import Form from wtforms import StringField, PasswordField, BooleanF
ield, SubmitField from wtforms.validators import Required, Length, Email class LoginForm(Form): email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) password = PasswordField('Lykilorð', validators=[Required()]) remember_me = BooleanField('
Muna eftir mér?') submit = SubmitField('Innskráning')
bgroff/kala-app
django_kala/projects/tasks/delete_document.py
Python
mit
724
0
from celery.task import Task from django.conf import settings from django.contrib.auth import get_user_model from documents.models import Document User = get_user_model() class DeleteDocumentTask(Task): def run(
self, *args, **kwargs): self.document = Document.objects.get(pk=args[0]) user = User.objects.get(pk=args[1]) if not self.document.can_manage(user): # TODO: Log this return manager = settings.PLATFORM_MANAGER(
) manager.delete_document(self.document) def on_success(self, retval, task_id, args, kwargs): self.document.delete() def on_failure(self, exc, task_id, args, kwargs, einfo): # TODO: Log this return
noplay/aiohttp
tests/test_parsers.py
Python
apache-2.0
18,159
0
"""Tests for parsers.py""" import asyncio import unittest import unittest.mock from aiohttp import errors from aiohttp import parsers class StreamParserTests(unittest.TestCase): DATA = b'line1\nline2\nline3\n' def setUp(self): self.lines_parser = parsers.LinesParser() self.loop = asyncio.n...
eof() self.assertEqual([bytearray(b'line1\r\n'), bytearray(b'line2\r\n')], list(s._buffer)) self.assertEqual(b'data', bytes(stream._buffer)) self.assertTrue(s.is_eof()) def test_feed_parser_exc(self): def p(out, buf): yield # read chunk ...
eam = parsers.StreamParser(paused=False) s = stream.set_parser(p) stream.feed_data(b'line1') self.assertIsInstance(s.exception(), ValueError) self.assertEqual(b'', bytes(stream._buffer)) def test_feed_parser_stop(self): def p(out, buf): yield # chunk s...
MG-RAST/kmerspectrumanalyzer
ksatools/rare.py
Python
bsd-2-clause
6,250
0.00128
#!/usr/bin/env python '''Tool to generate computationally-rarefied graphs kmer spectra''' import sys import os import scipy.stats from optparse import OptionParser import numpy as np import ksatools def fract(aa, epsilon, threshold): '''Evaluates the fraction of theoretically-subsampled spectra above a speci...
ategories ") plt.xlabel("Sampling effort") elif SHADED == 1: plt.subplot(numplots, 1, n + 1) plt.semilogx(pex, aug, "-", label=lab, color=color) plt.fill(pex2, aug2, "k", alpha=0.2) plt.title(label) plt.y
label("Fraction of data") else: plt.semilogx(pex, aug, "-", label=lab) plt.fill(pex2, aug2, "k", alpha=0.2) plt.title(label) plt.ylabel("Fraction of data") # label=str(thresholdlist[i])) # plt.fill(pex, aug, "k", alpha=0.2) plt.ylim((0, 1)) ...
mintuhouse/shotfactory
shotfactory04/__init__.py
Python
gpl-3.0
924
0
# browsershots.org - Test your web design in different browsers # Copyright (C) 2007 Johann C. Rocholl <johann@browsershots.org> # # Browsershots is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version ...
t will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public
License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ ShotFactory library. """ __revision__ = "$Rev: 2006 $" __date__ = "$Date: 2007-08-20 06:02:52 +0530 (Mon, 20 Aug 2007) $" __author__ = "$Author: johann $"
honeyflyfish/SubredditSimulator
setup.py
Python
mit
445
0
from setuptools imp
ort find_packages, setup setup( name="SubredditSimulator", version="", description="An automated bot-run subreddit using markov chains", author="Chad Birch", author_email="chad.birch@gmail.com", platforms=["any"], license="MIT", url="https://github.com/Deimos/SubredditSimulator", pa...
i in open("requirements.txt").readlines()], )
getting-things-gnome/gtg
GTG/gtk/backends/backendstree.py
Python
gpl-3.0
10,617
0.000094
# ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Gene...
xbuf', self.COLUMN_ICON) self.append_column(tvcolumn_pixbuf) # For the backend name text_cell = Gtk.CellRendererText() tvcolumn_text = Gtk.TreeViewColumn('Name', text_cell) tvcolumn_text.add_attribute(text_cell, 'markup', self.COLUMN_TEXT) self.append_column(tvcolumn_text...
l.connect('edited', self.cell_edited_callback) text_cell.set_property('editable', True) # For the backend tags tags_cell = Gtk.CellRendererText() tvcolumn_tags = Gtk.TreeViewColumn('Tags', tags_cell) tvcolumn_tags.add_attribute(tags_cell, 'markup', self.COLUMN_TAGS) self....
apocalyptech/pyinvedit
pyinveditlib/util.py
Python
isc
5,398
0.001667
#!/usr/bin/env python # vim: set expandtab tabstop=4 shiftwidth=4: # # Copyright (c) 2012, Christopher J. Kucera # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source c...
e(__file__, sys.getfilesystemencoding()))) fullpath = os.path.join(path, prefix, filename) if os.path.exists(fullpath): return fullpath else: # See if we were in an Egg fullpath = os.path.join(path, 'share', 'pyinvedit', prefix, filename) if os.pat...
return fullpath else: # Fall back to filesystem non-Egg installation fullpath = os.path.join(path, '..', '..', '..', 'share', 'pyinvedit', prefix, filename) return fullpath class Undo(object): """ Right now this is a dummy object which...
diveshuttam/MessMenuBot
bot.py
Python
mit
4,965
0.024371
import sys import time import datetime import telepot import pprint import json class GMT5(datetime.tzinfo): def utcoffset(self,dt): return datetime.timedelta(hours=5,minutes=30) def tzname(self,dt): return "GMT +5:30 (IST)" def dst(self,dt): return datetime.timedelta(0) gmt5 = GMT...
e!="text"): print(content_type) reply='Sorry, But, I only accept text :-(\nTy
pe or Click "/ " to see available commands' else: global dt global dt_yes global dt_tom dt=datetime.datetime.fromtimestamp(msg["date"],tz=gmt5) ti=dt.time() print(ti) global prdt reply=dt.strftime("Today is %A, %d %b %Y\n\n") #date change ...
axinging/chromium-crosswalk
tools/perf/benchmarks/scheduler.py
Python
bsd-3-clause
788
0.006345
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry import benchmark from core import perf_benchmark from measurements import smoothness import page_sets @benchmark.Disabled('reference') # c...
edulingCases(perf_benchmark.PerfBenchmark): """Measures rendering statistics while interacting with pages that have challenging scheduling properties. https://docs.google.com/a/chromium.org/document/d/ 17yhE5Po9By0sCdM1yZT3LiUECaUr_94rQt9j-4tOQIM/view""" test = smoothness.Smoothness page_set = page_set...
hod def Name(cls): return 'scheduler.tough_scheduling_cases'
Bushstar/UFO-Project
test/functional/rpc_signrawtransaction.py
Python
mit
7,698
0.002858
#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test transaction signing using the signrawtransaction* RPCs.""" from test_framework.test_framework imp...
s'][1]['txid'], inputs[2]['txid']) assert_equal(rawTxSigned['errors'][1]['vout'], inputs[2]['vout'])
assert not rawTxSigned['errors'][0]['witness'] # Perform same test with signrawtransaction rawTxSigned2 = self.nodes[0].signrawtransaction(rawTx, scripts, privKeys) assert_equal(rawTxSigned, rawTxSigned2) # Now test signing failure for transaction with input witnesses p...
codedragon/color_world
color_world.py
Python
bsd-3-clause
15,178
0.000922
from __future__ import division from direct.showbase.ShowBase import ShowBase from direct.actor.Actor import ActorNode from panda3d.core import WindowProperties, NodePath, LVector3 from panda3d.core import LineSegs, OrthographicLens, CardMaker from inputs import Inputs from sys import path import square try: path.i...
# print 'magnitude', magnitude self.velocity *= magnitude # print 'velocity', self.velocity # this makes for smooth movement move = self.velocity * self.vel_base * dt # print move self.avatar.setFluidPos(self.avatar, move) return move ...
r i in range(3): value = self.color_dict[i] if value is not None: stop[i] = False # keys correspond to x,y,z # values correspond to r,g,b if i == 2: # z axis is treated differently ...
credativ/gofer
test/unit/test_metrics.py
Python
lgpl-2.1
2,890
0.000346
# Copyright (c) 2014 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the impl...
(), 90.0) def test_unicode(self): t = Timer() # not started self.assertEqual(unicode(t), 'not-running') # started but not stopped t.started = 1 self.assertEqual(unicode(t), 'started: %d (running)' % t.started) # milliseconds t.started = 0.10 t...
ed = 10.0 t.stopped = 25.0 self.assertEqual(unicode(t), '15.000 (seconds)') # minutes t.started = 10.0 t.stopped = 100.0 self.assertEqual(unicode(t), '1.500 (minutes)') def test_str(self): t = Timer() # not started self.assertEqual(str(t), 'no...
thedespicableknight/web_crawlers
espncricinfo_stats_all.py
Python
mit
2,174
0.00322
# This is a script that scrapes all the data from espncricinfo.com, based on user's input of class (Tests, ODI's, T20's, # etc.) for all types (Batting, Bowling, Fie
lding, etc.), and dumps all the data into separate CSV files. import requests import os from bs4 import BeautifulSoup classes = { 'tests': 1, 'odis': 2, 't20s': 3, 'all': 11, 'womens tests': 8, 'womens odis': 9, 'womens t20s
': 10, 'youth tests': 20, 'youth odis': 21 } def spider(class_type): types = ['batting', 'bowling', 'fielding', 'allround', 'fow', 'team', 'official', 'aggregate'] for type in types: if not os.path.exists('Downloads'): os.makedirs('Downloads') f = open('Downloads/' + class_t...
dimagi/commcare-hq
corehq/apps/linked_domain/tests/test_views.py
Python
bsd-3-clause
3,062
0.004572
from unittest.mock import Mock, patch from django.test import SimpleTestCase from corehq.apps.domain.exceptions import DomainDoesNotExist from corehq.apps.linked_domain.exceptions import ( DomainLinkAlreadyExists, DomainLinkError, DomainLinkNotAllowed, ) from corehq.apps.linked_domain.views import link_do...
tream_domain, self.downstream_domain) self.assertIsNotNone(do
main_link)
skilstak/code-dot-org-python
solutions/stage05-artist1/s1level32b.py
Python
unlicense
181
0.005525
import sys sys.path.append('../..') import codestudio a = codestudio.load('s1level32') a.speed = 'f
astest' for count in
range(360): a.move_backward(1) a.left(1) a.check()
ademariag/kapitan
kapitan/inputs/jinja2.py
Python
apache-2.0
2,025
0.001481
#!/usr/bin/env python3 # Copyright 2019 The Kapitan Authors # SPDX-FileCopyrightText: 2020 The Kapitan Authors <kapitan-admins@googlegroups.com> # # SPDX-License-Identifier: Apache-2.0 import logging import os from kapitan.inputs.base import CompiledFile, InputType from kapitan.resources import inventory from kapita...
arch_paths, ref_controller) def compile_file(self, file_path, compile_path, ext_vars, **kwargs): """ Write items in path as jinja2 rendered files to compile_path. path can be either a file or directory. kwargs: reveal: default False, set to reveal refs on compile ...
target_name = kwargs.get("target_name", None) # set ext_vars and inventory for jinja2 context context = ext_vars.copy() context["inventory"] = inventory(self.search_paths, target_name) context["inventory_global"] = inventory(self.search_paths, None) jinja2_filters = kwargs.get("...
dims/heat
heat/objects/stack.py
Python
apache-2.0
7,744
0
# Copyright 2014 Intel Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.o
rg/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations...
om oslo_versionedobjects import fields from heat.common import exception from heat.common.i18n import _ from heat.db import api as db_api from heat.objects import base as heat_base from heat.objects import fields as heat_fields from heat.objects import raw_template from heat.objects import stack_tag class Stack( ...
nyu-mhealth/project-smsurvey
plugins/schedule_plugin/manage.py
Python
gpl-3.0
258
0
#!/usr/bin/env python import os import sys if __n
ame__ == "__main__": os.environ.setdefault("DJAN
GO_SETTINGS_MODULE", "schedule_plugin.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
rjschwei/azure-sdk-for-python
azure-mgmt-datalake-store/setup.py
Python
mit
2,242
0.001338
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #----------------------------------------------------------------...
ver = azure.__version__ raise Exception( 'This package is incompatible with azure=={}. '.format(ver) + 'Uninstall it with "pip uninstall azure".' ) except AttributeErr
or: pass except ImportError: pass # Version extraction inspired from 'requests' with open('azure/mgmt/datalake/store/version.py', 'r') as fd: version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) with open('README.rst', encoding='utf-8') a...
mindbender-studio/core
avalon/tools/views.py
Python
mit
504
0
from ..vendor.Qt import QtWidgets, QtCore class DeselectableTreeView(QtWidgets.QTreeView): """A tree view that deselects on clicking on an e
mpty area in the view""" def mousePressEvent(self, event): index = self.indexAt(event.pos()) if not index.isValid(): # clear the selection self.clearSelection() # clear the current index self.setCurrentIndex(QtCore.QM
odelIndex()) QtWidgets.QTreeView.mousePressEvent(self, event)
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/dnsserver/DNS_RPC_FORWARDERS_LONGHORN.py
Python
gpl-2.0
1,128
0.007979
# encoding: utf-8 # module samba.dcerpc.dnsserver # from /usr/lib/python2.7/dist-packages/samba/dcerpc/dnsserver.so # by generator 1.135 """ dnsserver DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class DNS_RPC_FORWARDERS_LONGHORN(__talloc.Object): # no doc def __init__(self, *arg...
Forwarders = property(lambda self: object(), lambda self, v: None, lambda self: None) # default dwForwardTimeout = property
(lambda self: object(), lambda self, v: None, lambda self: None) # default dwReserved0 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default dwRpcStructureVersion = property(lambda self: object(), lambda self, v: None, lambda self: None) # default fRecurseAfterForwarding...
dzeban/jrnl
jrnl/exporters.py
Python
mit
4,046
0.001977
#!/usr/bin/env python # encoding: utf-8 from __future__ import absolute_import, unicode_literals import os import json from .util import u, slugify import codecs def get_tags_count(journal): """Returns a set of tuples (count, tag) for all tags present in the journal.""" # Astute reader: should the following ...
make_filename(e)) if format == 'json': content = json.dumps(e.to_dict(), indent=2) + "\n" elif format in ('md', 'markdown'): content = e.to_md() elif format in ('txt', 'text'): content = e.__unicode__() with codecs.open(full_path, "w", "utf-8") as f: ...
{0}]".format(path)
Laurawly/tvm-1
tests/python/unittest/test_tir_analysis_calculate_workspace.py
Python
apache-2.0
8,017
0.003617
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
http:
//www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permission...
sebadiaz/rethinkdb
drivers/python/rethinkdb/ast.py
Python
agpl-3.0
43,683
0.000183
# Copyright 2010-2015 RethinkDB, all rights reserved. __all__ = ['expr', 'RqlQuery'] import datetime import collections import base64 import binascii import json as py_json import threading from .errors import RqlDriverError, QueryPrinter, T from . import ql2_pb2 as p pTerm = p.Term.TermType try: unicode excep...
object without timezone information. You can add timezone information with the third party module \"pytz\" or by constructing ReQL compatible timezone values with r.make_timezone(\"[+-]HH:MM\"). Alternatively, use one of ReQL's bultin time constructors, r.now, r.time, ...
val.isoformat()) elif isinstance(val, RqlBinary): return Binary(val) elif isinstance(val, (str, unicode)): return Datum(val) elif isinstance(val, bytes): return Binary(val) elif isinstance(val, collections.Mapping): # MakeObj doesn't take the dict as a keyword args to avo...
wezu/Avolition
naive_editor.py
Python
gpl-3.0
14,742
0.020554
# Nameless A.I. Version E editor from panda3d.core import * from direct.showbase.DirectObject import DirectObject import direct.directbase.DirectStart from direct.gui.DirectGui import * import json from dijkstra2 import Graph from vis_ninth import VisibilityPolygon from direct.gui.OnscreenText import OnscreenText impor...
ypoints[-1].setPos(wp.getPos(render)) #collision_poly.show() #export_node.writeBamFile('map2.bam') export_node.reparentTo(render) self.run_collisions() #we can build the graph data only after collisons graph_
data={} for i in range(len(waypoints)): graph_data[str(i)]={} for item in self.waypoints_connections[i]: distance=waypoints[i].getDistance(waypoints[int(item)]) #print distance graph_data[str(i)][item]=round(distance, 2) ...
Zahajamaan/Fudulbank
exams/migrations/0083_add_default_theme.py
Python
agpl-3.0
1,500
0.006667
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-24 19:13 from __future__ import unicode_literals from django.db import migrations def add_theme(apps, schema_editor): SessionTheme = apps.get_model('exams', 'SessionTheme') SessionTheme.objects.get_or_create(name="Ocean", ...
lass Migration(migrations.Migration): dependencies = [ ('exams', '0082_session_theme'),
] operations = [ migrations.RunPython(add_theme, reverse_code=delete_theme) ]
bretlowery/snakr
lib/django/core/servers/basehttp.py
Python
bsd-3-clause
7,315
0.000273
""" HTTP server that implements the Python WSGI protocol (PEP 333, rev 1.21). Based on wsgiref.simple_server which is part of the standard library since 2.5. This is a simple server for use in testing or debugging Django apps. It hasn't been reviewed for security issues. DON'T USE IT FOR PRODUCTION USE! """ from __f...
elf.parse_request(): # An error code has been sent, just exit return handler = ServerHandler( self.rfile, self.wfile, self.get_stderr(), self.get_environ() ) handler.request_handler = self # backpointer for logging handler.run(self.server.get_app()) def r...
ading=False): server_address = (addr, port) if threading: httpd_cls = type(str('WSGIServer'), (socketserver.ThreadingMixIn, WSGIServer), {}) else: httpd_cls = WSGIServer httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) if threading: # ThreadingMixIn.daemon_thr...
edespino/gpdb
src/test/tinc/tincrepo/mpp/gpdb/tests/storage/walrepl/run/test_gpstart.py
Python
apache-2.0
2,220
0.000901
""" Copyright (c) 2004-Present Pivotal Software, Inc. This program and the accompanying materials are made available under the terms of the under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache....
ld bring up the standby, too. cmd = Command("gpstart", "gpstart -a") cmd.run() self.assertTrue(cm
d.get_results().rc in (0, 1), str(cmd)) # wait for the standby to connect to the primary num_walsender = self.wait_for_walsender() self.assertEqual(num_walsender, 1) # make sure pg_ctl also agrees it's running cmd = Command("pg_ctl status", "pg_ctl status ...
bwall/bamfdetect
BAMF_Detect/__init__.py
Python
mit
9,344
0.00214
from sys import path import BAMF_Detect.modules import BAMF_Detect.modules.common import BAMF_Detect.preprocessors.common import BAMF_Detect.postprocessors.common from os.path import isfile, isdir, join, abspath, dirname, getsize from os import write, close, remove from pefile import PE from glob import iglob from zipf...
read() r = scan_file_data(file_content, module_filter, only_detect) if r is not None: if is_temp_file: yield None, r else: yield file_
path, r # async scanning variables result_queue = Queue.Queue() count_lock = threading.RLock() count_queued = 0 count_finished = 0 def async_handle_file(file_path, module_filter, only_detect): global count_lock, count_finished, result_queue try: for fp, r in handle_file(file_path, module_filter, only...
denismakogon/aria-cli
aria_cli/commands/init.py
Python
apache-2.0
1,869
0
# Copyright (c) 2016 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Un...
if not reset_config: msg = 'Current directory is already initialized' error = exceptions.AriaCliError(msg) error.possible_solutions = [ "Run 'aria init -p [path-to-a-blueprint]' " "to force re-initialization " "(might overwrite e...
] raise error else: shutil.rmtree(os.path.join( utils.get_cwd(), constants.ARIA_WD_SETTINGS_DIRECTORY_NAME)) settings = utils.AriaWorkingDirectorySettings() utils.dump_aria_working_dir_settings(settings) utils.dump_configuration_fi...
zbqf109/goodo
openerp/addons/stock/stock.py
Python
gpl-3.0
290,468
0.005539
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import date, datetime from dateutil import relativedelta import json import time import sets import openerp from openerp.osv import fields, osv from openerp.tools.float_utils import float_compare, float_ro...
'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'), 'child_ids': fields.one2many('stock.location', 'location_id',
'Contains'), 'partner_id': fields.many2one('res.partner', 'Owner', help="Owner of the location if not internal"), 'comment': fields.text('Additional Information'), 'posx': fields.integer('Corridor (X)', help="Optional localization details, for information purpose only"), 'posy': fields...
ctools/ctools
test/test_python_ctools.py
Python
gpl-3.0
4,967
0.004228
#! /usr/bin/env python # ========================================================================== # This scripts performs unit tests for the ctools package # # Copyright (C) 2012-2017 Juergen Knoedlseder # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General P...
abase to the one s
hipped with the # package; we don't need to set the 'TEST_DATA', this is done by the # test environment else: os.environ['CALDB'] = '%s/caldb' % (os.environ['TEST_SRCDIR']) # Create a local "pfiles" directory and set PFILES environment variable try: os.mkdir('pfiles') except: ...
savex/spectra
tools/salt_networks.py
Python
apache-2.0
2,298
0.003916
import re import sys import subprocess import json def shell(command): _ps = subprocess.Popen( command.split(), stdout=subprocess.PIPE ).communicate()[0].decode() return _ps def cut_option(_param, _options_list): _option = "n/a" _result_list = [] if _param in _options_list: ...
rn _option, _result_list def get_ifs_data(): _ifs_raw = shell('ip a') if_start = re.compile("^[0-9]+: .*: \<.*\> .*$") if_ipv4 = re.compile("^\s{4}inet\ .*$") _ifs = {} _if_name = None for line in _ifs_raw.splitlines(): _if_data = {} if if_start.match(line):
_tmp = line.split(':') _if_name = _tmp[1].strip() _if_options = _tmp[2].strip().split(' ') _if_data['order'] = _tmp[0] _if_data['mtu'], _if_options = cut_option("mtu", _if_options) _if_data['qlen'], _if_options = cut_option("qlen", _if_options) _if...
quater/calico-containers
calico_node/filesystem/startup.py
Python
apache-2.0
11,293
0.000266
# Copyright (c) 2016 Tigera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
P address %s. Calico requires each " \ "compute host to have a unique hostname. " \ "If this is your first time running " \ "the Calico node on this host, ensure " \ "that another host is not alre...
): ip = os.getenv("IP") ip = ip or None if ip and not netaddr.valid_ipv4(ip): print "IP environment (%s) is not a valid IPv4 address." % ip sys.exit(1)
csparpa/robograph
robograph/datamodel/tests/test_console_printer.py
Python
apache-2.0
554
0.001805
from robograph.datamodel.no
des.lib import printer def test_requirements(): expected = ['message'] instance = printer.ConsolePrinter() assert instance.requirements == expected def test_input(): msg =
'Hello world' instance = printer.ConsolePrinter() instance.input(dict(message=msg)) instance.set_output_label('any') assert instance.output() == msg def test_output(): msg = 'Hello world' instance = printer.ConsolePrinter(message=msg) instance.set_output_label('any') assert instance.ou...
kinshuk4/MoocX
misc/deep_learning_notes/pytorch_playground/attention-networks/test.py
Python
mit
114
0.008772
import time import sys
for i in range(10): sys.stdout.write
(str(i)) sys.stdout.flush() time.sleep(0.5)
PaulSonOfLars/tgbot
tg_bot/modules/notes.py
Python
gpl-3.0
11,067
0.003705
import re from io import BytesIO from typing import Optional, List from telegram import MAX_MESSAGE_LENGTH, ParseMode, InlineKeyboardMarkup from telegram import Message, Update, Bot from telegram.error import BadRequest from telegram.ext import CommandHandler, RegexHandler from telegram.ext.dispatcher import run_async...
except BadRequest as excp: if excp.message == "Entity_mention_user_invalid": message.reply_text("Looks like you tried to mention someone I've never seen before. If you really " "want to mention them, forward one of t
heir messages to me, and I'll be able " "to tag them!") elif FILE_MATCHER.match(note.value): message.reply_text("This note was an incorrectly imported file from another bot - I can't use " "it. If you reall...
CERNDocumentServer/invenio
modules/webstyle/lib/webdoc_webinterface.py
Python
gpl-2.0
9,639
0.005498
# This file is part of Invenio. # Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later v...
cking Pages")} navtrails = {'admin': '<a class="navtrail" href="%s/help/admin%s">%s</a>' % \ (CFG_SITE_URL, ln_link, _("Admin Area")), 'help': '<a class="navtrail" href="%s/help/%s">%s</a>'
% \ (CFG_SITE_URL, ln_link, _("Help Central")), 'hacking': '<a class="navtrail" href="%s/help/hacking%s">%s</a>' % \ (CFG_SITE_URL, ln_link, _("Hacking Invenio"))} body = '''<div style="float:right;clear:none;font-size:small;color:#666;width:auto;m...
probml/pyprobml
scripts/dummy.py
Python
mit
6,950
0.001439
# Online training of a logistic regression model # using Assumed Density Filtering (ADF). # We compare the ADF result with MCMC sampling # of the posterior distribution # Dependencies: # !pip install git+https://github.com/blackjax-devs/blackjax.git # !pip install jax_cosmo # Author: Gerardo Durán-Martín (@gerdm)...
lot_posterior_predictive(ax, X, Z_adf, title, colors) pml.savefig("laplace-logreg-predictive-surface.pdf") fig, ax = plt.subplots() t
itle = "(ADF) Predictive distribution" plot_posterior_predictive(ax, X, Z_adf, title, colors) pml.savefig("adf-logreg-predictive-surface.pdf") # ** Plotting training history ** w_batch_all = chains.mean(axis=0) w_batch_std_all = chains.std(axis=0) timesteps = jnp.arange(n_datapoints) lcolors = ["black", "tab:blue", "t...