uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b88985a2b25d2e3cb0c3e62b | train | class | class SeminarsConfig(AppConfig):
name = 'seminars'
| class SeminarsConfig(AppConfig):
| name = 'seminars'
| from django.apps import AppConfig
class SeminarsConfig(AppConfig):
| 14 | 64 | 14 | 7 | 6 | DevHub-Azerbaycan/python_web_site | src/seminars/apps.py | Python | SeminarsConfig | SeminarsConfig | 4 | 5 | 4 | 4 | 89000fb5578be789aaa2546a2672c20ed383637d | bigcode/the-stack | train |
eb09c24c5c1bad0986d7a964 | train | class | class SlaveIsNotConsistentRecoveryException(MirroringException):
pass
| class SlaveIsNotConsistentRecoveryException(MirroringException):
| pass
| MirroringException
from pyxcli.mirroring.errors import NoMirrorDefinedError
from pyxcli.mirroring.errors import MirrorInactiveError
CHAR_LIMIT = 60
class RecoveryMethodNotImplementedException(MirroringException):
pass
class SlaveIsNotConsistentRecoveryException(MirroringException):
| 64 | 64 | 16 | 13 | 50 | tzurE/pyxcli | pyxcli/mirroring/recovery_manager.py | Python | SlaveIsNotConsistentRecoveryException | SlaveIsNotConsistentRecoveryException | 38 | 39 | 38 | 38 | f54f06e7d251a8f26ebd57bc58bdab3e0bfa4fdf | bigcode/the-stack | train |
5d30fe79a3d1dd388bd5a525 | train | class | class RecoveryManager(object):
xcli_client = None
action_entities = None
# ============================================ INIT =================
def __init__(self, should_use_cache, xcli_client):
self.xcli_client = xcli_client
if (should_use_cache):
self.action_entit... | class RecoveryManager(object):
| xcli_client = None
action_entities = None
# ============================================ INIT =================
def __init__(self, should_use_cache, xcli_client):
self.xcli_client = xcli_client
if (should_use_cache):
self.action_entities = MirroredCachedEntities(
... | _entities import MirroredEntities
from pyxcli.mirroring.mirrored_entities import MirroredCachedEntities
from pyxcli.errors import XCLIError
from pyxcli.errors import CommandExecutionError
from pyxcli.errors import SyncAlreadyActiveError
from pyxcli.errors import SyncAlreadyInactiveError
from pyxcli.mirroring.erro... | 255 | 256 | 3,795 | 5 | 250 | tzurE/pyxcli | pyxcli/mirroring/recovery_manager.py | Python | RecoveryManager | RecoveryManager | 69 | 500 | 69 | 69 | 53d04ed0a8f0cbab1b51d6fa75b0142f2ac4a72b | bigcode/the-stack | train |
b46c67d6c70b9573b64e8fb7 | train | class | class NoLastReplicatedSnapshotRecoveryException(MirroringException):
pass
| class NoLastReplicatedSnapshotRecoveryException(MirroringException):
| pass
| oringException):
pass
class InsufficientSnapshotSpaceRecoveryException(MirroringException):
pass
class LunNumberRecoveryException(MirroringException):
pass
class AlreadyInTestFailoverStartRecoveryException(MirroringException):
pass
class NoLastReplicatedSnapshotRecoveryException(Mirro... | 64 | 64 | 16 | 13 | 50 | tzurE/pyxcli | pyxcli/mirroring/recovery_manager.py | Python | NoLastReplicatedSnapshotRecoveryException | NoLastReplicatedSnapshotRecoveryException | 58 | 59 | 58 | 58 | 723cd8d667f60bb7b79477a8a8f02c1fa1a355cc | bigcode/the-stack | train |
b270126868ec50276da748dc | train | class | class InsufficientSnapshotSpaceRecoveryException(MirroringException):
pass
| class InsufficientSnapshotSpaceRecoveryException(MirroringException):
| pass
| Error
CHAR_LIMIT = 60
class RecoveryMethodNotImplementedException(MirroringException):
pass
class SlaveIsNotConsistentRecoveryException(MirroringException):
pass
class NoMirrorConnectivityRecoveryException(MirroringException):
pass
class InsufficientSnapshotSpaceRecoveryException(Mirror... | 64 | 64 | 15 | 12 | 51 | tzurE/pyxcli | pyxcli/mirroring/recovery_manager.py | Python | InsufficientSnapshotSpaceRecoveryException | InsufficientSnapshotSpaceRecoveryException | 46 | 47 | 46 | 46 | ad26c8b80d6f7449da970ede6b2410294776d9a0 | bigcode/the-stack | train |
75e520ac28d36dcda18aae13 | train | class | class LunNumberRecoveryException(MirroringException):
pass
| class LunNumberRecoveryException(MirroringException):
| pass
| Exception(MirroringException):
pass
class SlaveIsNotConsistentRecoveryException(MirroringException):
pass
class NoMirrorConnectivityRecoveryException(MirroringException):
pass
class InsufficientSnapshotSpaceRecoveryException(MirroringException):
pass
class LunNumberRecoveryException(M... | 64 | 64 | 13 | 10 | 53 | tzurE/pyxcli | pyxcli/mirroring/recovery_manager.py | Python | LunNumberRecoveryException | LunNumberRecoveryException | 50 | 51 | 50 | 50 | eb8301f46c85eced58c8182b051c0b27e6fbab8f | bigcode/the-stack | train |
786047d930fec5f3226461ae | train | class | class RecoveryMethodNotImplementedException(MirroringException):
pass
| class RecoveryMethodNotImplementedException(MirroringException):
| pass
| .errors import SyncAlreadyInactiveError
from pyxcli.mirroring.errors import MirroringException
from pyxcli.mirroring.errors import NoMirrorDefinedError
from pyxcli.mirroring.errors import MirrorInactiveError
CHAR_LIMIT = 60
class RecoveryMethodNotImplementedException(MirroringException):
| 64 | 64 | 14 | 11 | 52 | tzurE/pyxcli | pyxcli/mirroring/recovery_manager.py | Python | RecoveryMethodNotImplementedException | RecoveryMethodNotImplementedException | 34 | 35 | 34 | 34 | 0181524c391b237c90b858025474dd9a29246b29 | bigcode/the-stack | train |
8385fac1cf4a2f18a053bf93 | train | class | class AlreadyInTestFailoverStartRecoveryException(MirroringException):
pass
| class AlreadyInTestFailoverStartRecoveryException(MirroringException):
| pass
| (MirroringException):
pass
class NoMirrorConnectivityRecoveryException(MirroringException):
pass
class InsufficientSnapshotSpaceRecoveryException(MirroringException):
pass
class LunNumberRecoveryException(MirroringException):
pass
class AlreadyInTestFailoverStartRecoveryException(Mirr... | 64 | 64 | 17 | 14 | 49 | tzurE/pyxcli | pyxcli/mirroring/recovery_manager.py | Python | AlreadyInTestFailoverStartRecoveryException | AlreadyInTestFailoverStartRecoveryException | 54 | 55 | 54 | 54 | 9a3764c534b83647f5d111217734bdd23bc3e806 | bigcode/the-stack | train |
73a3c390cc2c9ebbbeef5340 | train | class | class NoMirrorConnectivityRecoveryException(MirroringException):
pass
| class NoMirrorConnectivityRecoveryException(MirroringException):
| pass
| MirrorDefinedError
from pyxcli.mirroring.errors import MirrorInactiveError
CHAR_LIMIT = 60
class RecoveryMethodNotImplementedException(MirroringException):
pass
class SlaveIsNotConsistentRecoveryException(MirroringException):
pass
class NoMirrorConnectivityRecoveryException(MirroringException):
... | 64 | 64 | 14 | 11 | 52 | tzurE/pyxcli | pyxcli/mirroring/recovery_manager.py | Python | NoMirrorConnectivityRecoveryException | NoMirrorConnectivityRecoveryException | 42 | 43 | 42 | 42 | e99d4d628154e7f656d124517a12e6ac42e28f82 | bigcode/the-stack | train |
3e3ba07add2ea5e3fb55f18b | train | function | def setup(app):
app.add_css_file("css/frc-rtd.css")
# Local Api Docs support
app.add_js_file("js/api-docs-redirect.js")
# Right-to-left support
is_rtl = app.config.language in rtl_locale
app.config.hoverxref_tooltip_side = "left" if is_rtl else "right"
if is_rtl:
app.add_css_file("... | def setup(app):
| app.add_css_file("css/frc-rtd.css")
# Local Api Docs support
app.add_js_file("js/api-docs-redirect.js")
# Right-to-left support
is_rtl = app.config.language in rtl_locale
app.config.hoverxref_tooltip_side = "left" if is_rtl else "right"
if is_rtl:
app.add_css_file("css/frc-rtl.css"... | .png"
# URL favicon
html_favicon = "assets/FIRSTicon_RGB_withTM.ico"
html_theme_options = {
"collapse_navigation": True,
"sticky_navigation": False,
"titles_only": True,
}
user_options = [
("warning-is-error", True),
]
def setup(app):
| 64 | 64 | 96 | 4 | 60 | modelmat/frc-docs | source/conf.py | Python | setup | setup | 175 | 185 | 175 | 175 | a3a08496f3fda59ed9857ec071b6699e46df4f1b | bigcode/the-stack | train |
c9373353c37734d577a842fc | train | class | class HEMM(IndividualOutcomeEstimator):
"""Causal model implementing an heterogeneous effect mixture model (HEMM).
For further details, see `Interpretable Subgroup Discovery in Treatment Effect
Estimation with Application to Opioid Prescribing Guidelines <https://arxiv.org/pdf/1905.03297.pdf>`_ paper.
... | class HEMM(IndividualOutcomeEstimator):
| """Causal model implementing an heterogeneous effect mixture model (HEMM).
For further details, see `Interpretable Subgroup Discovery in Treatment Effect
Estimation with Application to Opioid Prescribing Guidelines <https://arxiv.org/pdf/1905.03297.pdf>`_ paper.
Notes:
**Requires PyTorch** >... | # (C) Copyright 2019 IBM 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | 198 | 256 | 2,010 | 9 | 188 | liranszlak/causallib | causallib/contrib/hemm/hemm_api.py | Python | HEMM | HEMM | 25 | 210 | 25 | 25 | 3794d600101a978775cd1e138b32b8e7a621a41b | bigcode/the-stack | train |
fe5f1cbac823a9275b5dbf12 | train | function | def inviteUser(email,configMap,allPermissions, plugin_tag, name):
done = False
username = email.split('@', 1)[0]
instruction = ''
for plugin in configMap['plugins']:
if plugin['plugin'] + ':' + plugin['tag'] == plugin_tag:
password= plugin['password']
user=plugin['admin'... | def inviteUser(email,configMap,allPermissions, plugin_tag, name):
| done = False
username = email.split('@', 1)[0]
instruction = ''
for plugin in configMap['plugins']:
if plugin['plugin'] + ':' + plugin['tag'] == plugin_tag:
password= plugin['password']
user=plugin['admin']
url=plugin['url']
data = {
"name": user... | import requests
import json
from project.user_provision import getJsonResponse
from project.plugin import inviteMessage, removalMessage, getCLIgroups
def inviteUser(email,configMap,allPermissions, plugin_tag, name):
| 46 | 212 | 708 | 16 | 29 | Signiant/External-user-provisioning | project/plugins/jira/__init__.py | Python | inviteUser | inviteUser | 7 | 84 | 7 | 7 | 1d7b29f33be490921bd7d0f6374add33fd771068 | bigcode/the-stack | train |
71d74eeaecd750667906449b | train | function | def removeUser(email, configMap,allPermissions, plugin_tag):
done = False
cont = False
username = email.split('@', 1)[0]
log = ''
instruction = ''
for plugin in configMap['plugins']:
if plugin['plugin'] + ':' + plugin['tag'] == plugin_tag:
password = plugin['password']
... | def removeUser(email, configMap,allPermissions, plugin_tag):
| done = False
cont = False
username = email.split('@', 1)[0]
log = ''
instruction = ''
for plugin in configMap['plugins']:
if plugin['plugin'] + ':' + plugin['tag'] == plugin_tag:
password = plugin['password']
user = plugin['admin']
url=plugin['url']
... | .status_code == 401:
log = plugin_tag + ": error: You are not authenticated to complete this action"
elif add.status_code == 403:
log = plugin_tag + ": error: you do not have administrator permissions to add the user " + username
elif add.status_code == 404:
log = plu... | 199 | 199 | 666 | 14 | 185 | Signiant/External-user-provisioning | project/plugins/jira/__init__.py | Python | removeUser | removeUser | 86 | 143 | 86 | 86 | 98cdfc382924afc9cbce2e0aadbb012b64022777 | bigcode/the-stack | train |
11ffabf7d252d82bf99b7758 | train | class | class Part(object):
"""
Base class for package parts. Provides common properties and methods, but
intended to be subclassed in client code to implement specific part
behaviors.
"""
def __init__(self, partname, content_type, blob=None, package=None):
super(Part, self).__init__()
s... | class Part(object):
| """
Base class for package parts. Provides common properties and methods, but
intended to be subclassed in client code to implement specific part
behaviors.
"""
def __init__(self, partname, content_type, blob=None, package=None):
super(Part, self).__init__()
self._partname = part... | # encoding: utf-8
"""
Open Packaging Convention (OPC) objects related to package parts.
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from .compat import cls_method_fn
from .oxml import serialize_part_xml
from ..oxml import parse_xml
from .packuri import PackURI
from ... | 91 | 256 | 1,175 | 4 | 86 | ajendrex/python-docx | docx/opc/part.py | Python | Part | Part | 19 | 175 | 19 | 19 | ac6eb3f92deb01cf91bfb18687ec2f5c901689a7 | bigcode/the-stack | train |
2282898e1f16625f8171d625 | train | class | class XmlPart(Part):
"""
Base class for package parts containing an XML payload, which is most of
them. Provides additional methods to the |Part| base class that take care
of parsing and reserializing the XML payload and managing relationships
to other parts.
"""
def __init__(self, partname,... | class XmlPart(Part):
| """
Base class for package parts containing an XML payload, which is most of
them. Provides additional methods to the |Part| base class that take care
of parsing and reserializing the XML payload and managing relationships
to other parts.
"""
def __init__(self, partname, content_type, elemen... | (cls, content_type):
"""
Return the custom part class registered for *content_type*, or the
default part class if no custom class is registered for
*content_type*.
"""
if content_type in cls.part_type_for:
return cls.part_type_for[content_type]
return ... | 75 | 75 | 253 | 6 | 68 | ajendrex/python-docx | docx/opc/part.py | Python | XmlPart | XmlPart | 216 | 252 | 216 | 216 | 8462dc1952342d595170a9580ef230d8dfc9ec34 | bigcode/the-stack | train |
f7c592e0fb3123e21db74cc3 | train | class | class PartFactory(object):
"""
Provides a way for client code to specify a subclass of |Part| to be
constructed by |Unmarshaller| based on its content type and/or a custom
callable. Setting ``PartFactory.part_class_selector`` to a callable
object will cause that object to be called with the paramete... | class PartFactory(object):
| """
Provides a way for client code to specify a subclass of |Part| to be
constructed by |Unmarshaller| based on its content type and/or a custom
callable. Setting ``PartFactory.part_class_selector`` to a callable
object will cause that object to be called with the parameters
``content_type, relt... | Return URL contained in target ref of relationship identified by
*rId*.
"""
rel = self.rels[rId]
return rel.target_ref
def _rel_ref_count(self, rId):
"""
Return the count of references in this part's XML to the relationship
identified by *rId*.
... | 113 | 113 | 377 | 5 | 108 | ajendrex/python-docx | docx/opc/part.py | Python | PartFactory | PartFactory | 178 | 213 | 178 | 178 | 86e0b4cab48c60d036158e3723b72f71eb6a82c0 | bigcode/the-stack | train |
9ccc32ddb2d70fa344b69f05 | train | class | class Solution:
def characterReplacement(self, s: str, k: int) -> int:
window_count = defaultdict(int)
res, left, right, count_s = 0, 0, 0, len(s)
max_repeat_count = 0
while right < count_s:
window_count[s[right]] += 1
max_repeat_count = max(max_repeat_count,... | class Solution:
| def characterReplacement(self, s: str, k: int) -> int:
window_count = defaultdict(int)
res, left, right, count_s = 0, 0, 0, len(s)
max_repeat_count = 0
while right < count_s:
window_count[s[right]] += 1
max_repeat_count = max(max_repeat_count, window_count[s[... | 何睿
# @Create Date: 2019-11-30 16:32:47
# @Last Modified by: 何睿
# @Last Modified time: 2019-11-30 16:44:05
from collections import defaultdict
class Solution:
| 64 | 64 | 158 | 3 | 60 | HeRuivio/-Algorithm | LeetCode/2019-11-30-424-Longest-Repeating-Character-Replacement.py | Python | Solution | Solution | 10 | 28 | 10 | 10 | a019cbfe73618a4d81552117eceffd281d9708f4 | bigcode/the-stack | train |
bdabcfb2a283feded2897da4 | train | class | class TestSiameseMatchingBiLSTM(DuplicateTestCase):
@overrides
def setUp(self):
super(TestSiameseMatchingBiLSTM, self).setUp()
self.write_duplicate_questions_train_file()
self.write_duplicate_questions_validation_file()
self.write_duplicate_questions_test_file()
self.data... | class TestSiameseMatchingBiLSTM(DuplicateTestCase):
@overrides
| def setUp(self):
super(TestSiameseMatchingBiLSTM, self).setUp()
self.write_duplicate_questions_train_file()
self.write_duplicate_questions_validation_file()
self.write_duplicate_questions_test_file()
self.data_manager = DataManager(STSInstance)
self.batch_size = 2
... | from overrides import overrides
import math
import tensorflow as tf
from duplicate_questions.data.data_manager import DataManager
from duplicate_questions.data.embedding_manager import EmbeddingManager
from duplicate_questions.models.siamese_bilstm.siamese_matching_bilstm import (
SiameseMatchingBiLSTM
)
from dupl... | 104 | 256 | 855 | 19 | 84 | tjaffri/paraphrase-id-tensorflow | tests/models/siamese_bilstm/test_siamese_matching_bilstm.py | Python | TestSiameseMatchingBiLSTM | TestSiameseMatchingBiLSTM | 15 | 109 | 15 | 16 | f9b1d483b201495a88102006fe4ed8c63c1815af | bigcode/the-stack | train |
f229885a5bf9ed54ffba4da3 | train | class | class UserBrowsingModel(ClickModel):
@property
def model_name(self):
return 'user_browsing_model'
def setExamProb(self,eta):
self.eta = eta
self.original_rd_exam_table = [
[1.0],
[0.98, 1.0],
[1.0, 0.62, 0.95],
[1.0, 0.77, 0.42, 0.82]... | class UserBrowsingModel(ClickModel):
@property
| def model_name(self):
return 'user_browsing_model'
def setExamProb(self,eta):
self.eta = eta
self.original_rd_exam_table = [
[1.0],
[0.98, 1.0],
[1.0, 0.62, 0.95],
[1.0, 0.77, 0.42, 0.82],
[1.0, 0.92, 0.55, 0.31, 0.69],
... | , click_p_list
def estimatePropensityWeightsForOneList(self, click_list, use_non_clicked_data=False):
propensity_weights = []
for r in range(len(click_list)):
pw = 0.0
if use_non_clicked_data | click_list[r] > 0:
pw = 1.0/self.getExamProb(r) * self.getExamPro... | 250 | 250 | 835 | 12 | 238 | Taosheng-ty/ULTRA | ultra/utils/click_models.py | Python | UserBrowsingModel | UserBrowsingModel | 96 | 163 | 96 | 98 | a04dc59343f611d6c8cc01cbd25f54fa59488548 | bigcode/the-stack | train |
bc5d32eca7cbffc08fe0c535 | train | function | def test_load_from_file():
file_name = sys.argv[1]
click_model = None
with open(file_name) as fin:
data = json.load(fin)
click_model = loadModelFromJson(data)
click_list, exam_p_list, click_p_list = click_model.sampleClicksForOneList([4,0,3,4])
print(click_list)
print(exam_p_list... | def test_load_from_file():
| file_name = sys.argv[1]
click_model = None
with open(file_name) as fin:
data = json.load(fin)
click_model = loadModelFromJson(data)
click_list, exam_p_list, click_p_list = click_model.sampleClicksForOneList([4,0,3,4])
print(click_list)
print(exam_p_list)
print(click_p_list)
... | , exam_p_list, click_p_list = test_model.sampleClicksForOneList([4,0,3,4])
print(click_list)
print(exam_p_list)
print(click_p_list)
print(test_model.estimatePropensityWeightsForOneList(click_list))
def test_load_from_file():
| 64 | 64 | 108 | 6 | 58 | Taosheng-ty/ULTRA | ultra/utils/click_models.py | Python | test_load_from_file | test_load_from_file | 237 | 247 | 237 | 237 | f6abbbd7cc618f1d42282b469eb983001915e37b | bigcode/the-stack | train |
51df9f7c3a7ecc4c17627a39 | train | function | def main():
MODELS = {
'pbm' : PositionBiasedModel,
'cascade' : CascadeModel,
'ubm' : UserBrowsingModel,
}
model_name = sys.argv[1]
neg_click_prob=float(sys.argv[2])
pos_click_prob=float(sys.argv[3])
max_relevance_grade=int(sys.argv[4])
eta=float(sys.argv[5])
output_path = s... | def main():
| MODELS = {
'pbm' : PositionBiasedModel,
'cascade' : CascadeModel,
'ubm' : UserBrowsingModel,
}
model_name = sys.argv[1]
neg_click_prob=float(sys.argv[2])
pos_click_prob=float(sys.argv[3])
max_relevance_grade=int(sys.argv[4])
eta=float(sys.argv[5])
output_path = sys.argv[6]
... | click_list, exam_p_list, click_p_list = click_model.sampleClicksForOneList([4,0,3,4])
print(click_list)
print(exam_p_list)
print(click_p_list)
print(click_model.estimatePropensityWeightsForOneList(click_list))
def main():
| 64 | 64 | 170 | 3 | 61 | Taosheng-ty/ULTRA | ultra/utils/click_models.py | Python | main | main | 249 | 267 | 249 | 249 | 11682b7e31903f20f00b9765b2f63cff31b33650 | bigcode/the-stack | train |
fda7ece60d2775eee2eb1ed9 | train | function | def loadModelFromJson(model_desc):
click_model = PositionBiasedModel()
if model_desc['model_name'] == 'user_browsing_model':
click_model = UserBrowsingModel()
elif model_desc['model_name'] == 'cascade_model':
click_model = CascadeModel()
click_model.eta = model_desc['eta']
click_mode... | def loadModelFromJson(model_desc):
| click_model = PositionBiasedModel()
if model_desc['model_name'] == 'user_browsing_model':
click_model = UserBrowsingModel()
elif model_desc['model_name'] == 'cascade_model':
click_model = CascadeModel()
click_model.eta = model_desc['eta']
click_model.click_prob = model_desc['click_pr... | import os,sys
import random, json
def loadModelFromJson(model_desc):
| 18 | 64 | 101 | 8 | 9 | Taosheng-ty/ULTRA | ultra/utils/click_models.py | Python | loadModelFromJson | loadModelFromJson | 4 | 13 | 4 | 4 | d2a830f906768f3251e4a1f16b098f4f4c0fa114 | bigcode/the-stack | train |
0cb472a02b7db1eb2f5ba835 | train | class | class CascadeModel(ClickModel):
@property
def model_name(self):
return 'cascade_model'
def setExamProb(self,eta):
self.eta = eta
self.exam_prob = [1.0 for _ in range(10)]
def sampleClicksForOneList(self, label_list):
click_list, exam_p_list, click_p_list = [], [], []
... | class CascadeModel(ClickModel):
@property
| def model_name(self):
return 'cascade_model'
def setExamProb(self,eta):
self.eta = eta
self.exam_prob = [1.0 for _ in range(10)]
def sampleClicksForOneList(self, label_list):
click_list, exam_p_list, click_p_list = [], [], []
has_click = False
for rank in ra... | return click, exam_p, click_p
def getExamProb(self, rank, last_click_rank):
distance = rank - last_click_rank
if rank < len(self.exam_prob):
exam_p = self.exam_prob[rank][distance-1]
else:
if distance > rank:
exam_p = self.exam_prob[-1][-1]
... | 127 | 127 | 425 | 11 | 115 | Taosheng-ty/ULTRA | ultra/utils/click_models.py | Python | CascadeModel | CascadeModel | 165 | 210 | 165 | 167 | b8df35586cfbb4b8fe0b87cde0ac31a7a5982c33 | bigcode/the-stack | train |
6b4224a84d0aa42d2a4d7cbb | train | class | class PositionBiasedModel(ClickModel):
@property
def model_name(self):
return 'position_biased_model'
def setExamProb(self,eta):
self.eta = eta
self.original_exam_prob = [0.68, 0.61, 0.48, 0.34, 0.28, 0.20, 0.11, 0.10, 0.08, 0.06]
self.exam_prob = [pow(x, eta) for x in self... | class PositionBiasedModel(ClickModel):
@property
| def model_name(self):
return 'position_biased_model'
def setExamProb(self,eta):
self.eta = eta
self.original_exam_prob = [0.68, 0.61, 0.48, 0.34, 0.28, 0.20, 0.11, 0.10, 0.08, 0.06]
self.exam_prob = [pow(x, eta) for x in self.original_exam_prob]
def sampleClicksForOneList(s... | _click_prob - b
self.click_prob = [a + pow(2,i)*b for i in range(relevance_grading_num+1)]
# Set the examination probability for the click model.
def setExamProb(self,eta):
self.eta = eta
return
# Sample clicks for a list
def sampleClicksForOneList(self, label_list):
re... | 132 | 132 | 443 | 13 | 118 | Taosheng-ty/ULTRA | ultra/utils/click_models.py | Python | PositionBiasedModel | PositionBiasedModel | 55 | 94 | 55 | 57 | b1db0b0bbb8bc6310a6e8fbefd6b8819fd3de16f | bigcode/the-stack | train |
913a0947eec202a1260a9361 | train | function | def test_initialization():
# Test PBM
test_model = PositionBiasedModel(0.1,0.9,4,1.0)
print('PBM(3, 4) -> %d, %f, %f' % test_model.sampleClick(3, 4))
print('PBM(2, 0) -> %d, %f, %f' % test_model.sampleClick(2, 0))
print('PBM(14, 1) -> %d, %f, %f' % test_model.sampleClick(14, 1))
click_list, exam... | def test_initialization():
# Test PBM
| test_model = PositionBiasedModel(0.1,0.9,4,1.0)
print('PBM(3, 4) -> %d, %f, %f' % test_model.sampleClick(3, 4))
print('PBM(2, 0) -> %d, %f, %f' % test_model.sampleClick(2, 0))
print('PBM(14, 1) -> %d, %f, %f' % test_model.sampleClick(14, 1))
click_list, exam_p_list, click_p_list = test_model.sampleC... | RELEVANCE LABEL MUST BE INTEGER!')
relevance_label = int(relevance_label) if relevance_label > 0 else 0
exam_p = self.getExamProb(rank)
click_p = self.click_prob[relevance_label if relevance_label < len(self.click_prob) else -1]
click = 1 if random.random() < exam_p * click_p else 0
... | 129 | 129 | 432 | 11 | 118 | Taosheng-ty/ULTRA | ultra/utils/click_models.py | Python | test_initialization | test_initialization | 213 | 235 | 213 | 214 | 1314b4de40d1b27a1ce308002f4de18ee6a77795 | bigcode/the-stack | train |
ba384292270b9c25910b3a93 | train | class | class ClickModel:
def __init__(self, neg_click_prob=0.0, pos_click_prob=1.0, relevance_grading_num=1, eta=1.0):
self.exam_prob = None
self.setExamProb(eta)
self.setClickProb(neg_click_prob, pos_click_prob, relevance_grading_num)
@property
def model_name(self):
return 'click_... | class ClickModel:
| def __init__(self, neg_click_prob=0.0, pos_click_prob=1.0, relevance_grading_num=1, eta=1.0):
self.exam_prob = None
self.setExamProb(eta)
self.setClickProb(neg_click_prob, pos_click_prob, relevance_grading_num)
@property
def model_name(self):
return 'click_model'
# Seri... | FromJson(model_desc):
click_model = PositionBiasedModel()
if model_desc['model_name'] == 'user_browsing_model':
click_model = UserBrowsingModel()
elif model_desc['model_name'] == 'cascade_model':
click_model = CascadeModel()
click_model.eta = model_desc['eta']
click_model.click_prob ... | 102 | 102 | 340 | 4 | 97 | Taosheng-ty/ULTRA | ultra/utils/click_models.py | Python | ClickModel | ClickModel | 15 | 53 | 15 | 15 | 4b6d94d62561f6e799acfb4b48172193147d1965 | bigcode/the-stack | train |
539932bbebbc2a66270b5280 | train | class | class EdgeView(object):
"""A EdgeView class to act as G.edges for a DGLGraph.
Can be used to get a list of current edges and get and set edge data.
See Also
--------
dgl.DGLGraph.edges
"""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __len__(s... | class EdgeView(object):
| """A EdgeView class to act as G.edges for a DGLGraph.
Can be used to get a list of current edges and get and set edge data.
See Also
--------
dgl.DGLGraph.edges
"""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __len__(self):
return sel... | ._node_frame)
def __iter__(self):
return iter(self._graph._node_frame)
def __repr__(self):
data = self._graph.get_n_repr(self._nodes)
return repr({key : data[key] for key in self._graph._node_frame})
class EdgeView(object):
| 65 | 65 | 218 | 5 | 60 | zhengdao-chen/dgl | python/dgl/view.py | Python | EdgeView | EdgeView | 83 | 112 | 83 | 83 | fc988d186ebcc2c60b51f5e37f2c9adbd16b44b6 | bigcode/the-stack | train |
c25fc33f5ba1bfff48daf10b | train | class | class EdgeDataView(MutableMapping):
"""The data view class when G.edges[...].data is called.
See Also
--------
dgl.DGLGraph.edges
"""
__slots__ = ['_graph', '_edges']
def __init__(self, graph, edges):
self._graph = graph
self._edges = edges
def __getitem__(self, key):
... | class EdgeDataView(MutableMapping):
| """The data view class when G.edges[...].data is called.
See Also
--------
dgl.DGLGraph.edges
"""
__slots__ = ['_graph', '_edges']
def __init__(self, graph, edges):
self._graph = graph
self._edges = edges
def __getitem__(self, key):
return self._graph.get_e_rep... | LError('Currently only full slice ":" is supported')
return EdgeSpace(data=EdgeDataView(self._graph, ALL))
else:
return EdgeSpace(data=EdgeDataView(self._graph, edges))
def __call__(self, *args, **kwargs):
"""Return all the edges."""
return self._graph.all_edges(*arg... | 84 | 84 | 283 | 8 | 76 | zhengdao-chen/dgl | python/dgl/view.py | Python | EdgeDataView | EdgeDataView | 114 | 149 | 114 | 114 | 23e5d5fd512704ac8fc675c2fa2b7cb927f1f281 | bigcode/the-stack | train |
a07b660632a5a6457e525fa4 | train | class | class HeteroEdgeDataView(MutableMapping):
"""The data view class when G.edata[etype] is called."""
__slots__ = ['_graph', '_etype', '_etid', '_edges']
def __init__(self, graph, etype, edges):
self._graph = graph
self._etype = etype
self._etid = [self._graph.get_etype_id(t) for t in ... | class HeteroEdgeDataView(MutableMapping):
| """The data view class when G.edata[etype] is called."""
__slots__ = ['_graph', '_etype', '_etid', '_edges']
def __init__(self, graph, etype, edges):
self._graph = graph
self._etype = etype
self._etid = [self._graph.get_etype_id(t) for t in etype] \
if isinstanc... | __init__(self, graph):
self._graph = graph
def __getitem__(self, key):
if isinstance(key, slice):
# slice
if not (key.start is None and key.stop is None
and key.step is None):
raise DGLError('Currently only full slice ":" is supported')
... | 220 | 220 | 736 | 11 | 209 | zhengdao-chen/dgl | python/dgl/view.py | Python | HeteroEdgeDataView | HeteroEdgeDataView | 388 | 459 | 388 | 388 | 69b1b137aa06da5e92dd960d43be144c9824f806 | bigcode/the-stack | train |
77dc3a2785e524f017011221 | train | class | class BlockView(object):
"""A BlockView class to act as nflow.blocks for a NodeFlow.
Can be used to get a list of current edges and get and set edge data.
"""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __len__(self):
return self._graph.num_blocks... | class BlockView(object):
| """A BlockView class to act as nflow.blocks for a NodeFlow.
Can be used to get a list of current edges and get and set edge data.
"""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __len__(self):
return self._graph.num_blocks
def __getitem__(sel... | _frames[self._layer])
def __iter__(self):
return iter(self._graph._node_frames[self._layer])
def __repr__(self):
data = self._graph._node_frames[self._layer]
return repr({key : data[key] for key in data})
class BlockView(object):
| 64 | 64 | 162 | 5 | 59 | zhengdao-chen/dgl | python/dgl/view.py | Python | BlockView | BlockView | 201 | 221 | 201 | 201 | c55c06e4b79d3ab837b45853b27cfa02d0014cb0 | bigcode/the-stack | train |
f0b7fad78fcca4754d7d7ee1 | train | class | class NodeDataView(MutableMapping):
"""The data view class when G.nodes[...].data is called.
See Also
--------
dgl.DGLGraph.nodes
"""
__slots__ = ['_graph', '_nodes']
def __init__(self, graph, nodes):
self._graph = graph
self._nodes = nodes
def __getitem__(self, key):
... | class NodeDataView(MutableMapping):
| """The data view class when G.nodes[...].data is called.
See Also
--------
dgl.DGLGraph.nodes
"""
__slots__ = ['_graph', '_nodes']
def __init__(self, graph, nodes):
self._graph = graph
self._nodes = nodes
def __getitem__(self, key):
return self._graph.get_n_rep... | ):
raise DGLError('Currently only full slice ":" is supported')
return NodeSpace(data=NodeDataView(self._graph, ALL))
else:
return NodeSpace(data=NodeDataView(self._graph, nodes))
def __call__(self):
"""Return the nodes."""
return F.copy_to(F.arange(0... | 84 | 84 | 283 | 8 | 76 | zhengdao-chen/dgl | python/dgl/view.py | Python | NodeDataView | NodeDataView | 46 | 81 | 46 | 46 | e7df56a8e7374316bd877fcedbf2737ed92ea973 | bigcode/the-stack | train |
663817118aae29aca036a1dc | train | class | class LayerView(object):
"""A LayerView class to act as nflow.layers for a NodeFlow.
Can be used to get a list of current nodes and get and set node data.
"""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __len__(self):
return self._graph.num_layers... | class LayerView(object):
| """A LayerView class to act as nflow.layers for a NodeFlow.
Can be used to get a list of current nodes and get and set node data.
"""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __len__(self):
return self._graph.num_layers()
def __getitem__(s... | edge_frame)
def __iter__(self):
return iter(self._graph._edge_frame)
def __repr__(self):
data = self._graph.get_e_repr(self._edges)
return repr({key : data[key] for key in self._graph._edge_frame})
class LayerView(object):
| 64 | 64 | 152 | 5 | 59 | zhengdao-chen/dgl | python/dgl/view.py | Python | LayerView | LayerView | 151 | 171 | 151 | 151 | b87ad797289d312812b1eb40ee77d096d212fea2 | bigcode/the-stack | train |
1e444be91fa08fbc0e96c69a | train | class | class HeteroNodeView(object):
"""A NodeView class to act as G.nodes for a DGLHeteroGraph."""
__slots__ = ['_graph', '_typeid_getter']
def __init__(self, graph, typeid_getter):
self._graph = graph
self._typeid_getter = typeid_getter
def __getitem__(self, key):
if isinstance(key,... | class HeteroNodeView(object):
| """A NodeView class to act as G.nodes for a DGLHeteroGraph."""
__slots__ = ['_graph', '_typeid_getter']
def __init__(self, graph, typeid_getter):
self._graph = graph
self._typeid_getter = typeid_getter
def __getitem__(self, key):
if isinstance(key, slice):
# slice
... | __len__(self):
return len(self._graph._edge_frames[self._flow])
def __iter__(self):
return iter(self._graph._edge_frames[self._flow])
def __repr__(self):
data = self._graph._edge_frames[self._flow]
return repr({key : data[key] for key in data})
class HeteroNodeView(object):
| 80 | 80 | 269 | 8 | 72 | zhengdao-chen/dgl | python/dgl/view.py | Python | HeteroNodeView | HeteroNodeView | 251 | 281 | 251 | 251 | 8a6d2bce2c5e2c5e069dc9b93fb23471df31b454 | bigcode/the-stack | train |
837782422bbb4a8f03f51a34 | train | class | class HeteroNodeDataView(MutableMapping):
"""The data view class when G.ndata[ntype] is called."""
__slots__ = ['_graph', '_ntype', '_ntid', '_nodes']
def __init__(self, graph, ntype, ntid, nodes):
self._graph = graph
self._ntype = ntype
self._ntid = ntid
self._nodes = nodes... | class HeteroNodeDataView(MutableMapping):
| """The data view class when G.ndata[ntype] is called."""
__slots__ = ['_graph', '_ntype', '_ntid', '_nodes']
def __init__(self, graph, ntype, ntid, nodes):
self._graph = graph
self._ntype = ntype
self._ntid = ntid
self._nodes = nodes
def __getitem__(self, key):
... | self._typeid_getter = typeid_getter
def __getitem__(self, key):
if isinstance(key, slice):
# slice
if not (key.start is None and key.stop is None
and key.step is None):
raise DGLError('Currently only full slice ":" is supported')
node... | 215 | 215 | 718 | 11 | 204 | zhengdao-chen/dgl | python/dgl/view.py | Python | HeteroNodeDataView | HeteroNodeDataView | 283 | 352 | 283 | 283 | ea506487b148ae8682c6d84ff726c115baf2f381 | bigcode/the-stack | train |
2077215b26387405aef06ff2 | train | class | class HeteroEdgeView(object):
"""A EdgeView class to act as G.edges for a DGLHeteroGraph."""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __getitem__(self, key):
if isinstance(key, slice):
# slice
if not (key.start is None and key.st... | class HeteroEdgeView(object):
| """A EdgeView class to act as G.edges for a DGLHeteroGraph."""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __getitem__(self, key):
if isinstance(key, slice):
# slice
if not (key.start is None and key.stop is None
... | ntid[i]]}
ret[ntype] = value
return repr(ret)
else:
data = self._graph._get_n_repr(self._ntid, self._nodes)
return repr({key : data[key]
for key in self._graph._node_frames[self._ntid]})
class HeteroEdgeView(object):
| 74 | 74 | 248 | 8 | 66 | zhengdao-chen/dgl | python/dgl/view.py | Python | HeteroEdgeView | HeteroEdgeView | 354 | 386 | 354 | 354 | ee238c6001744c4cc9a5c3d242ec9f69c94141a1 | bigcode/the-stack | train |
e00357199b624da5ba1efcae | train | class | class LayerDataView(MutableMapping):
"""The data view class when G.layers[...].data is called.
"""
__slots__ = ['_graph', '_layer']
def __init__(self, graph, layer):
self._graph = graph
self._layer = layer
def __getitem__(self, key):
return self._graph._node_frames[self._la... | class LayerDataView(MutableMapping):
| """The data view class when G.layers[...].data is called.
"""
__slots__ = ['_graph', '_layer']
def __init__(self, graph, layer):
self._graph = graph
self._layer = layer
def __getitem__(self, key):
return self._graph._node_frames[self._layer][key]
def __setitem__(self, ... | , int):
raise DGLError('Currently we only support the view of one layer')
return NodeSpace(data=LayerDataView(self._graph, layer))
def __call__(self):
"""Return the nodes."""
return F.arange(0, len(self))
class LayerDataView(MutableMapping):
| 64 | 64 | 212 | 8 | 56 | zhengdao-chen/dgl | python/dgl/view.py | Python | LayerDataView | LayerDataView | 173 | 199 | 173 | 173 | cbaffe4dbde31431c8e51dd206a87f3c5e076e50 | bigcode/the-stack | train |
34f502378a382282f60d88ce | train | class | class BlockDataView(MutableMapping):
"""The data view class when G.blocks[...].data is called.
"""
__slots__ = ['_graph', '_flow']
def __init__(self, graph, flow):
self._graph = graph
self._flow = flow
def __getitem__(self, key):
return self._graph._edge_frames[self._flow][... | class BlockDataView(MutableMapping):
| """The data view class when G.blocks[...].data is called.
"""
__slots__ = ['_graph', '_flow']
def __init__(self, graph, flow):
self._graph = graph
self._flow = flow
def __getitem__(self, key):
return self._graph._edge_frames[self._flow][key]
def __setitem__(self, key, ... | only support the view of one flow')
return EdgeSpace(data=BlockDataView(self._graph, flow))
def __call__(self, *args, **kwargs):
"""Return all the edges."""
return self._graph.all_edges(*args, **kwargs)
class BlockDataView(MutableMapping):
| 64 | 64 | 212 | 8 | 56 | zhengdao-chen/dgl | python/dgl/view.py | Python | BlockDataView | BlockDataView | 223 | 249 | 223 | 223 | 5555249b607fecb2d6c9c06004e367c08a50af04 | bigcode/the-stack | train |
b80f9822bb968a02a428588c | train | class | class NodeView(object):
"""A NodeView class to act as G.nodes for a DGLGraph.
Can be used to get a list of current nodes and get and set node data.
See Also
--------
dgl.DGLGraph.nodes
"""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __len__(s... | class NodeView(object):
| """A NodeView class to act as G.nodes for a DGLGraph.
Can be used to get a list of current nodes and get and set node data.
See Also
--------
dgl.DGLGraph.nodes
"""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __len__(self):
return sel... | namedtuple
from collections.abc import MutableMapping
import numpy as np
from .base import ALL, is_all, DGLError
from . import backend as F
NodeSpace = namedtuple('NodeSpace', ['data'])
EdgeSpace = namedtuple('EdgeSpace', ['data'])
class NodeView(object):
| 64 | 64 | 214 | 5 | 59 | zhengdao-chen/dgl | python/dgl/view.py | Python | NodeView | NodeView | 15 | 44 | 15 | 15 | be493e70f65ff34a69face9a8df332c518c58cdd | bigcode/the-stack | train |
e0de44b55bbc0499943ffc2c | train | class | class MaxMixtureCompletePrior(object):
"""Prior density estimation."""
def __init__(self, n_gaussians=6, prefix=3):
self.n_gaussians = n_gaussians
self.prefix = prefix
self.prior = self.create_prior_from_cmu()
def create_prior_from_cmu(self):
"""Get the prior from the CMU ... | class MaxMixtureCompletePrior(object):
| """Prior density estimation."""
def __init__(self, n_gaussians=6, prefix=3):
self.n_gaussians = n_gaussians
self.prefix = prefix
self.prior = self.create_prior_from_cmu()
def create_prior_from_cmu(self):
"""Get the prior from the CMU motion database."""
from os.path... | def __init__(self, means, precs, weights, prefix):
self.means = means
self.precs = precs # Already "sqrt"ed
self.weights = weights
self.prefix = prefix
def __call__(self, x):
return(MaxMixtureComplete(x=x[self.prefix:], means=self.means,
pr... | 92 | 93 | 311 | 8 | 84 | sg-first/Motion-Capture-CV | neural_body_fitting-master/external/up/up_tools/max_mixture_prior.py | Python | MaxMixtureCompletePrior | MaxMixtureCompletePrior | 76 | 108 | 76 | 77 | b669c51883b361550d89e09541632c0c0cf28469 | bigcode/the-stack | train |
bf37f3e54585b7df2f5f5477 | train | class | class MaxMixtureComplete(ch.Ch):
"""Define the MaxMixture class."""
dterms = 'x', 'means', 'precs', 'weights'
def on_changed(self, which):
# setup means, precs and loglikelihood expressions
if 'means' in which or 'precs' in which or 'weights' in which:
# This is just the mahal... | class MaxMixtureComplete(ch.Ch):
| """Define the MaxMixture class."""
dterms = 'x', 'means', 'precs', 'weights'
def on_changed(self, which):
# setup means, precs and loglikelihood expressions
if 'means' in which or 'precs' in which or 'weights' in which:
# This is just the mahalanobis part.
self.logl... | """
Copyright 2016 Max Planck Society, Federica Bogo, Angjoo Kanazawa. All
rights reserved.
This software is provided for research purposes only.
By using this software you agree to the terms of the SMPLify license here:
http://smplify.is.tue.mpg.de/license
"""
# pylint: disable=no-member, invalid-name, attribu... | 106 | 121 | 405 | 8 | 97 | sg-first/Motion-Capture-CV | neural_body_fitting-master/external/up/up_tools/max_mixture_prior.py | Python | MaxMixtureComplete | MaxMixtureComplete | 16 | 56 | 16 | 17 | 6f7a6991c15730edf17b0a0aa15499fd5e26cfa2 | bigcode/the-stack | train |
b2df29c5a57e0fe0e2a18c2f | train | class | class MaxMixtureCompleteWrapper(object):
"""Convenience wrapper to match interface spec."""
def __init__(self, means, precs, weights, prefix):
self.means = means
self.precs = precs # Already "sqrt"ed
self.weights = weights
self.prefix = prefix
def __call__(self, x):
... | class MaxMixtureCompleteWrapper(object):
| """Convenience wrapper to match interface spec."""
def __init__(self, means, precs, weights, prefix):
self.means = means
self.precs = precs # Already "sqrt"ed
self.weights = weights
self.prefix = prefix
def __call__(self, x):
return(MaxMixtureComplete(x=x[self.prefi... | Is, Js, Vs = sp.find(dr)
dr = sp.csc_matrix((Vs, (Is, Js)), shape=(dr.shape[0]+1, dr.shape[1]))
return dr
# pylint: disable=too-few-public-methods
class MaxMixtureCompleteWrapper(object):
| 64 | 64 | 103 | 8 | 55 | sg-first/Motion-Capture-CV | neural_body_fitting-master/external/up/up_tools/max_mixture_prior.py | Python | MaxMixtureCompleteWrapper | MaxMixtureCompleteWrapper | 60 | 72 | 60 | 61 | e6fc18954f70367bbee800ce8a7f6bc75d6eeaf6 | bigcode/the-stack | train |
2c37587e794d1bb6b89ad223 | train | class | class ExponentformatValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self,
plotly_name="exponentformat",
parent_name="contourcarpet.colorbar",
**kwargs
):
super(ExponentformatValidator, self).__init__(
plotly_name=plotly_name,
... | class ExponentformatValidator(_plotly_utils.basevalidators.EnumeratedValidator):
| def __init__(
self,
plotly_name="exponentformat",
parent_name="contourcarpet.colorbar",
**kwargs
):
super(ExponentformatValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colo... | import _plotly_utils.basevalidators
class ExponentformatValidator(_plotly_utils.basevalidators.EnumeratedValidator):
| 24 | 64 | 134 | 16 | 7 | acrucetta/Chicago_COVI_WebApp | env/lib/python3.8/site-packages/plotly/validators/contourcarpet/colorbar/_exponentformat.py | Python | ExponentformatValidator | ExponentformatValidator | 4 | 18 | 4 | 4 | 496bc0d03e5064c7271a905396776a0af2a35ddd | bigcode/the-stack | train |
d50a168b1b1e4f9b2109e2a1 | train | function | def go_to_next_page(driver, urls, max_urls):
next_button = driver.find_elements_by_xpath('//a[@id="pnnext"]')
if any(next_button) and len(urls) < max_urls:
next_button[0].click()
time.sleep(random.uniform(0.6, 1.8) * 10)
return True
return False
| def go_to_next_page(driver, urls, max_urls):
| next_button = driver.find_elements_by_xpath('//a[@id="pnnext"]')
if any(next_button) and len(urls) < max_urls:
next_button[0].click()
time.sleep(random.uniform(0.6, 1.8) * 10)
return True
return False
| _name] = urls
if len(queries_dict.keys()) > 1:
logging.info('[!] Waiting 2 minutes to extract the following spider.')
time.sleep(120)
driver.close()
del(driver)
return(spiders_results)
def go_to_next_page(driver, urls, max_urls):
| 64 | 64 | 80 | 12 | 52 | odarotto/start_urls_generation | start_urls_generation.py | Python | go_to_next_page | go_to_next_page | 409 | 415 | 409 | 409 | 2bd04e96739de026905efe9fcc099ac1ff9963d9 | bigcode/the-stack | train |
f2020e974c06b528a956c86e | train | function | def generate_google_query(
db_host, db_user, db_pass, db_name,
google_include_tpl, google_ignore1_tpl, look_for=None, query=''):
# you can generate queries only for some spiders by adding them as cmd params
addit = ''
if isinstance(look_for, list):
addit = " AND `name` IN ('{}')".fo... | def generate_google_query(
db_host, db_user, db_pass, db_name,
google_include_tpl, google_ignore1_tpl, look_for=None, query=''):
# you can generate queries only for some spiders by adding them as cmd params
| addit = ''
if isinstance(look_for, list):
addit = " AND `name` IN ('{}')".format("', '".join(look_for))
if isinstance(look_for, str):
addit = " AND `name` IN ('{}')".format(look_for)
# Connection to db
db = MySQLdb.connect(db_host, db_user, db_pass, db_name, use_unicode=True, charse... | , spider_name)
logging.info('[!] Saving {} to {}'.format(spider_name, folder))
df.to_csv(
file_path,
sep='\t',
index=False,
index_label=False,
header=False
)
def generate_google_query(
db_host,... | 104 | 105 | 351 | 52 | 52 | odarotto/start_urls_generation | start_urls_generation.py | Python | generate_google_query | generate_google_query | 305 | 342 | 305 | 309 | 39560124a7edb0be486ac5b282b7daac954adaa8 | bigcode/the-stack | train |
99ad89087d512dbd8df3aa40 | train | function | def generate_to_add_dict(publisher_dict, start_url):
to_add_dict = {
'company_slug': publisher_dict['company_slug'],
'company_name': publisher_dict['company_name'],
'start_url': start_url
} if 'company_slug' in publisher_dict.keys() else {
'company_name': publisher_dict['company_... | def generate_to_add_dict(publisher_dict, start_url):
| to_add_dict = {
'company_slug': publisher_dict['company_slug'],
'company_name': publisher_dict['company_name'],
'start_url': start_url
} if 'company_slug' in publisher_dict.keys() else {
'company_name': publisher_dict['company_name'],
'start_url': start_url
}
retu... | return url
return new_url
def rearrange_hirehive_com(url):
_format = 'https://{}.hirehive.com/'
parsed_url = urlparse(url)
return _format.format(parsed_url.path.strip('/'))
def generate_to_add_dict(publisher_dict, start_url):
| 63 | 64 | 89 | 12 | 51 | odarotto/start_urls_generation | start_urls_generation.py | Python | generate_to_add_dict | generate_to_add_dict | 248 | 257 | 248 | 248 | 75bdcfe64362702009e3bbd9528a53a461ebf35c | bigcode/the-stack | train |
45fbe07c7bcf18d8b7965714 | train | function | def load_csv_file(file_path, url_only=False):
spider_publishers = list()
if os.stat(file_path).st_size != 0:
with open(file_path, 'r') as file:
for line in file:
fields = line.strip().split('\t') \
if '\t' in line else line.strip().split()
... | def load_csv_file(file_path, url_only=False):
| spider_publishers = list()
if os.stat(file_path).st_size != 0:
with open(file_path, 'r') as file:
for line in file:
fields = line.strip().split('\t') \
if '\t' in line else line.strip().split()
if url_only:
line_dict = f... | = publishers_path + '/' + file_name
publishers[file_name.replace('.csv', '')] = load_csv_file(file_path)
return publishers
# ? Case of use: load publishers for only one spider
# return load_csv_format(file_path)
def load_csv_file(file_path, url_only=False):
| 64 | 64 | 180 | 11 | 53 | odarotto/start_urls_generation | start_urls_generation.py | Python | load_csv_file | load_csv_file | 88 | 109 | 88 | 88 | 1345594b6bc61b1b47adccdcbaf62a1ff10b03f0 | bigcode/the-stack | train |
1d5bd45a2502e87a2dc4709c | train | function | def insert_new_urls_to_repo(start_urls, comparing_publishers, from_action=''):
"""insert_new_urls_to_repo : This function compares each new publisher's URL found in the input
data against the comparing data.
Args:
start_urls (dict): input data
comparing_publishers (dict): comparing data
... | def insert_new_urls_to_repo(start_urls, comparing_publishers, from_action=''):
| """insert_new_urls_to_repo : This function compares each new publisher's URL found in the input
data against the comparing data.
Args:
start_urls (dict): input data
comparing_publishers (dict): comparing data
"""
for spider_name, publishers_list in comparing_publishers.items():
... | format.format(parsed_url.path.strip('/'))
def generate_to_add_dict(publisher_dict, start_url):
to_add_dict = {
'company_slug': publisher_dict['company_slug'],
'company_name': publisher_dict['company_name'],
'start_url': start_url
} if 'company_slug' in publisher_dict.keys() else {
... | 115 | 115 | 385 | 17 | 97 | odarotto/start_urls_generation | start_urls_generation.py | Python | insert_new_urls_to_repo | insert_new_urls_to_repo | 260 | 302 | 260 | 260 | 1942b53ca655a9c64cf86ee5ccb2ad92e1426f44 | bigcode/the-stack | train |
270c6c29430e89a3d6f7ecf6 | train | function | def load_spiders_from_db(query, db_host='127.0.0.1', db_user='root', db_pass='pass', db_name='db'):
"""load_spiders_from_db :Creates a Connection() object and makes a query to the database
using is Cursor() object.
Args:
db_host (str, optional): Database Host. Defaults to '127.0.0.1'.
db_u... | def load_spiders_from_db(query, db_host='127.0.0.1', db_user='root', db_pass='pass', db_name='db'):
| """load_spiders_from_db :Creates a Connection() object and makes a query to the database
using is Cursor() object.
Args:
db_host (str, optional): Database Host. Defaults to '127.0.0.1'.
db_user (str, optional): Database Username. Defaults to 'root'.
db_pass (str, optional): Databas... | .parse
from dotenv import load_dotenv, find_dotenv
from MySQLdb.cursors import DictCursor
from pandas import DataFrame
from scraping_common import *
from urllib.parse import urlparse
import start_urls_generation
def load_spiders_from_db(query, db_host='127.0.0.1', db_user='root', db_pass='pass', db_name='db'):
| 80 | 80 | 267 | 34 | 45 | odarotto/start_urls_generation | start_urls_generation.py | Python | load_spiders_from_db | load_spiders_from_db | 22 | 51 | 22 | 22 | dfb70f768a6730030e1cba6070658a01c245ed7a | bigcode/the-stack | train |
4c891b0ca75e4c4a233466c6 | train | function | def find_spider_by_name(name, spiders):
"""find_spider_by_name : Iterates over a list of dict objects until it find one with the name
given as an input.
Args:
name (str): name of the spider we need to find.
spiders (list): list of spiders on which the function will iterate.
Returns:
... | def find_spider_by_name(name, spiders):
| """find_spider_by_name : Iterates over a list of dict objects until it find one with the name
given as an input.
Args:
name (str): name of the spider we need to find.
spiders (list): list of spiders on which the function will iterate.
Returns:
dict: the dict object representing... | _domain_from_url : extracts the domain part of a URL.
Args:
url (str): URL that we need the domain from.
Returns:
str: domain part of the input URL.
"""
return urllib.parse.urlparse(url).netloc
def find_spider_by_name(name, spiders):
| 64 | 64 | 110 | 10 | 53 | odarotto/start_urls_generation | start_urls_generation.py | Python | find_spider_by_name | find_spider_by_name | 124 | 137 | 124 | 124 | fdbc1330bbb708ea0c12b78c1961224a963eb508 | bigcode/the-stack | train |
b620062bc1599d22d75b6feb | train | function | def rearrange_brassring(url):
_format = 'https://{}/TGnewUI/Search/Home/Home?partnerid={}&siteid={}#home'
domain = extract_domain_from_url(url)
try:
partnerid = re.search(r'partnerid=(\d+)', url).group(1)
siteid = re.search(r'siteid=(\d+)', url).group(1)
except Exception:
return ... | def rearrange_brassring(url):
| _format = 'https://{}/TGnewUI/Search/Home/Home?partnerid={}&siteid={}#home'
domain = extract_domain_from_url(url)
try:
partnerid = re.search(r'partnerid=(\d+)', url).group(1)
siteid = re.search(r'siteid=(\d+)', url).group(1)
except Exception:
return url
return _format.format(... | , spider_name):
logging.info('[!] Rearranging URL: {}'.format(url))
# Choose the rearranger
for f in dir(start_urls_generation):
if spider_name in f:
return getattr(start_urls_generation, f)(url)
return url
def rearrange_brassring(url):
| 64 | 64 | 109 | 8 | 55 | odarotto/start_urls_generation | start_urls_generation.py | Python | rearrange_brassring | rearrange_brassring | 212 | 220 | 212 | 212 | 3a244db2e99ebf6cfcfada9e1eb8aab3394cc5c1 | bigcode/the-stack | train |
4fda84c5590653508d283270 | train | function | def rearrange_myworkday(url):
try:
new_url = re.search(r'(.*)(?=/job)', url).group(0)
except Exception:
return url
return new_url
| def rearrange_myworkday(url):
| try:
new_url = re.search(r'(.*)(?=/job)', url).group(0)
except Exception:
return url
return new_url
| domain = extract_domain_from_url(r.url)
try:
token = re.search(r'token\=([a-zA-Z0-9]+)', url).group(1)
except AttributeError:
return url
return _format.format(domain, token)
def rearrange_myworkday(url):
| 64 | 64 | 44 | 8 | 56 | odarotto/start_urls_generation | start_urls_generation.py | Python | rearrange_myworkday | rearrange_myworkday | 234 | 239 | 234 | 234 | 34e1279c4d8183e02a89d8ef582f5dd968dcd8ea | bigcode/the-stack | train |
6a1008965505bafef24af524 | train | function | def show_repeated_results(driver, urls, max_urls):
repeat_with_all_results = driver.find_elements_by_xpath(
'//*[@id="ofr"]/i/a'
)
if any(repeat_with_all_results) and len(urls) < max_urls:
repeat_with_all_results[0].click()
time.sleep(random.uniform(0.6, 1.8) * 10)
return Tru... | def show_repeated_results(driver, urls, max_urls):
| repeat_with_all_results = driver.find_elements_by_xpath(
'//*[@id="ofr"]/i/a'
)
if any(repeat_with_all_results) and len(urls) < max_urls:
repeat_with_all_results[0].click()
time.sleep(random.uniform(0.6, 1.8) * 10)
return True
return False
| "]')
if any(next_button) and len(urls) < max_urls:
next_button[0].click()
time.sleep(random.uniform(0.6, 1.8) * 10)
return True
return False
def show_repeated_results(driver, urls, max_urls):
| 64 | 64 | 92 | 12 | 51 | odarotto/start_urls_generation | start_urls_generation.py | Python | show_repeated_results | show_repeated_results | 418 | 426 | 418 | 418 | 4d0d5cd3e143db01f476676f0f6fd8bd799c8bbe | bigcode/the-stack | train |
b886f44641adc4d0577a9c28 | train | function | def rearrange_publisher_url(url, spider_name):
logging.info('[!] Rearranging URL: {}'.format(url))
# Choose the rearranger
for f in dir(start_urls_generation):
if spider_name in f:
return getattr(start_urls_generation, f)(url)
return url
| def rearrange_publisher_url(url, spider_name):
| logging.info('[!] Rearranging URL: {}'.format(url))
# Choose the rearranger
for f in dir(start_urls_generation):
if spider_name in f:
return getattr(start_urls_generation, f)(url)
return url
| _dict)
except IndexError:
to_add_dict = generate_to_add_dict(publisher_dict, publisher_dict['start_url'])
spider_start_urls.append(to_add_dict)
start_urls[spider_name] = spider_start_urls
return start_urls
def rearrange_publisher_url(url, spider_name):
| 64 | 64 | 63 | 11 | 52 | odarotto/start_urls_generation | start_urls_generation.py | Python | rearrange_publisher_url | rearrange_publisher_url | 203 | 209 | 203 | 203 | 6a679ca69e5343b175035d6362dce1e9b1dddd32 | bigcode/the-stack | train |
1f4c8f38fd71aff04de250f1 | train | function | def rearrange_ripplehire(url):
_format = 'https://{}/ripplehire/candidate?token={}#list'
r = requests.get(url)
domain = extract_domain_from_url(r.url)
try:
token = re.search(r'token\=([a-zA-Z0-9]+)', url).group(1)
except AttributeError:
return url
return _format.format(domain, to... | def rearrange_ripplehire(url):
| _format = 'https://{}/ripplehire/candidate?token={}#list'
r = requests.get(url)
domain = extract_domain_from_url(r.url)
try:
token = re.search(r'token\=([a-zA-Z0-9]+)', url).group(1)
except AttributeError:
return url
return _format.format(domain, token)
| 'partnerid=(\d+)', url).group(1)
siteid = re.search(r'siteid=(\d+)', url).group(1)
except Exception:
return url
return _format.format(domain, partnerid, siteid)
def rearrange_ripplehire(url):
| 64 | 64 | 92 | 8 | 56 | odarotto/start_urls_generation | start_urls_generation.py | Python | rearrange_ripplehire | rearrange_ripplehire | 223 | 231 | 223 | 223 | c07134b4a775fb99676ec8c7ea8fe2a8455b1bfe | bigcode/the-stack | train |
4beb26a7870267d725152b8a | train | function | def make_google_query(queries_dict, max_urls, deepnest=0):
driver = get_chromedriver(
# headless=True,
user_agent=get_user_agent(),
fast_load=True,
images=True
)
js = ''
# Load the JavaScript to generate URLs from serach results
with open('Internet Marketing Ninjas S... | def make_google_query(queries_dict, max_urls, deepnest=0):
| driver = get_chromedriver(
# headless=True,
user_agent=get_user_agent(),
fast_load=True,
images=True
)
js = ''
# Load the JavaScript to generate URLs from serach results
with open('Internet Marketing Ninjas SERP Extractor User.js') as script:
js = script.read... | = row[3].split(',')
google_query = row[4]
if not isinstance(google_query, str):
google_query = ''
google_query += google_include_tpl.format(spider_domain)
for ignored_subdomain in ignored_subdomains:
google_query += google_ignore1_tpl.format(ignored_subdomain, sp... | 146 | 146 | 489 | 16 | 129 | odarotto/start_urls_generation | start_urls_generation.py | Python | make_google_query | make_google_query | 345 | 406 | 345 | 345 | c929f91df2aee8f2325548ab24fb9e4700062c93 | bigcode/the-stack | train |
a6abc19612092e584d9d0a52 | train | function | def generate_start_urls(publishers, spiders):
"""generate_start_urls : Iterates over the input publishers list, then finds the proper spider
for the current spider_name, if the spider does not exists it continues. If the spider exists
then iterates over all the publishers for that spider_name, matching the ... | def generate_start_urls(publishers, spiders):
| """generate_start_urls : Iterates over the input publishers list, then finds the proper spider
for the current spider_name, if the spider does not exists it continues. If the spider exists
then iterates over all the publishers for that spider_name, matching the publishers start url
with the spiders sta... | domain part of a URL.
Args:
url (str): URL that we need the domain from.
Returns:
str: domain part of the input URL.
"""
return urllib.parse.urlparse(url).netloc
def find_spider_by_name(name, spiders):
"""find_spider_by_name : Iterates over a list of dict objects until it find o... | 168 | 168 | 561 | 10 | 157 | odarotto/start_urls_generation | start_urls_generation.py | Python | generate_start_urls | generate_start_urls | 140 | 200 | 140 | 140 | 2e234e854ceb2556bbc75e621b7329b7cfbe5cc9 | bigcode/the-stack | train |
65fbacc6fd7aa2cecb0003b8 | train | function | def rearrange_hirehive_com(url):
_format = 'https://{}.hirehive.com/'
parsed_url = urlparse(url)
return _format.format(parsed_url.path.strip('/'))
| def rearrange_hirehive_com(url):
| _format = 'https://{}.hirehive.com/'
parsed_url = urlparse(url)
return _format.format(parsed_url.path.strip('/'))
|
return _format.format(domain, token)
def rearrange_myworkday(url):
try:
new_url = re.search(r'(.*)(?=/job)', url).group(0)
except Exception:
return url
return new_url
def rearrange_hirehive_com(url):
| 64 | 64 | 42 | 10 | 53 | odarotto/start_urls_generation | start_urls_generation.py | Python | rearrange_hirehive_com | rearrange_hirehive_com | 242 | 245 | 242 | 242 | dc1660ee3a9964fcf4372ea98b535ca41da08d75 | bigcode/the-stack | train |
44bb26da48bd21bf8c9d84a9 | train | function | def load_publishers(publishers_path=None, file_path=None):
"""load_publishers : Reads all of the CSV files in PUBLISHERS_PATH (not checked yet)
and generates a list() object with several dict() objects in the following structure:
{
"spider_name": [
{
"company_slug": "sl... | def load_publishers(publishers_path=None, file_path=None):
| """load_publishers : Reads all of the CSV files in PUBLISHERS_PATH (not checked yet)
and generates a list() object with several dict() objects in the following structure:
{
"spider_name": [
{
"company_slug": "slug",
"company_name": "name",
... | (query)
results = cursor.fetchall()
except Exception as identifier:
logging.info('[!] Error making query to database: {}'.format(identifier))
finally:
if db is not None and cursor is not None:
cursor.close()
db.close()
return results
def load_publishers(publi... | 70 | 70 | 235 | 14 | 55 | odarotto/start_urls_generation | start_urls_generation.py | Python | load_publishers | load_publishers | 54 | 83 | 54 | 54 | 3d67beb34d65a9e5263a5ab07375cc1fdf18ed64 | bigcode/the-stack | train |
13e83d410c46b33f2a6449ac | train | function | def extract_domain_from_url(url):
"""extract_domain_from_url : extracts the domain part of a URL.
Args:
url (str): URL that we need the domain from.
Returns:
str: domain part of the input URL.
"""
return urllib.parse.urlparse(url).netloc
| def extract_domain_from_url(url):
| """extract_domain_from_url : extracts the domain part of a URL.
Args:
url (str): URL that we need the domain from.
Returns:
str: domain part of the input URL.
"""
return urllib.parse.urlparse(url).netloc
| [-1]
} if len(fields) == 2 else {
'company_slug': fields[0],
'company_name': fields[1],
'start_url': fields[-1]
}
spider_publishers.append(line_dict)
return spider_publishers
def extract_domai... | 64 | 64 | 64 | 7 | 56 | odarotto/start_urls_generation | start_urls_generation.py | Python | extract_domain_from_url | extract_domain_from_url | 112 | 121 | 112 | 112 | 42f53687872c198d0568f1b3a3cf95ed59bbd8e5 | bigcode/the-stack | train |
2d4ece7afe742509f83409dd | train | function | def show_options(cards_in_hand: List, cost_available: int, test_user_input: int = None) -> dict:
value = None
card_to_play_now = {}
counter = 0
while card_to_play_now == {} and value != '' and counter < 10:
if test_user_input is not None:
value = test_user_input
else:
... | def show_options(cards_in_hand: List, cost_available: int, test_user_input: int = None) -> dict:
| value = None
card_to_play_now = {}
counter = 0
while card_to_play_now == {} and value != '' and counter < 10:
if test_user_input is not None:
value = test_user_input
else:
value = input('What card would you like to play? (Press ENTER to PLAY NOTHING) ')
i... | from typing import List
import click
def show_options(cards_in_hand: List, cost_available: int, test_user_input: int = None) -> dict:
| 33 | 64 | 203 | 25 | 7 | battleforcastile/battleforcastile | battleforcastile/utils/show_options.py | Python | show_options | show_options | 6 | 29 | 6 | 6 | 75a4f7b06f2dbd5d40b48be32671c1b495525054 | bigcode/the-stack | train |
d6d443cd7735e0f4b5f74705 | train | class | class ToGFA2:
def _to_gfa2_a(self):
items = []
for oline in self.captured_path:
if isinstance(oline.line, gfapy.line.segment.GFA1):
items.append(str(oline))
elif isinstance(oline.line, gfapy.line.edge.Link):
items.append(oline.line.eid + str(oline.orient))
a = ["O"]
a.appe... | class ToGFA2:
| def _to_gfa2_a(self):
items = []
for oline in self.captured_path:
if isinstance(oline.line, gfapy.line.segment.GFA1):
items.append(str(oline))
elif isinstance(oline.line, gfapy.line.edge.Link):
items.append(oline.line.eid + str(oline.orient))
a = ["O"]
a.append(self.field_t... | import gfapy
class ToGFA2:
| 10 | 64 | 109 | 6 | 3 | ujjwalsh/gfapy | gfapy/line/group/path/to_gfa2.py | Python | ToGFA2 | ToGFA2 | 3 | 15 | 3 | 4 | 8467a34f2dd5a4884142055367c7403eff484c2a | bigcode/the-stack | train |
97183c5eb4fd529d5bd4e0c3 | train | class | class InsufficientStorageException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Insufficient Storage'
super().__init__(status_code=507, message=message)
| class InsufficientStorageException(ServerException):
| def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Insufficient Storage'
super().__init__(status_code=507, message=message)
| message)
class VariantAlsoNegotiatesException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Variant Also Negotiates'
super().__init__(status_code=506, message=message)
class InsufficientStorageException(ServerException):
| 64 | 64 | 52 | 8 | 56 | DeveloperRSquared/http-exceptions | src/http_exceptions/server_exceptions.py | Python | InsufficientStorageException | InsufficientStorageException | 58 | 61 | 58 | 58 | 630d3a1e3e1edc11cdf7518b259425699333b01e | bigcode/the-stack | train |
fcea71dfdf8e993f04acd571 | train | class | class BadGatewayException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Bad Gateway'
super().__init__(status_code=502, message=message)
| class BadGatewayException(ServerException):
| def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Bad Gateway'
super().__init__(status_code=502, message=message)
| 500, message=message)
class NotImplementedException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Not Implemented'
super().__init__(status_code=501, message=message)
class BadGatewayException(ServerException):
| 64 | 64 | 50 | 7 | 57 | DeveloperRSquared/http-exceptions | src/http_exceptions/server_exceptions.py | Python | BadGatewayException | BadGatewayException | 28 | 31 | 28 | 28 | 814c04c24fbf2c59d983bd492c9a65345d4d7d7d | bigcode/the-stack | train |
a43a20fd3da988f13578de68 | train | class | class GatewayTimeoutException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Gateway Timeout'
super().__init__(status_code=504, message=message)
| class GatewayTimeoutException(ServerException):
| def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Gateway Timeout'
super().__init__(status_code=504, message=message)
| 502, message=message)
class ServiceUnavailableException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Service Unavailable'
super().__init__(status_code=503, message=message)
class GatewayTimeoutException(ServerException):
| 64 | 64 | 50 | 7 | 57 | DeveloperRSquared/http-exceptions | src/http_exceptions/server_exceptions.py | Python | GatewayTimeoutException | GatewayTimeoutException | 40 | 43 | 40 | 40 | 05b0af06530771509c6c96460beccd1cb2975e40 | bigcode/the-stack | train |
332bcc6f6d97b6b5ce486c31 | train | class | class NotExtendedException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Not Extended'
super().__init__(status_code=510, message=message)
| class NotExtendedException(ServerException):
| def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Not Extended'
super().__init__(status_code=510, message=message)
| 507, message=message)
class LoopDetectedException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Loop Detected'
super().__init__(status_code=508, message=message)
class NotExtendedException(ServerException):
| 64 | 64 | 50 | 7 | 57 | DeveloperRSquared/http-exceptions | src/http_exceptions/server_exceptions.py | Python | NotExtendedException | NotExtendedException | 70 | 73 | 70 | 70 | 0487905e669c4bfc6690153d51209f9140cfd7f6 | bigcode/the-stack | train |
bffc6c762cd99af54134f6f5 | train | class | class InternalServerErrorException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Internal Server Error'
super().__init__(status_code=500, message=message)
| class InternalServerErrorException(ServerException):
| def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Internal Server Error'
super().__init__(status_code=500, message=message)
| # pylint: disable=cyclic-import
from __future__ import annotations
from typing import Mapping
from typing import Optional
from typing import Type
from typing import Union
from .http_exception import HTTPException
class ServerException(HTTPException):
pass
class InternalServerErrorException(ServerException):
| 62 | 64 | 52 | 8 | 53 | DeveloperRSquared/http-exceptions | src/http_exceptions/server_exceptions.py | Python | InternalServerErrorException | InternalServerErrorException | 16 | 19 | 16 | 16 | b674f5e5225008bcba9cf9b5255c3e4aa97df650 | bigcode/the-stack | train |
426af51c1cce240f4a5f5500 | train | class | class VariantAlsoNegotiatesException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Variant Also Negotiates'
super().__init__(status_code=506, message=message)
| class VariantAlsoNegotiatesException(ServerException):
| def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Variant Also Negotiates'
super().__init__(status_code=506, message=message)
| )
class HTTPVersionNotSupportedException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'HTTP Version Not Supported'
super().__init__(status_code=505, message=message)
class VariantAlsoNegotiatesException(ServerException):
| 64 | 64 | 54 | 9 | 55 | DeveloperRSquared/http-exceptions | src/http_exceptions/server_exceptions.py | Python | VariantAlsoNegotiatesException | VariantAlsoNegotiatesException | 52 | 55 | 52 | 52 | 799ec36923e3aaea25a48abaecf25afd88ceabe2 | bigcode/the-stack | train |
7f2f3f4dec0664885db6b0c2 | train | class | class ServiceUnavailableException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Service Unavailable'
super().__init__(status_code=503, message=message)
| class ServiceUnavailableException(ServerException):
| def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Service Unavailable'
super().__init__(status_code=503, message=message)
| =501, message=message)
class BadGatewayException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Bad Gateway'
super().__init__(status_code=502, message=message)
class ServiceUnavailableException(ServerException):
| 64 | 64 | 51 | 7 | 57 | DeveloperRSquared/http-exceptions | src/http_exceptions/server_exceptions.py | Python | ServiceUnavailableException | ServiceUnavailableException | 34 | 37 | 34 | 34 | 275b0a703eae5313679e5698fbcbbb191de3d8d8 | bigcode/the-stack | train |
a448b99269b2be3f18dccc59 | train | class | class ServerException(HTTPException):
pass
| class ServerException(HTTPException):
| pass
| # pylint: disable=cyclic-import
from __future__ import annotations
from typing import Mapping
from typing import Optional
from typing import Type
from typing import Union
from .http_exception import HTTPException
class ServerException(HTTPException):
| 51 | 64 | 10 | 7 | 43 | DeveloperRSquared/http-exceptions | src/http_exceptions/server_exceptions.py | Python | ServerException | ServerException | 12 | 13 | 12 | 12 | 378f879049dda9bd5eac7a2746a5913a38716b90 | bigcode/the-stack | train |
a650a4203a887bbaf3991b8f | train | class | class LoopDetectedException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Loop Detected'
super().__init__(status_code=508, message=message)
| class LoopDetectedException(ServerException):
| def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Loop Detected'
super().__init__(status_code=508, message=message)
| , message=message)
class InsufficientStorageException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Insufficient Storage'
super().__init__(status_code=507, message=message)
class LoopDetectedException(ServerException):
| 64 | 64 | 51 | 7 | 57 | DeveloperRSquared/http-exceptions | src/http_exceptions/server_exceptions.py | Python | LoopDetectedException | LoopDetectedException | 64 | 67 | 64 | 64 | 2c4f89989950675b8db1cce2124126866ec0ceff | bigcode/the-stack | train |
b792d5e4958d361b4dd7d272 | train | class | class NetworkAuthenticationRequiredException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Network Authentication Required'
super().__init__(status_code=511, message=message)
| class NetworkAuthenticationRequiredException(ServerException):
| def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Network Authentication Required'
super().__init__(status_code=511, message=message)
| 508, message=message)
class NotExtendedException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Not Extended'
super().__init__(status_code=510, message=message)
class NetworkAuthenticationRequiredException(ServerException):
| 64 | 64 | 52 | 8 | 56 | DeveloperRSquared/http-exceptions | src/http_exceptions/server_exceptions.py | Python | NetworkAuthenticationRequiredException | NetworkAuthenticationRequiredException | 76 | 79 | 76 | 76 | d27d66bca8a10803eaf7adc4d6f17e43666ddc02 | bigcode/the-stack | train |
d30af7c6d73fe0722799bdbf | train | class | class HTTPVersionNotSupportedException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'HTTP Version Not Supported'
super().__init__(status_code=505, message=message)
| class HTTPVersionNotSupportedException(ServerException):
| def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'HTTP Version Not Supported'
super().__init__(status_code=505, message=message)
| , message=message)
class GatewayTimeoutException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Gateway Timeout'
super().__init__(status_code=504, message=message)
class HTTPVersionNotSupportedException(ServerException):
| 64 | 64 | 54 | 9 | 55 | DeveloperRSquared/http-exceptions | src/http_exceptions/server_exceptions.py | Python | HTTPVersionNotSupportedException | HTTPVersionNotSupportedException | 46 | 49 | 46 | 46 | e9e5be5f3ecca19c22cd7bca4c4edf527af2c040 | bigcode/the-stack | train |
27397a8231c2d0417203303c | train | class | class NotImplementedException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Not Implemented'
super().__init__(status_code=501, message=message)
| class NotImplementedException(ServerException):
| def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Not Implemented'
super().__init__(status_code=501, message=message)
| Exception):
pass
class InternalServerErrorException(ServerException):
def __init__(self, message: Optional[str] = None) -> None:
message = message if message else 'Internal Server Error'
super().__init__(status_code=500, message=message)
class NotImplementedException(ServerException):
| 64 | 64 | 51 | 7 | 57 | DeveloperRSquared/http-exceptions | src/http_exceptions/server_exceptions.py | Python | NotImplementedException | NotImplementedException | 22 | 25 | 22 | 22 | fdbe2054f23452f3df378f70543cfe6fa862332d | bigcode/the-stack | train |
a09882c4c96f2dbe42022c29 | train | class | class TestUniqueIdExistsValidator(unittest.TestCase):
def setUp(self):
self.validator = UniqueIdExistsValidator()
self.field1 = TextField('a', 'a', 'a')
self.field2 = TextField('b', 'b', 'b')
self.field3 = UniqueIdField('unique_id_type1', 'name1', 'code1', 'label1')
self.fiel... | class TestUniqueIdExistsValidator(unittest.TestCase):
| def setUp(self):
self.validator = UniqueIdExistsValidator()
self.field1 = TextField('a', 'a', 'a')
self.field2 = TextField('b', 'b', 'b')
self.field3 = UniqueIdField('unique_id_type1', 'name1', 'code1', 'label1')
self.field4 = UniqueIdField('unique_id_type2', 'name2', 'code2'... | c' in errors.keys())
self.assertFalse('a' in errors.keys())
def test_should_create_mandatory_validator_from_json(self):
validator_json = {
'cls': ValidatorTypes.MANDATORY
}
self.assertTrue(isinstance(validator_factory(validator_json), MandatoryValidator))
def test_m... | 116 | 116 | 387 | 10 | 106 | mariot/mangrove | mangrove/form_model/tests/test_validators.py | Python | TestUniqueIdExistsValidator | TestUniqueIdExistsValidator | 48 | 75 | 48 | 48 | 201b9d0d9e6851ec81e04e8e80201f8a97e0e428 | bigcode/the-stack | train |
df49e2903a818081fa9124f7 | train | class | class TestMandatoryValidator(unittest.TestCase):
def setUp(self):
self.validator = MandatoryValidator()
self.field1 = TextField('a', 'a', 'a')
self.field2 = TextField('b', 'b', 'b', required=False)
self.field3 = TextField('c', 'c', 'c')
self.field4 = TextField('d', 'd', 'd')
... | class TestMandatoryValidator(unittest.TestCase):
| def setUp(self):
self.validator = MandatoryValidator()
self.field1 = TextField('a', 'a', 'a')
self.field2 = TextField('b', 'b', 'b', required=False)
self.field3 = TextField('c', 'c', 'c')
self.field4 = TextField('d', 'd', 'd')
self.fields = [self.field1, self.field2, ... | , patch, MagicMock
from mangrove.datastore.database import DatabaseManager
from mangrove.errors.MangroveException import DataObjectNotFound
from mangrove.form_model.validator_types import ValidatorTypes
from mangrove.form_model.validator_factory import validator_factory
from mangrove.form_model.field import TextField, ... | 98 | 98 | 327 | 8 | 89 | mariot/mangrove | mangrove/form_model/tests/test_validators.py | Python | TestMandatoryValidator | TestMandatoryValidator | 12 | 45 | 12 | 12 | e5127cc03b2f9de82b70fde872189b6b5af608dd | bigcode/the-stack | train |
dc5760ffa8fd9b93ac1e4956 | train | function | def gen_citefields(citekey):
# Rearrange the bib entries into something more useful.
entry = load_citekey(citekey)
D = entry.fields
authors = [" ".join( p.first() + p.prelast() + p.last() ) for p in entry.persons['author']]
D['authors'] = ", ".join(authors)
return D
| def gen_citefields(citekey):
# Rearrange the bib entries into something more useful.
| entry = load_citekey(citekey)
D = entry.fields
authors = [" ".join( p.first() + p.prelast() + p.last() ) for p in entry.persons['author']]
D['authors'] = ", ".join(authors)
return D
| = Tracer()
from functools import cmp_to_key
def load_citekey(citekey):
# Get the info corresponding to specific citekey
entry = bib_data.entries[citekey]
return entry
def gen_citefields(citekey):
# Rearrange the bib entries into something more useful.
| 64 | 64 | 85 | 20 | 43 | cshen/cshen.github.com | list_pdf/bin/bin/bibparse.py | Python | gen_citefields | gen_citefields | 34 | 41 | 34 | 35 | 91909b4e70a34ca11b950e4df289a88f755cc7ec | bigcode/the-stack | train |
ba4967e9b30de46b2dad2960 | train | function | def remove_curly_bracket(x):
x = x.replace('{', '')
x = x.replace('}', '')
return x
| def remove_curly_bracket(x):
| x = x.replace('{', '')
x = x.replace('}', '')
return x
| transform:
y = y + x[ i ].lower()
else:
y = y + x[ i ]
z =''
z = z + y[0].upper()
z = z + y[1:len(y)]
return z
def remove_curly_bracket(x):
| 64 | 64 | 28 | 8 | 55 | cshen/cshen.github.com | list_pdf/bin/bin/bibparse.py | Python | remove_curly_bracket | remove_curly_bracket | 131 | 134 | 131 | 131 | 309ed70b9007de2723cd02b9c4ce96fbd357adcb | bigcode/the-stack | train |
0a3bc69f9abb46a18f793527 | train | function | def initialize_name(x):
# x is in the format of "Chunhua Shen, X XX ..."
# return "C. Shen, X. XX"
change = 1
s = ''
for i in range(len(x)):
if change == -1 and i < len(x) and x[i] == " ":
change = 0
if change == 0:
s = s + x[i]
if change == 1 and x[i] != "... | def initialize_name(x):
# x is in the format of "Chunhua Shen, X XX ..."
# return "C. Shen, X. XX"
| change = 1
s = ''
for i in range(len(x)):
if change == -1 and i < len(x) and x[i] == " ":
change = 0
if change == 0:
s = s + x[i]
if change == 1 and x[i] != " " :
s = s + x[i]
s = s + "."
change = -1 # ignore the rest of ... | if x[1].fields['title'] > y[1].fields['title']:
return 1
else:
return -1
def initialize_name(x):
# x is in the format of "Chunhua Shen, X XX ..."
# return "C. Shen, X. XX"
| 64 | 64 | 169 | 32 | 31 | cshen/cshen.github.com | list_pdf/bin/bin/bibparse.py | Python | initialize_name | initialize_name | 70 | 91 | 70 | 72 | 23245555fb2d017c40435e08a9e7dcb72912eff1 | bigcode/the-stack | train |
b7945c730c6d1c3d94d2a307 | train | function | def load_citekey(citekey):
# Get the info corresponding to specific citekey
entry = bib_data.entries[citekey]
return entry
| def load_citekey(citekey):
# Get the info corresponding to specific citekey
| entry = bib_data.entries[citekey]
return entry
| install pybtex first!")
import re
# from datetime import datetime
# import os.path
# from IPython.core.debugger import Tracer
# debug_here = Tracer()
from functools import cmp_to_key
def load_citekey(citekey):
# Get the info corresponding to specific citekey
| 64 | 64 | 33 | 19 | 44 | cshen/cshen.github.com | list_pdf/bin/bin/bibparse.py | Python | load_citekey | load_citekey | 28 | 31 | 28 | 29 | 0363af36d7fd80c50482955f898b5acb844cde0d | bigcode/the-stack | train |
aad98b5c7660b6e7af8ba89c | train | function | def highlight_name( strx, highlight ):
x = highlight.replace('+', '')
x = r"\\highlight{" + x + "}"
s = re.sub( highlight, x, strx )
return s
| def highlight_name( strx, highlight ):
| x = highlight.replace('+', '')
x = r"\\highlight{" + x + "}"
s = re.sub( highlight, x, strx )
return s
| ignore the rest of the given name
if x[i] == "," and x[i+1] == " ":
change = 1
s = s + " "
return s
# highlight = "C. +Shen"
def highlight_name( strx, highlight ):
| 64 | 64 | 50 | 12 | 52 | cshen/cshen.github.com | list_pdf/bin/bin/bibparse.py | Python | highlight_name | highlight_name | 95 | 101 | 95 | 96 | 8284da6565727850174ea311d96adc4289452705 | bigcode/the-stack | train |
32b942d2bc2bfe422e98d6a3 | train | function | def single_dash(x):
for i in range(10):
x = x.replace('--', '-')
x = x.replace('-', '$-$')
return x
| def single_dash(x):
| for i in range(10):
x = x.replace('--', '-')
x = x.replace('-', '$-$')
return x
| z =''
z = z + y[0].upper()
z = z + y[1:len(y)]
return z
def remove_curly_bracket(x):
x = x.replace('{', '')
x = x.replace('}', '')
return x
def single_dash(x):
| 64 | 64 | 35 | 5 | 58 | cshen/cshen.github.com | list_pdf/bin/bin/bibparse.py | Python | single_dash | single_dash | 137 | 142 | 137 | 137 | 77a07ac0fb66fc6a7bf052951ee713c513fb237c | bigcode/the-stack | train |
47749e373e928483dd8e36d8 | train | function | def sort_list_cmp(y, x):
yearcmp = int(x[1].fields['year']) - int(y[1].fields['year'])
if yearcmp != 0:
return yearcmp
if 'journal' in x[1].fields and 'journal' not in y[1].fields:
return 1
if 'journal' not in x[1].fields and 'journal' in y[1].fields:
return -1
if 'booktitl... | def sort_list_cmp(y, x):
| yearcmp = int(x[1].fields['year']) - int(y[1].fields['year'])
if yearcmp != 0:
return yearcmp
if 'journal' in x[1].fields and 'journal' not in y[1].fields:
return 1
if 'journal' not in x[1].fields and 'journal' in y[1].fields:
return -1
if 'booktitle' in x[1].fields and 'bo... | key(citekey)
D = entry.fields
authors = [" ".join( p.first() + p.prelast() + p.last() ) for p in entry.persons['author']]
D['authors'] = ", ".join(authors)
return D
def sort_list_cmp(y, x):
| 67 | 67 | 224 | 8 | 58 | cshen/cshen.github.com | list_pdf/bin/bin/bibparse.py | Python | sort_list_cmp | sort_list_cmp | 44 | 67 | 44 | 44 | 41c55547cf54fca0a9959526c4689242c27fff78 | bigcode/the-stack | train |
34cb7a6f7819eff56386d49a | train | function | def capitalize_string(x):
# x = x.decode('ascii', 'ignore')
y=''
transform = 1
for i in range(len(x)):
if x[ i ] == "{":
transform = 0
continue
if x[ i ] == "}":
transform = 1
continue
if transform:
y = y + x[ i ].lo... | def capitalize_string(x):
# x = x.decode('ascii', 'ignore')
| y=''
transform = 1
for i in range(len(x)):
if x[ i ] == "{":
transform = 0
continue
if x[ i ] == "}":
transform = 1
continue
if transform:
y = y + x[ i ].lower()
else:
y = y + x[ i ]
z =''
... | ( strx, highlight ):
x = highlight.replace('+', '')
x = r"\\highlight{" + x + "}"
s = re.sub( highlight, x, strx )
return s
def capitalize_string(x):
# x = x.decode('ascii', 'ignore')
| 64 | 64 | 128 | 17 | 46 | cshen/cshen.github.com | list_pdf/bin/bin/bibparse.py | Python | capitalize_string | capitalize_string | 105 | 128 | 105 | 108 | b254d4e9ca0703cba2ddb4e8f36986aa657e8955 | bigcode/the-stack | train |
32171cc1af1da9b25cdd3481 | train | function | def instance_fields( x, fields ):
if x in fields and len( fields[x]) > 0:
return fields[x]
else:
return ""
| def instance_fields( x, fields ):
| if x in fields and len( fields[x]) > 0:
return fields[x]
else:
return ""
| ):
x = x.replace('{', '')
x = x.replace('}', '')
return x
def single_dash(x):
for i in range(10):
x = x.replace('--', '-')
x = x.replace('-', '$-$')
return x
def instance_fields( x, fields ):
| 64 | 64 | 34 | 8 | 55 | cshen/cshen.github.com | list_pdf/bin/bin/bibparse.py | Python | instance_fields | instance_fields | 145 | 149 | 145 | 145 | c6d2ceb61d2d9b1c7206e9d3f9ec5aa30ebef34f | bigcode/the-stack | train |
26ea00870cc6117188c1b297 | train | function | @tf.function
def train_step(model, inputs, outputs, optimizer):
with tf.GradientTape() as t:
loss = tf.reduce_mean(tf.square(outputs - model(inputs, training=True)))
grads = t.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
| @tf.function
def train_step(model, inputs, outputs, optimizer):
| with tf.GradientTape() as t:
loss = tf.reduce_mean(tf.square(outputs - model(inputs, training=True)))
grads = t.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
| .BatchNormalization(axis=3)(conv9)
conv10 = layers.Conv2D(1, (1, 1))(bn18)
model = tf.keras.models.Model(inputs=inputs, outputs=conv10)
return model
@tf.function
def train_step(model, inputs, outputs, optimizer):
| 64 | 64 | 67 | 15 | 48 | prl900/panpluie | unet_gradtape.py | Python | train_step | train_step | 102 | 109 | 102 | 104 | c9056d51e51882e5922956814cd16c952acc33ef | bigcode/the-stack | train |
35b6138fd398bbed0d4167a9 | train | function | def train(train_dataset, test_dataset, model):
optimizer = tf.keras.optimizers.SGD(learning_rate=0.001, decay=1e-6, momentum=0.9, nesterov=True)
train_loss = tf.keras.metrics.Mean()
test_loss = tf.keras.metrics.Mean()
f = open("train_record.out","w+")
f.write('epoch, train_loss, test_loss')
for epoch i... | def train(train_dataset, test_dataset, model):
| optimizer = tf.keras.optimizers.SGD(learning_rate=0.001, decay=1e-6, momentum=0.9, nesterov=True)
train_loss = tf.keras.metrics.Mean()
test_loss = tf.keras.metrics.Mean()
f = open("train_record.out","w+")
f.write('epoch, train_loss, test_loss')
for epoch in range(100):
for (batch, (inputs, outputs)... | .square(outputs - model(inputs, training=True)))
grads = t.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
@tf.function
def calc_loss(model, inputs, outputs):
return tf.reduce_mean(tf.square(outputs - model(inputs)))
def train(train_dataset, test_dat... | 70 | 71 | 239 | 10 | 60 | prl900/panpluie | unet_gradtape.py | Python | train | train | 117 | 142 | 117 | 117 | a1362f14893b93504a110a7678ba0bcf4e1ee8bb | bigcode/the-stack | train |
793c1d105d1c630aee994513 | train | function | @tf.function
def calc_loss(model, inputs, outputs):
return tf.reduce_mean(tf.square(outputs - model(inputs)))
| @tf.function
def calc_loss(model, inputs, outputs):
| return tf.reduce_mean(tf.square(outputs - model(inputs)))
| with tf.GradientTape() as t:
loss = tf.reduce_mean(tf.square(outputs - model(inputs, training=True)))
grads = t.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
@tf.function
def calc_loss(model, inputs, outputs):
| 64 | 64 | 25 | 13 | 51 | prl900/panpluie | unet_gradtape.py | Python | calc_loss | calc_loss | 112 | 114 | 112 | 113 | d0e14573d22c894fef99071ecd4f4b9ab1657ef4 | bigcode/the-stack | train |
80834ee04f1f434c9fe280c7 | train | function | def Unet():
concat_axis = 3
inputs = layers.Input(shape = (720, 1440, 3))
feats = 16
bn0 = layers.BatchNormalization(axis=3)(inputs)
conv1 = layers.Conv2D(feats, (5, 5), activation='relu', padding='same', name='conv1_1')(bn0)
bn1 = layers.BatchNormalization(axis=3)(conv1)
conv1 = layers.Con... | def Unet():
| concat_axis = 3
inputs = layers.Input(shape = (720, 1440, 3))
feats = 16
bn0 = layers.BatchNormalization(axis=3)(inputs)
conv1 = layers.Conv2D(feats, (5, 5), activation='relu', padding='same', name='conv1_1')(bn0)
bn1 = layers.BatchNormalization(axis=3)(conv1)
conv1 = layers.Conv2D(feats, (... | from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras import backend as K
import os
import time
import matplotlib.pyplot as plt
from nc_loader import ERA5Dataset
def Unet():
| 59 | 256 | 1,368 | 4 | 54 | prl900/panpluie | unet_gradtape.py | Python | Unet | Unet | 13 | 99 | 13 | 13 | 701c7ca5f48acfb1ef508990b005b00bbba82bfa | bigcode/the-stack | train |
a87bb2286b9ee27f1f6d0d29 | train | function | def x_profile(X,Hc,Hb):
Hc1, Hc2 = Hc[0], Hc[1]
dH = X['dH']
NH = int(np.sqrt((Hc2-Hc1)**2)/dH)
Hc0 = np.linspace(Hc1,Hc2,NH)
Hb0 = np.linspace(Hb,Hb,NH)
rho_int = X['Zint'](Hc0,Hb0)
coef = sps.norm.ppf(0.025/np.sum(rho_int.mask==False))
CI_int = X['SEint'](Hc0,Hb0)*coef
fig ... | def x_profile(X,Hc,Hb):
| Hc1, Hc2 = Hc[0], Hc[1]
dH = X['dH']
NH = int(np.sqrt((Hc2-Hc1)**2)/dH)
Hc0 = np.linspace(Hc1,Hc2,NH)
Hb0 = np.linspace(Hb,Hb,NH)
rho_int = X['Zint'](Hc0,Hb0)
coef = sps.norm.ppf(0.025/np.sum(rho_int.mask==False))
CI_int = X['SEint'](Hc0,Hb0)*coef
fig = plt.figure(figsize=(5,5... | x_Hb_widge
X['x_Hc_widge'] = x_Hc_widge
X['y_Hc_widge'] = y_Hc_widge
X['y_Hb_widge'] = y_Hb_widge
return X
def profile_plot(X):
if X['P_widge'].value==0:
X = x_profile(X,X['x_Hc_widge'].value,X['x_Hb_widge'].value)
else:
X = y_profile(X,X['y_Hc_widge'].value,X['y_Hb_widge'].v... | 142 | 142 | 476 | 9 | 132 | FORCaist/turbosensei | turbosensei/results.py | Python | x_profile | x_profile | 343 | 378 | 343 | 344 | 22e8f00ba9a4282a5c5fe345dab231419e8476ae | bigcode/the-stack | train |
12f35ccf3d3bb55734ddcc1a | train | function | def profile_options(X):
Hb1 = X['Hb1']-X['Hc2']
Hb2 = X['Hb2']
Hc1 = np.maximum(X['Hc1'],0)
Hc2 = X['Hc2']
style = {'description_width': 'initial'} #general style settings
HL = widgets.HTML(value='<hr style="height:3px;border:none;color:#333;background-color:#333;" />')
P_title = w... | def profile_options(X):
| Hb1 = X['Hb1']-X['Hc2']
Hb2 = X['Hb2']
Hc1 = np.maximum(X['Hc1'],0)
Hc2 = X['Hc2']
style = {'description_width': 'initial'} #general style settings
HL = widgets.HTML(value='<hr style="height:3px;border:none;color:#333;background-color:#333;" />')
P_title = widgets.HTML(value='<h3>S... | *vmax-vmin)/(vmax-vmin)
anchors[8]=(0.97*vmax-vmin)/(vmax-vmin)
anchors[9]=1.0
Rlst = list(cdict['red'])
Glst = list(cdict['green'])
Blst = list(cdict['blue'])
for i in range(9):
Rlst[i] = tuple((anchors[i],Rlst[i][1],Rlst[i][2]))
Glst[i] = tuple((anchors[i],Glst[i][1],Glst[i][... | 223 | 223 | 744 | 5 | 217 | FORCaist/turbosensei | turbosensei/results.py | Python | profile_options | profile_options | 242 | 332 | 242 | 242 | d7c18c8c939986d57b74d3ba58ce71ec48333e51 | bigcode/the-stack | train |
fa2e6a7ed98ab2f70a00ec6e | train | function | def forcplot(Xi,Yi,Zi,fn,mass,colorbar,level,contour,contourpts,xmin,xmax,ymin,ymax,download):
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(1,1,1)
if mass.value<0.0:
Xi_new = Xi
Yi_new = Yi
Zi_new = Zi
xlabel_text = '$\mu_0 H_c [T]$' #label Hc axis ... | def forcplot(Xi,Yi,Zi,fn,mass,colorbar,level,contour,contourpts,xmin,xmax,ymin,ymax,download):
| fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(1,1,1)
if mass.value<0.0:
Xi_new = Xi
Yi_new = Yi
Zi_new = Zi
xlabel_text = '$\mu_0 H_c [T]$' #label Hc axis [SI units]
ylabel_text = '$\mu_0 H_u [T]$' #label Hu axis [SI units]
cbar_text = '$Am... | #Include colorbar
level=level_widge, #Number of levels to plot
contour=contour_widge, #Contour levels to plot
contourpts=contourpts_widge, #Contour line width
xmin=xmin_widge, #X-minimum
xmax=xmax_widge, #X-maximum
ymin=ymin_wi... | 226 | 226 | 755 | 36 | 189 | FORCaist/turbosensei | turbosensei/results.py | Python | forcplot | forcplot | 100 | 164 | 100 | 102 | f8edce9f75d087bf03736e20e765a4f151090594 | bigcode/the-stack | train |
1aaadd26f5f1a86c88181416 | train | function | def forc(X):
#unpack data
Xi = X['Xi']
#if type(Xi) is str:
# print('Error: The current model is based on downsampled data. Run a full model using "calculate_model"') #return error
# return X
Yi = X['Yi']
Zi = X['Zi']
Hc1 = X['Hc1']
Hc2 = X['Hc2']
Hb1 = X['Hb1']
... | def forc(X):
#unpack data
| Xi = X['Xi']
#if type(Xi) is str:
# print('Error: The current model is based on downsampled data. Run a full model using "calculate_model"') #return error
# return X
Yi = X['Yi']
Zi = X['Zi']
Hc1 = X['Hc1']
Hc2 = X['Hc2']
Hb1 = X['Hb1']
Hb2 = X['Hb2']
#Set up... | import numpy as np
import ipywidgets as widgets
from ipywidgets import interact, interactive, fixed, Layout, VBox, HBox
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.tri as tri
import matplotlib.colors as colors
from matplotlib.colors import LinearSegmentedColormap
import scipy.stats as sps... | 87 | 256 | 915 | 10 | 76 | FORCaist/turbosensei | turbosensei/results.py | Python | forc | forc | 13 | 96 | 13 | 15 | 529c5e7d6ac55ae2a49dd5d41a91ce3d39c35daa | bigcode/the-stack | train |
d4d5f4111eb4437a3615b1a3 | train | function | def FORCinel_colormap(Z):
#setup initial colormap assuming that negative range does not require extension
cdict = {'red': ((0.0, 127/255, 127/255),
(0.1387, 255/255, 255/255),
(0.1597, 255/255, 255/255),
(0.1807, 255/255, 255/25... | def FORCinel_colormap(Z):
#setup initial colormap assuming that negative range does not require extension
| cdict = {'red': ((0.0, 127/255, 127/255),
(0.1387, 255/255, 255/255),
(0.1597, 255/255, 255/255),
(0.1807, 255/255, 255/255),
(0.3193, 102/255, 102/255),
(0.563, 204/255, 204/255),
... | # Set plot Xlimits
xlimits = np.sort((xmin,xmax))
ax.set_xlim(xlimits)
#Set plot Ylimits
ylimits = np.sort((ymin,ymax))
ax.set_ylim(ylimits)
#Set ticks and plot aspect ratio
ax.tick_params(labelsize=14)
ax.set_aspect('equal') #set 1:1 aspect ratio
ax.minorticks_on() #ad... | 256 | 256 | 988 | 23 | 233 | FORCaist/turbosensei | turbosensei/results.py | Python | FORCinel_colormap | FORCinel_colormap | 166 | 236 | 166 | 168 | 341a5d3bf16131cddd9e78070b913312fdce70b3 | bigcode/the-stack | train |
33985b249efaae1d7a1f1072 | train | function | def profile_plot(X):
if X['P_widge'].value==0:
X = x_profile(X,X['x_Hc_widge'].value,X['x_Hb_widge'].value)
else:
X = y_profile(X,X['y_Hc_widge'].value,X['y_Hb_widge'].value)
return X
| def profile_plot(X):
| if X['P_widge'].value==0:
X = x_profile(X,X['x_Hc_widge'].value,X['x_Hb_widge'].value)
else:
X = y_profile(X,X['y_Hc_widge'].value,X['y_Hb_widge'].value)
return X
| = x_Hb_widge
X['x_Hc_widge'] = x_Hc_widge
X['y_Hc_widge'] = y_Hc_widge
X['y_Hb_widge'] = y_Hb_widge
return X
def profile_plot(X):
| 64 | 64 | 75 | 5 | 58 | FORCaist/turbosensei | turbosensei/results.py | Python | profile_plot | profile_plot | 334 | 341 | 334 | 335 | 8bec273f504b36ba0bbdea7544983a9a3c0ac0e1 | bigcode/the-stack | train |
d50b3c31d12692a562b43333 | train | function | def y_profile(X,Hc,Hb):
Hb1, Hb2 = Hb[0], Hb[1]
dH = X['dH']
NH = int(np.sqrt((Hb2-Hb1)**2)/dH)
Hc0 = np.linspace(Hc,Hc,NH)
Hb0 = np.linspace(Hb1,Hb2,NH)
rho_int = X['Zint'](Hc0,Hb0)
coef = sps.norm.ppf(0.025/np.sum(rho_int.mask==False))
CI_int = X['SEint'](Hc0,Hb0)*coef
fig ... | def y_profile(X,Hc,Hb):
| Hb1, Hb2 = Hb[0], Hb[1]
dH = X['dH']
NH = int(np.sqrt((Hb2-Hb1)**2)/dH)
Hc0 = np.linspace(Hc,Hc,NH)
Hb0 = np.linspace(Hb1,Hb2,NH)
rho_int = X['Zint'](Hc0,Hb0)
coef = sps.norm.ppf(0.025/np.sum(rho_int.mask==False))
CI_int = X['SEint'](Hc0,Hb0)*coef
fig = plt.figure(figsize=(5,5... | 12)
ax1.tick_params(axis='both',which='major',direction='out',length=5,width=1,color='k',labelsize='12')
ax1.tick_params(axis='both',which='minor',direction='out',length=3.5,width=1,color='k')
ax1.set_xlabel('$\mu_0H_c$ [T]',fontsize=12)
ax1.minorticks_on()
outputfile = X['sample'].value+'_Hc... | 140 | 140 | 469 | 9 | 130 | FORCaist/turbosensei | turbosensei/results.py | Python | y_profile | y_profile | 380 | 415 | 380 | 381 | 2c83107bbed9c3d2e93d3f0b00f7013e289e55e0 | bigcode/the-stack | train |
41fbf673ef0097145bea7a8d | train | function | def get_application() -> FastAPI:
application = FastAPI(title=settings.PROJECT_NAME)
application.add_middleware(
CORSMiddleware,
allow_origins=settings.ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
application.include_route... | def get_application() -> FastAPI:
| application = FastAPI(title=settings.PROJECT_NAME)
application.add_middleware(
CORSMiddleware,
allow_origins=settings.ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
application.include_router(api_v1_router, prefix="/v1")
... | import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from app.api.v1.routes.api import router as api_v1_router
from app.core.settings import settings
def get_application() -> FastAPI:
| 52 | 64 | 78 | 8 | 43 | oxyyx/prdctr | app/main.py | Python | get_application | get_application | 9 | 22 | 9 | 9 | d1ab0141237ee94cc22e2d1e16b1fd5deabe3879 | bigcode/the-stack | train |
e5dba0e5a6122b7f25ca24f9 | train | function | def start():
uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)
| def start():
| uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)
| _middleware(
CORSMiddleware,
allow_origins=settings.ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
application.include_router(api_v1_router, prefix="/v1")
return application
app = get_application()
def start():
| 64 | 64 | 31 | 3 | 61 | oxyyx/prdctr | app/main.py | Python | start | start | 28 | 29 | 28 | 28 | 03d170627c82aa01cb5017442641ac0b548cb5b3 | bigcode/the-stack | train |
a8e1d16c68b04d409ab33e11 | train | function | def rmsprop(grad, init_params, callback=None, num_iters=100,
step_size=0.1, gamma=0.9, eps=10**-8):
"""Root mean squared prop: See Adagrad paper for details."""
flattened_grad, unflatten, x = flatten_func(grad, init_params)
avg_sq_grad = np.ones(len(x))
for i in range(num_iters):
g ... | def rmsprop(grad, init_params, callback=None, num_iters=100,
step_size=0.1, gamma=0.9, eps=10**-8):
| """Root mean squared prop: See Adagrad paper for details."""
flattened_grad, unflatten, x = flatten_func(grad, init_params)
avg_sq_grad = np.ones(len(x))
for i in range(num_iters):
g = flattened_grad(x, i)
if callback: callback(unflatten(x), i, unflatten(g))
avg_sq_grad = avg_sq... | if break_cond is not None:
if break_cond(x, i, g):
break
return unflatten(x)
def rmsprop(grad, init_params, callback=None, num_iters=100,
step_size=0.1, gamma=0.9, eps=10**-8):
| 64 | 64 | 156 | 38 | 26 | andymiller/vboost | code/vbproj/vi/vboost/optimizers.py | Python | rmsprop | rmsprop | 75 | 86 | 75 | 76 | a654ed33a606fa42f0129f0260c32f3e6746600e | bigcode/the-stack | train |
1f8e3ec165e1a7fb7cccb154 | train | function | def sgd(grad, init_params, subopt=None, callback=None,
break_cond=None, num_iters=200, step_size=0.1, mass=0.9):
"""Stochastic gradient descent with momentum.
grad() must have signature grad(x, i), where i is the iteration number."""
flattened_grad, unflatten, x = flatten_func(grad, init_params)
... | def sgd(grad, init_params, subopt=None, callback=None,
break_cond=None, num_iters=200, step_size=0.1, mass=0.9):
| """Stochastic gradient descent with momentum.
grad() must have signature grad(x, i), where i is the iteration number."""
flattened_grad, unflatten, x = flatten_func(grad, init_params)
# dynamic step sizes
if np.isscalar(step_size):
step_size = np.ones(num_iters) * step_size
assert len(s... | future__ import absolute_import
import autograd.numpy as np
from autograd.util import flatten_func
from builtins import range
from scipy.optimize import line_search
def sgd(grad, init_params, subopt=None, callback=None,
break_cond=None, num_iters=200, step_size=0.1, mass=0.9):
| 73 | 73 | 245 | 39 | 33 | andymiller/vboost | code/vbproj/vi/vboost/optimizers.py | Python | sgd | sgd | 15 | 39 | 15 | 16 | 4450b9b60adf38a1aa7127dee40e72dbefd0ca6b | bigcode/the-stack | train |
33c6fab5a9133c06e7c8d651 | train | function | def adam(grad, init_params, subopt=None, callback=None, break_cond=None,
num_iters=100, step_size=0.001, b1=0.9, b2=0.999, eps=10**-8):
"""Adam as described in http://arxiv.org/pdf/1412.6980.pdf.
It's basically RMSprop with momentum and some correction terms."""
flattened_grad, unflatten, x = flatt... | def adam(grad, init_params, subopt=None, callback=None, break_cond=None,
num_iters=100, step_size=0.001, b1=0.9, b2=0.999, eps=10**-8):
| """Adam as described in http://arxiv.org/pdf/1412.6980.pdf.
It's basically RMSprop with momentum and some correction terms."""
flattened_grad, unflatten, x = flatten_func(grad, init_params)
# dynamic step sizes
if np.isscalar(step_size):
step_size = np.ones(num_iters) * step_size
assert... | x + step_size[i] * velocity
if subopt is not None:
x = subopt(x, g, i)
if break_cond is not None:
if break_cond(x, i, g):
break
return unflatten(x)
def adam(grad, init_params, subopt=None, callback=None, break_cond=None,
num_iters=100, step_size=0.... | 108 | 108 | 362 | 53 | 55 | andymiller/vboost | code/vbproj/vi/vboost/optimizers.py | Python | adam | adam | 42 | 72 | 42 | 43 | 8bc02c9d92d490a050e31fd4b36ab0f0f7b5690b | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.