[Enhance] Few-shot design
Closed this issue · 6 comments
UniverseFly commented
We want to cherry-pick python seed snippets that cover a diverse range of coding concepts and programming features as our few-shot examples
UniverseFly commented
What we have already:
value = int(round((value - prev) * 1e5))
value = ~(value << 1) if value < 0 else (value << 1)
chunks = _split_into_chunks(value)
return (chr(chunk + 63) for chunk in chunks)
def _split_into_chunks(value):
while value >= 32: # 2^5, while there are at least 5 bits
# first & with 2^5-1, zeros out all the bits other than the first five
# then OR with 0x20 if another bit chunk follows
yield (value & 31) | 0x20
value >>= 5
def ceil_shift(n, b):
"""Return ceil(n / 2**b) without performing any floating-point or division operations.
This is done by right-shifting n by b bits and incrementing the result by 1
if any '1' bits were shifted out.
"""
if not isinstance(n, int) or not isinstance(b, int):
raise TypeError("unsupported operand type(s): %r and %r" % (type(n).__name__, type(b).__name__))
assert n >= 0 and b >= 0 # I haven't tested or even thought about negative values
mask = (1 << b) - 1
if n & mask:
return (n >> b) + 1
else:
isprime = n >= 2 and 1 or 0
for prime in prime_list: # Check for factors with all primes
if prime * prime > n: break # ... up to sqrt(n)
if not n % prime:
isprime = 0
break
if isprime: prime_dict[n] = 1 # Maintain a dictionary for fast lookup
return isprime
def prime(x):
''' Returns the xth prime '''
lastn = prime_list[-1]
while len(prime_list) <= x: # Keep working until we've got the xth prime
lastn = lastn + 1 # Check the next number
return (a + 1) * (b + 1) - 1
def keys_count(a, b):
return powerset(a, b) * 2 - a - b
def formula(k):
if k % 2 != 0:
return ((k + 1) ** 2) / 2 + k + 1
else:
return (k ** 2) / 2 + 2 * k + 1
def multiset_powerset(multiset):
n = len(multiset)
c = [0] * n
while True:
changed = False
i = n - 1
while i >= 0 and not changed:
while left<len(arr) and ryt >= start and left <= ryt:
mid = (left+ryt)//2
if arr[mid] == target:
return mid
elif arr[mid] > target:
ryt = mid-1
else:
left = mid+1
return left
def tripletsSorting(nums, t):
# TimeComplexity = O((n^2)logn)
nums.sort()
count = 0
for i in range(len(nums)):
def decompress(self):
source = self.compressed
if isinstance(source, (bytes, bytearray)):
return self.decompress_bytes()
pos = 0
node = self.root
res = bytearray()
while pos < len(source):
code = int(source[pos])
child = node.children[code]
if child.is_leaf:
res.append(child)
node = self.root
else:
node = child
pos += 1
return bytes(res)
def format_size(num):
"""http://stackoverflow.com/a/1094933
"""
for x in ['bytes', 'KB', 'MB', 'GB']:
if num < 1024.0 and num > -1024.0:
return "%3.1f%s" % (num, x)
num /= 1024.0
return "%3.1f%s" % (num, 'TB')
assert format_size(1024**2 - 1) == '1024.0KB'
assert format_size(1024*512) == '512.0KB'
def unify_stringlist(L: list):
""" Adds asterisks to strings that appear multiple times, so the resulting
list has only unique strings but still the same length, order, and meaning.
For example:
unify_stringlist(['a','a','b','a','c']) -> ['a','a*','b','a**','c']
"""
assert(all([isinstance(l,str) for l in L]))
return [L[i]+"*"*L[:i].count(L[i]) for i in range(len(L))]
assert unify_stringlist(list("abc")) == list("abc")
def _create_folds_list(data, count):
"""
Creates folds from the given data.
:param data: the data to fold
:param count: the number of folds to create
:return: a list of folds
"""
fold_count = len(data) / count
folds = list()
for fold_index in range(count):
low = int(fold_index * fold_count)
high = int((fold_index + 1) * fold_count)
fold = data[low:high]
folds.append(fold)
return folds
New examples to pick from:
import math
def alt2temp(h, mmHg=29.92):
if mmHg != 29.92:
dh = ((8.95e10 * 288.15) /
(-32.174 * 28.964) *
math.log(mmHg / 29.92))
h += dh
To = 518.69
if h > 36089:
T = 389.99
else:
T = To * (1 - 6.87559e-6 * h)
return T
IMPOSSIBLE = "impossible"
THRESHOLD = 100L
def multiplier(a, b):
difference = a - b
multiplier = (difference / b) + 1
return multiplier
def answer(M, F):
step = 0L
mach = long(M)
facula = long(F)
try:
if mach == facula or mach <= 0L or facula <= 0L:
raise ValueError('Incorrect number of bomb types encountered')
while True:
if mach <= 0L or facula <= 0L:
raise ValueError('Zero or less bomb types encountered')
# optimize for large integers
if mach > THRESHOLD or facula > THRESHOLD:
if mach > facula:
mul = multiplier(mach, facula)
mach -= facula * mul
step += mul
elif facula > mach:
mul = multiplier(facula, mach)
facula -= mach * mul
step += mul
else:
raise StopIteration('Same number of bomb types encountered')
else:
if mach > facula:
mach -= facula
elif facula > mach:
facula -= mach
else:
raise StopIteration('Same number of bomb types encountered')
step += 1L
except:
pass
if mach == 1L and facula == 1L and step >= 0:
return str(step)
else:
return IMPOSSIBLE
from collections import Counter
class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
return sum(k for k, v in Counter(nums).items() if v == 1)
def busca_linear_recursiva(array,elemento):
i = -1
return busca_recursiva(array,elemento, i)
def busca_recursiva(array,elemento, i):
i += 1
if(i == len(array)):
return -1
if(array[i] == elemento):
return i
return busca_recursiva(array,elemento,i)
def test_misc():
""" Test misc private methods for Transform.
"""
# Check that passing neither a mapping, nor an inverse_mapping raises
# a ValueError
yield assert_raises, ValueError, Transform, 'world1', 'world2'
transform = Transform('in', 'out', mapping=mapping)
# Check that the repr does not raise an error:
yield assert_true, isinstance(repr(transform), str)
# Check that copy and eq work
yield assert_equal, transform, copy.copy(transform)
await i2c.register_i2c_device(var, config)
for d in ["x", "y", "z"]:
accel_key = f"accel_{d}"
if accel_key in config:
sens = await sensor.new_sensor(config[accel_key])
cg.add(getattr(var, f"set_accel_{d}_sensor")(sens))
accel_key = f"gyro_{d}"
if accel_key in config:
sens = await sensor.new_sensor(config[accel_key])
cg.add(getattr(var, f"set_gyro_{d}_sensor")(sens))
if CONF_TEMPERATURE in config:
sens = await sensor.new_sensor(config[CONF_TEMPERATURE])
cg.add(var.set_temperature_sensor(sens))
def get_param_groups(network):
""" get param groups """
decay_params = []
no_decay_params = []
for x in network.trainable_params():
parameter_name = x.name
if parameter_name.endswith(".weight"):
# Dense or Conv's weight using weight decay
decay_params.append(x)
else:
# all bias not using weight decay
# bn weight bias not using weight decay, be carefully for now x not include LN
no_decay_params.append(x)
return [{'params': no_decay_params, 'weight_decay': 0.0}, {'params': decay_params}]
if pressed[pygame.K_UP]:
square.rect.y-=5
if pressed[pygame.K_RIGHT]:
square.rect.x+=5
if pressed[pygame.K_DOWN]:
square.rect.y+=5
surface.fill((0,0,0)) #fill surface with black
square.draw()
#Move and draw all the bullets
for b in bullets:
b.rect.x += b.dx
b.rect.y += b.dy
b.draw()
pygame.display.flip()
#Delay to get 30 fps
clock.tick(30)
pygame.quit()
def alternatingCharacters(s):
i = 0
j = 1
count = 0
while j<len(s):
if s[j] == s[i]:
while j<len(s) and s[j] == s[i]:
j+=1
count += j-i-1
i = j
j += 1
return count
# Push all characters of string to stack
for i in range(0,n,1):
push(stack,string[i])
# Making the string empty since all characters are saved in stack
string=""
# Pop all characters of string and put them back to string
for i in range(0,n,1):
string+=pop(stack)
return string
n = int(input())
for i in range(0,n):
str1 = input()
str2 = reverse(str1)
print(str2)
fp=open('cmd.sh','r')
lines=fp.readlines()
for i,line in enumerate(lines):
cmd=line.replace('\n','')
print i,cmd
p=os.popen(cmd)
x=p.read()
p.close()
fp.close
def solve(h, m):
if m == 0:
h_diff = 24 - h
m_diff = 0
else:
h_diff = 23 - h
m_diff = 60 - m
return (h_diff * 60) + m_diff
if __name__ == "__main__":
t = int(raw_input())
results = list()
for _ in xrange(0, t):
h, m = map(int, raw_input().split(" "))
results.append(solve(h, m))
for result in results:
print result
# Echo client program
import socket
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 7778))
s.send('ONE\n')
s.close()
data1 = s.recv(1024)
print 'Received data1', repr(data1)
class Restaurant():
def __init__(self, name, cuisine_type):
self.name = name.title()
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
msg = f"{self.name} tiene los mejores {self.cuisine_type}."
print(f"\n{msg}")
def open_restaurant(self):
msg = f"{self.name} Está Abierta. ¡Adelante! \n"
print(f"\n{msg}")
def set_number_served(self, number_served):
self.number_served = number_served #Aquí establecemos la cantidad de clientes atendidos
def increment_number_served(self, additional_served):
self.number_served += additional_served #Aquí incrementamos la cantidad de clientes atendidos
def tool_remove(args, area):
if len(args) < 1:
SCRAM.scramfatal("No tool name given: see \"scram tool -help\" for usage info.")
toolname = args[0].lower()
toolmanager = ToolManager(area)
if not toolmanager.hastool(toolname):
SCRAM.scramerror(">>>> Tool %s is not defined for this project area. <<<<" % toolname)
SCRAM.printmsg("Removing tool %s from current project area configuration." % toolname)
toolmanager.remove_tool(toolname)
return True
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
import json
def get_jsonparsed_data(url):
response = urlopen(url)
data = response.read().decode("utf-8")
return json.loads(data)
def get_metadata():
url = "http://169.254.169.254/opc/v1/instance/"
return get_jsonparsed_data(url)
reduced_mass_sum = 0
for element_a, element_b in combinations(comp.keys(), 2):
element_a, element_b = element_a.symbol, element_b.symbol
reduced_mass = element_masses[element_a] * element_masses[element_b] / \
(element_masses[element_a] + element_masses[element_b])
weight = comp[element_a] + comp[element_b]
reduced_mass_sum += weight * reduced_mass
reduced_mass_sum /= (len(comp) - 1) * natom
vol = mp_entry.data['volume'] / natom
gdelta = (
(-2.48e-4 * log(vol) - 8.94e-5 * reduced_mass_sum / vol) * temperature
+ 0.181 * log(temperature) - 0.882
)
refs = 0
for element, fraction in comp.items():
refs += element_g_interp[element.symbol](temperature) * fraction / natom
return dhf + gdelta - refs
def fib(limit):
nums = []
current, nxt = 0, 1
while len(nums) < limit:
current, nxt = nxt, current + nxt
nums.append(current)
return nums
def reverse_bisect(scores, value):
low, high = 0, len(scores)
while low < high:
mid = (low + high) // 2
if value > scores[mid]:
high = mid
else:
low = mid + 1
return low
if __name__ == "__main__":
arr = [5, 4, 2, 2, 1, 0]
op = reverse_bisect(arr, 3)
print(op)
def _depth(d: dict, depth: int = 0) -> int:
if not isinstance(d, MutableMapping):
return depth
max_depth = depth
for key in d:
max_depth = max(max_depth, _depth(d[key], depth + 1))
return max_depth
def duration(string):
match = re.match(PATTERN, string)
if not match:
raise ValueError('Invalid duration: {}'.format(string))
suffix = match.group(2)
if suffix not in SUFFIX_MAP:
raise ValueError('Invalid duration suffix: {}'.format(string))
return int(match.group(1)) * SUFFIX_MAP[suffix]
l.protocol_version = ldap.VERSION3
l.simple_bind_s(bindDN, bindPW)
res = l.search_s(base, scope, filter)
l.unbind_s()
if len(res)==0:
print "%s not found" % attrVal
sys.exit(1)
if len(res)>1:
print "Non deterministic uid. Found:"
for tup in res:
print "\t%s" % tup[0]
sys.exit(2)
dn = res[0][0]
# IF ONLY 1 MATCH IS FOUND: PRINT DN AND BIND AS THAT USER WITH THE DN
print "Binding as: %s" % dn
l = ldap.initialize("%s://%s:%s" % (protocol, host, port))
l.protocol_version = ldap.VERSION3
l.simple_bind_s(dn, userPassword)
if (reg_lambda < min_reg_lambda):
reg_lambda = i_rl
# logging.info("reset reg_lambda: %f to %f" % (reg_lambda, i_rl))
p_loss = c_loss
# logging.info('save model: %s' % (output))
model.save(output)
epoch += 1
if (epoch % epoch_delta == 0 and callback is not None):
callback()
import sys
from pathlib import Path
source = sys.argv[1]
destination = sys.argv[2]
timespan_start = sys.argv[3]
timespan_end = sys.argv[4]
print(sys.argv)
print(f'Running script, called with source: {source}, destination: {destination}')
print(f'timespan_start: {timespan_start}, timespan_end: {timespan_end}')
with open(Path(destination) / "output.txt", "w+") as dest:
for f in Path(source).glob("**/*"):
if f.is_dir():
continue
with open(f) as src:
lines = [line.upper() for line in src.readlines()]
print(lines)
dest.writelines(lines)
def oxford_comma_text_to_list(phrase):
"""Examples:
- 'Eeeny, Meeny, Miney, and Moe' --> ['Eeeny', 'Meeny', 'Miney', 'Moe']
- 'Black and White' --> ['Black', 'White']
- 'San Francisco and Saint Francis' -->
['San Francisco', 'Saint Francisco']
"""
items = []
for subphrase in phrase.split(', '):
items.extend(
[item.strip() for item in subphrase.split(' and ')])
return items
if best_dev_key is not None:
best_test_key = best_dev_key.replace('_dev', '')
best_test_path = key_to_path[best_test_key]
res = path_to_results(best_test_path)
results += [res[metric]]
print(f'd={d} rank={rank} & ' + " & ".join([f'{r:.3f}' for r in results]))
if __name__ == '__main__':
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
main(sys.argv[1:])
utility = proportionally_fair()
solve_num_problem(utility, R, capacity)
def test_large_weights(self):
w = [1.,20.]
R = [[1,1]]
c = [10]
solve_num_problem(weighted_log(w), R, c)
def test_x0(self):
R = [[1,1]]
c = [10]
solve_num_problem(proportionally_fair(), R, c, x0=[1,2])
if __name__ == '__main__':
unittest.main()
9
for step in range(STEPS):
for sstep in range(stepsPerStep):
hx = halton(indexH, 3)
hy = halton(indexH, 5)
indexH += 1
x = math.floor(hx * ITEMS_PER_ROW) * ITEM_W
y = math.floor(hy * ITEMS_PER_COL) * ITEM_H
x0 = stepW * (STEPS-1)
for ssstep in range(sssteps):
# draw box at x+x0,y
img = Image.new("RGB", (ITEM_W, ITEM_H), "white")
imageBase.paste(img, (int(x+x0), int(y)))
x0 -= stepW
sssteps -= 1
stepsPerStep = int(stepVelocity * stepsPerStep)
import os
import sysconfig
import sys
def distutils_dir_name(dname):
"""Returns the name of a distutils build directory"""
f = "{dirname}.{platform}-{version[0]}.{version[1]}"
return f.format(dirname=dname,
platform=sysconfig.get_platform(),
version=sys.version_info)
print(os.path.join('build', distutils_dir_name('lib')), end = '')
def handleCommands(self):
for module in self.modules:
module.parse(self.config)
self.config.checkOptions()
if self.config.getOption('showHelp'):
self.config.getParser().print_help()
elif self.config.getOption('showCommands'):
self.getCommands()
else:
commands = self.config.getArgs().command
if len(commands) == 0: commands = ['run']
for command in commands:
if self.execCommand(command) != 0: return 1
return 0
def get_hashes(buf):
hexdigests = namedtuple('Digests', 'md5 sha1 sha256 sha512 ctph')
if isinstance(buf, str):
buf = open(buf, 'rb').read()
md5 = hashlib.md5(buf).hexdigest()
sha1 = hashlib.sha1(buf).hexdigest()
sha256 = hashlib.sha256(buf).hexdigest()
sha512 = hashlib.sha512(buf).hexdigest()
ctph = ssdeep.hash(buf)
return hexdigests._make((md5, sha1, sha256, sha512, ctph))
def test_clip_multichan():
"""
Image channel 1 will be values from 0.005 to 0.5,
Plane 2 from 0.505 to 1
After clipping the 95th the max values should be:
0.95/2
and 0.95/2+0.5
"""
perc = 0.95
maxvals = (0.95 / 2, 0.95 / 2 + 0.5)
img = np.reshape(np.arange(1, 201.0) / 200, (10, 10, 2), order="F")
workspace, module = make_workspace(img, perc)
module.run(workspace)
result = workspace.image_set.get_image(OUTPUT_IMAGE_NAME).pixel_data
np.testing.assert_almost_equal(result.max(axis=(0, 1)), maxvals)
def even_odd ():
number = float(input("Enter a number: "))
if number % 2 == 0:
print(f"{number} is an even number")
elif number % 2 == 1:
print(f"{number} is an odd number")
else:
print(f"{number} is neither even nor odd")
even_odd()
class Solution:
def isIdealPermutation(self, A):
"""
:type A: List[int]
:rtype: bool
"""
size, m = len(A), 0
for i in range(size - 2):
m = max(m, A[i])
if m > A[i + 2]:
return False
return True
bn_training = [self.training] * self.get_num_batchnorms()
if do_training is None:
do_training = self.training
out = self.conv_blocks(
x, params=params, buffers=buffers, bn_training=bn_training, do_training=do_training, no_grad_hint_mask=no_grad_hint_mask[1:])
out = out.view(out.size(0),-1)
return out
def create_model(opt):
return ConvNet(opt)
masker = get_masker(mask_img=mask_img, target_affine=target_affine)
articles = coordinates.groupby("pmid")
for i, (pmid, coord) in enumerate(articles):
print(
"{:.1%} pmid: {:< 20}".format(i / len(articles), pmid),
end="\r",
flush=True,
)
img = gaussian_coord_smoothing(
coord.loc[:, ["x", "y", "z"]].values, fwhm=fwhm, mask_img=masker
)
yield pmid, img
# Method 1
# For loop
def reverseArray_1(a):
b = []
for i in a:
b.insert(0, i)
return b
# Method 2
# Copies the list prior to reversing it
def reverseArray_2(a):
return a[::-1]
# Method 3
# The fastest way to reverse a long list
def reverseArray_3(a):
a = a.reverse()
return a
a = [1, 4, 3, 2]
print (reverseArray_1(a))
print (reverseArray_2(a))
reverseArray_3(a)
print(a)
def couldUseDomain(self, domain):
useTLD = False
for tld in tlds:
if domain.endswith(tld):
useTLD = True
break
if not useTLD:
return False
label = domain.split('.', 1)[0]
if 'z' in label:
return False
return not any(char.isdigit() for char in domain)
# O(n) time | O(1) space
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def findLoop(head):
if not head and not head.next:
return None
slowPtr, fastPtr = head.next, head.next.next
while slowPtr != fastPtr:
slowPtr = slowPtr.next
fastPtr = fastPtr.next.next
fastPtr = head
while fastPtr != slowPtr:
slowPtr = slowPtr.next
fastPtr = fastPtr.next
return fastPtr
UniverseFly commented
UniverseFly commented
Requirements
- 30 few-shot examples in total (besides the 9 existing snippets we need to choose 21 out of 39 given examples)
- should cover diverse language features (dict/list/string/set) in a hopefully balanced way
- at least two I/O format
- anything else?
natedingyifeng commented
I pick the following 7 snippets:
def get_param_groups(network):
""" get param groups """
decay_params = []
no_decay_params = []
for x in network.trainable_params():
parameter_name = x.name
if parameter_name.endswith(".weight"):
# Dense or Conv's weight using weight decay
decay_params.append(x)
else:
# all bias not using weight decay
# bn weight bias not using weight decay, be carefully for now x not include LN
no_decay_params.append(x)
return [{'params': no_decay_params, 'weight_decay': 0.0}, {'params': decay_params}]
def alternatingCharacters(s):
i = 0
j = 1
count = 0
while j<len(s):
if s[j] == s[i]:
while j<len(s) and s[j] == s[i]:
j+=1
count += j-i-1
i = j
j += 1
return count
def oxford_comma_text_to_list(phrase):
"""Examples:
- 'Eeeny, Meeny, Miney, and Moe' --> ['Eeeny', 'Meeny', 'Miney', 'Moe']
- 'Black and White' --> ['Black', 'White']
- 'San Francisco and Saint Francis' -->
['San Francisco', 'Saint Francisco']
"""
items = []
for subphrase in phrase.split(', '):
items.extend(
[item.strip() for item in subphrase.split(' and ')])
return items
# O(n) time | O(1) space
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def findLoop(head):
if not head and not head.next:
return None
slowPtr, fastPtr = head.next, head.next.next
while slowPtr != fastPtr:
slowPtr = slowPtr.next
fastPtr = fastPtr.next.next
fastPtr = head
while fastPtr != slowPtr:
slowPtr = slowPtr.next
fastPtr = fastPtr.next
return fastPtr
import os
import sysconfig
import sys
def distutils_dir_name(dname):
"""Returns the name of a distutils build directory"""
f = "{dirname}.{platform}-{version[0]}.{version[1]}"
return f.format(dirname=dname,
platform=sysconfig.get_platform(),
version=sys.version_info)
print(os.path.join('build', distutils_dir_name('lib')), end = '')
def get_hashes(buf):
hexdigests = namedtuple('Digests', 'md5 sha1 sha256 sha512 ctph')
if isinstance(buf, str):
buf = open(buf, 'rb').read()
md5 = hashlib.md5(buf).hexdigest()
sha1 = hashlib.sha1(buf).hexdigest()
sha256 = hashlib.sha256(buf).hexdigest()
sha512 = hashlib.sha512(buf).hexdigest()
ctph = ssdeep.hash(buf)
return hexdigests._make((md5, sha1, sha256, sha512, ctph))
class Solution:
def isIdealPermutation(self, A):
"""
:type A: List[int]
:rtype: bool
"""
size, m = len(A), 0
for i in range(size - 2):
m = max(m, A[i])
if m > A[i + 2]:
return False
return True
natedingyifeng commented
I further pick 2 more:
def fib(limit):
nums = []
current, nxt = 0, 1
while len(nums) < limit:
current, nxt = nxt, current + nxt
nums.append(current)
return nums
class Restaurant():
def __init__(self, name, cuisine_type):
self.name = name.title()
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
msg = f"{self.name} tiene los mejores {self.cuisine_type}."
print(f"\n{msg}")
def open_restaurant(self):
msg = f"{self.name} Está Abierta. ¡Adelante! \n"
print(f"\n{msg}")
def set_number_served(self, number_served):
self.number_served = number_served #Aquí establecemos la cantidad de clientes atendidos
def increment_number_served(self, additional_served):
self.number_served += additional_served #Aquí incrementamos la cantidad de clientes atendidos
natedingyifeng commented
Add Example 15&16 in commit 549e600