content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
from reqlist import *
import random
from catalog.models import Course
def ceiling_thresh(progress, maximum):
"""Creates a progress object
Ensures that 0 < progress < maximum"""
effective_progress = max(0, progress)
if maximum > 0:
return Progress(min(effective_progress, maximum), maximum)
... | requirements/progress.py | 25,548 | Each of these keys will be filled in a RequirementsStatement JSON
representation decorated by a RequirementsProgress object.
An object describing simple progress towards a requirement
Different from RequirementsProgress object as it only includes progress information,
not nested RequirementsProgress objects, fulfillmen... | 4,551 | en | 0.858053 |
"""Constants for the AVM FRITZ!SmartHome integration."""
from __future__ import annotations
import logging
from typing import Final
from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW
from homeassistant.components.fritzbox.model import (
FritzBinarySensorEntityDescription,
FritzSensorEntity... | homeassistant/components/fritzbox/const.py | 3,355 | Constants for the AVM FRITZ!SmartHome integration.
type: ignore[no-any-return] type: ignore[no-any-return] type: ignore[no-any-return] type: ignore[no-any-return] type: ignore[no-any-return] type: ignore[no-any-return] | 220 | en | 0.34959 |
#!/usr/bin/env python2
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test addressindex generation and fetching
#
import time
from test_framework.test_framework import Sa... | qa/rpc-tests/addressindex.py | 14,751 | !/usr/bin/env python2 Copyright (c) 2014-2015 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Test addressindex generation and fetching Nodes 0/1 are "wallet" nodes Nodes 2/3 are used for testing Check that ... | 977 | en | 0.839172 |
# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
... | mockito-0.5.2/mockito_test/verification_errors_test.py | 3,501 | Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, co... | 1,136 | en | 0.851545 |
# version 0.1
# by DrLecter
import sys
from com.l2jfrozen import Config
from com.l2jfrozen.gameserver.model.quest import State
from com.l2jfrozen.gameserver.model.quest import QuestState
from com.l2jfrozen.gameserver.model.quest.jython import QuestJython as JQuest
qn = "420_LittleWings"
# variables section
REQUIRED_... | datapack/data/scripts/quests/420_LittleWings/__init__.py | 20,811 | version 0.1 by DrLecter variables sectionDrop rates in %Quest itemsNPCsmobstoad lordexarion'szwov'skalibran'ssuzet'sshamhai'sRewards helper functions section st.takeItems(SCALE_3,1) Main Quest Codeincipios dropdragon detectionfairy stone destruction Quest class and state definition Quest initialization Qu... | 471 | en | 0.448808 |
space1 = 'X'
space2 = 'X'
space3 = 'X'
space4 = 'X'
space5 = 'X'
space6 = ' '
space7 = 'O'
space8 = ' '
space9 = ' '
print(' | | ')
print(' {} | {} | {} '.format(space1,space2,space3))
print(' | | ')
print('-----------')
print(' | | ')
print(' {} | {} | {} '.format(space4,space5,space6... | noughts_crosses.py | 583 | toplinewinningdo the other winning options | 42 | en | 0.677327 |
from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
""" Test creating a new user with an email is successful """
def test_create_user_with_email_successful(self):
payload = {'email': 'pudgeinvonyx@gmail.com', 'password': '1111qqqq='}
user... | app/core/tests/test_models.py | 1,479 | Test creating a new user with an email is successful
Test that create a new superuser
Test creating a new user with an invalid email address
Test creating a new user with an lowercase email words | 198 | en | 0.884014 |
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc.textTools import safeEval, readHex
from fontTools.misc.encodingTools import getEncoding
from fontTools.ttLib import getSearchRange
from fontTools.unicode import Unicode
from . import DefaultTable
impor... | FontTools/fontTools/ttLib/tables/_c_m_a_p.py | 45,664 | Returns the Python encoding name for this cmap subtable based on its platformID,
platEncID, and language. If encoding for these values is not known, by default
None is returned. That can be overriden by passing a value to the default
argument.
Note that if you want to choose a "preferred" cmap subtable, most of the ... | 10,498 | en | 0.852224 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | venv1/Lib/site-packages/tensorflow/python/ops/distributions/exponential.py | 5,527 | Exponential distribution.
The Exponential distribution is parameterized by an event `rate` parameter.
#### Mathematical Details
The probability density function (pdf) is,
```none
pdf(x; lambda, x > 0) = exp(-lambda x) / Z
Z = 1 / lambda
```
where `rate = lambda` and `Z` is the normalizaing constant.
The Exponenti... | 2,820 | en | 0.750303 |
#from numba import jit
import numpy as np
#from joblib import Parallel, delayed, parallel_backend
#from joblib import load, dump
#import tempfile
#import shutil
#import os
#
#import sys
#sys.path.append('pyunicorn_timeseries')
#from pyunicorn_timeseries.surrogates import Surrogates
def set_model_constants(xx=50.E3,nx=... | coupled_channel/cutils.py | 25,330 | This is the main function for the coupled ocean--atm channel model.
## INPUT VARIABLES ##
tmax: running time in seconds
avep: averaging period for the ouput
T0: initial temperature
forcing: dimensionless scaling for the heat flux forcing - default strength is 5 W/m2
dt_f: timestep of the forcing
atm_adv: boolean, adv... | 9,043 | en | 0.774505 |
"""
Subdivide Cells
~~~~~~~~~~~~~~~
Increase the number of triangles in a single, connected triangular mesh.
The :func:`pyvista.PolyDataFilters.subdivide` filter utilitizes three different
subdivision algorithms to subdivide a mesh's cells: `butterfly`, `loop`,
or `linear`.
"""
from pyvista import examples
import pyv... | examples/01-filter/subdivide.py | 1,957 | Subdivide Cells
~~~~~~~~~~~~~~~
Increase the number of triangles in a single, connected triangular mesh.
The :func:`pyvista.PolyDataFilters.subdivide` filter utilitizes three different
subdivision algorithms to subdivide a mesh's cells: `butterfly`, `loop`,
or `linear`.
First, let's load a **triangulated** mesh to ... | 645 | en | 0.741904 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@package EFIT2D_Classes
Support Library: efit2d-pyopencl
Manuscript Title: Optimized OpenCL implementation of the Elastodynamic Finite Integration Technique for viscoelastic media
Authors: M Molero, U Iturraran-Viveros, S Aparicio, M.G. Hernández
Program title: EF... | EFIT2D_Classes.py | 16,007 | Class Inspection: used for the configuration of the inspections to be emulated
Class Material: Definition of a material
@param name Material Name
@param rho Density (kg/m3)
@param c11 C11 (Pa)
@param c12 C12 (Pa)
@param c22 C22 (Pa)
@param c44 C44 (Pa)
@param eta_v Bulk Viscosity Constant (Pa s)
@param eta_s Sh... | 6,446 | en | 0.638515 |
import csv
import enum
class Usability(enum.Enum):
UNKNOWN = 0
USER = 1
BOT = 2
BOTH = 4
class MethodInfo:
def __init__(self, name, usability, errors):
self.name = name
self.errors = errors
try:
self.usability = {
'unknown': Usability.UNKNOWN,
... | telethon_generator/parsers/methods.py | 1,312 | Parses the input CSV file with columns (method, usability, errors)
and yields `MethodInfo` instances as a result.
header | 122 | en | 0.699982 |
from math import pi
import pandas as pd
from bokeh.plotting import figure, output_file, show
from bokeh.sampledata.stocks import MSFT
df = pd.DataFrame(MSFT)[:50]
df["date"] = pd.to_datetime(df["date"])
inc = df.close > df.open
dec = df.open > df.close
w = 12*60*60*1000 # half day in ms
TOOLS = "pan,wheel_zoom,box... | examples/plotting/file/candlestick.py | 841 | half day in ms open a browser | 29 | en | 0.631442 |
"""Classes for more complex applications that have tabbed or paged navigation."""
from collections import OrderedDict
from copy import deepcopy
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from implements import implements
from .utils_app import AppBa... | dash_charts/utils_app_with_navigation.py | 13,863 | Base class for building Dash Application with multiple pages.
Base class for building Dash Application with tabs or URL routing.
Base class for building Dash Application with tabs.
Base class for building Dash Application with tabs that uses the full window.
Simple App without charts or callbacks.
Create each navigatio... | 3,122 | en | 0.707001 |
from test.test_json import PyTest, CTest
# 2007-10-05
JSONDOCS = [
# http://json.org/JSON_checker/test/fail1.json
'"A JSON payload should be an object or array, not a string."',
# http://json.org/JSON_checker/test/fail2.json
'["Unclosed array"',
# http://json.org/JSON_checker/test/fail3.json
'{... | Mark_attandance_py_selenium/py/App/Python/Lib/test/test_json/test_fail.py | 8,884 | 2007-10-05 http://json.org/JSON_checker/test/fail1.json http://json.org/JSON_checker/test/fail2.json http://json.org/JSON_checker/test/fail3.json http://json.org/JSON_checker/test/fail4.json http://json.org/JSON_checker/test/fail5.json http://json.org/JSON_checker/test/fail6.json http://json.org/JSON_checker/test/fail7... | 1,621 | en | 0.353131 |
import pytest
from sanic import Sanic
from sanic.response import json
from sanic_jwt import Authentication, exceptions, Initialize
class WrongAuthentication(Authentication):
async def build_payload(self, user, *args, **kwargs):
return {"not_user_id": 1}
class AnotherWrongAuthentication(Authentication):... | tests/test_authentication.py | 6,080 | assert "Auth required." in response.json.get('reasons') @sanic_app.exception(Exception) def in_case_of_exception(request, exception): exc_name = exception.args[0].__class__.__name__ status_code = exception.args[0].status_code return json({"exception": exc_name}, status=status_code) @sanic_app.exception(Exce... | 533 | en | 0.277494 |
import os
import copy
import pytest
import time
import shutil
import tempfile
import logging
from _pytest.logging import caplog as _caplog
from contextlib import suppress
from panoptes.utils.logging import logger
from panoptes.utils.database import PanDB
from panoptes.utils.config.client import get_config
from panopt... | conftest.py | 6,582 | Doctest modules multiprocessing Start new log file for each testing run. Give server time to start pragma: no cover Adjust various config items for testing pragma: no cover | 172 | en | 0.718363 |
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ['Patient Discharge System v2.0.py']
DATA_FILES = ['model.docx', 'logo.gif']
OPTIONS = {}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=[... | setup.py | 333 | This is a setup.py script generated by py2applet
Usage:
python setup.py py2app | 83 | en | 0.867131 |
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2015, ARM Limited and contributors.
#
# 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
#
# ... | tests/eas/rfc.py | 1,196 | Tests for the Energy-Aware Scheduler
A dummy test just to run configured workloads
SPDX-License-Identifier: Apache-2.0 Copyright (C) 2015, ARM Limited and contributors. 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 cop... | 730 | en | 0.810831 |
# Copyright (c) 2016-present, Facebook, Inc.
#
# 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... | caffe2/python/layers/merge_id_lists.py | 2,321 | Merge multiple ID_LISTs into a single ID_LIST
Arguments:
model: A layer model instance
input_record: Tuple (Struct) of ID_LIST features to be
merged
Returns:
the merged ID_LIST feature
Copyright (c) 2016-present, Facebook, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may ... | 769 | en | 0.836883 |
"""Test project for line_round_dot_setting.
Command examples:
$ python test_projects/line_round_dot_setting/main.py
"""
import sys
sys.path.append('./')
import os
from types import ModuleType
import apysc as ap
from apysc._file import file_util
this_module: ModuleType = sys.modules[__name__]
_D... | test_projects/line_round_dot_setting/main.py | 2,386 | Entry point of this test project.
Handler that called when polyline is clicked.
Parameters
----------
e : MouseEvent
Created MouseEvent instance.
options : dict
Optional parameters.
Test project for line_round_dot_setting.
Command examples:
$ python test_projects/line_round_dot_setting/main.py | 304 | en | 0.633595 |
"""
This module descibes how to split a dataset into two parts A and B: A is for
tuning the algorithm parameters, and B is for having an unbiased estimation of
its performances. The tuning is done by Grid Search.
"""
from __future__ import (absolute_import, division, print_function,
unicode_lit... | examples/split_data_for_unbiased_estimation.py | 1,581 | This module descibes how to split a dataset into two parts A and B: A is for
tuning the algorithm parameters, and B is for having an unbiased estimation of
its performances. The tuning is done by Grid Search.
Load the full dataset. shuffle ratings if you want A = 90% of the data, B = 10% of the data data is now the s... | 476 | en | 0.912124 |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# sla.slaprofile application
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# -----------------------------------------------------... | services/web/apps/sla/slaprofile/views.py | 786 | SLAProfile application
-*- coding: utf-8 -*- --------------------------------------------------------------------- sla.slaprofile application --------------------------------------------------------------------- Copyright (C) 2007-2018 The NOC Project See LICENSE for details ------------------------------------------... | 359 | en | 0.263746 |
from flask import Blueprint, request, jsonify
import subprocess
import json
import yamale
import yaml
import app_conf
import logging.handlers
import mydb
imageinfo = Blueprint('imageinfo', __name__)
# set logger
logger = logging.getLogger(__name__)
path = f'./logs/{__name__}.log'
fileHandler = logging.handlers.Rotati... | gs-engine/gse_api_server/imageinfo.py | 3,016 | set logger temp schema validation yamale.validate(schema_create, yamale.make_data(content=request.data.decode('utf-8'))) name schema validation | 143 | en | 0.155367 |
def is_sha1(maybe_sha):
if len(maybe_sha) != 40:
return False
try:
sha_int = int(maybe_sha, 16)
except ValueError:
return False
return True
def validate(date_text):
try:
datetime.datetime.strptime(date_text, '%d-%m-%Y:%S-%M-%H')
return True
except ValueEr... | load_balancer/docker_acts/app.py | 13,846 | IP = "127.0.0.1:5000"print("This part")print(data)print(sorted_data)print(required_data) @app.route("/api/v1/categories/<category>/acts?start=<startrange>&end=<endrange>", methods = ["GET"]) def range_acts(category = None, startrange = 0, endrange = 0): if request.method == 'GET': temp_path = DB + "/" + cat... | 1,654 | en | 0.292062 |
"""Generated message classes for cloudasset version v1p2beta1.
The cloud asset API manages the history and inventory of cloud resources.
"""
# NOTE: This file is autogenerated and should not be edited by hand.
from __future__ import absolute_import
from apitools.base.protorpclite import messages as _messages
from ap... | lib/googlecloudsdk/third_party/apis/cloudasset/v1p2beta1/cloudasset_v1p2beta1_messages.py | 35,781 | An additional property for a MetadataValue object.
Fields:
key: Name of the additional property.
value: A extra_types.JsonValue attribute.
An additional property for a ResponseValue object.
Fields:
key: Name of the additional property.
value: A extra_types.JsonValue attribute.
An additional property for a Dat... | 25,982 | en | 0.771063 |
# -*- coding: utf-8 -*-
"""Django page CMS test suite module for page links"""
from pages.tests.testcase import TestCase
from pages.models import Content
class LinkTestCase(TestCase):
"""Django page CMS link test suite class"""
def test_01_set_body_pagelink(self):
"""Test the get_body_pagelink_ids an... | pages/tests/test_pages_link.py | 1,229 | Django page CMS link test suite class
Test the get_body_pagelink_ids and set_body_pagelink functions.
Django page CMS test suite module for page links
-*- coding: utf-8 -*- page2 has a link on page1 | 200 | en | 0.523523 |
from ParseHandler import ParseHandler
from PathHandler import PathHandler
import paths
parser = ParseHandler()
pather = PathHandler()
# match subdirectories in both folders
pather.build_matching_subdir(paths.TOY_RAW, paths.TOY_CLEAN)
# get paths to folders in raw/ directory
dir_names = pather.get_dir_names(paths.TOY... | old/src/integrationClean.py | 982 | match subdirectories in both folders get paths to folders in raw/ directory iterate through the contents of each folder get raw file paths from each subdir parse each raw_file into the clean_file | 195 | en | 0.912252 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class MybankCreditLoanapplyInsturlQueryResponse(AlipayResponse):
def __init__(self):
super(MybankCreditLoanapplyInsturlQueryResponse, self).__init__()
self._target_url = No... | alipay/aop/api/response/MybankCreditLoanapplyInsturlQueryResponse.py | 748 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
"""
This file defines the database models
"""
from .common import db, Field, auth
from py4web import URL
from pydal.validators import IS_NOT_EMPTY, IS_FILE, IS_EMPTY_OR
import datetime
from . import settings
def get_time():
return datetime.datetime.utcnow()
def get_download_url(picture):
return f"images/{p... | models.py | 1,314 | This file defines the database models
We do not want these fields to appear in forms by default. | 98 | en | 0.915227 |
import imageio
import tensorflow as tf
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from tf_agents.replay_buffers import tf_uniform_replay_buffer
from tf_agents.drivers import dynamic_step_driver
from tf_agents.environments import tf_py_environment
def load_policy(path):
return tf.compat.v2.s... | trackdays/training/utils.py | 3,014 | The inner env should be used for rendering | 42 | en | 0.583987 |
#!/usr/bin/env python
import argparse
import open3d as o3d
import numpy as np
import os
import time
from os.path import join, dirname, basename, splitext, exists, isdir, isfile
from os import listdir
from numpy import linalg as LA
import math
import cv2
from pathlib import Path
def pcd_to_bin(pcd_path, outdir=None):
... | pointcloud/pcl_conv.py | 5,986 | !/usr/bin/env python binarize array and save to the same file path with .bin extension https://towardsdatascience.com/spherical-projection-for-point-clouds-56a2fc258e6c print(pcd_arr.shape) print(pcd_arr[:, :3].shape) print("yaw {} | {} -- {}".format(yaw.shape, np.amin(yaw), np.amax(yaw))) print("y {} | {} -- {}".forma... | 1,228 | en | 0.320352 |
import os
import traceback
import datetime
class DuplicatePlotException(Exception): pass
class ModelLogUtils():
'''
Collection of utility methods for logging and plotting of messages & metrics during training.
'''
def __init__(self):
# Add logging to stdout for local debugging
self.... | rafiki/model/log.py | 2,395 | Collection of utility methods for logging and plotting of messages & metrics during training.
Convenience method of defining a plot of ``loss`` against ``epoch``.
To be used with ``log_loss_metric()``.
Defines a plot for a set of metrics for analysis of model training.
By default, metrics will be plotted against time.
... | 596 | en | 0.84352 |
# -*- coding: utf-8 -*-
try:
# Python 2.7
from collections import OrderedDict
except:
# Python 2.6
from gluon.contrib.simplejson.ordered_dict import OrderedDict
from gluon import current
from gluon.storage import Storage
def config(settings):
"""
Template for WA-COP + CAD Cloud Integratio... | modules/templates/CAD/config.py | 8,740 | Template for WA-COP + CAD Cloud Integration
-*- coding: utf-8 -*- Python 2.7 Python 2.6 ========================================================================= System Settings Prepop options Prepop default Theme (folder to use for views/layout.html)settings.base.theme = "default" -----------------------------------... | 3,669 | en | 0.634979 |
from urllib.parse import quote
import re
def parse_equation(match):
# Converts a latex expression into something the tex API can understand
eq = match.group(0)
# Curly brackets need to be escaped
eq = eq.replace('{', '\{')
eq = eq.replace('}', '\}')
# Create the url using the quote method wh... | venv/lib/python3.7/site-packages/github_markdown.py | 1,021 | Converts a latex expression into something the tex API can understand Curly brackets need to be escaped Create the url using the quote method which converts special characters Return the markdown SVG tag Define a pattern for catching latex equations delimited by dollar signs Substitute any latex equations found Read in... | 385 | en | 0.788359 |
import pandas as pd
from oss_hugo.API_Hugo_OSS import API_Hugo_OSS
class OSS_Schedule:
def __init__(self):
self.hugo = API_Hugo_OSS()
def sessions_mapped_by_size(self):
mapping = []
for path, session in self.hugo.sessions().items():
content = session.get('content')
... | notebooks/api/oss_hugo/OSS_Schedule.py | 2,640 | todo get the result below using pandas | 38 | gl | 0.150502 |
# --------------
##File path for the file
file_path
def read_file(path):
file = open(file_path , 'r')
sentence = file.readline()
file.close()
return sentence
sample_message = read_file(file_path)
print(sample_message)
#Code starts here
# --------------
#Code starts here
fil... | Spy-Game/code.py | 3,307 | --------------File path for the file Code starts here --------------Code starts here --------------Code starts here -------------- File path for message 4 and message 5Code starts here --------------Code starts here --------------Secret message parts in the correct orderCode starts here | 288 | en | 0.396057 |
# signals are for when a user modifies something in the db, example, creates a post
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
# Creates a profile each time a new user is created
@receiver(post_save, send... | bookStore/users/signals.py | 557 | signals are for when a user modifies something in the db, example, creates a post Creates a profile each time a new user is created | 131 | en | 0.908849 |
import os
import numpy as np
import torch
import time
import sys
from collections import OrderedDict
from torch.autograd import Variable
from pathlib import Path
import warnings
warnings.filterwarnings('ignore')
mainpath = os.getcwd()
pix2pixhd_dir = Path(mainpath+'/src/pix2pixHD/')
sys.path.append(str(pix2pixhd_dir))... | train_pose2vid.py | 5,001 | whether to collect output images Forward Pass sum per device losses calculate final loss scalar Backward Pass update generator weights update discriminator weights Display results and errors print out errors CHANGE: removed [0] after v.data display output images save latest model end of epoch save model for this epo... | 471 | en | 0.740716 |
# MIT License
#
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# r... | art/defences/detector/poison/ground_truth_evaluator.py | 7,842 | Class to evaluate the performance of the poison detection method.
Evaluates ground truth constructor
For each training sample, determine whether the activation clustering method was correct.
:param assigned_clean_by_class: Result of clustering.
:param is_clean_by_class: is clean separated by class.
:return: Two variab... | 2,617 | en | 0.850704 |
import logging; log = logging.getLogger(__name__)
from .Menu import Menu
class HitboxMenu(Menu):
"""A menu for examining a hitbox."""
def __init__(self, parent):
super().__init__(parent)
self.title = "Hitboxes"
self.refresh()
def refresh(self):
if self.parent.model is Non... | modelviewer/programs/SfaModel/Menu/HitboxMenu.py | 1,614 | A menu for examining a hitbox.
def activate(self): selPoly = self.cursorPos - 1 if selPoly >= 0: poly = self.dlist.polys[selPoly] menu = PolyMenu(self.parent, poly, "Display List %d Poly %d: %s" % (poly['list'], selPoly, self.drawModes[poly['mode']], )) self.pare... | 540 | en | 0.375051 |
# -*- coding: utf-8 -*-
# Copyright 2017 Openstack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | shadowfiend/common/paths.py | 2,113 | Return an uninterpolated path relative to $pybasedir.
Return a path relative to $pybasedir.
Return an uninterpolated path relative to $bindir.
Return a path relative to $bindir.
Return an uninterpolated path relative to $state_path.
Return a path relative to $state_path.
-*- coding: utf-8 -*- Copyright 2017 Openstack... | 882 | en | 0.836584 |
import csv
def save2csv(dst_fh, row):
"""
Appends a list with data to a dst_fh csv
args:
dst_fh: str, output file
row: list, list of values to write in a row
"""
with open(dst_fh, "a", encoding="utf-8") as csvfile:
out = csv.writer(
csvfile,
delimit... | src/utils.py | 532 | Appends a list with data to a dst_fh csv
args:
dst_fh: str, output file
row: list, list of values to write in a row | 123 | en | 0.563405 |
#!/usr/bin/env python3
# Print out all the codons for the sequence below in reading frame 1
# Use a 'for' loop
dna = 'ATAGCGAATATCTCTCATGAGAGGGAA'
for nt in range(0, len(dna) - 2, 3):
print(dna[nt:nt+3])
"""
ATA
GCG
AAT
ATC
TCT
CAT
GAG
AGG
GAA
"""
| codons.py | 256 | !/usr/bin/env python3 Print out all the codons for the sequence below in reading frame 1 Use a 'for' loop | 105 | en | 0.550913 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\design.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWin... | design.py | 8,521 | -*- coding: utf-8 -*- Form implementation generated from reading ui file '.\design.ui' Created by: PyQt5 UI code generator 5.11.3 WARNING! All changes made in this file will be lost! | 182 | en | 0.870108 |
from django.contrib import admin
from django.contrib.auth.models import User
from django.test.testcases import TestCase
from django.urls import reverse
from pagetools.menus.admin import MenuAdmin, make_entrieable_admin
from pagetools.menus.apps import MenusConfig
from pagetools.menus.models import Link, Menu, MenuEntr... | pagetools/menus/tests/test_admin.py | 6,441 | test index because customdashboard with MenuModule is may used | 62 | en | 0.791006 |
# coding: utf8
from __future__ import absolute_import
import datetime
from celery import shared_task
from celery.utils.log import get_task_logger
from django.utils.translation import ugettext as _
from django.core.mail import send_mail
from django.contrib.auth import get_user_model
from django.conf import settings
f... | challenges/tasks.py | 1,414 | coding: utf8 Fetch runners that has challenges ending today. | 60 | en | 0.976006 |
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.goal.task_registrar import TaskRegistrar as task
from pants.contrib.codeanalysis.tasks.bundle_entries import BundleEntries
from pants.contrib.codeanalysis.tasks.extract_java im... | contrib/codeanalysis/src/python/pants/contrib/codeanalysis/register.py | 640 | Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). Licensed under the Apache License, Version 2.0 (see LICENSE). | 126 | en | 0.673559 |
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class OslusiadasextractItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
| root_package/oslusiadasextract/items.py | 273 | Define here the models for your scraped items See documentation in: https://docs.scrapy.org/en/latest/topics/items.html define the fields for your item here like: name = scrapy.Field() | 184 | en | 0.676575 |
import numpy as np
import math
# number will be decreased by a small amount when some deletions happen
number_of_vertices = 5_000
# probability of an arc between any two instances
probability_of_an_arc = 0.001
# number of reads in the read-heavy test
read_test_operations = 20_000
# probability of removing a ran... | Conflict-free_Replicated_Data_Types/experiments/benchmarking/OperationTestsGenerator.py | 4,235 | number will be decreased by a small amount when some deletions happen probability of an arc between any two instances number of reads in the read-heavy test probability of removing a random vertex in each after processing each vertex probability of adding a lookup command after each add arc command in write-heavy te... | 1,045 | en | 0.867408 |
"""Tests related to inheritance from interface."""
from datetime import datetime
import pytest
from generics import defended
from generics import delegated
from generics import private
pytestmark = pytest.mark.parametrize("f", [private, delegated, defended])
def test_allow_inheritance_from_interface(f, s):
""... | tests/test_subtyping.py | 474 | Allow inheritance from interface.
Tests related to inheritance from interface. | 78 | en | 0.906998 |
import math
import collections
import numpy as np
def __CheckEvaluationInput(y, yPredicted):
# Check sizes
if(len(y) != len(yPredicted)):
raise UserWarning("Attempting to evaluate between the true labels and predictions.\n Arrays contained different numbers of samples. Check your work and try again."... | Code/EvaluationsStub.py | 4,217 | Check sizes Check values Check sizes | 36 | en | 0.119323 |
"""
module housing core library functionality
"""
import numpy as np
from typing import Optional, Tuple
import humba.jits as jits
def histogram(
x: np.ndarray,
bins: int = 10,
range: Tuple[float, float] = (0, 10),
weights: Optional[np.ndarray] = None,
flow: bool = False,
) -> Tuple[np.ndarray, O... | humba/core.py | 4,312 | Calculate the histogram for the data ``x``.
Parameters
----------
x : :obj:`numpy.ndarray`
data to histogram
bins : int
number of bins
range : (float, float)
axis range
weights : :obj:`numpy.ndarray`, optional
array of weights for ``x``
flow : bool
include over and underflow content in first and la... | 2,167 | en | 0.58586 |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | qiskit/circuit/library/template_circuits/toffoli/template_2a_1.py | 896 | Returns:
QuantumCircuit: template as a quantum circuit.
Template 2a_1:
.. parsed-literal::
┌───┐┌───┐
q_0: ┤ X ├┤ X ├
└───┘└───┘
-*- coding: utf-8 -*- This code is part of Qiskit. (C) Copyright IBM 2020. This code is licensed under the Apache License, Version 2.0. You may obtain ... | 645 | en | 0.835209 |
import os
import csv
import logging
import itertools
import pandas as pd
import psutil as ps
from _pytest.monkeypatch import MonkeyPatch
from dataactcore.interfaces.db import GlobalDB
from dataactcore.config import CONFIG_SERVICES
from dataactcore.models.domainModels import concat_tas_dict
from dataactcore.models.look... | tests/integration/error_warning_file_tests.py | 62,907 | Overall integration tests for error/warning reports.
For each file type (single-file, cross-file, errors, warnings), test if each has
- the correct structure
- each column's content is correct after testing each possible type of error:
- formatting
- length
- types
- required/optional
- SQL validat... | 3,835 | en | 0.699792 |
# -*- coding: utf-8 -*-
import os
import sys
import csv
# -----------------------------------------------------------------------------
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root + '/python')
import ccxt # noqa: E402
# --------------------------------... | binance-fetch-ohlcv-to-csv.py | 3,008 | -*- coding: utf-8 -*- ----------------------------------------------------------------------------- noqa: E402 ----------------------------------------------------------------------------- print('Fetched', len(ohlcv), symbol, 'candles from', exchange.iso8601 (ohlcv[0][0]), 'to', exchange.iso8601 (ohlcv[-1][0])) Excepti... | 745 | en | 0.553811 |
##########################################
# File: refine_multiple_shards_joint.py #
# Copyright Richard Stebbing 2014. #
# Distributed under the MIT License. #
# (See accompany file LICENSE or copy at #
# http://opensource.org/licenses/MIT) #
##########################################
# Imports
... | refine_multiple_shards_joint.py | 3,417 | File: refine_multiple_shards_joint.py Copyright Richard Stebbing 2014. Distributed under the MIT License. (See accompany file LICENSE or copy at http://opensource.org/licenses/MIT) Imports Requires `rscommon`. main | 233 | en | 0.487308 |
import numpy as np
import math
from arena import Arena
from agent import HAgent, AAgent
import random
# np.random.seed(1234)
# place the humans on the arena
def place_soldiers(n, arena, agents):
x = 0
y = 0
for i in range(n):
agents[i + 1] = HAgent([x, y])
arena.arena[x, y] = 1
y ... | helper.py | 5,194 | np.random.seed(1234) place the humans on the arena place the alien agents on the arena x = [19, 19] adds half-cover tiles in random locations in the arena At most n cover tiles added, though potentially fewer movement for agents Check that agent has movement, if not, do nothing print('unsuccessful move') Check if in mo... | 1,092 | en | 0.78169 |
# -*- coding: utf-8 -*-
# This file was generated
import ctypes
import nidigital.errors as errors
import threading
from nidigital._visatype import * # noqa: F403,H303
import nidigital.history_ram_cycle_information as history_ram_cycle_information # noqa: F401
class Library(object):
'''Library
Wrapper ar... | generated/nidigital/nidigital/_library.py | 65,575 | Library
Wrapper around driver library.
Class will setup the correct ctypes information for every function on first call.
-*- coding: utf-8 -*- This file was generated noqa: F403,H303 noqa: F401 We cache the cfunc object from the ctypes.CDLL object noqa: N802 noqa: F405 noqa: F405 noqa: N802 noqa: F405 noqa: F405 noq... | 3,286 | uz | 0.385906 |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from chirpstack_api.as_pb.external.api import organization_pb2 as chirpstack__api_dot_as__pb_dot_external_dot_api_dot_organization__pb2
from google.protobuf impo... | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | 18,785 | OrganizationService is the service managing the organization access.
OrganizationService is the service managing the organization access.
OrganizationService is the service managing the organization access.
Add a new user to an organization.
Create a new organization.
Delete an organiza... | 870 | en | 0.882985 |
import sys
import base64
import platform
import functools
from keyring.util import properties
from keyring.backend import KeyringBackend
from keyring.errors import PasswordDeleteError, ExceptionRaisedContext
from . import file_base
try:
# prefer pywin32-ctypes
from win32ctypes import pywintypes
from win32... | src/site-packages/keyrings/alt/Windows.py | 5,833 | A File-based keyring secured by Windows Crypto API.
A compatibility wrapper for old PyWin32 errors, such as reported in
https://bitbucket.org/kang/python-keyring-lib/issue/140/
RegistryKeyring is a keyring which use Windows CryptAPI to encrypt
the user's passwords and store them under registry keys
Decrypt the password... | 1,266 | en | 0.804666 |
"""
This module is used to manage rules.
## Base format
A context and rule is written in JSON.
A context contains an identifier, AND one or three rules.
One of rules must specify the SCHC Compression/Decompression (CD).
Two specify SCHC Fragmentation/Reassembly (FR) if needed.
Therefore, a context has to be formed ... | rulemanager.py | 15,497 | RuleManager class is used to manage Compression/Decompression and Fragmentation/
Reassembly rules.
t in this
this[k]
this function looks if bits specified in ruleID are not outside of
rule_id_length
check if a conflict exists between to ruleID (i.e. same first bits equals)
add context into the db.
Check rule integr... | 6,359 | en | 0.772817 |
"""
This module is to support *bbox_inches* option in savefig command.
"""
import warnings
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
def adjust_bbox(fig, format, bbox_inches):
"""
Temporarily adjust the figure so that only the specified area
(bbox_inches) is saved.
It modifi... | editing files/Portable Python 3.2.5.1/App/Lib/site-packages/matplotlib/tight_bbox.py | 4,026 | Temporarily adjust the figure so that only the specified area
(bbox_inches) is saved.
It modifies fig.bbox, fig.bbox_inches,
fig.transFigure._boxout, and fig.patch. While the figure size
changes, the scale of the original figure is conserved. A
function which restores the original values are returned.
adjust_bbox fo... | 581 | en | 0.838439 |
import logging
from authlib.common.urls import add_params_to_uri
from .base import BaseGrant, AuthorizationEndpointMixin
from ..errors import (
OAuth2Error,
UnauthorizedClientError,
AccessDeniedError,
)
log = logging.getLogger(__name__)
class ImplicitGrant(BaseGrant, AuthorizationEndpointMixin):
"""T... | authlib/oauth2/rfc6749/grants/implicit.py | 9,391 | The implicit grant type is used to obtain access tokens (it does not
support the issuance of refresh tokens) and is optimized for public
clients known to operate a particular redirection URI. These clients
are typically implemented in a browser using a scripting language
such as JavaScript.
Since this is a redirectio... | 5,968 | en | 0.819414 |
import pandas as pd
import numpy as np
def load_from_tsfile_to_dataframe(full_file_path_and_name, replace_missing_vals_with='NaN'):
data_started = False
instance_list = []
class_val_list = []
has_time_stamps = False
has_class_labels = False
uses_tuples = False
is_first_case = True
w... | sktime/utils/load_data.py | 4,617 | we don't have any data formatted to test with yet if the 'data tag has been found, the header information has been cleared and now data can be loaded perhaps not the best way to do this, but on the first row, initialise stored depending on the number of dimensions that are present and determine whether data is stored i... | 895 | en | 0.923781 |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 17:14:19 2020
@author: Mitchell
model_training.py
~~~~~~~~~~~~~~~~~
This file serves as a script for building and training our VAE model. To do
so we used the VAE and DataSequence classes defined in the file `VAE.py`, as
well as helper functions from the file `dataset... | VAE/full_model/model_training.py | 4,667 | Created on Wed Apr 1 17:14:19 2020
@author: Mitchell
model_training.py
~~~~~~~~~~~~~~~~~
This file serves as a script for building and training our VAE model. To do
so we used the VAE and DataSequence classes defined in the file `VAE.py`, as
well as helper functions from the file `dataset_utils` for loading and pars... | 1,826 | en | 0.493169 |
# Copyright 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | novadocker/virt/docker/network.py | 2,227 | Copyright 2014 OpenStack Foundation All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable l... | 701 | en | 0.881976 |
import unittest
from tests.test_utils import get_sample_pdf_with_labels, get_sample_pdf, get_sample_sdf, get_sample_pdf_with_extra_cols, get_sample_pdf_with_no_text_col ,get_sample_spark_dataframe
from nlu import *
class TestSarcasm(unittest.TestCase):
def test_sarcasm_model(self):
pipe = nlu.load('sarc... | tests/nlu_core_tests/component_tests/classifier_tests/sarcasm_tests.py | 2,345 | def test_sarcasm_model_bench(self): Get dataset " todo test light pipe for 50k+ ! wget -N https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/resources/en/sarcasm/train-balanced-sarcasm.csv path = '/home/loan/Documents/freelancework/jsl/nlu/nlu_git/tests/datasets/train-balanced-sarcasm.csv' ... | 1,263 | en | 0.428725 |
# Generated by Django 2.2.6 on 2019-10-22 15:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | ProjectApplication/project_core/migrations/0051_createmodify_country.py | 1,733 | Generated by Django 2.2.6 on 2019-10-22 15:22 | 45 | en | 0.614653 |
def combination(n, r):
"""
:param n: the count of different items
:param r: the number of select
:return: combination
n! / (r! * (n - r)!)
"""
r = min(n - r, r)
result = 1
for i in range(n, n - r, -1):
result *= i
for i in range(1, r + 1):
result //= i
return ... | lib/python-lib/combination.py | 385 | :param n: the count of different items
:param r: the number of select
:return: combination
n! / (r! * (n - r)!)
from scipy.misc import comb | 141 | en | 0.543815 |
import os
import json
import time
import datetime
import manageMonitoredUsersDB
pathToJSON = os.getcwd() + '/generatedJSON'
def get_local_json_timestamp_epoch(username, filename):
monitoredJSON = None
try:
monitoredJSON = json.load(open(pathToJSON + os.sep + filename, "r+"))
except:
with o... | TFG/checkEpochAndUpdateJSON.py | 3,104 | Epoch LOCALEpoch REMOTO, el guardado en monitoredUser.dbObtención del epoch del JSON localObtención del epoch del JSON remoto, en monitoredUser.dbComprobación del tiempo transcurrido entre local y remotoprint("\033[92m" + "json_timestamp_epoch: " + str(json_timestamp_epoch) + "\033[0m" + "\n")print("\033[92m" + "json_... | 403 | es | 0.242577 |
"""CD SEM structures."""
from functools import partial
from typing import Optional, Tuple
from gdsfactory.cell import cell
from gdsfactory.component import Component
from gdsfactory.components.straight import straight as straight_function
from gdsfactory.components.text_rectangular import text_rectangular
from gdsfact... | gdsfactory/components/cdsem_straight.py | 1,525 | Returns straight waveguide lines width sweep.
Args:
widths: for the sweep
length: for the line
cross_section: for the lines
text: optional text for labels
spacing: edge to edge spacing
CD SEM structures. | 224 | en | 0.520754 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from ....unittest import TestCase
from oauthlib.oauth2.rfc6749 import BaseEndpoint, catch_errors_and_unavailability
from oauthlib.oauth2 import Server, RequestValidator, FatalClientError, OAuth2Error
class BaseEndpointTest(TestCase):
... | tests/oauth2/rfc6749/endpoints/test_base_endpoint.py | 2,462 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
from .protocol import *
import serial
import time
from threading import Lock
from PIL import Image, ImageDraw, ImageOps, ImageFont
class Device:
ser = None
inbuffer = ""
awaitingResponseLock = Lock()
testmode = False
nLeds = 0
dispW = 0
dispH = 0
rotFactor = 0
rotCircleSteps = 0
... | inkkeys/device.py | 9,921 | Defines the height of top and bottom bannerThis object stores callback functions that react directly to a keypress reported via serialCurrent LED status, so we can animate them over timeLast time LEDs were setStay on for 3 seconds and then fade out over 0.5 seconds | 265 | en | 0.870624 |
# -*- coding: utf-8 -*-
# Copyright 2018 Joshua Bronson. All Rights Reserved.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""Provides bidict duplication policies... | bidict/_dup.py | 1,001 | Base class for bidict's duplication policies.
*See also* :ref:`basic-usage:Values Must Be Unique`
Provides bidict duplication policies and the :class:`_OnDup` class.
-*- coding: utf-8 -*- Copyright 2018 Joshua Bronson. All Rights Reserved. This Source Code Form is subject to the terms of the Mozilla Public License, ... | 636 | en | 0.789912 |
#!/usr/bin/env python3
# Day 13: Transparent Origami
# https://adventofcode.com/2021/day/13
import sys
data = open("input.txt" if len(sys.argv) == 1 else sys.argv[1]).read().splitlines()
n = 2000
grid = [["." for _ in range(n)] for _ in range(n)]
for line in data:
if not line:
break
x, y = map(int,... | 2021/day13/day13.py | 1,264 | !/usr/bin/env python3 Day 13: Transparent Origami https://adventofcode.com/2021/day/13 for y, row in enumerate(grid): print("%3d" % y, "".join(str(x) for x in row)) | 168 | en | 0.353833 |
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
from typing import Callable, Dict, List, Sequence
from reggen.field import Field
from reggen.register import Register
from reggen.reg_block import RegBlock
from shared.ot... | hw/ip/otbn/dv/otbnsim/sim/ext_regs.py | 9,492 | A class representing OTBN's externally visible CSRs
This models an extra flop between the core and some of the externally
visible registers by ensuring that a write only becomes visible after an
intervening commit.
A wrapper around a field in a register as parsed by reggen
A wrapper around a register as parsed by regg... | 1,683 | en | 0.878336 |
import json
import os
import sys
import numpy as np
import random
import math
import time
from tqdm import tqdm
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
from env import R2RBatch
from utils import padding_idx, add_idx, Tokenizer
imp... | r2r_src/agent.py | 38,417 | Base class for an R2R agent to generate and save trajectories.
An agent based on an LSTM seq2seq model with attention.
The dijkstra algorithm.
Was called beam search to be consistent with existing work.
But it actually finds the Exact K paths with smallest listener log_prob.
:return:
[{
"scan": XXX
"instr_id"... | 5,978 | en | 0.810303 |
import xarray as xr
import pandas as pd
import numpy as np
import xgboost as xgb
import time
import pickle
import sys
from xgboost import XGBRegressor
# load dataframe with maximal temp
def load_df_max_TREFHT(member, start_date, end_date):
path = "/glade/scratch/zhonghua/CESM-LE-members-csv/"
print("*********... | 3_model_valid/pred/apply_model_members.py | 3,178 | load dataframe with maximal temp https://stackoverflow.com/questions/44124436/python-datetime-to-seasondf = df.dropna(subset=['time'])df_temp = df[(df["lat"]==lat) & (df["lon"]==lon)].reset_index()print("rmse:",np.sqrt(mean_squared_error(df_temp[member],df_temp[pred])))print("mae:",mean_absolute_error(df_temp[member],d... | 334 | en | 0.379107 |
'''
This is to fetch the tip table data for a telegram_id
Error Handling
==============
- /withdrawmemo tipuser11111 0.0001 TLOS pay_bill
- /withdrawmemo tipuser11111 0.00001 EOS pay_bill
{"code": 3050003, "name": "eosio_assert_message_exception", "what": "eosio_assert_message assertion failure"
, "details... | app/chain_table.py | 3,893 | This is to fetch the tip table data for a telegram_id
Error Handling
==============
- /withdrawmemo tipuser11111 0.0001 TLOS pay_bill
- /withdrawmemo tipuser11111 0.00001 EOS pay_bill
{"code": 3050003, "name": "eosio_assert_message_exception", "what": "eosio_assert_message assertion failure"
, "details": [{"message": ... | 2,440 | en | 0.439409 |
#!/usr/bin/env python
#Copyright (c) 2008 Erik Tollerud (erik.tollerud@gmail.com)
from __future__ import division,with_statement
from glob import glob
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup,find_packages
from distutils.command.build_py import build_py as du_build_py
... | setup.py | 5,968 | !/usr/bin/env pythonCopyright (c) 2008 Erik Tollerud (erik.tollerud@gmail.com) recommended/gui packages are stored in config module - used in extrascustom build_py overwrites version.py with a version overwriting the revno-generating version.pythis overwrites the actual version.pycustom sphinx builder just makes the di... | 645 | en | 0.662348 |
#!/usr/bin/env python
import argparse, re, os
from StringIO import StringIO
import language
#* Build instruction
#*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*#
def roundup(x, to=8):
return x if x % to == 0 else x + to - x % to
def build_form(ins):
form = ["%i"]... | assembler.py | 4,882 | !/usr/bin/env python* Build instruction*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~* print ins print hx print ins print build_form(ins) print language.ins[ins[0]] read in the file remove comments remove blank lines print lines build the bit tuple for each instructio... | 872 | en | 0.574001 |
import time
import serial
print "Iniciando Comunicao Serial com Arduino"
# Iniciando conexao serial
comport = serial.Serial('/dev/ttyACM0', 115200)
#comport = serial.Serial('/dev/ttyUSB0', 115200)
LED_ON='l'
LED_OFF='d'
# Time entre a conexao serial e o tempo para escrever (enviar algo)
time.sleep(1.8) # Entre 1.5s ... | comunicacao_serial.py | 555 | Iniciando conexao serialcomport = serial.Serial('/dev/ttyUSB0', 115200) Time entre a conexao serial e o tempo para escrever (enviar algo) Entre 1.5s a 2s Fechando conexao serial | 177 | es | 0.452225 |
#!/usr/bin/env python
# Copyright 2016 The Kubernetes Authors.
#
# 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 appli... | gubernator/main_test.py | 9,134 | !/usr/bin/env python Copyright 2016 The Kubernetes Authors. 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 ... | 659 | en | 0.826781 |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (9, 9, 9):
def swig_im... | venv/Lib/site-packages/osgeo/gdalconst.py | 9,328 | This file was automatically generated by SWIG (http://www.swig.org). Version 3.0.12 Do not make changes to this file unless you know what you are doing--modify the SWIG interface file instead. Python < 2.2 doesn't have 'property'. | 230 | en | 0.889602 |
from enum import IntFlag, IntEnum
import numpy as np
from . import Base
from . import ByteIO
from .axis_interp_rule import AxisInterpRule
from .jiggle_bone import JiggleRule
from .quat_interp_bone import QuatInterpRule
from ....utils.math_utilities import quat_to_matrix
class BoneFlags(IntFlag):
# BONE_CALCULA... | library/source1/mdl/structs/bone.py | 9,974 | BONE_CALCULATE_MASK = 0x1F bone is physically simulated when physics are active procedural when physics is active bone is always procedurally animated bone aligns to the screen, not constrained in motion. bone aligns to the screen, constrained by it's own axis. BONE_USED_MASK = 0x0007FF00 bone (or child) is used by a h... | 2,192 | en | 0.932847 |
"""
Core OpenBCI object for handling connections and samples from the WiFi Shield
Note that the LIB will take care on its own to print incoming ASCII messages if any (FIXME, BTW).
EXAMPLE USE:
def handle_sample(sample):
print(sample.channels_data)
wifi = OpenBCIWifi()
wifi.start(handle_sample)
TODO: Cyton/Gangli... | openbci/wifi.py | 27,227 | Handle a connection to an OpenBCI wifi shield.
Args:
ip_address: The IP address of the WiFi Shield, "None" to attempt auto-detect.
shield_name: The unique name of the WiFi Shield, such as `OpenBCI-2AD4`, will use SSDP to get IP address still,
if `shield_name` is "None" and `ip_address` is "None", will connect ... | 4,668 | en | 0.830439 |
"""
Code for understanding type annotations.
This file contains functions that turn various representations of
Python type annotations into :class:`pyanalyze.value.Value` objects.
There are three major functions:
- :func:`type_from_runtime` takes a runtime Python object, for example
``type_from_value(int)`` -> ``... | pyanalyze/annotations.py | 46,475 | A context for evaluating annotations.
The base implementation does very little. Subclass this to do something more useful.
Return the :class:`Value <pyanalyze.value.Value>` corresponding to a name.
Return the :class:`Value <pyanalyze.value.Value>` corresponding to a name.
Return the :class:`Value <pyanalyze.value.Valu... | 5,455 | en | 0.766294 |
"""
Unittests for gpsdio load
"""
from click.testing import CliRunner
import gpsdio
import gpsdio.cli.main
def test_load(types_json_path, types_msg_gz_path, tmpdir, compare_msg):
pth = str(tmpdir.mkdir('test').join('test_load'))
with open(types_json_path) as f:
stdin_input = f.read()
result =... | tests/test_cli_load.py | 738 | Unittests for gpsdio load | 25 | en | 0.325564 |
# -*- coding: utf-8 -*-
'''
Pillar data from vCenter or an ESXi host
.. versionadded:: 2017.7.0
:depends: - pyVmomi
This external pillar can pull attributes from objects in vCenter or an ESXi host and provide those attributes
as pillar data to minions. This can allow for pillar based targeting of minions on ESXi ho... | salt/pillar/vmware_pillar.py | 19,506 | Only return if python-etcd is installed
helper function to crawl an attribute specified for retrieval
helper function to recurse through a vim object and attempt to return all child objects
helper function to serialize some objects for prettier return
Check vmware/vcenter for all data
Pillar data from vCenter or an ESX... | 6,037 | en | 0.678128 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import unittest
from pyes.tests import ESTestCase
class IndexStatsTestCase(ESTestCase):
def setUp(self):
super(IndexStatsTestCase, self).setUp()
self.conn.indices.create_index(self.index_name)
self.conn.indices.put_mapping(self... | tests/test_index_stats.py | 1,862 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
from __future__ import unicode_literals, division, absolute_import
import logging
from flexget import plugin
from flexget.event import event
from flexget.entry import Entry
from flexget.utils.tools import group_entries
log = logging.getLogger('best_quality')
entry_actions = {
'accept': Entry.accept,
'reject'... | flexget/plugins/filter/best_quality.py | 2,036 | Sort entities in order of quality and best proper First entry will be the best quality | 86 | en | 0.877443 |
from mpp.models import SQLTestCase
from mpp.models import SQLConcurrencyTestCase
class HcatalogPrimitiveTypes(SQLConcurrencyTestCase):
"""
@product_version gpdb: [2.0-]
@db_name pxfautomation
@concurrency 1
@gpdiff True
"""
sql_dir = 'sql'
ans_dir = 'expected'
out_dir = 'output'
| automation/tincrepo/main/pxf/features/hcatalog/primitive_types/runTest.py | 318 | @product_version gpdb: [2.0-]
@db_name pxfautomation
@concurrency 1
@gpdiff True | 81 | en | 0.307618 |
'''
Given one or more regular expressions on the command line, searches
the PATH for all files that match.
Copyright (C) 2002 GDS Software
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either vers... | vyperlogix/gds/where.py | 2,980 | They'll get stored in here by filename so that there are no duplicates. Get a list of the directories in the path Make a list of compiled regular expressions Now check each command line regexp in each directory | 210 | en | 0.909919 |
import numpy as np
import pandas as pd
from shapely import prepared
from geopandas import GeoDataFrame
from geopandas import _compat as compat
from geopandas.array import _check_crs, _crs_mismatch_warn
def sjoin(
left_df, right_df, how="inner", op="intersects", lsuffix="left", rsuffix="right"
):
"""Spatial ... | geopandas/tools/sjoin.py | 9,252 | Spatial join of two GeoDataFrames.
Parameters
----------
left_df, right_df : GeoDataFrames
how : string, default 'inner'
The type of join:
* 'left': use keys from left_df; retain only left_df geometry column
* 'right': use keys from right_df; retain only right_df geometry column
* 'inner': use interse... | 1,706 | en | 0.73626 |
# coding: utf-8
#
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | scripts/build_test.py | 41,015 | Test the build methods.
Mocks build.safe_delete_file().
Test _compare_file_count raises exception when there is a
mismatched file count between 2 dirs list.
Test that compiled_js_dir is deleted before a fresh compilation.
Test that compiled_js_dir is deleted before a fresh watch mode
compilation.
Test that build.COMPIL... | 6,173 | en | 0.814023 |
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file acc... | tests/integration-tests/tests/dns/test_dns.py | 5,580 | Create a hosted zone stack.
Test hosted_zone_id is provided in the config file.
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at h... | 876 | en | 0.880868 |
import csv
import os
import numpy as np
dir_path = os.path.dirname(os.path.realpath(__file__))
survey_path = os.path.join(dir_path, '../data/test_two_entries.csv')
NUM_QUESTIONS = 8
RESPONSE_PERSON = ['pat', 'jeremy', 'zach']
TASTE_PROFILE_TYPES = ['deliciousness', 'heaviness', 'reliability', 'frequency', 'between']
... | sandwichbot/survey_processor.py | 2,254 | Loop through deliciousness, heaviness, etc. Pull out deliciousness, etc. scores and store in taste_profile[type] Loop through sando types and dump to CSV | 153 | en | 0.842603 |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | models/official/amoeba_net/amoeba_net.py | 18,537 | encodes an (numpy) image array to string.
Args:
image_array: (numpy) image array
fmt: image format to use
Returns:
encoded image string
Preprocess a single raw image.
Build tf.Hparams for training Amoeba Net.
Returns a input_receiver_fn for raw images during serving.
Return RunConfig for TPU estimator.
Override... | 2,397 | en | 0.679271 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.