uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
a9dedf17f390047e121a6101
train
class
class HomeView(ListView): template_name = "store/home.html" queryset = Product.objects.all()
class HomeView(ListView):
template_name = "store/home.html" queryset = Product.objects.all()
View, FormView, View, RedirectView, CreateView import stripe from .models import Product, Category, WishlistItem, Order, OrderItem, ShippingInformation, Review from .cart import Cart from .forms import ShippingInformationForm, CheckoutForm, ProductReviewForm class HomeView(ListView):
64
64
21
6
57
rafaellima47/django-ecommerce
store/views.py
Python
HomeView
HomeView
18
20
18
18
2b6792abae7d7d41c76a3d3749461ff8dc4257ee
bigcode/the-stack
train
92be114e4a8e175e5e6f0a67
train
class
class AccountPageView(LoginRequiredMixin ,TemplateView): template_name = "store/account.html"
class AccountPageView(LoginRequiredMixin ,TemplateView):
template_name = "store/account.html"
cancel_url=f"http://localhost:8000/", ) return HttpResponseRedirect(checkout_session.url) class OrdersHistory(ListView): template_name = "store/history.html" def get_queryset(self): return Order.objects.filter(customer=self.request.user) class AccountPageView(LoginRequiredMixin ,TemplateView):
64
64
19
11
53
rafaellima47/django-ecommerce
store/views.py
Python
AccountPageView
AccountPageView
132
133
132
132
79dad1edfe3d817add317efb2da8603690faa280
bigcode/the-stack
train
38a20db17cbfbc0a55df18ab
train
function
@require_POST def cart_add(request, pk): quantity = 1 override_quantity = False if request.POST.get("quantity"): quantity = int(request.POST["quantity"]) override_quantity = True cart = Cart(request) cart.add(pk, quantity, override_quantity) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))...
@require_POST def cart_add(request, pk):
quantity = 1 override_quantity = False if request.POST.get("quantity"): quantity = int(request.POST["quantity"]) override_quantity = True cart = Cart(request) cart.add(pk, quantity, override_quantity) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
.get(customer=customer, product=product) item.delete() except WishlistItem.DoesNotExist: item = WishlistItem(customer=customer, product=product) item.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) @require_POST def cart_add(request, pk):
63
64
76
11
52
rafaellima47/django-ecommerce
store/views.py
Python
cart_add
cart_add
199
210
199
200
5ffe9a2996780e6002f696dbc2327ed1247f955f
bigcode/the-stack
train
3785a8b59aa04544bd1925e9
train
function
@require_POST def cart_delete(request, pk): cart = Cart(request) cart.delete(pk) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
@require_POST def cart_delete(request, pk):
cart = Cart(request) cart.delete(pk) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
.POST.get("quantity"): quantity = int(request.POST["quantity"]) override_quantity = True cart = Cart(request) cart.add(pk, quantity, override_quantity) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) @require_POST def cart_delete(request, pk):
63
64
37
11
52
rafaellima47/django-ecommerce
store/views.py
Python
cart_delete
cart_delete
213
217
213
214
d194bec07993b6a09eb0d30c057ec9e9cf7cc144
bigcode/the-stack
train
c2574efaddb2a1224dc08fb4
train
class
class RackUnitPersonalityConsts: pass
class RackUnitPersonalityConsts:
pass
"""This module contains the general information for RackUnitPersonality ManagedObject.""" from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class RackUnitPersonalityConsts:
54
64
10
7
46
ecoen66/imcsdk
imcsdk/mometa/rack/RackUnitPersonality.py
Python
RackUnitPersonalityConsts
RackUnitPersonalityConsts
8
9
8
8
24ea2ceb26f634680c5ad92f359407894a336ffa
bigcode/the-stack
train
d9c778403d4a9bc6649fc9ef
train
class
class RackUnitPersonality(ManagedObject): """This is RackUnitPersonality class.""" consts = RackUnitPersonalityConsts() naming_props = set(['id']) mo_meta = { "classic": MoMeta("RackUnitPersonality", "rackUnitPersonality", "personality-[id]", VersionMeta.Version421a, "InputOutput", 0x7f, [], [...
class RackUnitPersonality(ManagedObject):
"""This is RackUnitPersonality class.""" consts = RackUnitPersonalityConsts() naming_props = set(['id']) mo_meta = { "classic": MoMeta("RackUnitPersonality", "rackUnitPersonality", "personality-[id]", VersionMeta.Version421a, "InputOutput", 0x7f, [], ["admin", "read-only", "user"], ['computeRa...
"""This module contains the general information for RackUnitPersonality ManagedObject.""" from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class RackUnitPersonalityConsts: pass class RackUnitPersonality(ManagedObject):
66
161
538
9
56
ecoen66/imcsdk
imcsdk/mometa/rack/RackUnitPersonality.py
Python
RackUnitPersonality
RackUnitPersonality
12
56
12
12
c388ece62bfe5547e769845ee3ddfc389a6e1f94
bigcode/the-stack
train
83cfd29c1b6639c3855dfe11
train
function
def score(data): score=True ## Calification rules max_border_1 = 360 # Max threshold for valid point min_border_1 = 0 # Min threshold for valid point max_border_2 = 90 # Max threshold for valid point min_border_2 = 0 # Min threshold for valid point ...
def score(data):
score=True ## Calification rules max_border_1 = 360 # Max threshold for valid point min_border_1 = 0 # Min threshold for valid point max_border_2 = 90 # Max threshold for valid point min_border_2 = 0 # Min threshold for valid point min_threshold_1 =...
import pandas as pd import numpy as np import math from scipy.signal import argrelextrema #1. brazos #2. piernas def score(data):
37
256
3,372
4
32
josemusso/DEKR
lib/modules/ex_score/dinamicos/D_BJ.py
Python
score
score
9
323
9
10
b5e174c04b4c502848f5cee34ecc98adb2b23dde
bigcode/the-stack
train
82fb3ec71b9247b592caa240
train
class
class Logger: """ @brief Class for logger. @example : l = Logger() l.log("this is msg", "{this_is_data}") l.info("this is msg", "{this_is_data}") l.error("this is msg", "{this_is_data}") l.warn(data="{this_is_data}") l.success("this is msg") """ def __init__(self): pass def _printLogDict(sel...
class Logger:
""" @brief Class for logger. @example : l = Logger() l.log("this is msg", "{this_is_data}") l.info("this is msg", "{this_is_data}") l.error("this is msg", "{this_is_data}") l.warn(data="{this_is_data}") l.success("this is msg") """ def __init__(self): pass def _printLogDict(self, logDict): ...
import datetime class Logger:
6
108
361
3
2
Himanshu-Mishr/up-for-grab
src/logger.py
Python
Logger
Logger
3
51
3
3
41d51f9d0da14ccd5cfd3214d0d0765a7f6cdd91
bigcode/the-stack
train
399a4791dcb60b191a117548
train
function
def wsg_50_description_mesh_files(): return [ "wsg_50_description/meshes/finger_without_tip.obj", "wsg_50_description/meshes/finger_with_tip.obj", "wsg_50_description/meshes/wsg_body.obj", ]
def wsg_50_description_mesh_files():
return [ "wsg_50_description/meshes/finger_without_tip.obj", "wsg_50_description/meshes/finger_with_tip.obj", "wsg_50_description/meshes/wsg_body.obj", ]
/skydio_2_1000_poly.mtl", "skydio_2/skydio_2_1000_poly.obj", "skydio_2/skydio_2.png", "skydio_2/LICENSE", ] def wsg_50_description_mesh_files():
64
64
61
9
55
RobotLocomotion/drake-python3.7
tools/workspace/models/files.bzl
Python
wsg_50_description_mesh_files
wsg_50_description_mesh_files
66
71
66
66
a5d5def7cb563792e21e97f1cb230f0bc2ab694c
bigcode/the-stack
train
55782eff5e5915d0d175373d
train
function
def franka_description_mesh_files(): return [ "franka_description/LICENSE", "franka_description/meshes/visual/finger.mtl", "franka_description/meshes/visual/finger.obj", "franka_description/meshes/visual/hand.mtl", "franka_description/meshes/visual/hand.obj", "franka_...
def franka_description_mesh_files():
return [ "franka_description/LICENSE", "franka_description/meshes/visual/finger.mtl", "franka_description/meshes/visual/finger.obj", "franka_description/meshes/visual/hand.mtl", "franka_description/meshes/visual/hand.obj", "franka_description/meshes/visual/link0.mtl",...
# -*- python -*- # Keep the macros sorted alphabetically by macro name. # Keep the lists of files sorted alphabetically by filename. def dishes_files(): return [ "dishes/bowls/evo_bowl_no_mtl.obj", ] def franka_description_mesh_files():
59
92
309
7
52
RobotLocomotion/drake-python3.7
tools/workspace/models/files.bzl
Python
franka_description_mesh_files
franka_description_mesh_files
11
34
11
11
1d62ea32612cfd4643d4557b8142e1a67332da52
bigcode/the-stack
train
9f69c38662e256e699520f1c
train
function
def dishes_files(): return [ "dishes/bowls/evo_bowl_no_mtl.obj", ]
def dishes_files():
return [ "dishes/bowls/evo_bowl_no_mtl.obj", ]
# -*- python -*- # Keep the macros sorted alphabetically by macro name. # Keep the lists of files sorted alphabetically by filename. def dishes_files():
31
64
25
4
27
RobotLocomotion/drake-python3.7
tools/workspace/models/files.bzl
Python
dishes_files
dishes_files
6
9
6
6
d16161c9fd74683e073a2e0580d80e3bad236804
bigcode/the-stack
train
d77616841d7fea290b69edf2
train
function
def ycb_mesh_files(): """Manual enumeration of mesh files, to avoid needing to write extra Bazel logic. Recipe to reproduce: $ cd models $ find ycb/meshes -type f | \ python3 -c 'import sys; print(repr(sys.stdin.read().split()))' """ return [ "ycb/meshes/003_crac...
def ycb_mesh_files():
"""Manual enumeration of mesh files, to avoid needing to write extra Bazel logic. Recipe to reproduce: $ cd models $ find ycb/meshes -type f | \ python3 -c 'import sys; print(repr(sys.stdin.read().split()))' """ return [ "ycb/meshes/003_cracker_box_textured.mtl",...
io_2_1000_poly.mtl", "skydio_2/skydio_2_1000_poly.obj", "skydio_2/skydio_2.png", "skydio_2/LICENSE", ] def wsg_50_description_mesh_files(): return [ "wsg_50_description/meshes/finger_without_tip.obj", "wsg_50_description/meshes/finger_with_tip.obj", "wsg_50_descr...
120
120
403
6
114
RobotLocomotion/drake-python3.7
tools/workspace/models/files.bzl
Python
ycb_mesh_files
ycb_mesh_files
73
102
73
73
91af582ed702ef969e0c4a8db57c4f2517b1661b
bigcode/the-stack
train
b9e72af2392b07ff629a011c
train
function
def skydio_2_mesh_files(): return [ "skydio_2/skydio_2_1000_poly.mtl", "skydio_2/skydio_2_1000_poly.obj", "skydio_2/skydio_2.png", "skydio_2/LICENSE", ]
def skydio_2_mesh_files():
return [ "skydio_2/skydio_2_1000_poly.mtl", "skydio_2/skydio_2_1000_poly.obj", "skydio_2/skydio_2.png", "skydio_2/LICENSE", ]
_description/meshes/shoulder.obj", "jaco_description/meshes/wrist.obj", "jaco_description/meshes/wrist_spherical_1.obj", "jaco_description/meshes/wrist_spherical_2.obj", ] def skydio_2_mesh_files():
64
64
74
9
55
RobotLocomotion/drake-python3.7
tools/workspace/models/files.bzl
Python
skydio_2_mesh_files
skydio_2_mesh_files
58
64
58
58
f19e5ea8a0870e9dde035c0e0094f22528d7d34a
bigcode/the-stack
train
cd950610060be7eb10da352b
train
function
def jaco_description_mesh_files(): return [ "jaco_description/LICENSE", "jaco_description/meshes/arm.obj", "jaco_description/meshes/arm_half_1.obj", "jaco_description/meshes/arm_half_2.obj", "jaco_description/meshes/arm_mico.obj", "jaco_description/meshes/base.obj", ...
def jaco_description_mesh_files():
return [ "jaco_description/LICENSE", "jaco_description/meshes/arm.obj", "jaco_description/meshes/arm_half_1.obj", "jaco_description/meshes/arm_half_2.obj", "jaco_description/meshes/arm_mico.obj", "jaco_description/meshes/base.obj", "jaco_description/meshes/fin...
/meshes/visual/link5.obj", "franka_description/meshes/visual/link6.mtl", "franka_description/meshes/visual/link6.obj", "franka_description/meshes/visual/link7.mtl", "franka_description/meshes/visual/link7.obj", ] def jaco_description_mesh_files():
76
76
256
7
69
RobotLocomotion/drake-python3.7
tools/workspace/models/files.bzl
Python
jaco_description_mesh_files
jaco_description_mesh_files
36
56
36
36
b9d2c9f21be857c017e234e789c262c7b8fdfeba
bigcode/the-stack
train
d089f917c04e0cfd6a13c354
train
function
def traverse(stepsToTake): x, y = 0, 0 noSteps = 0 for line in stepsToTake: for x, y in steps(line, x, y): noSteps += 1 yield x, y, noSteps
def traverse(stepsToTake):
x, y = 0, 0 noSteps = 0 for line in stepsToTake: for x, y in steps(line, x, y): noSteps += 1 yield x, y, noSteps
'L':(-1, 0), 'R':(1, 0)}[s[0]] for i in range(int(s[1:])): x, y = x + d[0], y + d[1] yield x, y def traverse(stepsToTake):
64
64
62
7
56
joelfak/advent_of_code_2019
Dyr-El-python/day03.py
Python
traverse
traverse
23
29
23
23
f842edc64e8c6ca2b6dc9d201a0bc0362f0a0a37
bigcode/the-stack
train
c64bcfc887780252c0495fb7
train
function
def part1(pinp): trace1 = traceFirst(pinp[0][0]) return findCollisions(trace1, pinp[1][0], distanceToStart)
def part1(pinp):
trace1 = traceFirst(pinp[0][0]) return findCollisions(trace1, pinp[1][0], distanceToStart)
ToTake, distFunc): dists = set() for x, y, stepCount in traverse(stepsToTake): if (x, y) in trace: dists.add(distFunc(trace, x, y, stepCount)) return min(dists) def part1(pinp):
64
64
38
6
58
joelfak/advent_of_code_2019
Dyr-El-python/day03.py
Python
part1
part1
51
53
51
51
1439dd34e1c3abef34405b88eb2a4e1f684e23a9
bigcode/the-stack
train
f2cf3ecf5847e8498f683cf0
train
function
def fileParse(inp, f=lineParse, ff=lambda x:x, fp=re.compile(r"^(.*)$")): return tuple(map(lambda x:f(x, ff, fp), inp.splitlines()))
def fileParse(inp, f=lineParse, ff=lambda x:x, fp=re.compile(r"^(.*)$")):
return tuple(map(lambda x:f(x, ff, fp), inp.splitlines()))
Input import re def lineParse(s, f, fp): m = fp.match(s) if m==None: raise s return tuple(map(f, m.groups())) def fileParse(inp, f=lineParse, ff=lambda x:x, fp=re.compile(r"^(.*)$")):
64
64
41
24
40
joelfak/advent_of_code_2019
Dyr-El-python/day03.py
Python
fileParse
fileParse
12
13
12
12
6053c068fd39bb30075b3355ccfc1f58793e95e0
bigcode/the-stack
train
5556fd7787f8ce25236e88ac
train
function
def distanceToStart(dist, x, y, noSteps): return abs(x)+abs(y)
def distanceToStart(dist, x, y, noSteps):
return abs(x)+abs(y)
First(stepsToTake): d = dict() for x, y, stepCount in traverse(stepsToTake): if (x, y) not in d: d[x, y] = stepCount return d def distanceToStart(dist, x, y, noSteps):
64
64
21
13
50
joelfak/advent_of_code_2019
Dyr-El-python/day03.py
Python
distanceToStart
distanceToStart
38
39
38
38
933532b3fd6d605b32ab0925c2963b9a50e1eb0a
bigcode/the-stack
train
0bcff76f5dbed50ca1ddf943
train
function
def part2(pinp): trace1 = traceFirst(pinp[0][0]) return findCollisions(trace1, pinp[1][0], noOfStepsToStart)
def part2(pinp):
trace1 = traceFirst(pinp[0][0]) return findCollisions(trace1, pinp[1][0], noOfStepsToStart)
dists.add(distFunc(trace, x, y, stepCount)) return min(dists) def part1(pinp): trace1 = traceFirst(pinp[0][0]) return findCollisions(trace1, pinp[1][0], distanceToStart) def part2(pinp):
64
64
40
6
58
joelfak/advent_of_code_2019
Dyr-El-python/day03.py
Python
part2
part2
55
57
55
55
19e1a2fe05b0a422680264bb55d512f91a956089
bigcode/the-stack
train
d331916d2fa63f1b94cbc818
train
function
def traceFirst(stepsToTake): d = dict() for x, y, stepCount in traverse(stepsToTake): if (x, y) not in d: d[x, y] = stepCount return d
def traceFirst(stepsToTake):
d = dict() for x, y, stepCount in traverse(stepsToTake): if (x, y) not in d: d[x, y] = stepCount return d
): x, y = 0, 0 noSteps = 0 for line in stepsToTake: for x, y in steps(line, x, y): noSteps += 1 yield x, y, noSteps def traceFirst(stepsToTake):
64
64
53
8
55
joelfak/advent_of_code_2019
Dyr-El-python/day03.py
Python
traceFirst
traceFirst
31
36
31
31
255fd48f64435641f0a5b5759ccc8222a3d58bf4
bigcode/the-stack
train
96d03822fbc79b55307e3111
train
function
def noOfStepsToStart(dist, x, y, noSteps): return dist[x, y] + noSteps
def noOfStepsToStart(dist, x, y, noSteps):
return dist[x, y] + noSteps
ToTake): if (x, y) not in d: d[x, y] = stepCount return d def distanceToStart(dist, x, y, noSteps): return abs(x)+abs(y) def noOfStepsToStart(dist, x, y, noSteps):
64
64
26
15
49
joelfak/advent_of_code_2019
Dyr-El-python/day03.py
Python
noOfStepsToStart
noOfStepsToStart
41
42
41
41
7d2939244631e116fb50801fd1010aa86abd8ef7
bigcode/the-stack
train
541f942a468426ec4fa74712
train
function
def lineParse(s, f, fp): m = fp.match(s) if m==None: raise s return tuple(map(f, m.groups()))
def lineParse(s, f, fp):
m = fp.match(s) if m==None: raise s return tuple(map(f, m.groups()))
## Start of header boilerplate ################################################# from aocbase import readInput import re def lineParse(s, f, fp):
28
64
35
9
18
joelfak/advent_of_code_2019
Dyr-El-python/day03.py
Python
lineParse
lineParse
6
10
6
6
8ac2e48af301506f2c09b8143fc179bf393e88ee
bigcode/the-stack
train
f16e6f6f59775423aa86e321
train
function
def steps(s, x, y): d = {'U':(0, 1), 'D':(0, -1), 'L':(-1, 0), 'R':(1, 0)}[s[0]] for i in range(int(s[1:])): x, y = x + d[0], y + d[1] yield x, y
def steps(s, x, y):
d = {'U':(0, 1), 'D':(0, -1), 'L':(-1, 0), 'R':(1, 0)}[s[0]] for i in range(int(s[1:])): x, y = x + d[0], y + d[1] yield x, y
tuple(map(f, m.groups())) def fileParse(inp, f=lineParse, ff=lambda x:x, fp=re.compile(r"^(.*)$")): return tuple(map(lambda x:f(x, ff, fp), inp.splitlines())) ## End of header boilerplate ################################################### def steps(s, x, y):
64
64
86
8
56
joelfak/advent_of_code_2019
Dyr-El-python/day03.py
Python
steps
steps
17
21
17
17
f9964654432d003b9102e4a1e3e3643fce2d4b37
bigcode/the-stack
train
fdeb9659c3834328055e24ac
train
function
def findCollisions(trace, stepsToTake, distFunc): dists = set() for x, y, stepCount in traverse(stepsToTake): if (x, y) in trace: dists.add(distFunc(trace, x, y, stepCount)) return min(dists)
def findCollisions(trace, stepsToTake, distFunc):
dists = set() for x, y, stepCount in traverse(stepsToTake): if (x, y) in trace: dists.add(distFunc(trace, x, y, stepCount)) return min(dists)
return d def distanceToStart(dist, x, y, noSteps): return abs(x)+abs(y) def noOfStepsToStart(dist, x, y, noSteps): return dist[x, y] + noSteps def findCollisions(trace, stepsToTake, distFunc):
64
64
65
13
50
joelfak/advent_of_code_2019
Dyr-El-python/day03.py
Python
findCollisions
findCollisions
44
49
44
44
d7473fcd3d6f50fd956c1bb7e816ba07c342717c
bigcode/the-stack
train
f06507cfbb6ea5f1a4445fd9
train
class
@keras_export("keras.layers.experimental.preprocessing.IntegerLookup", v1=[]) class IntegerLookup(index_lookup.IndexLookup): """Reindex integer inputs to be in a contiguous range, via a dict lookup. This layer maps a set of arbitrary integer input tokens into indexed integer output via a table-based vocabulary l...
@keras_export("keras.layers.experimental.preprocessing.IntegerLookup", v1=[]) class IntegerLookup(index_lookup.IndexLookup):
"""Reindex integer inputs to be in a contiguous range, via a dict lookup. This layer maps a set of arbitrary integer input tokens into indexed integer output via a table-based vocabulary lookup. The layer's output indices will be contiguously arranged up to the maximum vocab size, even if the input tokens ar...
# Copyright 2020 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...
221
256
3,786
23
197
phanvanthinh98/keras_LSTM
keras/layers/preprocessing/integer_lookup.py
Python
IntegerLookup
IntegerLookup
25
334
25
26
5a5e315f3c961f08279bae826e0e951bb54667b8
bigcode/the-stack
train
3e885ca39990d64ec2271f62
train
class
class Solution(object): def canIWin(self, maxChoosableInteger, desiredTotal): dp = dict() def search(state, total): for x in range(maxChoosableInteger, 0, -1): if not state & (1 << (x - 1)): if total + x >= desiredTotal: dp[stat...
class Solution(object):
def canIWin(self, maxChoosableInteger, desiredTotal): dp = dict() def search(state, total): for x in range(maxChoosableInteger, 0, -1): if not state & (1 << (x - 1)): if total + x >= desiredTotal: dp[state] = True ...
- nums[i]): self.memo[key]= True return True self.memo[key] = False return False # this problem is not very good... # sort of brutal force with memorization # time complexity -- O(2^M) # space complexity -- O(2^M) class Solution(object):
69
69
233
4
65
crazywiden/Leetcode_daily_submit
Widen/LC464_can_I_win.py
Python
Solution
Solution
65
87
65
65
f055e46cb1a2811254702ca41344b21980841e4d
bigcode/the-stack
train
58b050ce0e50889b9a387f09
train
class
class Solution(object): def canIWin(self, maxChoosableInteger, desiredTotal): """ :type maxChoosableInteger: int :type desiredTotal: int :rtype: bool """ if (1 + maxChoosableInteger) * maxChoosableInteger/2 < desiredTotal: return False self.memo = ...
class Solution(object):
def canIWin(self, maxChoosableInteger, desiredTotal): """ :type maxChoosableInteger: int :type desiredTotal: int :rtype: bool """ if (1 + maxChoosableInteger) * maxChoosableInteger/2 < desiredTotal: return False self.memo = {} return self.h...
first player, the second player will always win. """ # Runtime: 868 ms, faster than 61.70% of Python online submissions for Can I Win. # Memory Usage: 18.8 MB, less than 94.68% of Python online submissions for Can I Win. class Solution(object):
64
64
201
4
60
crazywiden/Leetcode_daily_submit
Widen/LC464_can_I_win.py
Python
Solution
Solution
31
58
31
31
845ef60b9057d3f31310ef7b38bd4688e5e78cfd
bigcode/the-stack
train
9e1238cbc4b42c8e20043ddc
train
class
class Metadata(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. a...
class Metadata(object):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The...
# coding: utf-8 """ IONOS DBaaS REST API An enterprise-grade Database is provided as a Service (DBaaS) solution that can be managed through a browser-based \"Data Center Designer\" (DCD) tool or via an easy to use API. The API allows you to create additional database clusters or modify existing ones. It is d...
181
256
1,842
4
176
ionos-cloud/sdk-python-dbaas-postgres
ionoscloud_dbaas_postgres/models/metadata.py
Python
Metadata
Metadata
21
294
21
21
aa6e2c43161e98e83297a067b67550123c881691
bigcode/the-stack
train
2c30553610eb94806903c7d8
train
class
class TFFuncMapper(ProxyDataFlow): def __init__(self, ds, get_placeholders, symbf, apply_symbf_on_dp, device='/cpu:0'): """ :param get_placeholders: a function returning the placeholders :param symbf: a symbolic function taking the placeholders :param apply_symbf_on_...
class TFFuncMapper(ProxyDataFlow):
def __init__(self, ds, get_placeholders, symbf, apply_symbf_on_dp, device='/cpu:0'): """ :param get_placeholders: a function returning the placeholders :param symbf: a symbolic function taking the placeholders :param apply_symbf_on_dp: apply the above function to dat...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: tf_func.py # Author: Yuxin Wu <ppwwyyxxc@gmail.com> import tensorflow as tf from .base import ProxyDataFlow """ This file was deprecated """ __all__ = [] class TFFuncMapper(ProxyDataFlow):
71
83
279
10
61
neale/A4C
multilstm_tensorpack/tensorpack/dataflow/tf_func.py
Python
TFFuncMapper
TFFuncMapper
15
47
15
15
b3ac3d4980800142a1f5d61c5e16bee6300f7d85
bigcode/the-stack
train
d210485476fea750621aa69c
train
function
@ex.command def get_lr_scheduler(optimizer, schedule_mode): if schedule_mode in {"exp_lin", "cos_cyc"}: return torch.optim.lr_scheduler.LambdaLR(optimizer, get_scheduler_lambda()) raise RuntimeError(f"schedule_mode={schedule_mode} Unknown.")
@ex.command def get_lr_scheduler(optimizer, schedule_mode):
if schedule_mode in {"exp_lin", "cos_cyc"}: return torch.optim.lr_scheduler.LambdaLR(optimizer, get_scheduler_lambda()) raise RuntimeError(f"schedule_mode={schedule_mode} Unknown.")
_lr_value) if schedule_mode == "cos_cyc": return cosine_cycle(warm_up_len, ramp_down_start, last_lr_value) raise RuntimeError(f"schedule_mode={schedule_mode} Unknown for a lambda funtion.") @ex.command def get_lr_scheduler(optimizer, schedule_mode):
63
64
59
14
49
JetRunner/PaSST-EE
ex_audioset.py
Python
get_lr_scheduler
get_lr_scheduler
87
91
87
88
33af31bd1e293cf68a1cde332198de7b781e4174
bigcode/the-stack
train
ec6226a758aac1a7e42a8f8d
train
function
@ex.command def get_optimizer(params, lr, adamw=True, weight_decay=0.0001): if adamw: print(f"\nUsing adamw weight_decay={weight_decay}!\n") return torch.optim.AdamW(params, lr=lr, weight_decay=weight_decay) return torch.optim.Adam(params, lr=lr)
@ex.command def get_optimizer(params, lr, adamw=True, weight_decay=0.0001):
if adamw: print(f"\nUsing adamw weight_decay={weight_decay}!\n") return torch.optim.AdamW(params, lr=lr, weight_decay=weight_decay) return torch.optim.Adam(params, lr=lr)
{"exp_lin", "cos_cyc"}: return torch.optim.lr_scheduler.LambdaLR(optimizer, get_scheduler_lambda()) raise RuntimeError(f"schedule_mode={schedule_mode} Unknown.") @ex.command def get_optimizer(params, lr, adamw=True, weight_decay=0.0001):
63
64
74
23
40
JetRunner/PaSST-EE
ex_audioset.py
Python
get_optimizer
get_optimizer
94
99
94
95
7271f04e2a3a22f0ae807c5eb108d85ba637ec6a
bigcode/the-stack
train
de231f3b6d7ef64154a80366
train
function
@ex.command def test_loaders(): ''' get one sample from each loader for debbuging @return: ''' for i, b in enumerate(ex.datasets.training.get_iter()): print(b) break for i, b in enumerate(ex.datasets.test.get_iter()): print(b) break
@ex.command def test_loaders():
''' get one sample from each loader for debbuging @return: ''' for i, b in enumerate(ex.datasets.training.get_iter()): print(b) break for i, b in enumerate(ex.datasets.test.get_iter()): print(b) break
print(f"\n\nValidation len={len(val_loader)}\n") res = trainer.validate(modul, val_dataloaders=val_loader) print("\n\n Validtaion:") print(res) print(modul.net.get_stats()) @ex.command def test_loaders():
64
64
69
9
55
JetRunner/PaSST-EE
ex_audioset.py
Python
test_loaders
test_loaders
424
436
424
425
36d5026bef0c93a3adf9698ad9ed543c4023e29d
bigcode/the-stack
train
a9768e2a8aeae9035958b9bb
train
class
class M(Ba3lModule): def __init__(self, experiment): self.mel = None self.da_net = None super(M, self).__init__(experiment) self.use_mixup = self.config.use_mixup or False self.mixup_alpha = self.config.mixup_alpha desc, sum_params, sum_non_zero = count_non_zero_par...
class M(Ba3lModule):
def __init__(self, experiment): self.mel = None self.da_net = None super(M, self).__init__(experiment) self.use_mixup = self.config.use_mixup or False self.mixup_alpha = self.config.mixup_alpha desc, sum_params, sum_non_zero = count_non_zero_params(self.net) ...
arm_up_len=5, ramp_down_start=50, ramp_down_len=50, last_lr_value=0.01, schedule_mode="exp_lin"): if schedule_mode == "exp_lin": return exp_warmup_linear_down(warm_up_len, ramp_down_len, ramp_down_start, last_lr_value) if schedule_mode == "cos_cyc": return cosine_cycle(w...
256
256
1,680
8
248
JetRunner/PaSST-EE
ex_audioset.py
Python
M
M
102
273
102
102
512042b6b2f8f33904831652f07492c9ca279564
bigcode/the-stack
train
d0cfe012f72adbd5f767cc8b
train
function
@ex.config def default_conf(): cmd = " ".join(sys.argv) # command line arguments saque_cmd = os.environ.get("SAQUE_CMD", "").strip() saque_id = os.environ.get("SAQUE_ID", "").strip() slurm_job_id = os.environ.get("SLURM_JOB_ID", "").strip() if os.environ.get("SLURM_ARRAY_JOB_ID", False): slu...
@ex.config def default_conf():
cmd = " ".join(sys.argv) # command line arguments saque_cmd = os.environ.get("SAQUE_CMD", "").strip() saque_id = os.environ.get("SAQUE_ID", "").strip() slurm_job_id = os.environ.get("SLURM_JOB_ID", "").strip() if os.environ.get("SLURM_ARRAY_JOB_ID", False): slurm_job_id = os.environ.get("SLU...
GPU" # define datasets and loaders ex.datasets.training.iter(DataLoader, static_args=dict(worker_init_fn=worker_init_fn), train=True, batch_size=12, num_workers=16, shuffle=None, dataset=CMD("/basedataset.get_full_training_set"), sampler=CMD("/basedataset.get_ft_wei...
122
123
412
8
114
JetRunner/PaSST-EE
ex_audioset.py
Python
default_conf
default_conf
40
70
40
41
e01c4708bd9d4502c30c622c6e27b800cfe3c358
bigcode/the-stack
train
4ff3bb468001e7ee1ee42634
train
function
@ex.command def model_speed_test(_run, _config, _log, _rnd, _seed, speed_test_batch_size=100): ''' Test training speed of a model @param _run: @param _config: @param _log: @param _rnd: @param _seed: @param speed_test_batch_size: the batch size during the test @return: ''' mo...
@ex.command def model_speed_test(_run, _config, _log, _rnd, _seed, speed_test_batch_size=100):
''' Test training speed of a model @param _run: @param _config: @param _log: @param _rnd: @param _seed: @param speed_test_batch_size: the batch size during the test @return: ''' modul = M(ex) modul = modul.cuda() batch_size = speed_test_batch_size print(f"\nBATCH...
veraging return [StochasticWeightAveraging(swa_epoch_start=swa_epoch_start, swa_freq=swa_freq)] @ex.command def main(_run, _config, _log, _rnd, _seed): trainer = ex.get_trainer() train_loader = ex.get_train_dataloaders() val_loader = ex.get_val_dataloaders() modul = M(ex) trainer.fit( ...
150
150
502
30
120
JetRunner/PaSST-EE
ex_audioset.py
Python
model_speed_test
model_speed_test
317
375
317
318
ca1142b9baa90e886290711c44c941c092ab1c96
bigcode/the-stack
train
42b79bb5bc05710d524a5a00
train
function
@ex.command def evaluate_fix_layer(_run, _config, _log, _rnd, _seed): # force overriding the config, not logged = not recommended trainer = ex.get_trainer() train_loader = ex.get_train_dataloaders() val_loader = ex.get_val_dataloaders() modul = M(ex) load_from = modul.config.trainer.resume_from_...
@ex.command def evaluate_fix_layer(_run, _config, _log, _rnd, _seed): # force overriding the config, not logged = not recommended
trainer = ex.get_trainer() train_loader = ex.get_train_dataloaders() val_loader = ex.get_val_dataloaders() modul = M(ex) load_from = modul.config.trainer.resume_from_checkpoint if load_from is not None: print("Loading checkpoint from", load_from) net = get_net_state_dict_from_che...
ataloaders=val_loader) print("\n\n Validtaion:") print(res) print(modul.net.get_stats()) @ex.command def evaluate_fix_layer(_run, _config, _log, _rnd, _seed): # force overriding the config, not logged = not recommended
64
64
213
36
28
JetRunner/PaSST-EE
ex_audioset.py
Python
evaluate_fix_layer
evaluate_fix_layer
402
421
402
404
6032fbed870bae06d075f7b0caed15f4fac9df8d
bigcode/the-stack
train
d68b800c182b298c795020fa
train
function
@ex.command def evaluate_only(_run, _config, _log, _rnd, _seed): # force overriding the config, not logged = not recommended trainer = ex.get_trainer() train_loader = ex.get_train_dataloaders() val_loader = ex.get_val_dataloaders() modul = M(ex) load_from = modul.config.trainer.resume_from_check...
@ex.command def evaluate_only(_run, _config, _log, _rnd, _seed): # force overriding the config, not logged = not recommended
trainer = ex.get_trainer() train_loader = ex.get_train_dataloaders() val_loader = ex.get_val_dataloaders() modul = M(ex) load_from = modul.config.trainer.resume_from_checkpoint if load_from is not None: print("Loading checkpoint from", load_from) net = get_net_state_dict_from_che...
test done:', (t2 - t1)) print("average speed: ", (test_length * batch_size) / (t2 - t1), " specs/second") @ex.command def evaluate_only(_run, _config, _log, _rnd, _seed): # force overriding the config, not logged = not recommended
72
72
241
35
37
JetRunner/PaSST-EE
ex_audioset.py
Python
evaluate_only
evaluate_only
378
400
378
380
afdc28bc0a452032591cdf94e68e549d5278ac02
bigcode/the-stack
train
aa5d287fac62c17d4fd4e92a
train
function
@ex.command def get_extra_checkpoint_callback(save_last_n=None): if save_last_n is None: return [] return [ModelCheckpoint(monitor="step", verbose=True, save_top_k=save_last_n, mode='max')]
@ex.command def get_extra_checkpoint_callback(save_last_n=None):
if save_last_n is None: return [] return [ModelCheckpoint(monitor="step", verbose=True, save_top_k=save_last_n, mode='max')]
get_extra_checkpoint_callback() + get_extra_swa_callback() @ex.command def get_dynamic_norm(model, dyn_norm=False): if not dyn_norm: return None, None raise RuntimeError('no dynamic norm supported yet.') @ex.command def get_extra_checkpoint_callback(save_last_n=None):
63
64
50
14
49
JetRunner/PaSST-EE
ex_audioset.py
Python
get_extra_checkpoint_callback
get_extra_checkpoint_callback
283
287
283
284
5d097566d13821984e5416394067cd1f39418ce3
bigcode/the-stack
train
97ca7e0196649b217327c2e2
train
function
@ex.command def get_scheduler_lambda(warm_up_len=5, ramp_down_start=50, ramp_down_len=50, last_lr_value=0.01, schedule_mode="exp_lin"): if schedule_mode == "exp_lin": return exp_warmup_linear_down(warm_up_len, ramp_down_len, ramp_down_start, last_lr_value) if schedule_mode == "c...
@ex.command def get_scheduler_lambda(warm_up_len=5, ramp_down_start=50, ramp_down_len=50, last_lr_value=0.01, schedule_mode="exp_lin"):
if schedule_mode == "exp_lin": return exp_warmup_linear_down(warm_up_len, ramp_down_len, ramp_down_start, last_lr_value) if schedule_mode == "cos_cyc": return cosine_cycle(warm_up_len, ramp_down_start, last_lr_value) raise RuntimeError(f"schedule_mode={schedule_mode} Unknown for a lambda fun...
12 fix_ic_output_layer_num = None # register extra possible configs add_configs(ex) @ex.command def get_scheduler_lambda(warm_up_len=5, ramp_down_start=50, ramp_down_len=50, last_lr_value=0.01, schedule_mode="exp_lin"):
64
64
122
42
22
JetRunner/PaSST-EE
ex_audioset.py
Python
get_scheduler_lambda
get_scheduler_lambda
77
84
77
79
2e0ddc387d7d0b46def2ad3d630cfcaa80bd0e66
bigcode/the-stack
train
dcb973666c628c099bec5053
train
function
@ex.command def get_extra_swa_callback(swa=True, swa_epoch_start=50, swa_freq=5): if not swa: return [] print("\n Using swa!\n") from helpers.swa_callback import StochasticWeightAveraging return [StochasticWeightAveraging(swa_epoch_start=swa_epoch_start, swa_freq=swa_f...
@ex.command def get_extra_swa_callback(swa=True, swa_epoch_start=50, swa_freq=5):
if not swa: return [] print("\n Using swa!\n") from helpers.swa_callback import StochasticWeightAveraging return [StochasticWeightAveraging(swa_epoch_start=swa_epoch_start, swa_freq=swa_freq)]
): if save_last_n is None: return [] return [ModelCheckpoint(monitor="step", verbose=True, save_top_k=save_last_n, mode='max')] @ex.command def get_extra_swa_callback(swa=True, swa_epoch_start=50, swa_freq=5):
63
64
81
26
37
JetRunner/PaSST-EE
ex_audioset.py
Python
get_extra_swa_callback
get_extra_swa_callback
290
297
290
292
74efaf9bb810a37f5b61b5f84549986cd9be9baf
bigcode/the-stack
train
2d09b8b0289cbfa46d4ccb17
train
function
@ex.command def preload_mp3(all_y=CMD("/basedataset.preload_mp3")): ''' read the dataset sequentially, useful if you have a network cache @param all_y: the dataset preload command @return: ''' print(all_y.shape)
@ex.command def preload_mp3(all_y=CMD("/basedataset.preload_mp3")):
''' read the dataset sequentially, useful if you have a network cache @param all_y: the dataset preload command @return: ''' print(all_y.shape)
for i, b in enumerate(ex.datasets.test.get_iter()): print(b) break def set_default_json_pickle(obj): if isinstance(obj, set): return list(obj) raise TypeError @ex.command def preload_mp3(all_y=CMD("/basedataset.preload_mp3")):
64
64
61
21
42
JetRunner/PaSST-EE
ex_audioset.py
Python
preload_mp3
preload_mp3
445
452
445
446
fd32bd190871b898716370fce4eb4c8f9559d615
bigcode/the-stack
train
58c363129e7eb0e3c0644a4e
train
function
@ex.command def get_dynamic_norm(model, dyn_norm=False): if not dyn_norm: return None, None raise RuntimeError('no dynamic norm supported yet.')
@ex.command def get_dynamic_norm(model, dyn_norm=False):
if not dyn_norm: return None, None raise RuntimeError('no dynamic norm supported yet.')
(self.parameters(), lr=self.config.lr) return { 'optimizer': optimizer, 'lr_scheduler': get_lr_scheduler(optimizer) } def configure_callbacks(self): return get_extra_checkpoint_callback() + get_extra_swa_callback() @ex.command def get_dynamic_norm(model, dyn_norm=Fal...
64
64
37
14
50
JetRunner/PaSST-EE
ex_audioset.py
Python
get_dynamic_norm
get_dynamic_norm
276
280
276
277
51697b34c66073e00038cdef13eccc41d3694cb3
bigcode/the-stack
train
c30816648c03f506dfe14f62
train
function
def set_default_json_pickle(obj): if isinstance(obj, set): return list(obj) raise TypeError
def set_default_json_pickle(obj):
if isinstance(obj, set): return list(obj) raise TypeError
get one sample from each loader for debbuging @return: ''' for i, b in enumerate(ex.datasets.training.get_iter()): print(b) break for i, b in enumerate(ex.datasets.test.get_iter()): print(b) break def set_default_json_pickle(obj):
64
64
24
7
56
JetRunner/PaSST-EE
ex_audioset.py
Python
set_default_json_pickle
set_default_json_pickle
439
442
439
439
fa83742a6fc2c446df5b3e6664ea77ecf2d26adc
bigcode/the-stack
train
3a66319f6e68b72a2cb9890d
train
function
def multiprocessing_run(rank, word_size): print("rank ", rank, os.getpid()) print("word_size ", word_size) os.environ['NODE_RANK'] = str(rank) os.environ['CUDA_VISIBLE_DEVICES'] = os.environ['CUDA_VISIBLE_DEVICES'].split(",")[rank] argv = sys.argv if rank != 0: print(f"Unobserved {os.get...
def multiprocessing_run(rank, word_size):
print("rank ", rank, os.getpid()) print("word_size ", word_size) os.environ['NODE_RANK'] = str(rank) os.environ['CUDA_VISIBLE_DEVICES'] = os.environ['CUDA_VISIBLE_DEVICES'].split(",")[rank] argv = sys.argv if rank != 0: print(f"Unobserved {os.getpid()} with rank {rank}") argv = a...
preload_mp3(all_y=CMD("/basedataset.preload_mp3")): ''' read the dataset sequentially, useful if you have a network cache @param all_y: the dataset preload command @return: ''' print(all_y.shape) def multiprocessing_run(rank, word_size):
64
64
178
8
56
JetRunner/PaSST-EE
ex_audioset.py
Python
multiprocessing_run
multiprocessing_run
455
474
455
455
17f143f17605229aacb1bfc0ade1380c2d78bbe7
bigcode/the-stack
train
17f55c4059d4de9a3aaf7f83
train
function
@ex.command def main(_run, _config, _log, _rnd, _seed): trainer = ex.get_trainer() train_loader = ex.get_train_dataloaders() val_loader = ex.get_val_dataloaders() modul = M(ex) trainer.fit( modul, train_dataloader=train_loader, val_dataloaders=val_loader, ) return ...
@ex.command def main(_run, _config, _log, _rnd, _seed):
trainer = ex.get_trainer() train_loader = ex.get_train_dataloaders() val_loader = ex.get_val_dataloaders() modul = M(ex) trainer.fit( modul, train_dataloader=train_loader, val_dataloaders=val_loader, ) return {"done": True}
swa!\n") from helpers.swa_callback import StochasticWeightAveraging return [StochasticWeightAveraging(swa_epoch_start=swa_epoch_start, swa_freq=swa_freq)] @ex.command def main(_run, _config, _log, _rnd, _seed):
63
64
92
21
42
JetRunner/PaSST-EE
ex_audioset.py
Python
main
main
300
314
300
301
b563bd8fe7210d33f93fa16ad7e2ddbcb664d24e
bigcode/the-stack
train
dfba728d4f35f6d15022238f
train
function
@ex.automain def default_command(): return main()
@ex.automain def default_command():
return main()
multiprocessing_run(rank, word_size) exit(0) pid, exit_code = os.wait() print(pid, exit_code) exit(0) print("__main__ is running pid", os.getpid(), "in module main: ", __name__) @ex.automain def default_command():
64
64
13
9
55
JetRunner/PaSST-EE
ex_audioset.py
Python
default_command
default_command
506
508
506
507
b37bfc19df19162c65558b3a9adef06123f73265
bigcode/the-stack
train
c52ccff6e47524f640b4b404
train
function
def has_waters(molecular_system): from molsysmt.basic import get output = False n_waters = get(molecular_system, target='system', n_waters=True) if n_waters>0: output = True return output
def has_waters(molecular_system):
from molsysmt.basic import get output = False n_waters = get(molecular_system, target='system', n_waters=True) if n_waters>0: output = True return output
from molsysmt._private.exceptions import * from molsysmt._private.digestion import * def has_waters(molecular_system):
28
64
58
8
20
uibcdf/MolModSAKs
molsysmt/build/has_waters.py
Python
has_waters
has_waters
4
15
4
5
bb09b7ebd11d554dcac133de0c195896e0dd7623
bigcode/the-stack
train
13b66ec1b404029ecc04a4d4
train
function
def imperial(x): """ This function will convert Imperial Feet (and Inches) to Metric Meters (or Centimeters if less than 1 whole Meter :return: Converted value from Imperial to Metric """ # FEET SECTION # Take the feet from Array and set to variable frac_ft frac_ft = float(x[0]) # Con...
def imperial(x):
""" This function will convert Imperial Feet (and Inches) to Metric Meters (or Centimeters if less than 1 whole Meter :return: Converted value from Imperial to Metric """ # FEET SECTION # Take the feet from Array and set to variable frac_ft frac_ft = float(x[0]) # Convert from Feet to...
Inches to Meters OR Meters to Feet and Inches Requirements: fractions.Fraction function built into Python3 Known Issues: 1. Negative Feet and Positive Inches. I can't be bothered to fix it at 11 PM. """ # Necessary imports for this script to function. from fractions import Fraction as Fracs # Imperial to ...
77
77
258
4
72
IntenseToxicity/Imperial-to-metric-conversion
the_script.py
Python
imperial
imperial
21
56
21
21
f529a56f407be9e94c0c95ce44e3e510782b93f2
bigcode/the-stack
train
c0c76d1c6110510674a18d09
train
function
def main(): # Initialize variables system_value = bool() # 0 for Metric start, 1 for Imperial start. initial = str() # The initial value to convert FROM. sysloop = True # Internal loop 1 initial starting value [Unit of measure validation loop] # User input and Validation while sysloop is Tru...
def main(): # Initialize variables
system_value = bool() # 0 for Metric start, 1 for Imperial start. initial = str() # The initial value to convert FROM. sysloop = True # Internal loop 1 initial starting value [Unit of measure validation loop] # User input and Validation while sysloop is True: try: # Get the s...
return result # Metric to Imperial Conversion def metric(x): """ This function will convert Metric meters to Imperial Feet (and Inches). :return: Converted value from Metric to Imperial """ # Initial conversion # Meters to Feet meters_in_ft = float("{:.4f}".format(x * 3.280839895)) ...
256
256
1,447
8
247
IntenseToxicity/Imperial-to-metric-conversion
the_script.py
Python
main
main
91
275
91
92
36e7598e1b6280e306e29127d6f1b79bf5fd4264
bigcode/the-stack
train
258184ab652572cde8f8590e
train
function
def metric(x): """ This function will convert Metric meters to Imperial Feet (and Inches). :return: Converted value from Metric to Imperial """ # Initial conversion # Meters to Feet meters_in_ft = float("{:.4f}".format(x * 3.280839895)) # Inches portion of conversion meters_in_in ...
def metric(x):
""" This function will convert Metric meters to Imperial Feet (and Inches). :return: Converted value from Metric to Imperial """ # Initial conversion # Meters to Feet meters_in_ft = float("{:.4f}".format(x * 3.280839895)) # Inches portion of conversion meters_in_in = meters_in_ft ...
RESULTS # Calculate the results result = result_1 + result_2 # Format to 4 decimal places result = float("{:.4f}".format(result)) # RETURN SECTION # Return the converted result to be displayed return result # Metric to Imperial Conversion def metric(x):
69
69
233
4
64
IntenseToxicity/Imperial-to-metric-conversion
the_script.py
Python
metric
metric
60
87
60
60
9ce9d847ee928d74c3539e6728985a461299eb93
bigcode/the-stack
train
123a70f3729900b0d61f561c
train
class
class MarloEnvBuilder(MarloEnvBuilderBase): """ Description: The layout of this mission is that of a series of interconnected rooms made out of stone bricks. Various obstacles are placed in and between these rooms, and doors actioned by levers separate them. The agent's goal is to find the gold/diamond/r...
class MarloEnvBuilder(MarloEnvBuilderBase):
""" Description: The layout of this mission is that of a series of interconnected rooms made out of stone bricks. Various obstacles are placed in and between these rooms, and doors actioned by levers separate them. The agent's goal is to find the gold/diamond/redstone block in one of the rooms. Act...
#!/usr/bin/env python import marlo from marlo import MarloEnvBuilderBase from marlo import MalmoPython import os from pathlib import Path class MarloEnvBuilder(MarloEnvBuilderBase):
47
105
353
11
35
spMohanty/marlo
marlo/envs/Obstacles/main.py
Python
MarloEnvBuilder
MarloEnvBuilder
11
63
11
11
c5bb5dca8b6621cc96694ab9d643818f9811966b
bigcode/the-stack
train
419e282596fc505fda59e963
train
class
class AttachmentLocationBase(AgilityModelBase): ''' classdocs ''' def __init__(self, path='', repository=None): AgilityModelBase.__init__(self) self._attrSpecs = getattr(self, '_attrSpecs', {}) self._attrSpecs.update({'path': {'type': 'string', 'name': 'path', 'native': True}, 'r...
class AttachmentLocationBase(AgilityModelBase):
''' classdocs ''' def __init__(self, path='', repository=None): AgilityModelBase.__init__(self) self._attrSpecs = getattr(self, '_attrSpecs', {}) self._attrSpecs.update({'path': {'type': 'string', 'name': 'path', 'native': True}, 'repository': {'type': 'Link', 'name': 'repository...
from core.agility.common.AgilityModelBase import AgilityModelBase class AttachmentLocationBase(AgilityModelBase):
26
64
112
10
15
harshp8l/deep-learning-lang-detection
data/train/python/de8b426e53db23dba09d6cc26f8d58723f758514AttachmentLocation.py
Python
AttachmentLocationBase
AttachmentLocationBase
4
13
4
4
5adc34d34c0a22329a1942a1735cb3775603047b
bigcode/the-stack
train
e8cf93a2afb2954db379c081
train
function
def all_ts_files(suffix=''): for filename in os.listdir(LOCALE_DIR): # process only language files, and do not process source language if not filename.endswith('.ts'+suffix) or filename == SOURCE_LANG+suffix: continue if suffix: # remove provided suffix filename = fil...
def all_ts_files(suffix=''):
for filename in os.listdir(LOCALE_DIR): # process only language files, and do not process source language if not filename.endswith('.ts'+suffix) or filename == SOURCE_LANG+suffix: continue if suffix: # remove provided suffix filename = filename[0:-len(suffix)] ...
Allow numerus translations to omit %n specifier (usually when it only has one possible value) return True errors.append("Mismatch between '%s' and '%s'" % (sanitize_string(source), sanitize_string(translation))) return False return True def all_ts_files(suffix=''):
64
64
93
8
55
VirtDexCoinvir/virtdex
contrib/devtools/update-translations.py
Python
all_ts_files
all_ts_files
97
105
97
97
f25ec7bd152fdbcac881f6aff16d3b5858a2e0ee
bigcode/the-stack
train
1182359c3df4ab6efb75023f
train
function
def check_format_specifiers(source, translation, errors, numerus): source_f = split_format_specifiers(find_format_specifiers(source)) # assert that no source messages contain both Qt and strprintf format specifiers # if this fails, go change the source as this is hacky and confusing! #assert(not(source_...
def check_format_specifiers(source, translation, errors, numerus):
source_f = split_format_specifiers(find_format_specifiers(source)) # assert that no source messages contain both Qt and strprintf format specifiers # if this fails, go change the source as this is hacky and confusing! #assert(not(source_f[0] and source_f[1])) try: translation_f = split_forma...
) # numeric (Qt) can be present in any order, others (strprintf) must be in specified order return set(numeric),other def sanitize_string(s): '''Sanitize string for printing''' return s.replace('\n',' ') def check_format_specifiers(source, translation, errors, numerus):
68
69
231
14
54
VirtDexCoinvir/virtdex
contrib/devtools/update-translations.py
Python
check_format_specifiers
check_format_specifiers
78
95
78
78
5e024ac6430c432c6ec5fff86410976a61d6fb9c
bigcode/the-stack
train
56c540b69b85c5a1a79512fc
train
function
def postprocess_translations(reduce_diff_hacks=False): print('Checking and postprocessing...') if reduce_diff_hacks: global _orig_escape_cdata _orig_escape_cdata = ET._escape_cdata ET._escape_cdata = escape_cdata for (filename,filepath) in all_ts_files(): os.rename(filepath...
def postprocess_translations(reduce_diff_hacks=False):
print('Checking and postprocessing...') if reduce_diff_hacks: global _orig_escape_cdata _orig_escape_cdata = ET._escape_cdata ET._escape_cdata = escape_cdata for (filename,filepath) in all_ts_files(): os.rename(filepath, filepath+'.orig') have_errors = False for (f...
) or filename == SOURCE_LANG+suffix: continue if suffix: # remove provided suffix filename = filename[0:-len(suffix)] filepath = os.path.join(LOCALE_DIR, filename) yield(filename, filepath) FIX_RE = re.compile(b'[\x00-\x09\x0b\x0c\x0e-\x1f]') def remove_invalid_character...
194
194
647
12
181
VirtDexCoinvir/virtdex
contrib/devtools/update-translations.py
Python
postprocess_translations
postprocess_translations
121
197
121
121
15bee6a32bf7dbeb48912f0b8d5ec9553a40f7bb
bigcode/the-stack
train
b3ee643be2b082aac1e20a71
train
function
def find_format_specifiers(s): '''Find all format specifiers in a string.''' pos = 0 specifiers = [] while True: percent = s.find('%', pos) if percent < 0: break try: specifiers.append(s[percent+1]) except: print('Failed to get specifie...
def find_format_specifiers(s):
'''Find all format specifiers in a string.''' pos = 0 specifiers = [] while True: percent = s.find('%', pos) if percent < 0: break try: specifiers.append(s[percent+1]) except: print('Failed to get specifier') pos = percent+2 ...
this script at the root of the repository', file=sys.stderr) exit(1) def fetch_all_translations(): if subprocess.call([TX, 'pull', '-f', '-a']): print('Error while fetching translations', file=sys.stderr) exit(1) def find_format_specifiers(s):
64
64
90
7
57
VirtDexCoinvir/virtdex
contrib/devtools/update-translations.py
Python
find_format_specifiers
find_format_specifiers
46
59
46
46
948e241f4d1445b95b1ad11701db51eb2146e7c1
bigcode/the-stack
train
8168e19dcb5292b16b27a40e
train
function
def fetch_all_translations(): if subprocess.call([TX, 'pull', '-f', '-a']): print('Error while fetching translations', file=sys.stderr) exit(1)
def fetch_all_translations():
if subprocess.call([TX, 'pull', '-f', '-a']): print('Error while fetching translations', file=sys.stderr) exit(1)
be considered at all MIN_NUM_MESSAGES = 10 def check_at_repository_root(): if not os.path.exists('.git'): print('No .git directory found') print('Execute this script at the root of the repository', file=sys.stderr) exit(1) def fetch_all_translations():
64
64
39
6
58
VirtDexCoinvir/virtdex
contrib/devtools/update-translations.py
Python
fetch_all_translations
fetch_all_translations
41
44
41
41
5a79d6e3fb86627130a006212ed7d7e829148656
bigcode/the-stack
train
8fb1c8e8a545449bc9b81386
train
function
def check_at_repository_root(): if not os.path.exists('.git'): print('No .git directory found') print('Execute this script at the root of the repository', file=sys.stderr) exit(1)
def check_at_repository_root():
if not os.path.exists('.git'): print('No .git directory found') print('Execute this script at the root of the repository', file=sys.stderr) exit(1)
TX = 'tx' # Name of source language file SOURCE_LANG = 'VirtDex_en.ts' # Directory with locale files LOCALE_DIR = 'src/qt/locale' # Minimum number of messages for translation to be considered at all MIN_NUM_MESSAGES = 10 def check_at_repository_root():
64
64
46
6
57
VirtDexCoinvir/virtdex
contrib/devtools/update-translations.py
Python
check_at_repository_root
check_at_repository_root
35
39
35
35
e22a674c83912abbe7de2097a642d2c88879b0a3
bigcode/the-stack
train
03583f6dd70f4134f2378c60
train
function
def sanitize_string(s): '''Sanitize string for printing''' return s.replace('\n',' ')
def sanitize_string(s):
'''Sanitize string for printing''' return s.replace('\n',' ')
','4','5','6','7','8','9'}: numeric.append(s) else: other.append(s) # numeric (Qt) can be present in any order, others (strprintf) must be in specified order return set(numeric),other def sanitize_string(s):
64
64
21
5
58
VirtDexCoinvir/virtdex
contrib/devtools/update-translations.py
Python
sanitize_string
sanitize_string
74
76
74
74
3bf41e4a161e3999fd7cc587b8f72f523ec406e8
bigcode/the-stack
train
049c8b59e0533d30e4bbcf2c
train
function
def split_format_specifiers(specifiers): '''Split format specifiers between numeric (Qt) and others (strprintf)''' numeric = [] other = [] for s in specifiers: if s in {'1','2','3','4','5','6','7','8','9'}: numeric.append(s) else: other.append(s) # numeric (Q...
def split_format_specifiers(specifiers):
'''Split format specifiers between numeric (Qt) and others (strprintf)''' numeric = [] other = [] for s in specifiers: if s in {'1','2','3','4','5','6','7','8','9'}: numeric.append(s) else: other.append(s) # numeric (Qt) can be present in any order, others (s...
percent = s.find('%', pos) if percent < 0: break try: specifiers.append(s[percent+1]) except: print('Failed to get specifier') pos = percent+2 return specifiers def split_format_specifiers(specifiers):
64
64
110
8
55
VirtDexCoinvir/virtdex
contrib/devtools/update-translations.py
Python
split_format_specifiers
split_format_specifiers
61
72
61
61
a623f04fb6a09cc9a2984ccd82df5aa2ff458231
bigcode/the-stack
train
4c2a0711ec545b6c30e345aa
train
function
def remove_invalid_characters(s): '''Remove invalid characters from translation string''' return FIX_RE.sub(b'', s)
def remove_invalid_characters(s):
'''Remove invalid characters from translation string''' return FIX_RE.sub(b'', s)
filename = filename[0:-len(suffix)] filepath = os.path.join(LOCALE_DIR, filename) yield(filename, filepath) FIX_RE = re.compile(b'[\x00-\x09\x0b\x0c\x0e-\x1f]') def remove_invalid_characters(s):
64
64
25
7
58
VirtDexCoinvir/virtdex
contrib/devtools/update-translations.py
Python
remove_invalid_characters
remove_invalid_characters
108
110
108
108
f01df57c7e739d19b8f8316a2a6f3ece5e1fe7c1
bigcode/the-stack
train
2461ce42ffdb71a9cc04a658
train
function
def escape_cdata(text): text = _orig_escape_cdata(text) text = text.replace("'", '&apos;') text = text.replace('"', '&quot;') return text
def escape_cdata(text):
text = _orig_escape_cdata(text) text = text.replace("'", '&apos;') text = text.replace('"', '&quot;') return text
acters(s): '''Remove invalid characters from translation string''' return FIX_RE.sub(b'', s) # Override cdata escape function to make our output match Qt's (optional, just for cleaner diffs for # comparison, disable by default) _orig_escape_cdata = None def escape_cdata(text):
64
64
42
6
57
VirtDexCoinvir/virtdex
contrib/devtools/update-translations.py
Python
escape_cdata
escape_cdata
115
119
115
115
a0ad083ad5161501d817976805d7156747d0fc02
bigcode/the-stack
train
577c067d53d83b2749373c68
train
class
class TestWaterfall(unittest.TestCase): """ Test the waterfall method for loading data from the data providers. """ def setUp(self) -> None: """ Create the providers and list of companies which we'll use later on. """ self.companies = [ {"company_name": "Comp...
class TestWaterfall(unittest.TestCase):
""" Test the waterfall method for loading data from the data providers. """ def setUp(self) -> None: """ Create the providers and list of companies which we'll use later on. """ self.companies = [ {"company_name": "Company A", "company_id": "JP0000000001"}, ...
import SBTi.data from SBTi import utils from SBTi.data.csv import CSVProvider import os import unittest class TestWaterfall(unittest.TestCase):
37
124
416
8
28
CarbonEdge2021/SBTi-finance-tool
test/data/test_waterfall.py
Python
TestWaterfall
TestWaterfall
9
66
9
9
273076654888892c42c272066bce2ecf092b9c2e
bigcode/the-stack
train
517c4253f6022413276b6abe
train
class
class ShardedModel(models.Model): objects = ShardManager() class Meta: abstract = True
class ShardedModel(models.Model):
objects = ShardManager() class Meta: abstract = True
new sharded table. Keeps all indexes and unique together. """ try: with connections[db].cursor() as cursor: cursor.execute('CREATE TABLE IF NOT EXISTS %s LIKE %s;' % (destination_table, source_table)) except: pass class ShardedModel(models.Model):
64
64
23
7
56
rayhern/django-table-sharding
django_table_sharding/managers.py
Python
ShardedModel
ShardedModel
160
165
160
161
713962ea1418c6cc32bc0d9da56a7ed8aac918cb
bigcode/the-stack
train
aa95801ca95dd706cf755131
train
class
class ShardManager(models.Manager): def shard(self, table_suffix, db='default'): """ Use a shard of the table and set it to the model. Usage: Model.objects.shard(1).all() """ global THREAD_LOCK, FORK_LOCK meta = getattr(self.model, '_meta') db_table = '%s_%s_...
class ShardManager(models.Manager):
def shard(self, table_suffix, db='default'): """ Use a shard of the table and set it to the model. Usage: Model.objects.shard(1).all() """ global THREAD_LOCK, FORK_LOCK meta = getattr(self.model, '_meta') db_table = '%s_%s_%s' % ( str(meta.app_labe...
from django.db import connections from django.db import models from .utils import copy_model, chunks import random import datetime import traceback import threading import multiprocessing class ShardException(Exception): pass THREAD_LOCK = threading.Lock() FORK_LOCK = multiprocessing.Lock() # Specific model m...
84
256
1,150
7
77
rayhern/django-table-sharding
django_table_sharding/managers.py
Python
ShardManager
ShardManager
20
157
20
21
7d564c8928238a1e274fb422b932b9bc8bf2b07f
bigcode/the-stack
train
c62d4f4ce18b523a108a77b4
train
class
class ShardException(Exception): pass
class ShardException(Exception):
pass
from django.db import connections from django.db import models from .utils import copy_model, chunks import random import datetime import traceback import threading import multiprocessing class ShardException(Exception):
42
64
9
6
35
rayhern/django-table-sharding
django_table_sharding/managers.py
Python
ShardException
ShardException
11
12
11
11
8466655d795bd9f6a24ebb08a3d38c214291693f
bigcode/the-stack
train
2ab4a1eb04a9aaf39c70d2cf
train
function
def relu(x): """ .. todo:: WRITEME properly Rectified linear activation """ return T.max(0, x)
def relu(x):
""" .. todo:: WRITEME properly Rectified linear activation """ return T.max(0, x)
""" .. todo:: WRITEME """ import theano T = theano.tensor def identity(x): """ .. todo:: WRITEME properly Importable identity function. Created for the purposes of pickling. """ return x def relu(x):
61
64
34
5
55
BouchardLab/pylearn2
pylearn2/expr/activations.py
Python
relu
relu
21
29
21
21
82d5e0340868f35febfa0d55577006b5efde0f9a
bigcode/the-stack
train
772b13f768aad06e261c9d9f
train
function
def rescaled_softmax(x, min_val=1e-5): """ .. todo:: WRITEME """ return _rescale_softmax(T.nnet.softmax(x), min_val=min_val)
def rescaled_softmax(x, min_val=1e-5):
""" .. todo:: WRITEME """ return _rescale_softmax(T.nnet.softmax(x), min_val=min_val)
Avoid upcast to float64 when floatX==float32 and n_classes is int64 n_classes = n_classes.astype(theano.config.floatX) return sm * (1 - n_classes * min_val) + min_val def rescaled_softmax(x, min_val=1e-5):
64
64
46
15
48
BouchardLab/pylearn2
pylearn2/expr/activations.py
Python
rescaled_softmax
rescaled_softmax
44
50
44
44
b529871eaafc43f46e8600895eb4acda7d10421c
bigcode/the-stack
train
ec02936fdcac601f5a6a409f
train
function
def _rescale_softmax(sm, min_val): """ .. todo:: WRITEME """ n_classes = sm.shape[-1] # Avoid upcast to float64 when floatX==float32 and n_classes is int64 n_classes = n_classes.astype(theano.config.floatX) return sm * (1 - n_classes * min_val) + min_val
def _rescale_softmax(sm, min_val):
""" .. todo:: WRITEME """ n_classes = sm.shape[-1] # Avoid upcast to float64 when floatX==float32 and n_classes is int64 n_classes = n_classes.astype(theano.config.floatX) return sm * (1 - n_classes * min_val) + min_val
Importable identity function. Created for the purposes of pickling. """ return x def relu(x): """ .. todo:: WRITEME properly Rectified linear activation """ return T.max(0, x) def _rescale_softmax(sm, min_val):
64
64
84
11
53
BouchardLab/pylearn2
pylearn2/expr/activations.py
Python
_rescale_softmax
_rescale_softmax
32
41
32
32
fffecdc06c332663c5c037e0bbff520b00346c57
bigcode/the-stack
train
e6d742287413c1943b178f41
train
function
def identity(x): """ .. todo:: WRITEME properly Importable identity function. Created for the purposes of pickling. """ return x
def identity(x):
""" .. todo:: WRITEME properly Importable identity function. Created for the purposes of pickling. """ return x
""" .. todo:: WRITEME """ import theano T = theano.tensor def identity(x):
24
64
36
4
19
BouchardLab/pylearn2
pylearn2/expr/activations.py
Python
identity
identity
10
18
10
10
a2eb7117acef0dccd1608663d677d7cb1b80eb39
bigcode/the-stack
train
23533039a51988bca3c9cff9
train
class
class CommandTests(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create_user(username="patrick") @patch("stripe.Customer.retrieve") @patch("stripe.Customer.create") def test_init_customer_creates_customer(self, CreateMock, RetrieveMock): CreateMoc...
class CommandTests(TestCase):
def setUp(self): User = get_user_model() self.user = User.objects.create_user(username="patrick") @patch("stripe.Customer.retrieve") @patch("stripe.Customer.create") def test_init_customer_creates_customer(self, CreateMock, RetrieveMock): CreateMock.return_value.id = "cus_XXXXX"...
# pylint: disable=C0301 from django.core import management from django.test import TestCase from mock import patch from ..models import Customer from ..utils import get_user_model class CommandTests(TestCase):
46
143
478
6
39
adi-li/django-stripe-payments
payments/tests/test_commands.py
Python
CommandTests
CommandTests
11
54
11
12
eb602cb9b400f15a0c850246eb7cfdc1bdc5e2c9
bigcode/the-stack
train
5ef84715e9d569bb3f0eca54
train
function
def run(): if file_path == '': save_prompt = Toplevel() text = Label(save_prompt, text='Please save your code to rune it!') text.pack() return command = f'python {file_path}' process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True...
def run():
if file_path == '': save_prompt = Toplevel() text = Label(save_prompt, text='Please save your code to rune it!') text.pack() return command = f'python {file_path}' process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) outpu...
(filetypes=[('Python Files', '*.py')]) #TO save a file extension else: path = file_path with open(path, 'w') as file: code = editor.get('1.0', END) file.write(code) set_file_path(path) def run():
64
64
103
3
61
AnonymousAmatuer/MaplePython-Compiler
Python Compiler.py
Python
run
run
36
46
36
36
357954d1d34348142c1fabc50ff56adb6f1ec730
bigcode/the-stack
train
3451a30ee836c8d25d972f2a
train
function
def open_file(): path = askopenfilename(filetypes=[('Python Files', '*.py')]) with open(path, 'r') as file: code = file.read() editor.delete('1.0', END) editor.insert('1.0', code) set_file_path(path)
def open_file():
path = askopenfilename(filetypes=[('Python Files', '*.py')]) with open(path, 'r') as file: code = file.read() editor.delete('1.0', END) editor.insert('1.0', code) set_file_path(path)
ccesary things needed import subprocess compiler = Tk() compiler.title('Maple Python compiler') compiler.iconbitmap(r'C:\Users\User\Downloads\monitor_IZU_icon.ico') file_path = '' def set_file_path(path): global file_path file_path = path def open_file():
64
64
64
4
59
AnonymousAmatuer/MaplePython-Compiler
Python Compiler.py
Python
open_file
open_file
16
22
16
16
2d4cde475455325353df018f3bcad6a5b2e8fad9
bigcode/the-stack
train
702aa2661be7428c095b9a11
train
function
def set_file_path(path): global file_path file_path = path
def set_file_path(path):
global file_path file_path = path
tkinter.filedialog import asksaveasfilename, askopenfilename #neccesary things needed import subprocess compiler = Tk() compiler.title('Maple Python compiler') compiler.iconbitmap(r'C:\Users\User\Downloads\monitor_IZU_icon.ico') file_path = '' def set_file_path(path):
63
64
17
6
57
AnonymousAmatuer/MaplePython-Compiler
Python Compiler.py
Python
set_file_path
set_file_path
11
13
11
11
c6675a14c396ac876fbf91c4e93d03deb85c970b
bigcode/the-stack
train
a53d1219847c44ebe11acaa5
train
function
def save_as(): if file_path == '': path = asksaveasfilename(filetypes=[('Python Files', '*.py')]) #TO save a file extension else: path = file_path with open(path, 'w') as file: code = editor.get('1.0', END) file.write(code) set_file_path(path)
def save_as():
if file_path == '': path = asksaveasfilename(filetypes=[('Python Files', '*.py')]) #TO save a file extension else: path = file_path with open(path, 'w') as file: code = editor.get('1.0', END) file.write(code) set_file_path(path)
path = askopenfilename(filetypes=[('Python Files', '*.py')]) with open(path, 'r') as file: code = file.read() editor.delete('1.0', END) editor.insert('1.0', code) set_file_path(path) def save_as():
64
64
79
4
60
AnonymousAmatuer/MaplePython-Compiler
Python Compiler.py
Python
save_as
save_as
25
33
25
25
1a5e941bf0b412b97665e2cdc7f24e5b2c52afa8
bigcode/the-stack
train
1633876e7bf41758537180ef
train
class
class TellstickSwitch(TellstickDevice, ToggleEntity): """Representation of a Tellstick switch.""" def _parse_ha_data(self, kwargs): """Turn the value from HA into something useful.""" return None def _parse_tellcore_data(self, tellcore_data): """Turn the value received from tellcor...
class TellstickSwitch(TellstickDevice, ToggleEntity):
"""Representation of a Tellstick switch.""" def _parse_ha_data(self, kwargs): """Turn the value from HA into something useful.""" return None def _parse_tellcore_data(self, tellcore_data): """Turn the value received from tellcore into something useful.""" return None d...
ATTR_DISCOVER_CONFIG, DEFAULT_SIGNAL_REPETITIONS) add_devices(TellstickSwitch(tellcore_id, hass.data['tellcore_registry'], signal_repetitions) for tellcore_id in discovery_info[ATTR_DISCOVER_DEVICES]) class TellstickSwitch(...
64
64
192
12
52
jamescurtin/home-assistant
homeassistant/components/switch/tellstick.py
Python
TellstickSwitch
TellstickSwitch
34
59
34
34
e4f6b7a006d11904d6a4cb1465346e27f81c1622
bigcode/the-stack
train
6d3acb950baf6aca7c8dc8ad
train
function
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up Tellstick switches.""" if (discovery_info is None or discovery_info[ATTR_DISCOVER_DEVICES] is None): return # Allow platform level override, fallback to module config signal_repetitions = discovery_info.ge...
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up Tellstick switches.""" if (discovery_info is None or discovery_info[ATTR_DISCOVER_DEVICES] is None): return # Allow platform level override, fallback to module config signal_repetitions = discovery_info.get(ATTR_DISCOVER_CONFIG, ...
OVER_DEVICES, ATTR_DISCOVER_CONFIG, DOMAIN, TellstickDevice) from homeassistant.helpers.entity import ToggleEntity PLATFORM_SCHEMA = vol.Schema({vol.Required("platform"): DOMAIN}) # pylint: disable=unused-argument def set...
64
64
123
15
48
jamescurtin/home-assistant
homeassistant/components/switch/tellstick.py
Python
setup_platform
setup_platform
19
31
19
19
70f6ab5c806c2986b301e990e24ba423867f04d8
bigcode/the-stack
train
cf0b5c0fac64e1bf378515f8
train
function
def readme(): """Load the README file.""" with open('README.md') as f: return f.read()
def readme():
"""Load the README file.""" with open('README.md') as f: return f.read()
# -*- coding: utf-8 -*- '''This sets up the package. Stolen from http://python-packaging.readthedocs.io/en/latest/everything.html and modified by me. ''' __version__ = '0.1.0' from setuptools import setup, find_packages def readme():
64
64
26
4
59
dr-guangtou/asap
setup.py
Python
readme
readme
11
14
11
11
f9c4ea210316b52bcf66d43ca3ae401323bd4f5f
bigcode/the-stack
train
36d05a1f2c36ce3eea2a0679
train
function
def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """ Calculate great circle distance between two points in a sphere, given longitudes and latitudes https://en.wikipedia.org/wiki/Haversine_formula We know that the globe is "sort of" spherical, so a path between two po...
def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
""" Calculate great circle distance between two points in a sphere, given longitudes and latitudes https://en.wikipedia.org/wiki/Haversine_formula We know that the globe is "sort of" spherical, so a path between two points isn't exactly a straight line. We need to account for the Earth's curvature ...
from math import asin, atan, cos, radians, sin, sqrt, tan def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
45
188
629
28
16
JB1959/Python
geodesy/haversine_distance.py
Python
haversine_distance
haversine_distance
4
50
4
4
76bde4a05590d6017b39e038de04d951af970a68
bigcode/the-stack
train
8fb0df3548c86bcb34836979
train
function
def level_json(commits, head): # We've formally replicated the input string in memory level = { 'topology': [], 'branches': {}, 'tags': {}, 'commits': {}, 'HEAD': {}, } all_branches = [] all_tags = [] for commit_name, parents, branches_here, tags_here in...
def level_json(commits, head): # We've formally replicated the input string in memory
level = { 'topology': [], 'branches': {}, 'tags': {}, 'commits': {}, 'HEAD': {}, } all_branches = [] all_tags = [] for commit_name, parents, branches_here, tags_here in commits: level['topology'].append(commit_name) level['commits'][commit_nam...
branches.append(branch) all_branches.add(branch) commits.append((commit_name, parents, branches, tags)) head = commits[-1][0] del commits[-1] return commits, head def level_json(commits, head): # We've formally replicated the input string in memory
65
65
218
19
45
e-leclercq/git-gud
gitgud/skills/util.py
Python
level_json
level_json
82
122
82
84
d709272159372ec949d8218e0ef9760a2c01850e
bigcode/the-stack
train
1644f31bb0d6e24a2d8c949e
train
function
def get_topology(tree): tree['topology'] = None raise NotImplementedError
def get_topology(tree):
tree['topology'] = None raise NotImplementedError
import os from copy import deepcopy # TODO GitPython topology def get_topology(tree):
20
64
21
6
13
e-leclercq/git-gud
gitgud/skills/util.py
Python
get_topology
get_topology
7
9
7
7
2fcf8231ff3b2cc21c52aebf43ce4969367dbe5a
bigcode/the-stack
train
48e8d2676254911b95ae101d
train
function
def parse_spec(file_name): # The purpose of this method is to get a more computer-readable commit tree with open(file_name) as spec_file: spec = spec_file.read() commits = [] # List of (commit_name, [parents], [branches], [tags]) all_branches = set() all_tags = set() for line in spec....
def parse_spec(file_name): # The purpose of this method is to get a more computer-readable commit tree
with open(file_name) as spec_file: spec = spec_file.read() commits = [] # List of (commit_name, [parents], [branches], [tags]) all_branches = set() all_tags = set() for line in spec.split('\n'): if len(line) == 0 or line[0] == '#': # Last line or comment co...
import os from copy import deepcopy # TODO GitPython topology def get_topology(tree): tree['topology'] = None raise NotImplementedError def parse_spec(file_name): # The purpose of this method is to get a more computer-readable commit tree
58
137
459
23
34
e-leclercq/git-gud
gitgud/skills/util.py
Python
parse_spec
parse_spec
12
79
12
13
064675ef0064f8e33cd171a2728b523c2ddde053
bigcode/the-stack
train
ef5383563dd23d060bb6a98a
train
class
class Level: def __init__(self, name): self.name = name self.skill = None self.next_level = None self.prev_level = None def __repr__(self): return "<{class_name}: '{full_name}'>".format( class_name=type(self).__name__, full_name=self.full_name() ...
class Level:
def __init__(self, name): self.name = name self.skill = None self.next_level = None self.prev_level = None def __repr__(self): return "<{class_name}: '{full_name}'>".format( class_name=type(self).__name__, full_name=self.full_name() ) ...
_level = last_level last_level = level class Skill(NamedList): def __init__(self, name, levels): super().__init__([level.name for level in levels], levels) self.name = name for level in levels: level.skill = self class Level:
64
64
134
3
60
e-leclercq/git-gud
gitgud/skills/util.py
Python
Level
Level
262
288
262
262
d4251fea6cfc533419f36b0e3017bd1f33fdee2b
bigcode/the-stack
train
613dab7f2961e488c040a87d
train
function
def test_skill(skill, test): # We don't know the names of merges, so we match them with their test names # TODO Only works when merges don't have other merges as parents # TODO Topological sort merge commits skill = deepcopy(skill) merge_name_map = {} for commit_name in skill['commits']: ...
def test_skill(skill, test): # We don't know the names of merges, so we match them with their test names # TODO Only works when merges don't have other merges as parents # TODO Topological sort merge commits
skill = deepcopy(skill) merge_name_map = {} for commit_name in skill['commits']: skill_commit = skill['commits'][commit_name] if len(skill_commit['parents']) >= 2: # TODO Stop here to get list of merges for test_commit_name in test['commits']: # TODO Do this iteration in an int...
level['topology'].append(commit_name) level['commits'][commit_name] = { 'parents': parents, 'id': commit_name } all_branches.extend(branches_here) all_tags.extend(tags_here) for branch in branches_here: level['branches'][branch] = { ...
188
188
628
49
138
e-leclercq/git-gud
gitgud/skills/util.py
Python
test_skill
test_skill
125
193
125
128
71a00c541febdada61be295061c56d533e1376b7
bigcode/the-stack
train
d5cf7cac2b4e1ee9ab0dd47b
train
class
class NamedList: # names is a list populated with type str, items is a list populated with any type def __init__(self, names, items): assert len(names) == len(items) self._name_dict = {name: index for index, name in enumerate(names)} self._items = items def __getitem__(self, qu...
class NamedList: # names is a list populated with type str, items is a list populated with any type
def __init__(self, names, items): assert len(names) == len(items) self._name_dict = {name: index for index, name in enumerate(names)} self._items = items def __getitem__(self, query): if isinstance(query, str): if query.isnumeric(): if 0 < int(que...
_name not in skill['tags']: return False if skill['tags'][tag_name]['target'] != test['tags'][tag_name]['target']: return False # Check HEAD if skill['HEAD']['target'] != test['HEAD']['target']: return False return True class NamedList: # names is a list populat...
88
88
294
24
63
e-leclercq/git-gud
gitgud/skills/util.py
Python
NamedList
NamedList
196
236
196
197
9930d0a1349edd0d743f800d5f1e4a67daa53b94
bigcode/the-stack
train
13379d12c04f5229f41c65ca
train
class
class BasicLevel(Level): def __init__(self, name, path): super().__init__(name) self.path = path self.setup_spec_path = os.path.join(self.path, 'setup.spec') self.instructions_path = os.path.join(self.path, 'instructions.txt') self.goal_path = os.path.join(self.path, 'goal.tx...
class BasicLevel(Level):
def __init__(self, name, path): super().__init__(name) self.path = path self.setup_spec_path = os.path.join(self.path, 'setup.spec') self.instructions_path = os.path.join(self.path, 'instructions.txt') self.goal_path = os.path.join(self.path, 'goal.txt') self.test_spe...
repr__(self): return "<{class_name}: '{full_name}'>".format( class_name=type(self).__name__, full_name=self.full_name() ) def full_name(self): return '{} {}'.format(self.skill.name, self.name) def setup(self, file_operator): pass def instructions(se...
179
180
603
5
174
e-leclercq/git-gud
gitgud/skills/util.py
Python
BasicLevel
BasicLevel
301
379
301
301
b09b347299f0d7e1757212f6ec1c1c752162a66a
bigcode/the-stack
train
41683afa722da48e5dd1971d
train
function
def print_all_complete(): print("Wow! You've complete every level, congratulations!") print("If you want to keep learning git, why not try contributing" " to git-gud by forking the project at https://github.com/benthayer/git-gud/") print("We're always looking for contributions and are more than"...
def print_all_complete():
print("Wow! You've complete every level, congratulations!") print("If you want to keep learning git, why not try contributing" " to git-gud by forking the project at https://github.com/benthayer/git-gud/") print("We're always looking for contributions and are more than" " happy to acce...
() ) def full_name(self): return '{} {}'.format(self.skill.name, self.name) def setup(self, file_operator): pass def instructions(self): pass def goal(self): pass def test(self, file_operator): pass def print_all_complete():
64
64
81
5
58
e-leclercq/git-gud
gitgud/skills/util.py
Python
print_all_complete
print_all_complete
291
298
291
291
adeb10147c5569aca74b74607ee6ce4405d2dd36
bigcode/the-stack
train
f5afe6cc9c6a8dc7b3266508
train
class
class AllSkills(NamedList): def __init__(self, skills): super().__init__([skill.name for skill in skills], skills) last_level = None for skill in self: for level in skill: if last_level is not None: last_level.next_level = level ...
class AllSkills(NamedList):
def __init__(self, skills): super().__init__([skill.name for skill in skills], skills) last_level = None for skill in self: for level in skill: if last_level is not None: last_level.next_level = level level.prev_level = last_lev...
(self): return self._items def keys(self): set_indices = { str(i) for i in range(1, len(self) + 1) } set_names = set(self._name_dict.keys()) return set_indices | set_names class AllSkills(NamedList):
62
64
79
7
54
e-leclercq/git-gud
gitgud/skills/util.py
Python
AllSkills
AllSkills
240
249
240
240
d63b2b1b9148414611d0bc72df4b6eed2e1e5c1f
bigcode/the-stack
train
fc7cd0e525fe7693e2508c23
train
class
class Skill(NamedList): def __init__(self, name, levels): super().__init__([level.name for level in levels], levels) self.name = name for level in levels: level.skill = self
class Skill(NamedList):
def __init__(self, name, levels): super().__init__([level.name for level in levels], levels) self.name = name for level in levels: level.skill = self
([skill.name for skill in skills], skills) last_level = None for skill in self: for level in skill: if last_level is not None: last_level.next_level = level level.prev_level = last_level last_level = level class Skill(NamedL...
64
64
50
6
57
e-leclercq/git-gud
gitgud/skills/util.py
Python
Skill
Skill
253
259
253
253
ebf61731ff4eb93eee3a54e85387b78f156b6b57
bigcode/the-stack
train
6658c484043ebe92650837f7
train
class
class Pcc(Base): """Pcep Session (Device) level Configuration The Pcc class encapsulates a list of pcc resources that are managed by the user. A list of resources can be retrieved from the server using the Pcc.find() method. The list can be managed by using the Pcc.add() and Pcc.remove() methods. ...
class Pcc(Base):
"""Pcep Session (Device) level Configuration The Pcc class encapsulates a list of pcc resources that are managed by the user. A list of resources can be retrieved from the server using the Pcc.find() method. The list can be managed by using the Pcc.add() and Pcc.remove() methods. """ __sl...
Copyright 1997 - 2020 by IXIA Keysight # # 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, copy, modify, merge, publ...
256
256
12,741
5
250
rfrye-github/ixnetwork_restpy
ixnetwork_restpy/testplatform/sessions/ixnetwork/topology/pcc_9346785b55d17399fecd6fe36c418219.py
Python
Pcc
Pcc
26
1,173
26
26
95f242721cb5b419ed48bafb1ed5bf68813ff6db
bigcode/the-stack
train
c9be2b75072a68c1a7b72b34
train
function
def test_confirm_destructive_query_notty(): stdin = click.get_text_stream('stdin') assert stdin.isatty() is False sql = 'drop database foo;' assert confirm_destructive_query(sql) is None
def test_confirm_destructive_query_notty():
stdin = click.get_text_stream('stdin') assert stdin.isatty() is False sql = 'drop database foo;' assert confirm_destructive_query(sql) is None
# -*- coding: utf-8 -*- import click from pgcli.packages.prompt_utils import confirm_destructive_query def test_confirm_destructive_query_notty():
34
64
49
9
24
akshay-joshi/pgcli
tests/test_prompt_utils.py
Python
test_confirm_destructive_query_notty
test_confirm_destructive_query_notty
9
14
9
9
6c375494410e3fee49d553244508a0ff38675d80
bigcode/the-stack
train
2dc16c02b474294f07ce52dc
train
function
def test_mount_nfs_failure(mocker): _mock_popen(mocker, returncode=1) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') with pytest.raises(SystemExit) as ex: mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', DEFAULT_OPTIONS) assert 0 != ex.value.code ut...
def test_mount_nfs_failure(mocker):
_mock_popen(mocker, returncode=1) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') with pytest.raises(SystemExit) as ex: mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', DEFAULT_OPTIONS) assert 0 != ex.value.code utils.assert_not_called(optimize_reada...
args = args[0] assert DNS_NAME not in args[NFS_MOUNT_PATH_IDX] assert '127.0.0.1' in args[NFS_MOUNT_PATH_IDX] utils.assert_called_once(optimize_readahead_window_mock) def test_mount_nfs_failure(mocker):
64
64
94
9
55
openshift-bot/aws-efs-utils
test/mount_efs_test/test_mount_nfs.py
Python
test_mount_nfs_failure
test_mount_nfs_failure
104
113
104
104
21c35a986a9e4f0d1f47320b8715315f7c72d0e1
bigcode/the-stack
train
6fc3565121ed186ed0d53f56
train
function
def test_mount_nfs_tls_macos(mocker): mock = _mock_popen(mocker) mocker.patch('mount_efs.check_if_platform_is_mac', return_value=True) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') DEFAULT_OPTIONS['nfsvers'] = 4.0 options = dict(DEFAULT_OPTIONS) options['tl...
def test_mount_nfs_tls_macos(mocker):
mock = _mock_popen(mocker) mocker.patch('mount_efs.check_if_platform_is_mac', return_value=True) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') DEFAULT_OPTIONS['nfsvers'] = 4.0 options = dict(DEFAULT_OPTIONS) options['tls'] = None mount_efs.mount_nfs(CO...
[0] assert '/sbin/mount_nfs' == args[NFS_BIN_ARG_IDX] assert DNS_NAME in args[-2] assert '/mnt' == args[-1] utils.assert_called_once(optimize_readahead_window_mock) def test_mount_nfs_tls_macos(mocker):
64
64
174
11
53
openshift-bot/aws-efs-utils
test/mount_efs_test/test_mount_nfs.py
Python
test_mount_nfs_tls_macos
test_mount_nfs_tls_macos
171
187
171
171
df7ae0a5c30e32180f2c91e6e3eee8583d7ba7de
bigcode/the-stack
train
14ceb2cd153bb5b749640c4b
train
function
def test_mount_nfs_tls(mocker): mock = _mock_popen(mocker) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') options = dict(DEFAULT_OPTIONS) options['tls'] = None mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', options) args, _ = mock.call_args args =...
def test_mount_nfs_tls(mocker):
mock = _mock_popen(mocker) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') options = dict(DEFAULT_OPTIONS) options['tls'] = None mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', options) args, _ = mock.call_args args = args[0] assert DNS_NAME no...
assert DNS_NAME not in args[NFS_MOUNT_PATH_IDX] assert FALLBACK_IP_ADDRESS in args[NFS_MOUNT_PATH_IDX] assert '/mnt' == args[NFS_MOUNT_POINT_IDX] utils.assert_called_once(optimize_readahead_window_mock) def test_mount_nfs_tls(mocker):
64
64
136
9
55
openshift-bot/aws-efs-utils
test/mount_efs_test/test_mount_nfs.py
Python
test_mount_nfs_tls
test_mount_nfs_tls
86
101
86
86
a8ce97dc14e6d409a3a705e1058242b6d3bd0cac
bigcode/the-stack
train
7b19d900e0303e4c1403e283
train
function
def test_mount_tls_mountpoint_mounted_with_nfs(mocker, capsys): options = dict(DEFAULT_OPTIONS) options['tls'] = None bootstrap_tls_mock = mocker.patch('mount_efs.bootstrap_tls') optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') mocker.patch('os.path.ismount', ret...
def test_mount_tls_mountpoint_mounted_with_nfs(mocker, capsys):
options = dict(DEFAULT_OPTIONS) options['tls'] = None bootstrap_tls_mock = mocker.patch('mount_efs.bootstrap_tls') optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') mocker.patch('os.path.ismount', return_value=True) _mock_popen(mocker, stdout='nfs') mount_...
args[NFS_MOUNT_PATH_IDX + NETNS_NFS_OFFSET] assert '/mnt' in args[NFS_MOUNT_POINT_IDX + NETNS_NFS_OFFSET] utils.assert_called_once(optimize_readahead_window_mock) def test_mount_tls_mountpoint_mounted_with_nfs(mocker, capsys):
64
64
165
17
47
openshift-bot/aws-efs-utils
test/mount_efs_test/test_mount_nfs.py
Python
test_mount_tls_mountpoint_mounted_with_nfs
test_mount_tls_mountpoint_mounted_with_nfs
139
152
139
139
b40123afe1b7c16a210c22759b4d277570ce23f9
bigcode/the-stack
train
f8b6d1d4786bdf26732bc01f
train
function
def test_mount_nfs(mocker): mock = _mock_popen(mocker) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', DEFAULT_OPTIONS) args, _ = mock.call_args args = args[0] assert '/sbin/mount.nfs4' == args[NFS_BIN_ARG...
def test_mount_nfs(mocker):
mock = _mock_popen(mocker) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', DEFAULT_OPTIONS) args, _ = mock.call_args args = args[0] assert '/sbin/mount.nfs4' == args[NFS_BIN_ARG_IDX] assert DNS_NAME in...
='stdout', stderr='stderr'): popen_mock = MagicMock() popen_mock.communicate.return_value = (stdout, stderr, ) popen_mock.returncode = returncode return mocker.patch('subprocess.Popen', return_value=popen_mock) def test_mount_nfs(mocker):
64
64
133
8
56
openshift-bot/aws-efs-utils
test/mount_efs_test/test_mount_nfs.py
Python
test_mount_nfs
test_mount_nfs
53
66
53
53
4f68687e252b7abc583ffa8071acb3b213e541b9
bigcode/the-stack
train
ad3e9776348db09409c8bfc9
train
function
def _mock_popen(mocker, returncode=0, stdout='stdout', stderr='stderr'): popen_mock = MagicMock() popen_mock.communicate.return_value = (stdout, stderr, ) popen_mock.returncode = returncode return mocker.patch('subprocess.Popen', return_value=popen_mock)
def _mock_popen(mocker, returncode=0, stdout='stdout', stderr='stderr'):
popen_mock = MagicMock() popen_mock.communicate.return_value = (stdout, stderr, ) popen_mock.returncode = returncode return mocker.patch('subprocess.Popen', return_value=popen_mock)
to the NFS call for MACOS NFS_MOUNT_PATH_IDX_MACOS = -2 NFS_MOUNT_POINT_IDX_MACOS = -1 NETNS = '/proc/1/net/ns' def _mock_popen(mocker, returncode=0, stdout='stdout', stderr='stderr'):
64
64
70
21
43
openshift-bot/aws-efs-utils
test/mount_efs_test/test_mount_nfs.py
Python
_mock_popen
_mock_popen
45
50
45
45
3130499c17d780ca9300d08a89a80daf18884f1d
bigcode/the-stack
train
664a637f70dbd7cd6b33aaee
train
function
def test_mount_nfs_with_fallback_ip_address(mocker): mock = _mock_popen(mocker) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', DEFAULT_OPTIONS, fallback_ip_address=FALLBACK_IP_ADDRESS) args, _ = mock.call_args ...
def test_mount_nfs_with_fallback_ip_address(mocker):
mock = _mock_popen(mocker) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', DEFAULT_OPTIONS, fallback_ip_address=FALLBACK_IP_ADDRESS) args, _ = mock.call_args args = args[0] assert '/sbin/mount.nfs4' == arg...
fs4' == args[NFS_BIN_ARG_IDX] assert DNS_NAME in args[NFS_MOUNT_PATH_IDX] assert '/mnt' == args[NFS_MOUNT_POINT_IDX] utils.assert_called_once(optimize_readahead_window_mock) def test_mount_nfs_with_fallback_ip_address(mocker):
64
64
164
13
51
openshift-bot/aws-efs-utils
test/mount_efs_test/test_mount_nfs.py
Python
test_mount_nfs_with_fallback_ip_address
test_mount_nfs_with_fallback_ip_address
69
83
69
69
23c1d168dc30df5dcf1940d3f43f1eb9b15f47ea
bigcode/the-stack
train
86bf7f33fca18793cff7cd20
train
function
def test_mount_nfs_macos(mocker): mock = _mock_popen(mocker) mocker.patch('mount_efs.check_if_platform_is_mac', return_value=True) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') DEFAULT_OPTIONS['nfsvers'] = 4.0 mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', ...
def test_mount_nfs_macos(mocker):
mock = _mock_popen(mocker) mocker.patch('mount_efs.check_if_platform_is_mac', return_value=True) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') DEFAULT_OPTIONS['nfsvers'] = 4.0 mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', DEFAULT_OPTIONS) args, _ = mo...
, FS_ID, MOUNT_POINT, options) out, err = capsys.readouterr() assert 'is already mounted' in out utils.assert_not_called(bootstrap_tls_mock) utils.assert_not_called(optimize_readahead_window_mock) def test_mount_nfs_macos(mocker):
64
64
158
10
54
openshift-bot/aws-efs-utils
test/mount_efs_test/test_mount_nfs.py
Python
test_mount_nfs_macos
test_mount_nfs_macos
155
169
155
155
967180964bad7476e988ef207d7c922fd593d71a
bigcode/the-stack
train
abdc5abbf6284ce1d0ad81b7
train
function
def test_mount_nfs_tls_netns(mocker): mock = _mock_popen(mocker) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') options = dict(DEFAULT_OPTIONS) options['tls'] = None options['netns'] = NETNS mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', options) ...
def test_mount_nfs_tls_netns(mocker):
mock = _mock_popen(mocker) optimize_readahead_window_mock = mocker.patch('mount_efs.optimize_readahead_window') options = dict(DEFAULT_OPTIONS) options['tls'] = None options['netns'] = NETNS mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', options) args, _ = mock.call_args args = ar...
mount_efs.optimize_readahead_window') with pytest.raises(SystemExit) as ex: mount_efs.mount_nfs(CONFIG, DNS_NAME, '/', '/mnt', DEFAULT_OPTIONS) assert 0 != ex.value.code utils.assert_not_called(optimize_readahead_window_mock) def test_mount_nfs_tls_netns(mocker):
71
71
238
11
60
openshift-bot/aws-efs-utils
test/mount_efs_test/test_mount_nfs.py
Python
test_mount_nfs_tls_netns
test_mount_nfs_tls_netns
116
136
116
116
399fb0cd69aa2141f3741d7a6c8f67f480e3be0d
bigcode/the-stack
train