anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
Return the proper location used to export our JSON data. | def set_location(self, location):
if not location:
location = getcwd() + '/stormpath-exports'
return location |
Return welcome page for nonlogin user | def login():
user_type = get_admin_type_in_session()
login_form = LoginForm(request.form)
current_app.logger.info(f'user_type{user_type}')
if user_type != UserTypeEnum.NOT_LOGIN:
return redirect(url_for('admin.admin'))
if 'login' in request.form:
# read form data
username = ... |
Computes minimum interspike frequency (equivalent to maximum interspike interval). | def min_spike_frequency_tV(t, V):
intervals = interspike_intervals(t, V)
raise_if_not_multiple_spikes(intervals)
max_int = np.amax(intervals)
return 1/max_int |
a help function to print the intentinformation in format | def format_print_jobs(intent):
print "\nintentName: %s" %(intent['name'])
for k,v in intent.iteritems():
if k <> 'name':
print "\t" + str(k) + ": " + str(v) |
Calculate the 2D Cartesian (planar) area of each geometry. | def area(self):
return _property_op(arctern.ST_Area, self) |
Testing {% attr %} with "nocondense" option preserves whitespace | def test_with_nocondense_preserves_whitespace(self):
t = Template('{% load djblets_utils %}'
'<span{% attr "data-foo" nocondense %}\n'
'some \n\n'
'value\n'
'{% endattr %}>')
self.assertEqual(
t.render(Co... |
Adds a new item to a meal and stores information about it in the class dictionary Params needed for post request's payload | def add_item(self, m_id):
# Take the meals entires from TOML file
meals = self.cfg.get('payload',{}).get('plan',{})[0].get('meal',{})
for entries in meals:
# Check for valid entires
if entries:
# Construct payload
for payl... |
Downloads media item to given directory (with metadata, except GPS). | def download(self, directory):
# Setting filename (full path) and URL of file to download
filename = os.path.join(directory, self.name)
download_url = '{}=d'.format(self.base_url)
# Downloading
urlretrieve(download_url, filename)
return filename |
does this source image have any face alts yet | def hasAnyFaces(self, uri):
return self.graph.queryd(
'ASK { ?uri pho:alternate ?alt . ?alt pho:tag "face" .}',
initBindings={'uri':uri}) |
Output the top level cells from the GDSII data. Top level cells are those that are not referenced by any other cells. Returns | def top_level(self):
top = set(self)
for cell in self:
top.difference_update(cell.get_dependencies())
return list(top) |
Reorder a given array into a max heap. | def heapify(array):
# Start by sifting down the first parent node
n = len(array)
node = (n - 2) // 2
# Sift down all nodes, finishing with the root
while node >= 0:
sift_down(array, node, n)
node -= 1 |
Wrapper for parmcheck with default parameters | def run_parmchk ( lig ):
# Check if it is a string, otherwise assumes it is a pdb object
if isinstance(lig,basestring) :
name = lig
else :
name = lig.name
# Remove the extension from the filename
out_name = os.path.splitext ( name )[0]
cmd = 'parmchk -i %s.prepi -f prepi -o %s.frcm... |
Gets the email of this UserBase. The Zulip API email address of the user or bot. If you do not have permission to view the email address of the target user, this will be a fake email address that is usable for the Zulip API but nothing else. | def email(self):
return self._email |
Map MXNet's log operator attributes to onnx's Log operator and return the created node. | def convert_log(node, **kwargs):
return create_basic_op_node('Log', node, kwargs) |
Most regressors return a dot product for the prediction | def predict(self, Xtest):
ytest = np.dot(Xtest, self.weights)
return ytest |
Delete all of the SQS Queues that start with the given domain name | def sqs_delete_all(session, domain):
client = session.client('sqs')
resp = client.list_queues(QueueNamePrefix=domain.replace('.','-'))
for url in resp.get('QueueUrls', []):
client.delete_queue(QueueUrl=url) |
Define the tool (tool name is the name of the class). | def __init__(self):
self.label = "CDU-PAT"
self.description = "da scrivere"
self.canRunInBackground = False |
Returns given vm's/templates's disks collection href or list of disk objects | def getObjDisks(name, get_href=True, is_template=False):
response = get_disk_attachments(
name, 'template' if is_template else 'vm', get_href
)
if get_href:
return response
return get_disk_list_from_disk_attachments(response) |
Common is the common specification for both controller and node plugins | def __init__(__self__, *,
args: Optional[Sequence[str]] = None,
envs: Optional[Sequence['outputs.CSIUnitySpecDriverCommonEnvs']] = None,
image: Optional[str] = None,
image_pull_policy: Optional[str] = None,
name: Optional[str] = None,
... |
Test case for networking_project_network_tag_put | def test_networking_project_network_tag_put(self):
pass |
Compresses a byte array with the xz binary | def compress(value):
process = Popen(["xz", "--compress", "--force"], stdin=PIPE, stdout=PIPE)
return process.communicate(value)[0] |
Read a csv file. | def read_csv(file_name):
data = {}
with open(file_name) as f:
f = MyIter(f)
try:
for line in f:
if not line.strip():
continue
if line == 'Points\n':
break
key, val = read_key_value(line, separator... |
Normalises and reshapes the images in the dataset. | def normalise(dataset):
# Scale images to the [0, 1] range
dataset = dataset.astype("float32") / 255
# Make sure images have shape (28, 28, 1)
return np.expand_dims(dataset, -1) |
Given a vector of predictions, save results in CSV format. | def save_results(predictions, filename):
with open(filename, 'w') as f:
f.write("id,ACTION\n")
for i, pred in enumerate(predictions):
f.write("%d,%f\n" % (i + 1, pred)) |
Start the client listening to the game. Pass in a function that accepts the available actions and the current state of the game, and returns the action to take. The SDK will handle the rest. Checks if any commandline arguments are passed when running, if there are any, they are assumed to be client keys that are sent t... | def start(turn_handler):
if os.environ.get('BOTBOX_SECRET'):
print('Using env secret:', os.environ['BOTBOX_SECRET'])
headers = {'Authorization': os.environ['BOTBOX_SECRET']}
elif len(sys.argv) > 1:
print('Using cli secret:', sys.argv[1])
headers = {'Authorization': sys.argv[1]}
... |
Garbage collect temporary cached data structures. | def gc(self):
self._complete_grid = None |
Initialize an Agent object. Params ====== | def __init__(self, state_size, action_size, random_seed):
self.state_size = state_size
self.action_size = action_size
self.seed = random.seed(random_seed)
# Actor Network (w/ Target Network)
self.actor_local = Actor(state_size, action_size, random_seed).to(device)
self.a... |
Average values from an array according to some specification. The default is to have a direction that is nearly the same. a is a 2dim array | def average_close(a,tol=0.5):
if a.ndim != 2:
raise ValueError,"array should be 2-dimensional!"
n = normalize(a)
nrow = a.shape[0]
cnt = zeros(nrow,dtype=int32)
while cnt.min() == 0:
w = where(cnt==0)
nw = n[w]
wok = where(dotpr(nw[0],nw) >= tol)
wi = w[0][wok... |
If a listiter_op returns something besides an iterator as output, raise a ValueError. | def test_listiter_op_3():
@ops.listiter_op
def f(x):
return [4, 5, 6] # Returning a list instead of an iterator
with pytest.raises(ValueError):
result = f([1, 2, 3]) |
Return if x == y, if eps is not None, return if abs(xy) <= eps | def all_equal(x, y, eps=None):
if eps:
return all([abs(i - j) <= eps
for i, j in zip(x, y)
if i is not None and j is not None])
return all([i == j for i, j in zip(x, y)]) |
Returns True if the item is in the set | def __contains__(self, item):
return item in self._index_map |
The SMAPI Audit Logs API provides customers with an audit history of all SMAPI calls made by a developer or developers with permissions on that account. | def query_development_audit_logs_v1(self, get_audit_logs_request, **kwargs):
# type: (AuditLogsRequest_13316e3e, **Any) -> Union[ApiResponse, object, Error_fbe913d9, AuditLogsResponse_bbbe1918, BadRequestError_f854b05]
operation_name = "query_development_audit_logs_v1"
params = locals()
... |
Calculate the aggregated mean and stds. | def _get_aggregated_mean_std(self, means, stds, n):
mean = means.view(n, -1).sum(0) / n
std = (
stds.view(n, -1).sum(0) / n
+ ((means.view(n, -1) - mean) ** 2).view(n, -1).sum(0) / n
)
return mean.detach(), std.detach() |
Returns a cash payment based on the dividends that should be paid out according to the accumulated bookkeeping of earned, unpaid, and stock dividends. | def pay_dividends(self, next_trading_day):
net_cash_payment = 0.0
try:
payments = self._unpaid_dividends[next_trading_day]
# Mark these dividends as paid by dropping them from our unpaid
del self._unpaid_dividends[next_trading_day]
except KeyError:
... |
Open vector field with independent directories. | def openVectorWT(w_dir, t_dir):
tx_dir, ty_dir = t_dir
W = openFile(w_dir)
Tx = openFile(tx_dir)
Ty = openFile(ty_dir)
assert Tx.shape == Ty.shape, "Tx and Ty must have same dimensions."
Nt, Nc = W.shape
Ny, Nx = Tx.shape
V = np.zeros((Nt, 2, Ny, Nx))
for n in range(Nt):
V[n... |
This function is used for validation process. It returns a list of stockCode items and a list of quantities for each item. | def get_order_lists(self, n_items, n_quantities):
arr_stock_code = self._df_invoice_original.StockCode.unique()
arr_stock_code = np.random.choice(arr_stock_code, n_items)
list_stockCode = list(arr_stock_code)
list_quantities = np.ones(arr_stock_code.shape[0])
list_quantities *=n_quantities... |
Process the received message based on its type. | def run(self):
alogger.info("Recieved message from %s, Message: (%d) %s" % (self.client.getaddress(), self.action_type, self.message))
#Try to call th function associated with this message type.
#format = "handle_<type>" (eg: handle_100)
fn = globals().get("handle_" + str(self.action_type... |
correctly convert to specified moltype | def test_sequence_to_moltype(self):
s = Sequence("TTTTTTTTTTAAAA", name="test1")
annot1 = s.add_annotation(Feature, "exon", "fred", [(0, 10)])
annot2 = s.add_annotation(Feature, "exon", "trev", [(10, 14)])
got = s.to_moltype("rna")
annot1_slice = str(annot1.get_slice())
a... |
Restart another round. Check the remaining budget and leave the game if budget <= 0. Create new BJCards | def restart(self):
self.state ='active'
if self.budget <= 0:
return self.leave()
self.cards =BJCards()
self.bet_amount =0 |
Get neofunctionalisation events of all enzymes in the core metabolism. | def neofunctionalisations(self, majorityPercentageCoreMetabolism = defaultMajorityPercentageCoreMetabolism, eValue = defaultEValue, considerOnlyECs = None) -> Set[Neofunctionalisation]:
# get neofunctionalisations
return self._neofunctionalisedEnzymes(majorityPercentageCoreMetabolism, eValue, co... |
Tests API call to onboard NS descriptor resources | def test_post_ns_descriptors(post_ns_descriptors_keys):
sonata_vnfpkgm = SONATAClient.VnfPkgm(HOST_URL)
sonata_nsd = SONATAClient.Nsd(HOST_URL)
sonata_auth = SONATAClient.Auth(HOST_URL)
_token = json.loads(sonata_auth.auth(username=USERNAME, password=PASSWORD))
_token = json.loads(_token["data"... |
Create a onehot encoding of x of size k. | def one_hot(x, k, dtype=np.float32):
return np.array(x[:, None] == np.arange(k), dtype) |
Return 500 if internal error | def page_not_found(e):
return render_template("500.html"), 500 |
Takes fragment lowest and highest limits as an integers and get all the prime numbers in that range, NOT including the limit itself. Returns a numpy array of the primes. Needs the primes from the first fragment of the program as input. | def get_primes_in_fragment(fragment_lowest, fragment_highest,
primes_in_first_fragment):
fragment_range = np.arange(fragment_lowest, fragment_highest)
prime_mask = np.ones(len(fragment_range), dtype=bool)
for p in primes_in_first_fragment:
if fragment_lowest % p == 0:
... |
Representation of gridded 2 or 3 dimensional data | def __init__(self, path: str = None, buffer: io.BytesIO = None):
if not path and not buffer:
raise ValueError("Must supply path or buffer")
if buffer:
memory = buffer.getvalue()
buffer.close()
path = tempfile.TemporaryFile()
else:
... |
Creating fake profiles for given number of people using namedtuples | def init_profiles_using_namedtuple(no_profiles: int):
profiles = []
Profile = namedtuple('Profile', fake.profile().keys())
for _ in range(no_profiles):
profiles.append(Profile(**fake.profile()))
return profiles |
Returns a URL to the GOES data for the specified date. | def _get_url_for_timerange(self, timerange, **kwargs):
timerange = TimeRange(timerange.start.strftime('%Y-%m-%d'), timerange.end)
if timerange.end < parse_time("1999/01/15"):
goes_file = "%Y/go{satellitenumber:02d}%y%m%d.fits"
elif timerange.start < parse_time("1999/01/15") and timer... |
Redirect index to students page | def index() -> str:
return redirect('/students') |
adds a user in db and logs in with client | async def logged_user(client, user_role: UserRole) -> UserDict:
async with LoggedUser(
client,
{"role": user_role.name},
check_if_succeeds=user_role != UserRole.ANONYMOUS,
) as user:
print("-----> logged in user", user["name"], user_role)
yield user
print("<----- ... |
Generates a Single SignOn (SSO) session for the iLO Java Applet console and returns the URL to launch it. [Arguments] | def fusion_api_get_server_hardware_java_remote_console_url(self, uri, api=None, headers=None):
return self.sh.get(uri=uri, api=api, headers=headers, param='/javaRemoteConsoleUrl') |
Iterate over modes. Synchronized iterator to iterate the modes in an order. | def modes(self):
try:
order = self._current_order
except AttributeError:
raise AttributeError('Cannot iterate over modes without iterating over orders!') from None
mode = -order
while mode <= order:
yield mode
mode += 1 |
Creates a hard link to dst. dst DNE Dir F SLF SLD SLB s DNR R R N N R R e Dir R R R R R R l F R R R R ? ? f SL R R R R ? ? R means raises. N means new hardlink created. | def link(self, dst):
assert isinstance(dst, Path)
link(dst._path, self._path) |
Test case for change_relation_types | def test_change_relation_types(self):
pass |
Print a line to the output file, discarding duplicate blank lines. | def write(s):
global prev_line
if not (prev_line == "\n" and s == "\n"):
fo.write(s)
prev_line = s |
Parses help function related command line arguments | def parse_help_command(args):
if len(args) < 2:
print_generic_help()
elif len(args) == 2:
print_specific_help(args[1])
else:
print 'Error! Found too many arguments for --help! Use --help with ' \
'0 arguments to print generic help or type --help <tool_name> ' \
... |
Move the monkey across the scree, turnaround when it reaches the end. | def _walk(self):
new_pos = self.rect.move((self.move, 0)) # move 9 pixel to the right per frame
if self.rect.left < self.area.left or self.rect.right > self.area.right:
self.move = -self.move # move to the opposite direction when the chimp position exceeds the screen
new_pos = ... |
Implementing click view price list detail page inline action button functionality | def click_view_price_list_detail_first_row_inline_action_button(self):
self.click_inline_action_button(self.view_price_list_div_id, None, self.view_price_list_column_number, True)
self.wait_for_ajax_spinner_load() |
Test addition for Complex with Complex, complex, int and float | def test_add():
z = Complex(1, -2)
w = Complex(1, 1)
assert (z + w) == Complex(2, -1)
assert (z + (1+1j)) == Complex(2, -1)
assert (z + 2) == Complex(3, -2)
assert (z + 2.0) == Complex(3, -2) |
List walks, or create a new walks. | def walk_list_api(request):
if request.method == 'GET':
walks = Walk.objects.filter(user=request.user).order_by("-date")
serializer = WalkSerializer(walks, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = WalkSerializer(data=request.data)
... |
Retrieve Node object for a domain with a provided uuid. | def ex_get_node_by_uuid(self, uuid):
domain = self._get_domain_for_uuid(uuid=uuid)
node = self._to_node(domain=domain)
return node |
Getter method for action, mapped from YANG variable /input/mapping_record/action (enumeration) | def _get_action(self):
return self.__action |
The number of full days since last checkin. We consider the current day to start from 5AM local time. Note that this can be more than 24 hours ago! | def days_since_last_checkin(self):
# TODO use local timezone
checkin_date = (self.last_checkin - datetime.timedelta(hours=5)).date()
today = datetime.date.today()
return (today - checkin_date).days |
Create a clone of the sentinel. | def clone(self) -> "set_default":
return type(self)(self.value) |
Create a fragment used to display the XBlock to a student. `context` is a dictionary used to configure the display (unused) Returns a `Fragment` object specifying the HTML, CSS, and JavaScript to display. | def student_view(self, context=None): # pylint: disable=W0613
# Load the HTML fragment from within the package and fill in the template
html_str = pkg_resources.resource_string(__name__,
"static/html/thumbs.html").decode('utf-8')
frag = Fragment... |
Uses average damage to determine time (ticks) to level up attack or strength Enemy has 1 def and 0 def bonus Weapon is best available scimitar | def level_time_average(start_levels, attack_style, attack_bonus, strength_bonus):
ticks_per_attack = 4 # Scimitar attack speed
max_hit, accuracy = get_max_hit_and_accuracy(
start_levels, attack_style, attack_bonus, strength_bonus)
if attack_style == Attack_Style.ATTACK:
start_exp = osrs... |
Run spark job that will associate vendor's users (loaded from REST API) with our users (loaded from MySQL) | def run(sc, logger):
start = time.time()
# Spark SQL Context
sqlContext = sql.context.SQLContext(sc)
# 1) Practices - Small table so no need to partition it, could even broadcast across all executors
# Spark SQL JDBC Options: https://spark.apache.org/docs/latest/sql-data-sources-jdbc.html
prac... |
Returns an OAuth2 authorization token or None in case of errors. This is the flow for nonweb clients. | def get_token(client_id, client_secret, username, password):
try:
if oauth2db.check_client(client_id, client_secret):
if oauth2db.check_user(username, password):
token, refresh = oauth2db.generate_token(client_id, username)
res = { "token": token }
excep... |
Determine if the transaction(t) belongs to trade(tr) without altering the tr | def tranBelong(tr, lst, t):
if tr.isReal():
cp = Trade()
cp.state = tr.state
cp.addTrans(tr.tranCol+lst, False)
else:
cp = tr
return cp.belong(t) |
ingest from a particular sequence | def sequence_ingest(self,sequence):
data=self.data
counter=0
for item in data[sequence]:
datestring=item['specimenDate']
date=fetchdate(datestring)
row,created=DailyCases.objects.get_or_create(specimenDate=date,areacode=item['areaCode'])
row.areaname=item['areaName']
row.dailyLabConfirmedCases=... |
This function tests for all NaN values | def test_NaNall(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(
float('nan'), float('nan'), float('nan'), float('nan'))
self.assertEqual(str(e.exception), 'width must be an integer') |
The entry endpoint of our API. | def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request),
'groups': reverse('group-list', request=request),
'pools': reverse('pool-list', request=request),
}) |
Given data about a Bundle returned by any blockstore REST API, convert it to a Bundle instance. | def _bundle_from_response(data):
return Bundle(
uuid=UUID(data['uuid']),
title=data['title'],
description=data['description'],
slug=data['slug'],
# drafts: Convert from a dict of URLs to a dict of UUIDs:
drafts={draft_name: UUID(url.split('/')[-1]) for (draft_name, ur... |
>>> validate_n_digits_range(1920, 2002)("2002") True >>> validate_n_digits_range(1920, 2002)("2003") False | def validate_n_digits_range(min_val: int, max_val: int, n: int = 4) -> bool:
def func(s: str):
return validate_n_digits(n)(s) and min_val <= int(s) <= max_val
return func |
Secures handlers with auth token taken from ndb | def token_required(func):
def func_wrapper(self, *args, **kwargs):
auth_token = self.request.headers.get('X-Auth-Token',
self.request.get('token', ''))
namespace = self.request.route_kwargs.get('namespace', '')
try:
token = base64.url... |
function which change cells | def change(self, num):
if self.manhattan(self[0], self[num]) != 1:
raise RuntimeError(
"Numbers {} {} in positions {} {} can't change".format(0, num, self[0], self[num]))
z_i, z_j = self[0]
n_i, n_j = self[num]
self.pos_to_num[(z_i, z_j)] = num
self.... |
Specify whether the Secret or its key must be defined | def optional(self) -> Optional[bool]:
return pulumi.get(self, "optional") |
Extract a set of ngrams from a list of integers. create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2) {(4, 9), (4, 1), (1, 4), (9, 4)} create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3) [(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)] | def create_ngram_set(self, input_list, ngram_value=2):
return set(zip(*[input_list[i:] for i in range(ngram_value)])) |
Extracts MFCCs from music dataset and saves them into a json file. | def preprocess_dataset(dataset_path, SAMPLES_TO_CONSIDER: int, num_mfcc = 13, n_fft = 2048, hop_length = 512):
data = {
'mapping': [],
'labels': [],
'MFCCs': [],
'files': []
}
# loop through all sub-dirs
total_samples = 0
valid_samples = 0
for i, (di... |
Confidence interval for differences between the two samples. | def non_param_paired_ci(sample1, sample2, alpha):
n = len(sample1)
N = norm.ppf(1 - alpha/2)
diff_sample = sorted(list(map(operator.sub, sample2, sample1)))
averages = sorted([(s1+s2)/2 for i, s1 in enumerate(diff_sample)
for _, s2 in enumerate(diff_sample[i:])]... |
! Brief Gets the binary and source files from the Github Release server [in] `tag_name` Git tag of the current release [in] `config` confi metadata set in main.py `List[ReleaseFile]` List of release files `Dict[str, SourceFile]` Dictionary of source files Sends an `HTTP GET` request to github using their REST API to re... | def get_release_files(tag_name, config) -> Tuple[List[ReleaseFile], Dict[str, SourceFile]]:
@retry_multi(5) # retry at most 5 times
def execute_request(path):
"""!
@brief Performs a GET request with the given path. To be used with Github's REST API.
@returns If successful, returns a .JS... |
.mfk play Begin the game ||| [+/] Edit the mfk user list ||| marry fuck kill Give the verdict ||| score Retrieves the score of a user | def mfk(inp, db=None):
db_init(db)
inp = inp.lower()
m_regex = re.compile(r"marry\s([a-zA-Z0-9_]+\s|[a-zA-Z0-9_]+)").finditer(inp)
f_regex = re.compile(r"fuck\s([a-zA-Z0-9_]+\s|[a-zA-Z0-9_]+)").finditer(inp)
k_regex = re.compile(r"kill\s([a-zA-Z0-9_]+|[a-zA-Z0-9_]+\s)").finditer(inp)
if inp... |
Initialize the dancling links matrix with a given number of columns | def __init__(self, numcols):
# Start by making a root cell
# This isn't part of the matrix, but it gives an entry point to the matrix
# root.right is the first column header, root.left is the last
# root.up and root.down just wrap around to itself
root = Column("root")
se... |
Part 3 of Pressure | def get_pressurexlsb(self):
byte_list = self.i2c.readfrom_mem(
self.device_address,
self.REGISTER_PRESSUREXLSB,
1,
addrsize=8
)
val = 0
val = val << 8 | byte_list[0]
return val |
It gets its default key from settings. | def test_decrypt_key_default(self, settings):
settings.CHITON_ENCRYPTION_KEY = b'0' * 32
encrypted = encrypt('message')
assert decrypt(encrypted) == 'message'
settings.CHITON_ENCRYPTION_KEY = b'1' * 32
with pytest.raises(EncryptionError):
decrypt(encrypted) |
Calculates total circumferences of a rectangle | def rectangle_circumference(a,b):
return (2*(a+b)) |
emulate post request with get handler, we don't need the data | def do_POST(self):
self.do_GET() |
Truncates forest to maximum number of trees. | def truncate(self):
self.population = self.population[:self.max_number_trees] |
Read a prn file. | def read_prn(file_name):
with open(file_name) as f:
f = MyIter(f)
try:
assert next(f).strip() == 'prn:13|'
assert next(f).strip() == 'subtype = MT2500'
assert next(f).strip() == 'Doc={MT2500:14|'
assert next(f).strip() == 'Film={12.1|'
fi... |
Create LeaderModel and send it as a PDF to the browser | def get_leader_model_pdf(currentEmpl, employees):
lm = LeaderModel()
employee_actions = {}
legend = []
colors = {}
errors = {'noactions': []}
# numbered_actions = {}
for empl in employees:
if not currentEmpl.hasAccessTo(empl):
raise PermissionDenied()
actions ... |
Given a normal feature matrix, creates a transpose feature matrix, a list of discrete features, and a list of nonempty features for each id. If the dataset is dense, this uses a Numpy matrix to save on space. Otherwise, it uses a listofdicts structure. | def __init__(self,db):
self._numFeatures = len(db.keys)
self._numEntries = len(db.entries)
numMissing = 0
if isinstance(db.entries[0],dict):
#already sparse database given as input
self.featureMatrix = None
self.featureDicts = [{} for i in range(self._... |
Pause writing callback from transport. | def pause_writing(self):
self._stream.pause_writing() |
Returns parent of node at n; None if there isn't a parent | def parent(self, n):
return None if n == 0 else (n - 1) // 2 |
Verifies CAS 1.0 authentication ticket. Returns username on success and None on failure. | def _verify_cas1(ticket, service):
params = {'ticket': ticket, 'service': service}
url = (urljoin(settings.CAS_SERVER_URL, 'validate') + '?' +
urlencode(params))
page = urlopen(url)
try:
verified = page.readline().strip()
if verified == 'yes':
return page.readline(... |
Test explicit overrides for the leading time dimension | def test_dimension_size_override(self, nt=100):
i, j, k = dimify('i j k')
a = TimeData(name='a', dimensions=(i, j, k))
one = symbol(name='one', dimensions=(i, j, k), value=1.)
op = Operator(Eq(a.forward, a + one))
# Test dimension override via the buffered dimenions
a.da... |
Inplace reformulation of a QCQP to a COP toconic(self) | def toconic(self):
res = __library__.MSK_XX_toconic(self.__nativep)
if res != 0:
_,msg = self.__getlasterror(res)
raise Error(rescode(res),msg) |
r""" Samples a 3d function f over specified intervals and returns three 2d arrays (X, Y, Z) suitable for plotting with matlab (matplotlib) syntax. See examples\mplot3d.py. f is a function of two variables, such as x2 + y2. x_args and y_args are intervals given in the form (var, min, max, n) | def sample3d(f, x_args, y_args):
x, x_min, x_max, x_n = None, None, None, None
y, y_min, y_max, y_n = None, None, None, None
try:
f = sympify(f)
except SympifyError:
raise ValueError("f could not be interpreted as a SymPy function")
try:
x, x_min, x_max, x_n = x_args
... |
Creates a new git repo on the server (do not include the .git ending in git_repo_name) | def create_prod_git_repo(git_repo_name):
with cd(git_dir):
run("git init --bare %s.git && cd %s.git && git config http.receivepack true" %
(git_repo_name,git_repo_name)) |
Returns the number of frames in the trajectory in universe u, using teq as equilibration time and tsample as sampling time | def traj_nslice (u,teq,tsample) :
# get the number of frames in the slice (http://stackoverflow.com/a/7223557)
traj_slice = u.trajectory[teq::tsample]
return sum(1 for _ in traj_slice) |
Returns the projection of the BinaryStateSequences using DAG functionality | def find_approx(self, gamma):
if self.jumps != []:
# first we divide the jumps of the BSS into subarrays in each of which the subsequent jumps are closer to each other than \gamma
jump_seq_list = identify_jump_subseq(self.jumps, gamma)
# jumps will store all jumps of the proj... |
Convert from camera_frame to world_frame | def cam_to_world(cam_point, world_to_cam):
# cam_point = np.array([cam_pose[0], cam_pose[1], cam_pose[2]])
obj_vector = np.concatenate((cam_point, np.ones(1))).reshape((4, 1))
world_point = np.dot(world_to_cam, obj_vector)
world_point = [p[0] for p in world_point]
return world_point[0:3] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.