code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
Context manager returning the appropriate up-to-date readable filesystem
Use ``cache`` if it is a valid filessystem and has a file at
``read_path``, otherwise use ``authority``. If the file at
``read_path`` is out of date, update the file in ``cache`` before
returning it.
'''
if ca... | def _choose_read_fs(authority, cache, read_path, version_check, hasher) | Context manager returning the appropriate up-to-date readable filesystem
Use ``cache`` if it is a valid filessystem and has a file at
``read_path``, otherwise use ``authority``. If the file at
``read_path`` is out of date, update the file in ``cache`` before
returning it. | 3.410235 | 2.005928 | 1.700078 |
'''
Context manager returning a writable filesystem
Use a temporary directory and clean on exit.
.. todo::
Evaluate options for using a cached memoryFS or streaming object
instead of an OSFS(tmp). This could offer significant performance
improvements. Writing to the cache is l... | def _get_write_fs() | Context manager returning a writable filesystem
Use a temporary directory and clean on exit.
.. todo::
Evaluate options for using a cached memoryFS or streaming object
instead of an OSFS(tmp). This could offer significant performance
improvements. Writing to the cache is less of a pro... | 12.006305 | 2.188756 | 5.485446 |
'''
Prepare a temporary filesystem for writing to read_path
The file will be moved to write_path on close if modified.
'''
with _get_write_fs() as write_fs:
# If opening in read/write or append mode, make sure file data is
# accessible
if readwrite_mode:
if no... | def _prepare_write_fs(read_fs, cache, read_path, readwrite_mode=True) | Prepare a temporary filesystem for writing to read_path
The file will be moved to write_path on close if modified. | 4.280751 | 3.141369 | 1.362703 |
'''
Context manager for retrieving a system path for I/O and updating on change
Parameters
----------
authority : object
:py:mod:`pyFilesystem` filesystem object to use as the authoritative,
up-to-date source for the archive
cache : object
:py:mod:`pyFilesystem` file... | def get_local_path(
authority,
cache,
update,
version_check,
hasher,
read_path,
write_path=None,
cache_on_write=False) | Context manager for retrieving a system path for I/O and updating on change
Parameters
----------
authority : object
:py:mod:`pyFilesystem` filesystem object to use as the authoritative,
up-to-date source for the archive
cache : object
:py:mod:`pyFilesystem` filesystem objec... | 3.842343 | 2.457297 | 1.563646 |
assert isinstance(robot, BaseRoBot),\
"RoBot should be an BaseRoBot instance."
@csrf_exempt
def werobot_view(request):
timestamp = request.GET.get("timestamp", "")
nonce = request.GET.get("nonce", "")
signature = request.GET.get("signature", "")
if not robot.che... | def make_view(robot) | 为一个 BaseRoBot 生成 Django view。
:param robot: 一个 BaseRoBot 实例。
:return: 一个标准的 Django view | 2.765187 | 2.541666 | 1.087943 |
if key in data and last_type == STRING_TYPE:
data[key] = data[key].strip()
return data | def text_cleanup(data, key, last_type) | I strip extra whitespace off multi-line strings if they are ready to be stripped! | 3.819179 | 3.252787 | 1.174125 |
records = []
last_type = None
key = None
data = {}
directive = False
lines = text.splitlines()
for index, line in enumerate(lines):
# check for directives
if len(line) and line.strip().startswith(".."):
directive = True
continue
# set t... | def rst_to_json(text) | I convert Restructured Text with field lists into Dictionaries!
TODO: Convert to text node approach. | 3.677298 | 3.703192 | 0.993007 |
if text.isdigit():
return int(text), int
try:
return float(text), float
except ValueError:
return text, STRING_TYPE | def type_converter(text) | I convert strings into integers, floats, and strings! | 4.580288 | 4.3132 | 1.061923 |
filename = sys.argv[-1]
if not filename.endswith(".rst"):
print("ERROR! Please enter a ReStructuredText filename!")
sys.exit()
print(rst_to_json(file_opener(filename))) | def command_line_runner() | I run functions from the command-line! | 7.211844 | 6.332927 | 1.138785 |
kwargs.setdefault('use_bin_type', True)
return msgpack.packb(obj, **kwargs) | def packb(obj, **kwargs) | wrap msgpack.packb, setting use_bin_type=True by default | 2.666535 | 1.926757 | 1.38395 |
pygame.mixer.init()
try:
pygame.mixer.music.load(file_path)
except pygame.error as e:
if logger is not None:
logger.warning(str(e))
return
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
time... | def play(cls, file_path, on_done=None, logger=None) | Play an audio file.
:param file_path: the path to the file to play.
:param on_done: callback when audio playback completes. | 2.033229 | 2.164553 | 0.93933 |
thread = threading.Thread(
target=AudioPlayer.play, args=(file_path, on_done,))
thread.start() | def play_async(cls, file_path, on_done=None) | Play an audio file asynchronously.
:param file_path: the path to the file to play.
:param on_done: callback when audio playback completes. | 3.972466 | 5.166282 | 0.768922 |
res = copy.deepcopy(self)
for i in range(self.ndims):
d = disp[i]
s = self.domain[i]
if d > 0:
res.domain[i] = slice(s.start, d)
elif d < 0:
res.domain[i] = slice(d, s.stop)
return res | def extract(self, disp) | Extraction operation
@param displacement vector in index space
@return the part of the domain that is exposed by the shift | 2.79473 | 2.650073 | 1.054586 |
self.row = 0
self.column = 0
self.command(Command.RETURN_HOME)
msleep(2) | def home(self) | Return to initial position (row=0, column=0) | 11.568224 | 6.825715 | 1.6948 |
self._display_control = ByteUtil.apply_flag(self._display_control, Command.DISPLAY_ON, status)
self.command(self._display_control) | def visible(self, status) | Turn the display on/off (quickly) | 10.36798 | 7.486919 | 1.384813 |
self._display_control = ByteUtil.apply_flag(self._display_control, Command.CURSOR_ON, status)
self.command(self._display_control) | def cursor(self, status) | Turn underline cursor visibility on/off | 11.064955 | 8.458817 | 1.308097 |
self._display_control = ByteUtil.apply_flag(self._display_control, Command.BLINKING_ON, status)
self.command(self._display_control) | def blink(self, status) | Turn blink cursor visibility on/off | 9.405711 | 8.411489 | 1.118198 |
self._entry_mode |= Command.MODE_INCREMENT
self.command(self._entry_mode) | def left_to_right(self) | This is for text that flows Left to Right | 22.616575 | 21.297846 | 1.061918 |
self._entry_mode &= ~Command.MODE_INCREMENT
self.command(self._entry_mode) | def right_to_left(self) | This is for text that flows Right to Left | 21.248308 | 21.92485 | 0.969143 |
tempdir = tempfile.mkdtemp(dir=self.base_location)
name = os.path.join(
os.path.basename(tempdir),
os.path.basename(name),
)
method = super(TempFileSystemStorage, self).get_available_name
return method(name, max_length=max_length) | def get_available_name(self, name, max_length=None) | Return relative path to name placed in random directory | 3.183262 | 3.106131 | 1.024832 |
'''Takes list of dictionaries and prints a menu.
items parameter should be in the form of a list, containing
dictionaries with the keys: {"key", "text", "function"}.
Typing the key for a menuitem, followed by return, will run
"function".
'''
heading = "\n"*5 + heading ... | def menu(items, heading) | Takes list of dictionaries and prints a menu.
items parameter should be in the form of a list, containing
dictionaries with the keys: {"key", "text", "function"}.
Typing the key for a menuitem, followed by return, will run
"function". | 6.297831 | 3.506108 | 1.796245 |
'''
Takes the text prompt, and presents it, takes only "y" or "n" for
answers, and returns True or False. Repeats itself on bad input.
'''
text = "\n"+ text + "\n('y' or 'n'): "
while True:
answer = input(text).strip()
if answer != 'y' and answer != 'n':
co... | def yn_prompt(text) | Takes the text prompt, and presents it, takes only "y" or "n" for
answers, and returns True or False. Repeats itself on bad input. | 5.612253 | 2.417707 | 2.321312 |
'''Takes a string, and returns it underscored.'''
text += "\n"
for i in range(len(text)-1):
text += "="
text += "\n"
return text | def underline(text) | Takes a string, and returns it underscored. | 5.550598 | 3.662636 | 1.515465 |
try:
od = voevent.WhereWhen.ObsDataLocation[index]
ol = od.ObservationLocation
coord_sys = ol.AstroCoords.attrib['coord_system_id']
timesys_identifier = coord_sys.split('-')[0]
if timesys_identifier == 'UTC':
isotime_str = str(ol.AstroCoords.Time.TimeInstant... | def get_event_time_as_utc(voevent, index=0) | Extracts the event time from a given `WhereWhen.ObsDataLocation`.
Returns a datetime (timezone-aware, UTC).
Accesses a `WhereWhere.ObsDataLocation.ObservationLocation`
element and returns the AstroCoords.Time.TimeInstant.ISOTime element,
converted to a (UTC-timezoned) datetime.
Note that a packet... | 3.477444 | 2.603779 | 1.335537 |
od = voevent.WhereWhen.ObsDataLocation[index]
ac = od.ObservationLocation.AstroCoords
ac_sys = voevent.WhereWhen.ObsDataLocation.ObservationLocation.AstroCoordSystem
sys = ac_sys.attrib['id']
if hasattr(ac.Position2D, "Name1"):
assert ac.Position2D.Name1 == 'RA' and ac.Position2D.Name2... | def get_event_position(voevent, index=0) | Extracts the `AstroCoords` from a given `WhereWhen.ObsDataLocation`.
Note that a packet may include multiple 'ObsDataLocation' entries
under the 'WhereWhen' section, for example giving locations of an object
moving over time. Most packets will have only one, however, so the
default is to just return co... | 5.247857 | 4.111835 | 1.276281 |
groups_omd = OMDict()
w = deepcopy(voevent.What)
lxml.objectify.deannotate(w)
if w.find('Group') is not None:
for grp in w.Group:
groups_omd.add(grp.attrib.get('name'),
_get_param_children_as_omdict(grp))
return groups_omd | def get_grouped_params(voevent) | Fetch grouped Params from the `What` section of a voevent as an omdict.
This fetches 'grouped' Params, i.e. those enclosed in a Group element,
and returns them as a nested dict-like structure, keyed by
GroupName->ParamName->AttribName.
Note that since multiple Params may share the same ParamName, the ... | 6.105036 | 4.773361 | 1.278981 |
result = OrderedDict()
w = deepcopy(voevent.What)
lxml.objectify.deannotate(w)
return _get_param_children_as_omdict(w) | def get_toplevel_params(voevent) | Fetch ungrouped Params from the `What` section of a voevent as an omdict.
This fetches 'toplevel' Params, i.e. those not enclosed in a Group element,
and returns them as a nested dict-like structure, keyed like
ParamName->AttribName.
Note that since multiple Params may share the same ParamName, the re... | 15.51208 | 10.621165 | 1.460488 |
import warnings
warnings.warn(
,
FutureWarning)
return get_event_position(voevent, index) | def pull_astro_coords(voevent, index=0) | Deprecated alias of :func:`.get_event_position` | 12.379263 | 5.86676 | 2.110068 |
import warnings
warnings.warn(
,
FutureWarning)
return get_event_time_as_utc(voevent, index) | def pull_isotime(voevent, index=0) | Deprecated alias of :func:`.get_event_time_as_utc` | 10.798459 | 4.637174 | 2.328672 |
import warnings
warnings.warn(
,
FutureWarning)
result = OrderedDict()
w = deepcopy(voevent.What)
lxml.objectify.deannotate(w)
if w.countchildren() == 0:
return result
toplevel_params = OrderedDict()
result[None] = toplevel_params
if w.find('Param') is no... | def pull_params(voevent) | Attempts to load the `What` section of a voevent as a nested dictionary.
.. warning:: Deprecated due to `Missing name attributes` issues.
`Param` or `Group` entries which are missing the `name` attribute
will be entered under a dictionary key of ``None``. This means that if
there are multi... | 3.326366 | 2.787011 | 1.193524 |
subtree = deepcopy(subtree)
lxml.objectify.deannotate(subtree)
lxml.etree.cleanup_namespaces(subtree)
return lxml.etree.tostring(subtree, pretty_print=True).decode(
encoding="utf-8") | def prettystr(subtree) | Print an element tree with nice indentation.
Prettyprinting a whole VOEvent often doesn't seem to work, probably for
issues relating to whitespace cf.
http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output
This function is a quick workaround for prettyprinting a subsection
... | 2.932577 | 3.552341 | 0.825534 |
url = 'https://{}:{}/api/'.format(self.host, self.port)
url += path.format(site=self.site)
try:
async with self.session.request(method, url, json=json) as res:
if res.content_type != 'application/json':
raise ResponseError(
... | async def request(self, method, path, json=None) | Make a request to the API. | 2.709807 | 2.620857 | 1.033939 |
self.thread_handler.run(target=self.start_blocking)
self.thread_handler.start_run_loop() | def start(self) | Start the MQTT client. | 9.367449 | 7.807244 | 1.199841 |
topics = [("hermes/intent/#", 0), ("hermes/hotword/#", 0), ("hermes/asr/#", 0), ("hermes/nlu/#", 0),
("snipsmanager/#", 0)]
self.log_info("Connecting to {} on port {}".format(self.mqtt_hostname, str(self.mqtt_port)))
retry = 0
while True and run_event.is_set(... | def start_blocking(self, run_event) | Start the MQTT client, as a blocking method.
:param run_event: a run event object provided by the thread handler. | 2.731837 | 2.650591 | 1.030652 |
self.log_info("Connected with result code {}".format(result_code))
self.state_handler.set_state(State.welcome) | def on_connect(self, client, userdata, flags, result_code) | Callback when the MQTT client is connected.
:param client: the client being connected.
:param userdata: unused.
:param flags: unused.
:param result_code: result code. | 5.936513 | 7.195943 | 0.824981 |
self.log_info("Disconnected with result code " + str(result_code))
self.state_handler.set_state(State.goodbye)
time.sleep(5)
self.thread_handler.run(target=self.start_blocking) | def on_disconnect(self, client, userdata, result_code) | Callback when the MQTT client is disconnected. In this case,
the server waits five seconds before trying to reconnected.
:param client: the client being disconnected.
:param userdata: unused.
:param result_code: result code. | 5.380677 | 5.917101 | 0.909343 |
if msg is None:
return
self.log_info("New message on topic {}".format(msg.topic))
self.log_debug("Payload {}".format(msg.payload))
if msg.payload is None or len(msg.payload) == 0:
pass
if msg.payload:
payload = json.loads(msg.payloa... | def on_message(self, client, userdata, msg) | Callback when the MQTT client received a new message.
:param client: the MQTT client.
:param userdata: unused.
:param msg: the MQTT message. | 2.26442 | 2.286082 | 0.990524 |
params = {'per_page': per_page, 'page': page}
return self.request.get(str(identity_id) + '/token', params) | def list(self, identity_id, per_page=20, page=1) | Get a list of tokens
:param identity_id: The ID of the identity to retrieve tokens for
:param per_page: The number of results per page returned
:param page: The page number of the results
:return: dict of REST API output with headers attached
:rtype: :class:`... | 4.359734 | 4.825416 | 0.903494 |
params = {'service': service, 'token': token}
return self.request.post(str(identity_id) + '/token', params) | def create(self, identity_id, service, token) | Create the token
:param identity_id: The ID of the identity to retrieve
:param service: The service that the token is linked to
:param token: The token provided by the the service
:param expires_at: Set an expiry for this token
:return: dict of REST API outpu... | 5.103631 | 6.091053 | 0.83789 |
params = {}
if token:
params['token'] = token
return self.request.put(str(identity_id) + '/token/' + service, params) | def update(self, identity_id, service, token=None) | Update the token
:param identity_id: The ID of the identity to retrieve
:return: dict of REST API output with headers attached
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`,
:class:`requests.ex... | 4.718246 | 5.170944 | 0.912454 |
FNAME = 'handle_%s_autocloud_%s'
if ('compose_id' in msg['msg'] or 'compose_job_id' in msg['msg'] or
'autocloud.compose' in msg['topic']):
return getattr(self, FNAME % ('v2', fname))(msg, **config)
else:
return getattr(self, FNAME % ('v1', fname)... | def _func_router(self, msg, fname, **config) | This method routes the messages based on the params and calls the
appropriate method to process the message. The utility of the method is
to cope up with the major message change during different releases. | 5.67426 | 5.615573 | 1.010451 |
sesames = []
account = CandyHouseAccount(email, password, timeout=timeout)
for sesame in account.sesames:
if device_ids is not None and sesame['device_id'] not in device_ids:
continue
if nicknames is not None and sesame['nickname'] not in nicknames:
continue
... | def get_sesames(email, password, device_ids=None, nicknames=None, timeout=5) | Return list of available Sesame objects. | 2.493408 | 2.285237 | 1.091094 |
new_b_value = self.gpio_b.is_active
new_a_value = self.gpio_a.is_active
value = self.table_values.value(new_b_value, new_a_value, self.old_b_value, self.old_a_value)
self.old_b_value = new_b_value
self.old_a_value = new_a_value
if value != 0:
self.... | def pulse(self) | Calls when_rotated callback if detected changes | 3.491441 | 2.775238 | 1.258069 |
'''
Set archive default read versions
Parameters
----------
default_versions: dict
Dictionary of archive_name, version pairs. On read/download,
archives in this dictionary will download the specified version
by default. Before assignment, arch... | def default_versions(self, default_versions) | Set archive default read versions
Parameters
----------
default_versions: dict
Dictionary of archive_name, version pairs. On read/download,
archives in this dictionary will download the specified version
by default. Before assignment, archive_names are checke... | 8.080509 | 2.11703 | 3.816908 |
'''
Create a DataFS archive
Parameters
----------
archive_name: str
Name of the archive
authority_name: str
Name of the data service to use as the archive's data authority
versioned: bool
If true, store all versions with exp... | def create(
self,
archive_name,
authority_name=None,
versioned=True,
raise_on_err=True,
metadata=None,
tags=None,
helper=False) | Create a DataFS archive
Parameters
----------
archive_name: str
Name of the archive
authority_name: str
Name of the data service to use as the archive's data authority
versioned: bool
If true, store all versions with explicit version number... | 3.26016 | 1.812861 | 1.798351 |
'''
Retrieve a data archive
Parameters
----------
archive_name: str
Name of the archive to retrieve
default_version: version
str or :py:class:`~distutils.StrictVersion` giving the default
version number to be used on read operations
... | def get_archive(self, archive_name, default_version=None) | Retrieve a data archive
Parameters
----------
archive_name: str
Name of the archive to retrieve
default_version: version
str or :py:class:`~distutils.StrictVersion` giving the default
version number to be used on read operations
Returns
... | 4.361876 | 2.288343 | 1.906128 |
'''
Batch version of :py:meth:`~DataAPI.get_archive`
Parameters
----------
archive_names: list
Iterable of archive names to retrieve
default_versions: str, object, or dict
Default versions to assign to each returned archive. May be a dict
... | def batch_get_archive(self, archive_names, default_versions=None) | Batch version of :py:meth:`~DataAPI.get_archive`
Parameters
----------
archive_names: list
Iterable of archive names to retrieve
default_versions: str, object, or dict
Default versions to assign to each returned archive. May be a dict
with archive... | 3.474232 | 1.838344 | 1.88987 |
'''
List archive path components at a given location
.. Note ::
When using listdir on versioned archives, listdir will provide the
version numbers when a full archive path is supplied as the
location argument. This is because DataFS stores the archive path
... | def listdir(self, location, authority_name=None) | List archive path components at a given location
.. Note ::
When using listdir on versioned archives, listdir will provide the
version numbers when a full archive path is supplied as the
location argument. This is because DataFS stores the archive path
as a dire... | 6.52581 | 1.394764 | 4.678792 |
'''
Searches based on tags specified by users
Parameters
---------
query: str
tags to search on. If multiple terms, provided in comma delimited
string format
prefix: str
start of archive name. Providing a start string improves searc... | def search(self, *query, **kwargs) | Searches based on tags specified by users
Parameters
---------
query: str
tags to search on. If multiple terms, provided in comma delimited
string format
prefix: str
start of archive name. Providing a start string improves search
speed. | 12.548002 | 2.790312 | 4.496989 |
'''
Utility function for creating and validating archive names
Parameters
----------
archive_name: str
Name of the archive from which to create a service path
Returns
-------
archive_path: str
Internal path used by services to r... | def _validate_archive_name(self, archive_name) | Utility function for creating and validating archive names
Parameters
----------
archive_name: str
Name of the archive from which to create a service path
Returns
-------
archive_path: str
Internal path used by services to reference archive dat... | 5.32375 | 2.737691 | 1.944613 |
'''
Utility function for hashing file contents
Overload this function to change the file equality checking algorithm
Parameters
----------
f: file-like
File-like object or file path from which to compute checksum value
Returns
-------
... | def hash_file(f) | Utility function for hashing file contents
Overload this function to change the file equality checking algorithm
Parameters
----------
f: file-like
File-like object or file path from which to compute checksum value
Returns
-------
checksum: dict
... | 4.05747 | 1.684043 | 2.409363 |
if data is None:
return None
as_li = lambda v: "<li>%s</li>" % v
items = [as_li(v) for v in data]
return mark_safe("<ul>%s</ul>" % ''.join(items)) | def html_list(data) | Convert dict into formatted HTML. | 3.099328 | 3.071965 | 1.008908 |
for p in queryset:
if p.is_editable:
logger.debug("Ignoring version update '%s' is editable", p.package_name)
else:
p.update_from_pypi() | def check_pypi(modeladmin, request, queryset) | Update latest package info from PyPI. | 6.454794 | 6.65285 | 0.97023 |
if self.value() == '-1':
return queryset.filter(latest_version__isnull=True)
elif self.value() == '0':
return (
queryset
.filter(
current_version__isnull=False,
latest_version__isnull=False,
... | def queryset(self, request, queryset) | Filter based on whether an update (of any sort) is available. | 1.841192 | 1.808326 | 1.018174 |
if obj.latest_version is None or obj.is_editable:
return None
else:
return obj.latest_version != obj.current_version | def _updateable(self, obj) | Return True if there are available updates. | 6.273454 | 4.740996 | 1.323235 |
from package_monitor import pypi
package = pypi.Package(obj.package_name)
versions = package.all_versions()
return html_list([v for v in versions if v > obj.current_version]) | def available_updates(self, obj) | Print out all versions ahead of the current one. | 7.289975 | 6.101205 | 1.194842 |
agent = msg['msg']['agent']
if isinstance(agent, list):
agent = agent[0]
return agent | def get_agent(msg) | Handy hack to handle legacy messages where 'agent' was a list. | 3.761958 | 2.342122 | 1.606218 |
config["name"] = case
model_dir = os.path.join(livvkit.model_dir, config['data_dir'], case)
bench_dir = os.path.join(livvkit.bench_dir, config['data_dir'], case)
tabs = []
case_summary = LIVVDict()
model_cases = functions.collect_cases(model_dir)
bench_cases = functions.collect_cases(be... | def run_suite(case, config, summary) | Run the full suite of verification tests | 3.333017 | 3.315443 | 1.005301 |
bundle = livvkit.verification_model_module
model_out = functions.find_file(model_dir, "*"+config["output_ext"])
bench_out = functions.find_file(bench_dir, "*"+config["output_ext"])
model_config = functions.find_file(model_dir, "*"+config["config_ext"])
bench_config = functions.find_file(bench_d... | def _analyze_case(model_dir, bench_dir, config) | Runs all of the verification checks on a particular case | 4.277813 | 4.077453 | 1.049139 |
for dof, data in summary.items():
b4b = data["Bit for Bit"]
conf = data["Configurations"]
stdout = data["Std. Out Files"]
print(" " + case + " " + str(dof))
print(" --------------------")
print(" Bit for bit matches : " + str(b4b[0]) + " of " + str(b4... | def _print_summary(case, summary) | Show some statistics from the run | 4.72505 | 4.451242 | 1.061513 |
if "Bit for Bit" not in summary:
summary["Bit for Bit"] = [0, 0]
if "Configurations" not in summary:
summary["Configurations"] = [0, 0]
if "Std. Out Files" not in summary:
summary["Std. Out Files"] = 0
# Get the number of bit for bit failures
total_count = 0
failure... | def _summarize_result(result, summary) | Trim out some data to return for the index page | 2.52819 | 2.544431 | 0.993617 |
fname = model_path.split(os.path.sep)[-1]
# Error handling
if not (os.path.isfile(bench_path) and os.path.isfile(model_path)):
return elements.error("Bit for Bit",
"File named " + fname + " has no suitable match!")
try:
model_data = Dataset(model_path)
... | def bit_for_bit(model_path, bench_path, config) | Checks whether the given files have bit for bit solution matches
on the given variable list.
Args:
model_path: absolute path to the model dataset
bench_path: absolute path to the benchmark dataset
config: the configuration of the set of analyses
Returns:
A dictionary create... | 2.799335 | 2.739731 | 1.021755 |
diff_dict = LIVVDict()
model_data = model_bundle.parse_config(model_config)
bench_data = bench_bundle.parse_config(bench_config)
if model_data == {} and bench_data == {}:
return elements.error("Configuration Comparison",
"Could not open file: " + model_config.s... | def diff_configurations(model_config, bench_config, model_bundle, bench_bundle) | Description
Args:
model_config: a dictionary with the model configuration data
bench_config: a dictionary with the benchmark configuration data
model_bundle: a LIVVkit model bundle object
bench_bundle: a LIVVkit model bundle object
Returns:
A dictionary created by the e... | 2.330139 | 2.330008 | 1.000056 |
plot_title = ""
plot_name = case + "_" + var_name + ".png"
plot_path = os.path.join(os.path.join(livvkit.output_dir, "verification", "imgs"))
functions.mkdir_p(plot_path)
m_ndim = np.ndim(model_data)
b_ndim = np.ndim(bench_data)
if m_ndim != b_ndim:
return "Dataset dimensions di... | def plot_bit_for_bit(case, var_name, model_data, bench_data, diff_data) | Create a bit for bit plot | 2.042564 | 2.02953 | 1.006422 |
campaign = super(Campaign, self).save(*args, **kwargs)
save_campaign_special_coverage_percolator.delay(self.tunic_campaign_id)
return campaign | def save(self, *args, **kwargs) | Kicks off celery task to re-save associated special coverages to percolator
:param args: inline arguments (optional)
:param kwargs: keyword arguments
:return: `bulbs.campaigns.Campaign` | 13.204877 | 5.948348 | 2.219923 |
return self.count_rows(table, '*') - self.count_rows_distinct(table, cols) | def count_rows_duplicates(self, table, cols='*') | Get the number of rows that do not contain distinct values. | 4.726849 | 3.597401 | 1.313962 |
query = 'SELECT COUNT({0}) FROM {1}'.format(join_cols(cols), wrap(table))
result = self.fetch(query)
return result if result is not None else 0 | def count_rows(self, table, cols='*') | Get the number of rows in a particular table. | 4.594653 | 4.351382 | 1.055906 |
return self.fetch('SELECT COUNT(DISTINCT {0}) FROM {1}'.format(join_cols(cols), wrap(table))) | def count_rows_distinct(self, table, cols='*') | Get the number distinct of rows in a particular table. | 6.0281 | 5.158353 | 1.168609 |
for col in self.get_columns(table):
if self.count_rows_duplicates(table, col) == 0:
return col | def get_unique_column(self, table) | Determine if any of the columns in a table contain exclusively unique values. | 4.523259 | 3.828711 | 1.181405 |
query = 'SELECT {0} FROM {1} GROUP BY {0} HAVING COUNT(*) > 1'.format(join_cols(column), wrap(table))
return self.fetch(query) | def get_duplicate_vals(self, table, column) | Retrieve duplicate values in a column of a table. | 4.096261 | 3.777071 | 1.084507 |
field_info = self.get_attributes(field)
field_info["required"] = getattr(field, "required", False)
field_info["type"] = self.get_label_lookup(field)
if getattr(field, "child", None):
field_info["child"] = self.get_field_info(field.child)
elif getattr(field,... | def get_field_info(self, field) | This method is basically a mirror from rest_framework==3.3.3
We are currently pinned to rest_framework==3.1.1. If we upgrade,
this can be refactored and simplified to rely more heavily on
rest_framework's built in logic. | 2.432403 | 2.221718 | 1.094829 |
if len(self.model.db) == 0:
return 0
return max(map(lambda obj: obj["id"], self.model.db)) | def maxId(self) | int: current max id of objects | 4.303941 | 3.823313 | 1.12571 |
if not isinstance(obj, dict):
raise TypeError("Add object should be a dict object")
obj = self.validation(obj)
obj["id"] = self.maxId + 1
obj = self._cast_model(obj)
self.model.db.append(obj)
if not self._batch.enable.is_set():
self.model... | def add(self, obj) | Add a object
Args:
Object: Object will be added
Returns:
Object: Object with id
Raises:
TypeError: If add object is not a dict
MultipleInvalid: If input object is invaild | 6.439365 | 5.564073 | 1.157311 |
for obj in self.model.db:
if obj["id"] == id:
return self._cast_model(obj)
return None | def get(self, id) | Get a object by id
Args:
id (int): Object id
Returns:
Object: Object with specified id
None: If object not found | 6.638396 | 7.82469 | 0.848391 |
before_len = len(self.model.db)
self.model.db = [t for t in self.model.db if t["id"] != id]
if not self._batch.enable.is_set():
self.model.save_db()
return before_len - len(self.model.db) | def remove(self, id) | Remove a object by id
Args:
id (int): Object's id should be deleted
Returns:
len(int): affected rows | 4.389212 | 4.64715 | 0.944496 |
before_len = len(self.model.db)
self.model.db = []
if not self._batch.enable.is_set():
self.model.save_db()
return before_len - len(self.model.db) | def removeAll(self) | Remove all objects
Returns:
len(int): affected rows | 6.568685 | 6.433276 | 1.021048 |
newObj = self.validation(newObj)
for obj in self.model.db:
if obj["id"] != id:
continue
newObj.pop("id", None)
obj.update(newObj)
obj = self._cast_model(obj)
if not self._batch.enable.is_set():
self.mod... | def update(self, id, newObj) | Update a object
Args:
id (int): Target Object ID
newObj (object): New object will be merged into original object
Returns:
Object: Updated object
None: If specified object id is not found
MultipleInvalid: If input obj... | 5.647197 | 6.060878 | 0.931746 |
newObj = self.validation(newObj)
for index in xrange(0, len(self.model.db)):
if self.model.db[index]["id"] != id:
continue
newObj["id"] = id
self.model.db[index] = self._cast_model(newObj)
if not self._batch.enable.is_set():
... | def set(self, id, newObj) | Set a object
Args:
id (int): Target Object ID
newObj (object): New object will be set
Returns:
Object: New object
None: If specified object id is not found
MultipleInvalid: If input object is invaild | 4.363841 | 4.76422 | 0.915961 |
objs = []
for obj in self.model.db:
objs.append(self._cast_model(obj))
return objs | def getAll(self) | Get all objects
Returns:
List: list of all objects | 8.00972 | 7.7788 | 1.029686 |
new_len = max(len(self._buf[0]) * 2, (len(self._buf[0]) + len(self._buf[1])))
self._merge_prefix(new_len) | def _double_prefix(self) | Grow the given deque by doubling, but don't split the second chunk just
because the first one is small. | 5.764701 | 4.386404 | 1.31422 |
if len(self._buf) == 1 and len(self._buf[0]) <= size:
return
prefix = []
remaining = size
while self._buf and remaining > 0:
chunk = self._buf.popleft()
if len(chunk) > remaining:
self._buf.appendleft(chunk[remaining:])
... | def _merge_prefix(self, size) | Replace the first entries in a deque of strings with a single
string of up to size bytes.
>>> d = collections.deque(['abc', 'de', 'fghi', 'j'])
>>> _merge_prefix(d, 5); print(d)
deque(['abcde', 'fghi', 'j'])
Strings will be split as necessary to reach the desired size.
... | 2.169906 | 2.246413 | 0.965943 |
now = timezone.now()
qs = SpecialCoverage.objects.filter(
tunic_campaign_id__isnull=False,
)
return qs.filter(
start_date__lte=now,
end_date__gt=now
) | qs.filter(
start_date__lte=now,
end_date__isnull=True
) | def get_sponsored_special_coverages() | :returns: Django query for all active special coverages with active campaigns. | 3.481143 | 2.927702 | 1.189036 |
special_coverages = get_sponsored_special_coverages()
es_query = SearchParty(special_coverages).search()
if only_recent:
offset = getattr(settings, "RECENT_SPONSORED_OFFSET_HOURS", 0)
es_query = es_query.filter(
Published(after=timezone.now() - timezone.timedelta(hours=offse... | def get_sponsored_special_coverage_query(only_recent=False) | Reference to all SpecialCovearge queries.
:param only_recent: references RECENT_SPONSORED_OFFSET_HOURS from django settings.
Used to return sponsored content within a given configuration of hours.
:returns: Djes.LazySearch query matching all active speical coverages. | 4.30804 | 3.677863 | 1.171343 |
app_iter = None
try:
app_iter = self.app(environ, start_response)
for item in app_iter:
yield item
if hasattr(app_iter, 'close'):
app_iter.close()
except Exception:
if hasattr(app_iter, 'close'):
... | def debug_application(self, environ, start_response) | Run the application and conserve the traceback frames. | 5.650928 | 5.549918 | 1.0182 |
if 0 not in self.frames:
self.frames[0] = _ConsoleFrame(self.console_init_func())
return Response(render_console_html(secret=self.secret),
content_type='text/html') | def display_console(self, request) | Display a standalone shell. | 8.914674 | 8.814756 | 1.011335 |
rv = traceback.paste()
return Response(json.dumps(rv), content_type='application/json') | def paste_traceback(self, request, traceback) | Paste the traceback and return a JSON response. | 6.339242 | 5.112232 | 1.240015 |
start_value = self.get_start(request)
if start_value:
queryset = self.apply_published_filter(queryset, "after", start_value)
end_value = self.get_end(request)
if end_value:
# Forces the end_value to be the last second of the date provided in the query.
... | def filter_queryset(self, request, queryset, view) | Apply the relevant behaviors to the view queryset. | 5.717689 | 5.651005 | 1.0118 |
if operation not in ["after", "before"]:
raise ValueError()
return queryset.filter(Published(**{operation: value})) | def apply_published_filter(self, queryset, operation, value) | Add the appropriate Published filter to a given elasticsearch query.
:param queryset: The DJES queryset object to be filtered.
:param operation: The type of filter (before/after).
:param value: The date or datetime value being applied to the filter. | 9.220969 | 9.195834 | 1.002733 |
if param in request.GET:
param_value = request.GET.get(param, None)
# Match and interpret param if formatted as a date.
date_match = dateparse.date_re.match(param_value)
if date_match:
return timezone.datetime.combine(
... | def get_date_datetime_param(self, request, param) | Check the request for the provided query parameter and returns a rounded value.
:param request: WSGI request object to retrieve query parameter data.
:param param: the name of the query parameter. | 2.354357 | 2.502819 | 0.940682 |
with self.session_lock:
if not hasattr(message, "id"):
message.__setattr__("id", "event-%s" % (uuid.uuid4().hex,))
if self.session_list.get(message.id, None) is not None:
if force is False:
raise SessionError("Message id: %s du... | def create(self, message, mid=None, age=60, force=True) | create session
force if you pass `force = False`, it may raise SessionError
due to duplicate message id | 4.020723 | 3.679493 | 1.092738 |
def get_all_quiz_submissions(self, quiz_id, course_id, include=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
path["quiz_id"] = quiz_id
... | Get all quiz submissions.
Get a list of all submissions for this quiz. Users who can view or manage
grades for a course will have submissions from multiple users returned. A
user who can only submit will have only their own submissions returned. When
a user has an in-progress submi... | null | null | null | |
def create_quiz_submission_start_quiz_taking_session(self, quiz_id, course_id, access_code=None, preview=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
... | Create the quiz submission (start a quiz-taking session).
Start taking a Quiz by creating a QuizSubmission which you can use to answer
questions and submit your answers.
<b>Responses</b>
* <b>200 OK</b> if the request was successful
* <b>400 Bad Request... | null | null | null | |
def update_student_question_scores_and_comments(self, id, quiz_id, attempt, course_id, fudge_points=None, questions=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id... | Update student question scores and comments.
Update the amount of points a student has scored for questions they've
answered, provide comments for the student about their answer(s), or simply
fudge the total score by a specific amount of points.
<b>Responses</b>
... | null | null | null | |
def complete_quiz_submission_turn_it_in(self, id, quiz_id, attempt, course_id, validation_token, access_code=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
... | Complete the quiz submission (turn it in).
Complete the quiz submission by marking it as complete and grading it. When
the quiz submission has been marked as complete, no further modifications
will be allowed.
<b>Responses</b>
* <b>200 OK</b> if the req... | null | null | null | |
parser = argparse.ArgumentParser(description="Main script to run LIVVkit.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
fromfile_prefix_chars='@')
parser.add_argument('-o', '--out-dir',
default=os... | def parse_args(args=None) | Handles the parsing of options for LIVVkit's command line interface
Args:
args: The list of arguments, typically sys.argv[1:] | 4.075498 | 3.859723 | 1.055904 |
# Set matlplotlib's backend so LIVVkit can plot to files.
import matplotlib
matplotlib.use('agg')
livvkit.output_dir = os.path.abspath(options.out_dir)
livvkit.index_dir = livvkit.output_dir
livvkit.verify = True if options.verify is not None else False
livvkit.validate = True if opti... | def init(options) | Initialize some defaults | 2.599011 | 2.599509 | 0.999809 |
def list_group_categories_for_context_accounts(self, account_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = account_id
self.logger.debug("GET /api/v1/accounts/{account_id}/group_categories with query ... | List group categories for a context.
Returns a list of group categories in a context | null | null | null | |
def list_group_categories_for_context_courses(self, course_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
self.logger.debug("GET /api/v1/courses/{course_id}/group_categories with query params:... | List group categories for a context.
Returns a list of group categories in a context | null | null | null | |
def get_single_group_category(self, group_category_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_category_id
path["group_category_id"] = group_category_id
self.logger.debug("GET /api/v1/group_categories/{group_category_id} wi... | Get a single group category.
Returns the data for a single group category, or a 401 if the caller doesn't have
the rights to see it. | null | null | null | |
def create_group_category_accounts(self, name, account_id, auto_leader=None, create_group_count=None, group_limit=None, self_signup=None, split_group_count=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = accoun... | Create a Group Category.
Create a new group category | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.