body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
def ValidateSingleFile(input_api, output_api, file_obj, cwd, results): 'Does corresponding validations if histograms.xml or enums.xml is changed.\n\n Args:\n input_api: An input_api instance that contains information about changes.\n output_api: An output_api instance to create results of the PRESUBMIT check...
8,915,752,243,759,788,000
Does corresponding validations if histograms.xml or enums.xml is changed. Args: input_api: An input_api instance that contains information about changes. output_api: An output_api instance to create results of the PRESUBMIT check. file_obj: A file object of one of the changed files. cwd: Path to current workin...
tools/metrics/histograms/PRESUBMIT.py
ValidateSingleFile
Ron423c/chromium
python
def ValidateSingleFile(input_api, output_api, file_obj, cwd, results): 'Does corresponding validations if histograms.xml or enums.xml is changed.\n\n Args:\n input_api: An input_api instance that contains information about changes.\n output_api: An output_api instance to create results of the PRESUBMIT check...
def CheckChange(input_api, output_api): 'Checks that histograms.xml is pretty-printed and well-formatted.' results = [] cwd = input_api.PresubmitLocalPath() xml_changed = False for file_obj in input_api.AffectedTextFiles(): is_changed = ValidateSingleFile(input_api, output_api, file_obj, cwd...
-6,462,003,374,697,380,000
Checks that histograms.xml is pretty-printed and well-formatted.
tools/metrics/histograms/PRESUBMIT.py
CheckChange
Ron423c/chromium
python
def CheckChange(input_api, output_api): results = [] cwd = input_api.PresubmitLocalPath() xml_changed = False for file_obj in input_api.AffectedTextFiles(): is_changed = ValidateSingleFile(input_api, output_api, file_obj, cwd, results) xml_changed = (xml_changed or is_changed) i...
def test_randomizer_basic(self): '\n Test functionality of basic randomizer.\n ' randomizer = EnvParameterRandomizer(DummyEnvParameter()) assert (len(randomizer.get_parameters()) == 3) with self.assertRaises(AssertionError): randomizer.register_parameter(DummyRandomizerParameter('a...
6,277,896,458,699,098,000
Test functionality of basic randomizer.
robogym/randomization/tests/test_randomization.py
test_randomizer_basic
0xflotus/robogym
python
def test_randomizer_basic(self): '\n \n ' randomizer = EnvParameterRandomizer(DummyEnvParameter()) assert (len(randomizer.get_parameters()) == 3) with self.assertRaises(AssertionError): randomizer.register_parameter(DummyRandomizerParameter('a', 1)) randomizer.register_paramete...
def __init__(self, model, name=None, category=None, endpoint=None, url=None, static_folder=None, menu_class_name=None, menu_icon_type=None, menu_icon_value=None): '\n Constructor\n\n :param model:\n Model class\n :param name:\n Display name\n ...
-1,822,298,911,502,670,000
Constructor :param model: Model class :param name: Display name :param category: Display category :param endpoint: Endpoint :param url: Custom URL :param menu_class_name: Optional class name for the menu item. :param menu_icon_type: Optional icon. Possible icon types: - `flask_admin.c...
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
__init__
hexlism/css_platform
python
def __init__(self, model, name=None, category=None, endpoint=None, url=None, static_folder=None, menu_class_name=None, menu_icon_type=None, menu_icon_value=None): '\n Constructor\n\n :param model:\n Model class\n :param name:\n Display name\n ...
def _refresh_cache(self): '\n Refresh cache.\n ' if (self.form_subdocuments is None): self.form_subdocuments = {} self._form_subdocuments = convert_subdocuments(self.form_subdocuments) super(ModelView, self)._refresh_cache()
3,943,640,994,616,751,000
Refresh cache.
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
_refresh_cache
hexlism/css_platform
python
def _refresh_cache(self): '\n \n ' if (self.form_subdocuments is None): self.form_subdocuments = {} self._form_subdocuments = convert_subdocuments(self.form_subdocuments) super(ModelView, self)._refresh_cache()
def _process_ajax_references(self): '\n AJAX endpoint is exposed by top-level admin view class, but\n subdocuments might have AJAX references too.\n\n This method will recursively go over subdocument configuration\n and will precompute AJAX references for them ensuring th...
6,137,773,626,474,018,000
AJAX endpoint is exposed by top-level admin view class, but subdocuments might have AJAX references too. This method will recursively go over subdocument configuration and will precompute AJAX references for them ensuring that subdocuments can also use AJAX to populate their ReferenceFields.
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
_process_ajax_references
hexlism/css_platform
python
def _process_ajax_references(self): '\n AJAX endpoint is exposed by top-level admin view class, but\n subdocuments might have AJAX references too.\n\n This method will recursively go over subdocument configuration\n and will precompute AJAX references for them ensuring th...
def _get_model_fields(self, model=None): '\n Inspect model and return list of model fields\n\n :param model:\n Model to inspect\n ' if (model is None): model = self.model return sorted(iteritems(model._fields), key=(lambda n: n[1].creation_counter))
707,176,458,598,894,100
Inspect model and return list of model fields :param model: Model to inspect
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
_get_model_fields
hexlism/css_platform
python
def _get_model_fields(self, model=None): '\n Inspect model and return list of model fields\n\n :param model:\n Model to inspect\n ' if (model is None): model = self.model return sorted(iteritems(model._fields), key=(lambda n: n[1].creation_counter))
def get_pk_value(self, model): '\n Return the primary key value from the model instance\n\n :param model:\n Model instance\n ' return model.pk
3,359,469,410,447,919,600
Return the primary key value from the model instance :param model: Model instance
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
get_pk_value
hexlism/css_platform
python
def get_pk_value(self, model): '\n Return the primary key value from the model instance\n\n :param model:\n Model instance\n ' return model.pk
def scaffold_list_columns(self): '\n Scaffold list columns\n ' columns = [] for (n, f) in self._get_model_fields(): field_class = type(f) if ((field_class == mongoengine.ListField) and isinstance(f.field, mongoengine.EmbeddedDocumentField)): continue if ...
-1,257,183,833,292,583,000
Scaffold list columns
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
scaffold_list_columns
hexlism/css_platform
python
def scaffold_list_columns(self): '\n \n ' columns = [] for (n, f) in self._get_model_fields(): field_class = type(f) if ((field_class == mongoengine.ListField) and isinstance(f.field, mongoengine.EmbeddedDocumentField)): continue if (field_class == mongo...
def scaffold_sortable_columns(self): '\n Return a dictionary of sortable columns (name, field)\n ' columns = {} for (n, f) in self._get_model_fields(): if (type(f) in SORTABLE_FIELDS): if (self.column_display_pk or (type(f) != mongoengine.ObjectIdField)): ...
-1,914,602,255,142,035,000
Return a dictionary of sortable columns (name, field)
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
scaffold_sortable_columns
hexlism/css_platform
python
def scaffold_sortable_columns(self): '\n \n ' columns = {} for (n, f) in self._get_model_fields(): if (type(f) in SORTABLE_FIELDS): if (self.column_display_pk or (type(f) != mongoengine.ObjectIdField)): columns[n] = f return columns
def init_search(self): '\n Init search\n ' if self.column_searchable_list: for p in self.column_searchable_list: if isinstance(p, string_types): p = self.model._fields.get(p) if (p is None): raise Exception('Invalid search field')...
-2,954,653,945,820,696,600
Init search
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
init_search
hexlism/css_platform
python
def init_search(self): '\n \n ' if self.column_searchable_list: for p in self.column_searchable_list: if isinstance(p, string_types): p = self.model._fields.get(p) if (p is None): raise Exception('Invalid search field') ...
def scaffold_filters(self, name): '\n Return filter object(s) for the field\n\n :param name:\n Either field name or field instance\n ' if isinstance(name, string_types): attr = self.model._fields.get(name) else: attr = name if (attr is None): ...
-1,826,513,185,149,695,500
Return filter object(s) for the field :param name: Either field name or field instance
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
scaffold_filters
hexlism/css_platform
python
def scaffold_filters(self, name): '\n Return filter object(s) for the field\n\n :param name:\n Either field name or field instance\n ' if isinstance(name, string_types): attr = self.model._fields.get(name) else: attr = name if (attr is None): ...
def is_valid_filter(self, filter): '\n Validate if the provided filter is a valid MongoEngine filter\n\n :param filter:\n Filter object\n ' return isinstance(filter, BaseMongoEngineFilter)
-6,644,047,060,746,446,000
Validate if the provided filter is a valid MongoEngine filter :param filter: Filter object
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
is_valid_filter
hexlism/css_platform
python
def is_valid_filter(self, filter): '\n Validate if the provided filter is a valid MongoEngine filter\n\n :param filter:\n Filter object\n ' return isinstance(filter, BaseMongoEngineFilter)
def scaffold_form(self): '\n Create form from the model.\n ' form_class = get_form(self.model, self.model_form_converter(self), base_class=self.form_base_class, only=self.form_columns, exclude=self.form_excluded_columns, field_args=self.form_args, extra_fields=self.form_extra_fields) retur...
-5,255,561,762,624,256,000
Create form from the model.
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
scaffold_form
hexlism/css_platform
python
def scaffold_form(self): '\n \n ' form_class = get_form(self.model, self.model_form_converter(self), base_class=self.form_base_class, only=self.form_columns, exclude=self.form_excluded_columns, field_args=self.form_args, extra_fields=self.form_extra_fields) return form_class
def scaffold_list_form(self, custom_fieldlist=ListEditableFieldList, validators=None): "\n Create form for the `index_view` using only the columns from\n `self.column_editable_list`.\n\n :param validators:\n `form_args` dict with only validators\n {'nam...
1,362,413,955,699,600,400
Create form for the `index_view` using only the columns from `self.column_editable_list`. :param validators: `form_args` dict with only validators {'name': {'validators': [required()]}} :param custom_fieldlist: A WTForm FieldList class. By default, `ListEditableFieldList`.
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
scaffold_list_form
hexlism/css_platform
python
def scaffold_list_form(self, custom_fieldlist=ListEditableFieldList, validators=None): "\n Create form for the `index_view` using only the columns from\n `self.column_editable_list`.\n\n :param validators:\n `form_args` dict with only validators\n {'nam...
def get_query(self): '\n Returns the QuerySet for this view. By default, it returns all the\n objects for the current model.\n ' return self.model.objects
-4,986,645,289,561,858,000
Returns the QuerySet for this view. By default, it returns all the objects for the current model.
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
get_query
hexlism/css_platform
python
def get_query(self): '\n Returns the QuerySet for this view. By default, it returns all the\n objects for the current model.\n ' return self.model.objects
def get_list(self, page, sort_column, sort_desc, search, filters, execute=True): '\n Get list of objects from MongoEngine\n\n :param page:\n Page number\n :param sort_column:\n Sort column\n :param sort_desc:\n Sort descending\...
-6,554,609,987,189,399,000
Get list of objects from MongoEngine :param page: Page number :param sort_column: Sort column :param sort_desc: Sort descending :param search: Search criteria :param filters: List of applied filters :param execute: Run query immediately or not
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
get_list
hexlism/css_platform
python
def get_list(self, page, sort_column, sort_desc, search, filters, execute=True): '\n Get list of objects from MongoEngine\n\n :param page:\n Page number\n :param sort_column:\n Sort column\n :param sort_desc:\n Sort descending\...
def get_one(self, id): '\n Return a single model instance by its ID\n\n :param id:\n Model ID\n ' try: return self.get_query().filter(pk=id).first() except mongoengine.ValidationError as ex: flash(gettext('Failed to get model. %(error)s', error=for...
7,872,424,681,330,008,000
Return a single model instance by its ID :param id: Model ID
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
get_one
hexlism/css_platform
python
def get_one(self, id): '\n Return a single model instance by its ID\n\n :param id:\n Model ID\n ' try: return self.get_query().filter(pk=id).first() except mongoengine.ValidationError as ex: flash(gettext('Failed to get model. %(error)s', error=for...
def create_model(self, form): '\n Create model helper\n\n :param form:\n Form instance\n ' try: model = self.model() form.populate_obj(model) self._on_model_change(form, model, True) model.save() except Exception as ex: if (...
903,978,773,780,675,300
Create model helper :param form: Form instance
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
create_model
hexlism/css_platform
python
def create_model(self, form): '\n Create model helper\n\n :param form:\n Form instance\n ' try: model = self.model() form.populate_obj(model) self._on_model_change(form, model, True) model.save() except Exception as ex: if (...
def update_model(self, form, model): '\n Update model helper\n\n :param form:\n Form instance\n :param model:\n Model instance to update\n ' try: form.populate_obj(model) self._on_model_change(form, model, False) model...
764,570,345,739,556,700
Update model helper :param form: Form instance :param model: Model instance to update
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
update_model
hexlism/css_platform
python
def update_model(self, form, model): '\n Update model helper\n\n :param form:\n Form instance\n :param model:\n Model instance to update\n ' try: form.populate_obj(model) self._on_model_change(form, model, False) model...
def delete_model(self, model): '\n Delete model helper\n\n :param model:\n Model instance\n ' try: self.on_model_delete(model) model.delete() except Exception as ex: if (not self.handle_view_exception(ex)): flash(gettext('Failed...
3,090,824,996,892,932,000
Delete model helper :param model: Model instance
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
delete_model
hexlism/css_platform
python
def delete_model(self, model): '\n Delete model helper\n\n :param model:\n Model instance\n ' try: self.on_model_delete(model) model.delete() except Exception as ex: if (not self.handle_view_exception(ex)): flash(gettext('Failed...
def estimate(particles, weights): 'returns mean and variance of the weighted particles' pos = particles mean = np.average(pos, weights=weights, axis=0) var = np.average(((pos - mean) ** 2), weights=weights, axis=0) return (mean, var)
1,993,265,891,749,680,400
returns mean and variance of the weighted particles
002_Particle_Filter/Particle_Filter.py
estimate
zhyongquan/Automotive-Software-Blog
python
def estimate(particles, weights): pos = particles mean = np.average(pos, weights=weights, axis=0) var = np.average(((pos - mean) ** 2), weights=weights, axis=0) return (mean, var)
def test_builder_is_pickled(self): 'Unlike most tree builders, HTMLParserTreeBuilder and will\n be restored after pickling.\n ' tree = self.soup('<a><b>foo</a>') dumped = pickle.dumps(tree, 2) loaded = pickle.loads(dumped) self.assertTrue(isinstance(loaded.builder, type(tree.builder)))
-6,423,651,160,975,675,000
Unlike most tree builders, HTMLParserTreeBuilder and will be restored after pickling.
virtual/lib/python3.6/site-packages/bs4/tests/test_htmlparser.py
test_builder_is_pickled
AG371/bus-reservation-system
python
def test_builder_is_pickled(self): 'Unlike most tree builders, HTMLParserTreeBuilder and will\n be restored after pickling.\n ' tree = self.soup('<a><b>foo</a>') dumped = pickle.dumps(tree, 2) loaded = pickle.loads(dumped) self.assertTrue(isinstance(loaded.builder, type(tree.builder)))
def test_error(self): "Verify that our HTMLParser subclass implements error() in a way\n that doesn't cause a crash.\n " parser = BeautifulSoupHTMLParser() parser.error("don't crash")
-6,519,268,211,641,346,000
Verify that our HTMLParser subclass implements error() in a way that doesn't cause a crash.
virtual/lib/python3.6/site-packages/bs4/tests/test_htmlparser.py
test_error
AG371/bus-reservation-system
python
def test_error(self): "Verify that our HTMLParser subclass implements error() in a way\n that doesn't cause a crash.\n " parser = BeautifulSoupHTMLParser() parser.error("don't crash")
async def async_setup_entry(hass, config_entry, async_add_entities): 'Set up the inverter select entities from a config entry.' inverter = hass.data[DOMAIN][config_entry.entry_id][KEY_INVERTER] device_info = hass.data[DOMAIN][config_entry.entry_id][KEY_DEVICE_INFO] entities = [] for description in N...
-6,143,632,953,803,178,000
Set up the inverter select entities from a config entry.
homeassistant/components/goodwe/number.py
async_setup_entry
kubawolanin/core
python
async def async_setup_entry(hass, config_entry, async_add_entities): inverter = hass.data[DOMAIN][config_entry.entry_id][KEY_INVERTER] device_info = hass.data[DOMAIN][config_entry.entry_id][KEY_DEVICE_INFO] entities = [] for description in NUMBERS: try: current_value = (await de...
def __init__(self, device_info: DeviceInfo, description: GoodweNumberEntityDescription, inverter: Inverter, current_value: int) -> None: 'Initialize the number inverter setting entity.' self.entity_description = description self._attr_unique_id = f'{DOMAIN}-{description.key}-{inverter.serial_number}' se...
-6,500,139,910,043,170,000
Initialize the number inverter setting entity.
homeassistant/components/goodwe/number.py
__init__
kubawolanin/core
python
def __init__(self, device_info: DeviceInfo, description: GoodweNumberEntityDescription, inverter: Inverter, current_value: int) -> None: self.entity_description = description self._attr_unique_id = f'{DOMAIN}-{description.key}-{inverter.serial_number}' self._attr_device_info = device_info self._att...
async def async_set_value(self, value: float) -> None: 'Set new value.' if self.entity_description.setter: (await self.entity_description.setter(self._inverter, int(value))) self._attr_value = value self.async_write_ha_state()
6,044,406,391,341,202,000
Set new value.
homeassistant/components/goodwe/number.py
async_set_value
kubawolanin/core
python
async def async_set_value(self, value: float) -> None: if self.entity_description.setter: (await self.entity_description.setter(self._inverter, int(value))) self._attr_value = value self.async_write_ha_state()
@runnable def run_targets(*args): 'Run targets for Python.' Options.show_coverage = ('coverage' in args) count = 0 for (count, (command, title, retry)) in enumerate(Options.targets, start=1): success = call(command, title, retry) if (not success): message = (('✅ ' * (count - ...
-73,758,141,938,422,160
Run targets for Python.
scent.py
run_targets
EazeAI/AI-WS
python
@runnable def run_targets(*args): Options.show_coverage = ('coverage' in args) count = 0 for (count, (command, title, retry)) in enumerate(Options.targets, start=1): success = call(command, title, retry) if (not success): message = (('✅ ' * (count - 1)) + '❌') sh...
def call(command, title, retry): 'Run a command-line program and display the result.' if Options.rerun_args: (command, title, retry) = Options.rerun_args Options.rerun_args = None success = call(command, title, retry) if (not success): return False print('') p...
3,937,803,438,086,842,000
Run a command-line program and display the result.
scent.py
call
EazeAI/AI-WS
python
def call(command, title, retry): if Options.rerun_args: (command, title, retry) = Options.rerun_args Options.rerun_args = None success = call(command, title, retry) if (not success): return False print() print(('$ %s' % ' '.join(command))) failure = subpr...
def show_notification(message, title): 'Show a user notification.' if (notify and title): notify(message, title=title, group=Options.group)
1,002,222,407,043,525,500
Show a user notification.
scent.py
show_notification
EazeAI/AI-WS
python
def show_notification(message, title): if (notify and title): notify(message, title=title, group=Options.group)
def show_coverage(): 'Launch the coverage report.' if Options.show_coverage: subprocess.call(['make', 'read-coverage']) Options.show_coverage = False
2,950,738,002,091,552,300
Launch the coverage report.
scent.py
show_coverage
EazeAI/AI-WS
python
def show_coverage(): if Options.show_coverage: subprocess.call(['make', 'read-coverage']) Options.show_coverage = False
def download_scripts(destination_dir: Path=Path('ptlflow_scripts')) -> None: 'Download the main scripts and configs to start working with PTLFlow.' github_url = 'https://raw.githubusercontent.com/hmorimitsu/ptlflow/main/' script_names = ['datasets.yml', 'infer.py', 'test.py', 'train.py', 'validate.py'] ...
-5,417,779,943,224,005,000
Download the main scripts and configs to start working with PTLFlow.
ptlflow/__init__.py
download_scripts
hmorimitsu/ptlflow
python
def download_scripts(destination_dir: Path=Path('ptlflow_scripts')) -> None: github_url = 'https://raw.githubusercontent.com/hmorimitsu/ptlflow/main/' script_names = ['datasets.yml', 'infer.py', 'test.py', 'train.py', 'validate.py'] destination_dir.mkdir(parents=True, exist_ok=True) for sname in sc...
def get_model(model_name: str, pretrained_ckpt: Optional[str]=None, args: Optional[Namespace]=None) -> BaseModel: 'Return an instance of a chosen model.\n\n The instance can have configured by he arguments, and load some existing pretrained weights.\n\n Note that this is different from get_model_reference(), ...
-7,413,552,895,945,898,000
Return an instance of a chosen model. The instance can have configured by he arguments, and load some existing pretrained weights. Note that this is different from get_model_reference(), which returns a reference to the model class. The instance, returned by this function, is a class already instantiated. Therefore, ...
ptlflow/__init__.py
get_model
hmorimitsu/ptlflow
python
def get_model(model_name: str, pretrained_ckpt: Optional[str]=None, args: Optional[Namespace]=None) -> BaseModel: 'Return an instance of a chosen model.\n\n The instance can have configured by he arguments, and load some existing pretrained weights.\n\n Note that this is different from get_model_reference(), ...
def get_model_reference(model_name: str) -> BaseModel: 'Return a reference to the class of a chosen model.\n\n Note that this is different from get_model(), which returns an instance of a model. The reference, returned by this\n function, is a class before instantiation. Therefore, the return of this function...
-1,848,291,867,390,122,500
Return a reference to the class of a chosen model. Note that this is different from get_model(), which returns an instance of a model. The reference, returned by this function, is a class before instantiation. Therefore, the return of this function can be used to instantiate a model as "model_ref = get_model_reference...
ptlflow/__init__.py
get_model_reference
hmorimitsu/ptlflow
python
def get_model_reference(model_name: str) -> BaseModel: 'Return a reference to the class of a chosen model.\n\n Note that this is different from get_model(), which returns an instance of a model. The reference, returned by this\n function, is a class before instantiation. Therefore, the return of this function...
def get_trainable_model_names() -> List[str]: 'Return a list of model names that are able to be trained.\n \n This function return the names of the model that have a loss function defined.\n\n Returns\n =======\n List[str]\n The list of the model names that can be trained.\n ' return [m...
2,144,936,162,105,759,000
Return a list of model names that are able to be trained. This function return the names of the model that have a loss function defined. Returns ======= List[str] The list of the model names that can be trained.
ptlflow/__init__.py
get_trainable_model_names
hmorimitsu/ptlflow
python
def get_trainable_model_names() -> List[str]: 'Return a list of model names that are able to be trained.\n \n This function return the names of the model that have a loss function defined.\n\n Returns\n =======\n List[str]\n The list of the model names that can be trained.\n ' return [m...
def blackbody_specific_intensity(wl_nm, T_K): 'Get the monochromatic specific intensity for a blackbody -\n wl_nm = wavelength [nm]\n T_K = temperature [K]\n This is the energy radiated per second per unit wavelength per unit solid angle.\n Reference - Shu, eq. 4.6, p. 78.' a = ((PLANCK_CO...
2,590,742,495,800,728,600
Get the monochromatic specific intensity for a blackbody - wl_nm = wavelength [nm] T_K = temperature [K] This is the energy radiated per second per unit wavelength per unit solid angle. Reference - Shu, eq. 4.6, p. 78.
colorpy/colorpy-0.1.0/blackbody.py
blackbody_specific_intensity
gmweir/QuasiOptics
python
def blackbody_specific_intensity(wl_nm, T_K): 'Get the monochromatic specific intensity for a blackbody -\n wl_nm = wavelength [nm]\n T_K = temperature [K]\n This is the energy radiated per second per unit wavelength per unit solid angle.\n Reference - Shu, eq. 4.6, p. 78.' a = ((PLANCK_CO...
def blackbody_spectrum(T_K): 'Get the spectrum of a blackbody, as a numpy array.' spectrum = ciexyz.empty_spectrum() (num_rows, num_cols) = spectrum.shape for i in xrange(0, num_rows): specific_intensity = blackbody_specific_intensity(spectrum[i][0], T_K) spectrum[i][1] = ((specific_inte...
-4,814,021,675,059,225,000
Get the spectrum of a blackbody, as a numpy array.
colorpy/colorpy-0.1.0/blackbody.py
blackbody_spectrum
gmweir/QuasiOptics
python
def blackbody_spectrum(T_K): spectrum = ciexyz.empty_spectrum() (num_rows, num_cols) = spectrum.shape for i in xrange(0, num_rows): specific_intensity = blackbody_specific_intensity(spectrum[i][0], T_K) spectrum[i][1] = ((specific_intensity * ciexyz.delta_wl_nm) * 1e-09) return spec...
def blackbody_color(T_K): 'Given a temperature (K), return the xyz color of a thermal blackbody.' spectrum = blackbody_spectrum(T_K) xyz = ciexyz.xyz_from_spectrum(spectrum) return xyz
-5,026,878,936,742,433,000
Given a temperature (K), return the xyz color of a thermal blackbody.
colorpy/colorpy-0.1.0/blackbody.py
blackbody_color
gmweir/QuasiOptics
python
def blackbody_color(T_K): spectrum = blackbody_spectrum(T_K) xyz = ciexyz.xyz_from_spectrum(spectrum) return xyz
def blackbody_patch_plot(T_list, title, filename): 'Draw a patch plot of blackbody colors for the given temperature range.' xyz_colors = [] color_names = [] for Ti in T_list: xyz = blackbody_color(Ti) xyz_colors.append(xyz) name = ('%g K' % Ti) color_names.append(name) ...
687,483,277,840,238,200
Draw a patch plot of blackbody colors for the given temperature range.
colorpy/colorpy-0.1.0/blackbody.py
blackbody_patch_plot
gmweir/QuasiOptics
python
def blackbody_patch_plot(T_list, title, filename): xyz_colors = [] color_names = [] for Ti in T_list: xyz = blackbody_color(Ti) xyz_colors.append(xyz) name = ('%g K' % Ti) color_names.append(name) plots.xyz_patch_plot(xyz_colors, color_names, title, filename)
def blackbody_color_vs_temperature_plot(T_list, title, filename): 'Draw a color vs temperature plot for the given temperature range.' num_T = len(T_list) rgb_list = numpy.empty((num_T, 3)) for i in xrange(0, num_T): T_i = T_list[i] xyz = blackbody_color(T_i) rgb_list[i] = colormo...
3,642,871,054,975,440,400
Draw a color vs temperature plot for the given temperature range.
colorpy/colorpy-0.1.0/blackbody.py
blackbody_color_vs_temperature_plot
gmweir/QuasiOptics
python
def blackbody_color_vs_temperature_plot(T_list, title, filename): num_T = len(T_list) rgb_list = numpy.empty((num_T, 3)) for i in xrange(0, num_T): T_i = T_list[i] xyz = blackbody_color(T_i) rgb_list[i] = colormodels.rgb_from_xyz(xyz) plots.color_vs_param_plot(T_list, rgb_li...
def blackbody_spectrum_plot(T_K): 'Draw the spectrum of a blackbody at the given temperature.' spectrum = blackbody_spectrum(T_K) title = ('Blackbody Spectrum - T %d K' % int(T_K)) filename = ('BlackbodySpectrum-%dK' % int(T_K)) plots.spectrum_plot(spectrum, title, filename, xlabel='Wavelength (nm)'...
-2,097,509,183,976,489,700
Draw the spectrum of a blackbody at the given temperature.
colorpy/colorpy-0.1.0/blackbody.py
blackbody_spectrum_plot
gmweir/QuasiOptics
python
def blackbody_spectrum_plot(T_K): spectrum = blackbody_spectrum(T_K) title = ('Blackbody Spectrum - T %d K' % int(T_K)) filename = ('BlackbodySpectrum-%dK' % int(T_K)) plots.spectrum_plot(spectrum, title, filename, xlabel='Wavelength (nm)', ylabel='Specific Intensity')
def figures(): 'Create some blackbody plots.' T_list_0 = plots.log_interpolate(1200.0, 20000.0, 48) T_list_hot = plots.log_interpolate(10000.0, 40000.0, 24) T_list_cool = plots.log_interpolate(950.0, 1200.0, 24) blackbody_patch_plot(T_list_0, 'Blackbody Colors', 'Blackbody-Patch') blackbody_patc...
5,560,260,944,193,342,000
Create some blackbody plots.
colorpy/colorpy-0.1.0/blackbody.py
figures
gmweir/QuasiOptics
python
def figures(): T_list_0 = plots.log_interpolate(1200.0, 20000.0, 48) T_list_hot = plots.log_interpolate(10000.0, 40000.0, 24) T_list_cool = plots.log_interpolate(950.0, 1200.0, 24) blackbody_patch_plot(T_list_0, 'Blackbody Colors', 'Blackbody-Patch') blackbody_patch_plot(T_list_hot, 'Hot Blackb...
@cached_property def additional_properties_type(): '\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n ' lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type)
1,702,168,743,392,494,600
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
cryptoapis/model/coins_forwarding_success_data.py
additional_properties_type
Crypto-APIs/Crypto_APIs_2.0_SDK_Python
python
@cached_property def additional_properties_type(): '\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n ' lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type)
@cached_property def openapi_types(): '\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n ...
-2,012,564,197,808,641,800
This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type.
cryptoapis/model/coins_forwarding_success_data.py
openapi_types
Crypto-APIs/Crypto_APIs_2.0_SDK_Python
python
@cached_property def openapi_types(): '\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n ...
@classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, product, event, item, *args, **kwargs): 'CoinsForwardingSuccessData - a model defined in OpenAPI\n\n Args:\n product (str): Represents the Crypto APIs 2.0 product which sends the callback.\n event (str): Defines th...
-2,732,593,822,327,209,000
CoinsForwardingSuccessData - a model defined in OpenAPI Args: product (str): Represents the Crypto APIs 2.0 product which sends the callback. event (str): Defines the specific event, for which a callback subscription is set. item (CoinsForwardingSuccessDataItem): Keyword Args: _check_type (bool): if T...
cryptoapis/model/coins_forwarding_success_data.py
_from_openapi_data
Crypto-APIs/Crypto_APIs_2.0_SDK_Python
python
@classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, product, event, item, *args, **kwargs): 'CoinsForwardingSuccessData - a model defined in OpenAPI\n\n Args:\n product (str): Represents the Crypto APIs 2.0 product which sends the callback.\n event (str): Defines th...
@convert_js_args_to_python_args def __init__(self, product, event, item, *args, **kwargs): 'CoinsForwardingSuccessData - a model defined in OpenAPI\n\n Args:\n product (str): Represents the Crypto APIs 2.0 product which sends the callback.\n event (str): Defines the specific event, for ...
-791,863,898,841,504,600
CoinsForwardingSuccessData - a model defined in OpenAPI Args: product (str): Represents the Crypto APIs 2.0 product which sends the callback. event (str): Defines the specific event, for which a callback subscription is set. item (CoinsForwardingSuccessDataItem): Keyword Args: _check_type (bool): if T...
cryptoapis/model/coins_forwarding_success_data.py
__init__
Crypto-APIs/Crypto_APIs_2.0_SDK_Python
python
@convert_js_args_to_python_args def __init__(self, product, event, item, *args, **kwargs): 'CoinsForwardingSuccessData - a model defined in OpenAPI\n\n Args:\n product (str): Represents the Crypto APIs 2.0 product which sends the callback.\n event (str): Defines the specific event, for ...
def _activation_summary(x): 'Helper to create summaries for activations.\n\n Creates a summary that provides a histogram of activations.\n Creates a summary that measures the sparsity of activations.\n\n Args:\n x: Tensor\n Returns:\n nothing\n ' tensor_name = re.sub(('%s_[0-9]*/' % TOWER_NAME), '', ...
553,231,555,851,507,140
Helper to create summaries for activations. Creates a summary that provides a histogram of activations. Creates a summary that measures the sparsity of activations. Args: x: Tensor Returns: nothing
examples/cifar10/cifar10.py
_activation_summary
13927729580/TensorFlowOnSpark
python
def _activation_summary(x): 'Helper to create summaries for activations.\n\n Creates a summary that provides a histogram of activations.\n Creates a summary that measures the sparsity of activations.\n\n Args:\n x: Tensor\n Returns:\n nothing\n ' tensor_name = re.sub(('%s_[0-9]*/' % TOWER_NAME), , x....
def _variable_on_cpu(name, shape, initializer): 'Helper to create a Variable stored on CPU memory.\n\n Args:\n name: name of the variable\n shape: list of ints\n initializer: initializer for Variable\n\n Returns:\n Variable Tensor\n ' with tf.device('/cpu:0'): dtype = (tf.float16 if FLAGS...
2,365,013,275,469,490,700
Helper to create a Variable stored on CPU memory. Args: name: name of the variable shape: list of ints initializer: initializer for Variable Returns: Variable Tensor
examples/cifar10/cifar10.py
_variable_on_cpu
13927729580/TensorFlowOnSpark
python
def _variable_on_cpu(name, shape, initializer): 'Helper to create a Variable stored on CPU memory.\n\n Args:\n name: name of the variable\n shape: list of ints\n initializer: initializer for Variable\n\n Returns:\n Variable Tensor\n ' with tf.device('/cpu:0'): dtype = (tf.float16 if FLAGS...
def _variable_with_weight_decay(name, shape, stddev, wd): 'Helper to create an initialized Variable with weight decay.\n\n Note that the Variable is initialized with a truncated normal distribution.\n A weight decay is added only if one is specified.\n\n Args:\n name: name of the variable\n shape: list of ...
8,132,621,707,787,137,000
Helper to create an initialized Variable with weight decay. Note that the Variable is initialized with a truncated normal distribution. A weight decay is added only if one is specified. Args: name: name of the variable shape: list of ints stddev: standard deviation of a truncated Gaussian wd: add L2Loss weigh...
examples/cifar10/cifar10.py
_variable_with_weight_decay
13927729580/TensorFlowOnSpark
python
def _variable_with_weight_decay(name, shape, stddev, wd): 'Helper to create an initialized Variable with weight decay.\n\n Note that the Variable is initialized with a truncated normal distribution.\n A weight decay is added only if one is specified.\n\n Args:\n name: name of the variable\n shape: list of ...
def distorted_inputs(): 'Construct distorted input for CIFAR training using the Reader ops.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] size.\n\n Raises:\n ValueError: If no data_dir\n ' if (not FLAGS.data_dir)...
5,244,124,816,898,738,000
Construct distorted input for CIFAR training using the Reader ops. Returns: images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size. labels: Labels. 1D tensor of [batch_size] size. Raises: ValueError: If no data_dir
examples/cifar10/cifar10.py
distorted_inputs
13927729580/TensorFlowOnSpark
python
def distorted_inputs(): 'Construct distorted input for CIFAR training using the Reader ops.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] size.\n\n Raises:\n ValueError: If no data_dir\n ' if (not FLAGS.data_dir)...
def inputs(eval_data): 'Construct input for CIFAR evaluation using the Reader ops.\n\n Args:\n eval_data: bool, indicating if one should use the train or eval data set.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] si...
5,745,744,370,990,534,000
Construct input for CIFAR evaluation using the Reader ops. Args: eval_data: bool, indicating if one should use the train or eval data set. Returns: images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size. labels: Labels. 1D tensor of [batch_size] size. Raises: ValueError: If no data_dir
examples/cifar10/cifar10.py
inputs
13927729580/TensorFlowOnSpark
python
def inputs(eval_data): 'Construct input for CIFAR evaluation using the Reader ops.\n\n Args:\n eval_data: bool, indicating if one should use the train or eval data set.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] si...
def inference(images): 'Build the CIFAR-10 model.\n\n Args:\n images: Images returned from distorted_inputs() or inputs().\n\n Returns:\n Logits.\n ' with tf.variable_scope('conv1') as scope: kernel = _variable_with_weight_decay('weights', shape=[5, 5, 3, 64], stddev=0.05, wd=0.0) conv ...
4,760,979,126,026,873,000
Build the CIFAR-10 model. Args: images: Images returned from distorted_inputs() or inputs(). Returns: Logits.
examples/cifar10/cifar10.py
inference
13927729580/TensorFlowOnSpark
python
def inference(images): 'Build the CIFAR-10 model.\n\n Args:\n images: Images returned from distorted_inputs() or inputs().\n\n Returns:\n Logits.\n ' with tf.variable_scope('conv1') as scope: kernel = _variable_with_weight_decay('weights', shape=[5, 5, 3, 64], stddev=0.05, wd=0.0) conv ...
def loss(logits, labels): 'Add L2Loss to all the trainable variables.\n\n Add summary for "Loss" and "Loss/avg".\n Args:\n logits: Logits from inference().\n labels: Labels from distorted_inputs or inputs(). 1-D tensor\n of shape [batch_size]\n\n Returns:\n Loss tensor of type float.\n ' ...
2,034,962,917,631,843,600
Add L2Loss to all the trainable variables. Add summary for "Loss" and "Loss/avg". Args: logits: Logits from inference(). labels: Labels from distorted_inputs or inputs(). 1-D tensor of shape [batch_size] Returns: Loss tensor of type float.
examples/cifar10/cifar10.py
loss
13927729580/TensorFlowOnSpark
python
def loss(logits, labels): 'Add L2Loss to all the trainable variables.\n\n Add summary for "Loss" and "Loss/avg".\n Args:\n logits: Logits from inference().\n labels: Labels from distorted_inputs or inputs(). 1-D tensor\n of shape [batch_size]\n\n Returns:\n Loss tensor of type float.\n ' ...
def _add_loss_summaries(total_loss): 'Add summaries for losses in CIFAR-10 model.\n\n Generates moving average for all losses and associated summaries for\n visualizing the performance of the network.\n\n Args:\n total_loss: Total loss from loss().\n Returns:\n loss_averages_op: op for generating moving a...
3,010,989,842,750,706,000
Add summaries for losses in CIFAR-10 model. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for generating moving averages of losses.
examples/cifar10/cifar10.py
_add_loss_summaries
13927729580/TensorFlowOnSpark
python
def _add_loss_summaries(total_loss): 'Add summaries for losses in CIFAR-10 model.\n\n Generates moving average for all losses and associated summaries for\n visualizing the performance of the network.\n\n Args:\n total_loss: Total loss from loss().\n Returns:\n loss_averages_op: op for generating moving a...
def train(total_loss, global_step): 'Train CIFAR-10 model.\n\n Create an optimizer and apply to all trainable variables. Add moving\n average for all trainable variables.\n\n Args:\n total_loss: Total loss from loss().\n global_step: Integer Variable counting the number of training steps\n processed.\...
-1,121,517,191,392,497,900
Train CIFAR-10 model. Create an optimizer and apply to all trainable variables. Add moving average for all trainable variables. Args: total_loss: Total loss from loss(). global_step: Integer Variable counting the number of training steps processed. Returns: train_op: op for training.
examples/cifar10/cifar10.py
train
13927729580/TensorFlowOnSpark
python
def train(total_loss, global_step): 'Train CIFAR-10 model.\n\n Create an optimizer and apply to all trainable variables. Add moving\n average for all trainable variables.\n\n Args:\n total_loss: Total loss from loss().\n global_step: Integer Variable counting the number of training steps\n processed.\...
def maybe_download_and_extract(): "Download and extract the tarball from Alex's website." dest_directory = FLAGS.data_dir if (not os.path.exists(dest_directory)): os.makedirs(dest_directory) filename = DATA_URL.split('/')[(- 1)] filepath = os.path.join(dest_directory, filename) if (not o...
-304,177,207,173,734,000
Download and extract the tarball from Alex's website.
examples/cifar10/cifar10.py
maybe_download_and_extract
13927729580/TensorFlowOnSpark
python
def maybe_download_and_extract(): dest_directory = FLAGS.data_dir if (not os.path.exists(dest_directory)): os.makedirs(dest_directory) filename = DATA_URL.split('/')[(- 1)] filepath = os.path.join(dest_directory, filename) if (not os.path.exists(filepath)): def _progress(count,...
@unavailable((not _has_matplotlib), 'matplotlib') def plot_ellipsoid_3D(p, q, ax, n_points=100): ' Plot an ellipsoid in 3D\n\n Based on\n https://stackoverflow.com/questions/7819498/plotting-ellipsoid-with-matplotlib\n\n TODO: Untested!\n\n Parameters\n ----------\n p: 3x1 array[float]\n Ce...
-1,664,333,436,179,161,300
Plot an ellipsoid in 3D Based on https://stackoverflow.com/questions/7819498/plotting-ellipsoid-with-matplotlib TODO: Untested! Parameters ---------- p: 3x1 array[float] Center of the ellipsoid q: 3x3 array[float] Shape matrix of the ellipsoid ax: matplotlib.Axes object Ax on which to plot the ellipsoid ...
safe_exploration/visualization/utils_visualization.py
plot_ellipsoid_3D
Pathetiue/safe-exploration
python
@unavailable((not _has_matplotlib), 'matplotlib') def plot_ellipsoid_3D(p, q, ax, n_points=100): ' Plot an ellipsoid in 3D\n\n Based on\n https://stackoverflow.com/questions/7819498/plotting-ellipsoid-with-matplotlib\n\n TODO: Untested!\n\n Parameters\n ----------\n p: 3x1 array[float]\n Ce...
@unavailable((not _has_matplotlib), 'matplotlib') def plot_ellipsoid_2D(p, q, ax, n_points=100, color='r'): ' Plot an ellipsoid in 2D\n\n TODO: Untested!\n\n Parameters\n ----------\n p: 3x1 array[float]\n Center of the ellipsoid\n q: 3x3 array[float]\n Shape matrix of the ellipsoid\n ...
-6,846,811,146,890,000,000
Plot an ellipsoid in 2D TODO: Untested! Parameters ---------- p: 3x1 array[float] Center of the ellipsoid q: 3x3 array[float] Shape matrix of the ellipsoid ax: matplotlib.Axes object Ax on which to plot the ellipsoid Returns ------- ax: matplotlib.Axes object The Ax containing the ellipsoid
safe_exploration/visualization/utils_visualization.py
plot_ellipsoid_2D
Pathetiue/safe-exploration
python
@unavailable((not _has_matplotlib), 'matplotlib') def plot_ellipsoid_2D(p, q, ax, n_points=100, color='r'): ' Plot an ellipsoid in 2D\n\n TODO: Untested!\n\n Parameters\n ----------\n p: 3x1 array[float]\n Center of the ellipsoid\n q: 3x3 array[float]\n Shape matrix of the ellipsoid\n ...
def __init__(self, p): 'Defines the modulus p which must be a prime\n ' self.F = self self.p = gmpy.mpz(p) self.char = self.p self.q = (self.p + 1) assert gmpy.is_prime(p) self.rep = None self.g = None '\n g is a random quadratic residue used to compute square roots and...
3,367,812,278,402,845,000
Defines the modulus p which must be a prime
mathTools/field.py
__init__
ecuvelier/PPAT
python
def __init__(self, p): '\n ' self.F = self self.p = gmpy.mpz(p) self.char = self.p self.q = (self.p + 1) assert gmpy.is_prime(p) self.rep = None self.g = None '\n g is a random quadratic residue used to compute square roots and it is\n initialized the first time ...
def one(self): 'unit element for multiplication' return FieldElem(1, self)
-5,955,065,089,090,498,000
unit element for multiplication
mathTools/field.py
one
ecuvelier/PPAT
python
def one(self): return FieldElem(1, self)
def zero(self): 'unit element for addition' return FieldElem(0, self)
3,455,417,634,989,473,300
unit element for addition
mathTools/field.py
zero
ecuvelier/PPAT
python
def zero(self): return FieldElem(0, self)
def elem(self, x): ' return an element of value x\n ' if isinstance(x, FieldElem): assert (x.F == self) return x m = gmpy.mpz(1) assert (isinstance(x, int) or isinstance(x, long) or (type(x) == type(m))) return FieldElem(x, self)
-8,415,939,500,760,490,000
return an element of value x
mathTools/field.py
elem
ecuvelier/PPAT
python
def elem(self, x): ' \n ' if isinstance(x, FieldElem): assert (x.F == self) return x m = gmpy.mpz(1) assert (isinstance(x, int) or isinstance(x, long) or (type(x) == type(m))) return FieldElem(x, self)
def random(self, low=1, high=None): ' Return a random element of the Field\n ' if (high == None): high = int((self.p - 1)) rand = randint(low, high) return self.elem(rand)
-6,226,670,074,696,561,000
Return a random element of the Field
mathTools/field.py
random
ecuvelier/PPAT
python
def random(self, low=1, high=None): ' \n ' if (high == None): high = int((self.p - 1)) rand = randint(low, high) return self.elem(rand)
def __eq__(self, other): 'testing if we are working in the same field' try: return (self.p == other.p) except: return False
-4,467,265,234,563,478,500
testing if we are working in the same field
mathTools/field.py
__eq__
ecuvelier/PPAT
python
def __eq__(self, other): try: return (self.p == other.p) except: return False
def add(self, a, b): '\n field operation: addition mod p\n ' return FieldElem(((a.val + b.val) % self.p), self)
-6,150,732,098,473,979,000
field operation: addition mod p
mathTools/field.py
add
ecuvelier/PPAT
python
def add(self, a, b): '\n \n ' return FieldElem(((a.val + b.val) % self.p), self)
def sub(self, a, b): '\n field operation: substraction mod p\n ' return FieldElem(((a.val - b.val) % self.p), self)
-921,403,297,015,566,600
field operation: substraction mod p
mathTools/field.py
sub
ecuvelier/PPAT
python
def sub(self, a, b): '\n \n ' return FieldElem(((a.val - b.val) % self.p), self)
def neg(self, a): '\n field operation: opposite mod p\n ' return FieldElem(((self.p - a.val) % self.p), self)
6,358,035,490,914,622,000
field operation: opposite mod p
mathTools/field.py
neg
ecuvelier/PPAT
python
def neg(self, a): '\n \n ' return FieldElem(((self.p - a.val) % self.p), self)
def mul(self, a, b): '\n field operation: multiplication of field elements\n ' '\n if isinstance(a,FieldElem) and isinstance(b, FieldElem) and not a.F == b.F :\n raise Exception("multiplication between elements of different fields")\n ' if (not isinstance(b, FieldElem)...
-6,066,617,828,850,303,000
field operation: multiplication of field elements
mathTools/field.py
mul
ecuvelier/PPAT
python
def mul(self, a, b): '\n \n ' '\n if isinstance(a,FieldElem) and isinstance(b, FieldElem) and not a.F == b.F :\n raise Exception("multiplication between elements of different fields")\n ' if (not isinstance(b, FieldElem)): if (b < 0): return self.sm...
def smul(self, a, b): ' Return a*b where a or b is scalar\n ' if (not isinstance(b, FieldElem)): return FieldElem(((gmpy.mpz(b) * a.val) % self.p), self) else: return self.smul(b, a)
4,092,931,305,875,793,000
Return a*b where a or b is scalar
mathTools/field.py
smul
ecuvelier/PPAT
python
def smul(self, a, b): ' \n ' if (not isinstance(b, FieldElem)): return FieldElem(((gmpy.mpz(b) * a.val) % self.p), self) else: return self.smul(b, a)
def sm(self, b, a): ' Quick multiplication between a field element a and a scalar b\n ' return FieldElem(((gmpy.mpz(b) * a.val) % self.p), self)
1,369,684,940,761,127,000
Quick multiplication between a field element a and a scalar b
mathTools/field.py
sm
ecuvelier/PPAT
python
def sm(self, b, a): ' \n ' return FieldElem(((gmpy.mpz(b) * a.val) % self.p), self)
def pmul(self, a, b): ' product between two field element in Fp\n ' return FieldElem(((a.val * b.val) % self.p), self)
-1,657,878,191,410,303,200
product between two field element in Fp
mathTools/field.py
pmul
ecuvelier/PPAT
python
def pmul(self, a, b): ' \n ' return FieldElem(((a.val * b.val) % self.p), self)
def dbleAndAdd(self, P, Pp, n): 'return n*P using double and add technique' if (n == 0): return self.zero() if (n == 1): return P elif ((n % 2) == 1): Q = self.dbleAndAdd(P, Pp, ((n - 1) / 2)) return ((P + Q) + Q) elif ((n % 2) == 0): Q = self.dbleAndAdd(P, Pp...
304,071,089,569,589,100
return n*P using double and add technique
mathTools/field.py
dbleAndAdd
ecuvelier/PPAT
python
def dbleAndAdd(self, P, Pp, n): if (n == 0): return self.zero() if (n == 1): return P elif ((n % 2) == 1): Q = self.dbleAndAdd(P, Pp, ((n - 1) / 2)) return ((P + Q) + Q) elif ((n % 2) == 0): Q = self.dbleAndAdd(P, Pp, (n / 2)) return (Q + Q)
def powop(self, a, b): 'return a**b' m = gmpy.mpz(1) 'exponentiation by a scalar' if ((not isinstance(b, int)) and (not isinstance(b, long)) and (not (type(b) == type(m)))): raise Exception('Exponentation by a non integer, long or mpz') c = b if ((c > (self.char - 1)) or (c < 0)): ...
-2,940,484,699,847,163,000
return a**b
mathTools/field.py
powop
ecuvelier/PPAT
python
def powop(self, a, b): m = gmpy.mpz(1) 'exponentiation by a scalar' if ((not isinstance(b, int)) and (not isinstance(b, long)) and (not (type(b) == type(m)))): raise Exception('Exponentation by a non integer, long or mpz') c = b if ((c > (self.char - 1)) or (c < 0)): c = (b % (s...
def sqrtAndMultply(self, P, Pp, n): 'return P**n using square and multiply technique' if (n == 0): return self.one() elif (n == 1): return P elif ((n % 2) == 1): Q = self.sqrtAndMultply(P, Pp, ((n - 1) / 2)) return (P * self.square(Q)) elif ((n % 2) == 0): Q =...
781,381,006,290,647,300
return P**n using square and multiply technique
mathTools/field.py
sqrtAndMultply
ecuvelier/PPAT
python
def sqrtAndMultply(self, P, Pp, n): if (n == 0): return self.one() elif (n == 1): return P elif ((n % 2) == 1): Q = self.sqrtAndMultply(P, Pp, ((n - 1) / 2)) return (P * self.square(Q)) elif ((n % 2) == 0): Q = self.sqrtAndMultply(P, Pp, (n / 2)) retu...
def square(self, a): '\n This method returns the square of a\n ' return FieldElem(pow(a.val, 2, self.p), self)
-7,983,734,526,397,552,000
This method returns the square of a
mathTools/field.py
square
ecuvelier/PPAT
python
def square(self, a): '\n \n ' return FieldElem(pow(a.val, 2, self.p), self)
def findnonresidue(self): '\n find a random non quadratic residue in the Field F,\n that is, find g that is not a square in F, this is\n needed to compute square roots\n ' g = self.random() while g.isquadres(): g = self.random() return g
1,602,797,222,163,183,900
find a random non quadratic residue in the Field F, that is, find g that is not a square in F, this is needed to compute square roots
mathTools/field.py
findnonresidue
ecuvelier/PPAT
python
def findnonresidue(self): '\n find a random non quadratic residue in the Field F,\n that is, find g that is not a square in F, this is\n needed to compute square roots\n ' g = self.random() while g.isquadres(): g = self.random() return g
def __init__(self, val, F): 'Creating a new field element.\n ' self.F = F self.val = gmpy.mpz(val) self.poly = polynom(self.F, [self])
5,470,238,425,599,405,000
Creating a new field element.
mathTools/field.py
__init__
ecuvelier/PPAT
python
def __init__(self, val, F): '\n ' self.F = F self.val = gmpy.mpz(val) self.poly = polynom(self.F, [self])
def isquadres(self): ' This method return True if the element is a quadratic residue mod q\n different than zero\n it returns False otherwhise\n ' if (self + self.F.zero()).iszero(): return False else: c = (self ** ((self.F.q - 1) / 2)) return (c == self....
-1,876,804,704,010,010,000
This method return True if the element is a quadratic residue mod q different than zero it returns False otherwhise
mathTools/field.py
isquadres
ecuvelier/PPAT
python
def isquadres(self): ' This method return True if the element is a quadratic residue mod q\n different than zero\n it returns False otherwhise\n ' if (self + self.F.zero()).iszero(): return False else: c = (self ** ((self.F.q - 1) / 2)) return (c == self....
def squareroot(self): ' This method returns the positive square root of\n an element of the field\n using the Tonelli-Shanks algorithm\n\n Carefull : if the element has no square root, the method does not\n check this case and raises an error. Verification has to be done\...
-3,225,873,158,965,586,000
This method returns the positive square root of an element of the field using the Tonelli-Shanks algorithm Carefull : if the element has no square root, the method does not check this case and raises an error. Verification has to be done before calling the method.
mathTools/field.py
squareroot
ecuvelier/PPAT
python
def squareroot(self): ' This method returns the positive square root of\n an element of the field\n using the Tonelli-Shanks algorithm\n\n Carefull : if the element has no square root, the method does not\n check this case and raises an error. Verification has to be done\...
def __init__(self, F, irpoly, g=None, rep=None): "Define the base Field or extension Field and the irreducible polynomial\n F is the base field on top of which the extension\n field is built\n irpoly is the irreducible polynomial used to build\n the extension field as F/irpoly\n ...
3,613,551,871,637,081,600
Define the base Field or extension Field and the irreducible polynomial F is the base field on top of which the extension field is built irpoly is the irreducible polynomial used to build the extension field as F/irpoly g is a non quadratic residue used to compute square roots, if it is set to None, computing ...
mathTools/field.py
__init__
ecuvelier/PPAT
python
def __init__(self, F, irpoly, g=None, rep=None): "Define the base Field or extension Field and the irreducible polynomial\n F is the base field on top of which the extension\n field is built\n irpoly is the irreducible polynomial used to build\n the extension field as F/irpoly\n ...
def one(self): 'unit element for multiplication' One = ([self.F.zero()] * (self.deg - 1)) One[(self.deg - 2)] = self.F.one() return ExtensionFieldElem(self, polynom(self.F, One))
8,906,210,674,035,437,000
unit element for multiplication
mathTools/field.py
one
ecuvelier/PPAT
python
def one(self): One = ([self.F.zero()] * (self.deg - 1)) One[(self.deg - 2)] = self.F.one() return ExtensionFieldElem(self, polynom(self.F, One))
def zero(self): 'unit element for addition' Zero = ([self.F.zero()] * (self.deg - 1)) return ExtensionFieldElem(self, polynom(self.F, Zero))
-6,735,012,592,271,312,000
unit element for addition
mathTools/field.py
zero
ecuvelier/PPAT
python
def zero(self): Zero = ([self.F.zero()] * (self.deg - 1)) return ExtensionFieldElem(self, polynom(self.F, Zero))
def unit(self): ' root of the irreducible polynomial\n e.g. return element 1*A+0 (or the complex value i) if the irpoly is X**2+1\n ' I = self.zero() I.poly.coef[(- 2)] = self.F.one() return I
8,046,764,757,817,881,000
root of the irreducible polynomial e.g. return element 1*A+0 (or the complex value i) if the irpoly is X**2+1
mathTools/field.py
unit
ecuvelier/PPAT
python
def unit(self): ' root of the irreducible polynomial\n e.g. return element 1*A+0 (or the complex value i) if the irpoly is X**2+1\n ' I = self.zero() I.poly.coef[(- 2)] = self.F.one() return I
def elem(self, x): ' Provided that x belongs to F, return an element of the extension field\n of value x\n ' P = self.zero() P.poly.coef[(- 1)] = x return P
7,193,894,804,630,438,000
Provided that x belongs to F, return an element of the extension field of value x
mathTools/field.py
elem
ecuvelier/PPAT
python
def elem(self, x): ' Provided that x belongs to F, return an element of the extension field\n of value x\n ' P = self.zero() P.poly.coef[(- 1)] = x return P
def random(self): ' Return a random element of the Extension Field\n ' polycoef = ([0] * (self.deg - 1)) for i in range((self.deg - 1)): polycoef[i] = self.F.random() poly = polynom(self.F, polycoef) return ExtensionFieldElem(self, poly)
2,462,468,952,993,113,000
Return a random element of the Extension Field
mathTools/field.py
random
ecuvelier/PPAT
python
def random(self): ' \n ' polycoef = ([0] * (self.deg - 1)) for i in range((self.deg - 1)): polycoef[i] = self.F.random() poly = polynom(self.F, polycoef) return ExtensionFieldElem(self, poly)
def __eq__(self, other): 'testing if we are working in the same extension field' try: return ((self.F == other.F) and (self.irpoly == other.irpoly)) except: return False
-6,034,864,863,400,111,000
testing if we are working in the same extension field
mathTools/field.py
__eq__
ecuvelier/PPAT
python
def __eq__(self, other): try: return ((self.F == other.F) and (self.irpoly == other.irpoly)) except: return False
def add(self, a, b): '\n field operation: addition of polynomial > addition of coefficients in the appropriate field\n ' if (not (a.deg == b.deg)): a = self.reduc(a) b = self.reduc(b) polysum = ([0] * a.deg) for i in range(a.deg): polysum[i] = (a.poly.coef[i] + b.po...
-4,685,965,467,103,141,000
field operation: addition of polynomial > addition of coefficients in the appropriate field
mathTools/field.py
add
ecuvelier/PPAT
python
def add(self, a, b): '\n \n ' if (not (a.deg == b.deg)): a = self.reduc(a) b = self.reduc(b) polysum = ([0] * a.deg) for i in range(a.deg): polysum[i] = (a.poly.coef[i] + b.poly.coef[i]) P = polynom(self.F, polysum) return ExtensionFieldElem(self, P)
def sub(self, a, b): '\n field operation: substraction of polynomials > substraction of each coefficient in the appropriate field\n ' if (not (a.deg == b.deg)): a = self.reduc(a) b = self.reduc(b) c = self.neg(b) return self.add(a, c)
-7,821,902,978,157,330,000
field operation: substraction of polynomials > substraction of each coefficient in the appropriate field
mathTools/field.py
sub
ecuvelier/PPAT
python
def sub(self, a, b): '\n \n ' if (not (a.deg == b.deg)): a = self.reduc(a) b = self.reduc(b) c = self.neg(b) return self.add(a, c)
def neg(self, a): '\n field operation: opposite of a polynomial > opposite of each coefficient in appropriate field\n ' ap = ([0] * a.deg) for i in range(a.deg): ap[i] = (- a.poly.coef[i]) P = polynom(self.F, ap) return ExtensionFieldElem(self, P)
-7,593,053,574,250,158,000
field operation: opposite of a polynomial > opposite of each coefficient in appropriate field
mathTools/field.py
neg
ecuvelier/PPAT
python
def neg(self, a): '\n \n ' ap = ([0] * a.deg) for i in range(a.deg): ap[i] = (- a.poly.coef[i]) P = polynom(self.F, ap) return ExtensionFieldElem(self, P)
def smul(self, a, b): ' Return a*b where a or b is scalar\n ' if (not isinstance(b, FieldElem)): A = a.poly.coef Pc = ([0] * len(A)) for i in range(len(Pc)): Pc[i] = (A[i] * gmpy.mpz(b)) return ExtensionFieldElem(self, polynom(self.F, Pc)) else: ret...
-2,841,629,317,917,324,300
Return a*b where a or b is scalar
mathTools/field.py
smul
ecuvelier/PPAT
python
def smul(self, a, b): ' \n ' if (not isinstance(b, FieldElem)): A = a.poly.coef Pc = ([0] * len(A)) for i in range(len(Pc)): Pc[i] = (A[i] * gmpy.mpz(b)) return ExtensionFieldElem(self, polynom(self.F, Pc)) else: return self.smul(b, a)
def pmul(self, a, b): 'Multiplication between polynomials\n ' if (not (a.deg == b.deg)): a = self.reduc(a) b = self.reduc(b) A = a.poly.coef B = b.poly.coef k = (self.deg - 1) if ((k == 2) and (self.F.rep == 'A')): (a0, a1, b0, b1) = (A[0].val, A[1].val, B[0].val, ...
-429,399,036,203,879,040
Multiplication between polynomials
mathTools/field.py
pmul
ecuvelier/PPAT
python
def pmul(self, a, b): '\n ' if (not (a.deg == b.deg)): a = self.reduc(a) b = self.reduc(b) A = a.poly.coef B = b.poly.coef k = (self.deg - 1) if ((k == 2) and (self.F.rep == 'A')): (a0, a1, b0, b1) = (A[0].val, A[1].val, B[0].val, B[1].val) p = self.char ...
def square(self, a): ' This algortihm returns the square of a in the field\n using different methods if the degree of the extension\n is 2,3 or more\n ' assert (a.F == self) if (not (a.deg == (self.deg - 1))): a = self.reduc(a) A = a.poly.coef k = (self.deg - 1) ...
392,524,527,384,159,500
This algortihm returns the square of a in the field using different methods if the degree of the extension is 2,3 or more
mathTools/field.py
square
ecuvelier/PPAT
python
def square(self, a): ' This algortihm returns the square of a in the field\n using different methods if the degree of the extension\n is 2,3 or more\n ' assert (a.F == self) if (not (a.deg == (self.deg - 1))): a = self.reduc(a) A = a.poly.coef k = (self.deg - 1) ...
def invert(self, a): " Ths method returns the inverse of a in the field\n The inverse is computed by determining the Bezout coefficient using the\n extended Euclide's algorithm or by specialized algorithms depending\n on the degree of the extension (2 or 3)\n " assert (a....
1,190,864,874,066,247,400
Ths method returns the inverse of a in the field The inverse is computed by determining the Bezout coefficient using the extended Euclide's algorithm or by specialized algorithms depending on the degree of the extension (2 or 3)
mathTools/field.py
invert
ecuvelier/PPAT
python
def invert(self, a): " Ths method returns the inverse of a in the field\n The inverse is computed by determining the Bezout coefficient using the\n extended Euclide's algorithm or by specialized algorithms depending\n on the degree of the extension (2 or 3)\n " assert (a....
def invertible(self, a): ' Return True if a is invertible\n ' return (not (self.reduc(a) == self.zero()))
8,636,644,282,939,494,000
Return True if a is invertible
mathTools/field.py
invertible
ecuvelier/PPAT
python
def invertible(self, a): ' \n ' return (not (self.reduc(a) == self.zero()))
def eucldiv(self, a, b): ' Return a/b and a%b\n a and b are of length d-1 where d is the degree of the irreducible polynomial\n ' zero = self.F.zero() izero = self.zero() d = self.deg assert (not b.poly.iszero()) if a.poly.iszero(): return (izero, izero) elif (a == ...
-7,539,930,612,907,431,000
Return a/b and a%b a and b are of length d-1 where d is the degree of the irreducible polynomial
mathTools/field.py
eucldiv
ecuvelier/PPAT
python
def eucldiv(self, a, b): ' Return a/b and a%b\n a and b are of length d-1 where d is the degree of the irreducible polynomial\n ' zero = self.F.zero() izero = self.zero() d = self.deg assert (not b.poly.iszero()) if a.poly.iszero(): return (izero, izero) elif (a == ...
def reduc(self, a): ' Return a % self.irpoly\n The polynomial a = [a_0,...,a_n-1] is returned modulo the irreducible polynomial\n The reduced polynomial has length at most d-1 where d is the length\n of the irreducible polynomial\n ' assert (a.F.F == self.F) if a.poly.iszero(): ...
-6,581,890,971,430,029,000
Return a % self.irpoly The polynomial a = [a_0,...,a_n-1] is returned modulo the irreducible polynomial The reduced polynomial has length at most d-1 where d is the length of the irreducible polynomial
mathTools/field.py
reduc
ecuvelier/PPAT
python
def reduc(self, a): ' Return a % self.irpoly\n The polynomial a = [a_0,...,a_n-1] is returned modulo the irreducible polynomial\n The reduced polynomial has length at most d-1 where d is the length\n of the irreducible polynomial\n ' assert (a.F.F == self.F) if a.poly.iszero(): ...
def reduc2(self, a): ' a is a list of length (d-1)*2-1 (polynomial length)\n this method returns the equivalent element of length d-1\n using the table of equivalences (build from the irreducible polynomial)\n in the function self.table()\n ' As = a[:(self.deg - 2)] A...
8,261,773,372,050,492,000
a is a list of length (d-1)*2-1 (polynomial length) this method returns the equivalent element of length d-1 using the table of equivalences (build from the irreducible polynomial) in the function self.table()
mathTools/field.py
reduc2
ecuvelier/PPAT
python
def reduc2(self, a): ' a is a list of length (d-1)*2-1 (polynomial length)\n this method returns the equivalent element of length d-1\n using the table of equivalences (build from the irreducible polynomial)\n in the function self.table()\n ' As = a[:(self.deg - 2)] A...
def trunc(self, a): 'Return an ExtensionFieldElem of length d-1 where d = deg(irpoly)\n ' d = self.deg if (a.deg == (d - 1)): return a c = a.poly.coef[((a.deg - d) + 1):] cp = polynom(self.F, c) return ExtensionFieldElem(self, cp)
-675,842,933,097,962,800
Return an ExtensionFieldElem of length d-1 where d = deg(irpoly)
mathTools/field.py
trunc
ecuvelier/PPAT
python
def trunc(self, a): '\n ' d = self.deg if (a.deg == (d - 1)): return a c = a.poly.coef[((a.deg - d) + 1):] cp = polynom(self.F, c) return ExtensionFieldElem(self, cp)
def table(self): ' This method returns a table (usually) stored in self.tabular\n which is used to compute reduction after a multiplication\n between two elements\n ' d = self.deg T = zeros(((d - 2), (d - 1)), dtype=object_) Pc = self.irpoly.coef[1:] for i in range(0, (d -...
1,688,632,231,972,374,500
This method returns a table (usually) stored in self.tabular which is used to compute reduction after a multiplication between two elements
mathTools/field.py
table
ecuvelier/PPAT
python
def table(self): ' This method returns a table (usually) stored in self.tabular\n which is used to compute reduction after a multiplication\n between two elements\n ' d = self.deg T = zeros(((d - 2), (d - 1)), dtype=object_) Pc = self.irpoly.coef[1:] for i in range(0, (d -...
def extendedeuclide(self, a, b): 'Return s,u,v such as s = ua + vb, s is the gcd of a and b\n This method is used to compute the inverse of a mod b (when s=1)\n ' one = self.one() zero = self.zero() s = a u = one v = zero sp = b up = zero vp = one while (not sp.poly...
2,513,439,641,807,605,000
Return s,u,v such as s = ua + vb, s is the gcd of a and b This method is used to compute the inverse of a mod b (when s=1)
mathTools/field.py
extendedeuclide
ecuvelier/PPAT
python
def extendedeuclide(self, a, b): 'Return s,u,v such as s = ua + vb, s is the gcd of a and b\n This method is used to compute the inverse of a mod b (when s=1)\n ' one = self.one() zero = self.zero() s = a u = one v = zero sp = b up = zero vp = one while (not sp.poly...