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
5839212463a5ba7aa8fa5dfd
train
function
def updateMsgs(client, message,redis): pass
def updateMsgs(client, message,redis):
pass
Markup, InlineKeyboardButton import threading, requests, time, random, re, json import importlib from uuid import uuid4 from pyrogram.types import ( InlineQueryResultArticle, InputTextMessageContent, InlineKeyboardMarkup, InlineKeyboardButton ) def updateMsgs(client, message,redis):
64
64
12
9
55
Tshakel/AEK1-files
xo.py
Python
updateMsgs
updateMsgs
18
19
18
18
cb8214db7f756a2bd93c42afcd4a3ed86fdde8e6
bigcode/the-stack
train
c1a7cef2b843ebe45bd342a3
train
function
def getwin(tb): winners=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)) win = False xo = "no" for ar in winners: if tb[ar[0]] == 1 and tb[ar[1]] == 1 and tb[ar[2]] ==1: win = True xo = tb[ar[0]] break if tb[ar[0]] == 2 and tb[ar[1]] == 2 and tb[ar[2]] ==2: win =...
def getwin(tb):
winners=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)) win = False xo = "no" for ar in winners: if tb[ar[0]] == 1 and tb[ar[1]] == 1 and tb[ar[2]] ==1: win = True xo = tb[ar[0]] break if tb[ar[0]] == 2 and tb[ar[1]] == 2 and tb[ar[2]] ==2: win = True xo =...
: t += "❌ " if n == 2: t += "⭕️ " i += 1 if i == 3: tx += "\n"+t t = "" i = 0 return tx def getwin(tb):
64
64
199
5
58
Tshakel/AEK1-files
xo.py
Python
getwin
getwin
39
56
39
39
1605d5be6960211b4f883bfd37d6ff0289aa960c
bigcode/the-stack
train
339503862659e20a1b3202bc
train
function
def updateCb(client, callback_query,redis): if callback_query.inline_message_id: return False date = callback_query.data userID = callback_query.from_user.id userFN = callback_query.from_user.first_name username = callback_query.from_user.username chatID = callback_query.message.chat.id message_id = c...
def updateCb(client, callback_query,redis):
if callback_query.inline_message_id: return False date = callback_query.data userID = callback_query.from_user.id userFN = callback_query.from_user.first_name username = callback_query.from_user.username chatID = callback_query.message.chat.id message_id = callback_query.message.message_id go = """{...
1 and tb[ar[1]] == 1 and tb[ar[2]] ==1: win = True xo = tb[ar[0]] break if tb[ar[0]] == 2 and tb[ar[1]] == 2 and tb[ar[2]] ==2: win = True xo = tb[ar[0]] break if win == False and 0 not in tb: win = True xo = "tie" return win,xo def get(client,userID,userFN,...
256
256
1,915
10
245
Tshakel/AEK1-files
xo.py
Python
updateCb
updateCb
78
244
78
78
096319850e142d883725adf556e9fa92852bc97d
bigcode/the-stack
train
b9a00d46583b2e2b8d512b92
train
function
def get(client,userID,userFN,p1,p2): if userID == int(p1): fn1 = userFN else: try: getUser = client.get_users(int(p1)) fn1 = getUser.first_name except Exception as e: fn1 = p1 if userID == int(p2): fn2 = userFN else: try: getUser = client.get_users(int(p2)) fn2 ...
def get(client,userID,userFN,p1,p2):
if userID == int(p1): fn1 = userFN else: try: getUser = client.get_users(int(p1)) fn1 = getUser.first_name except Exception as e: fn1 = p1 if userID == int(p2): fn2 = userFN else: try: getUser = client.get_users(int(p2)) fn2 = getUser.first_name except Excep...
2]] ==2: win = True xo = tb[ar[0]] break if win == False and 0 not in tb: win = True xo = "tie" return win,xo def get(client,userID,userFN,p1,p2):
64
64
130
12
51
Tshakel/AEK1-files
xo.py
Python
get
get
60
77
60
60
96e1f2940c62d793e378129aec761e5c26540797
bigcode/the-stack
train
ca54d608f036ddf65374cacd
train
class
class ThePlatformFeedIE(ThePlatformBaseIE): _URL_TEMPLATE = '%s//feed.theplatform.com/f/%s/%s?form=json&%s' _VALID_URL = r'https?://feed\.theplatform\.com/f/(?P<provider_id>[^/]+)/(?P<feed_id>[^?/]+)\?(?:[^&]+&)*(?P<filter>by(?:Gui|I)d=(?P<id>[\w-]+))' _TESTS = [{ # From http://player.theplatform.co...
class ThePlatformFeedIE(ThePlatformBaseIE):
_URL_TEMPLATE = '%s//feed.theplatform.com/f/%s/%s?form=json&%s' _VALID_URL = r'https?://feed\.theplatform\.com/f/(?P<provider_id>[^/]+)/(?P<feed_id>[^?/]+)\?(?:[^&]+&)*(?P<filter>by(?:Gui|I)d=(?P<id>[\w-]+))' _TESTS = [{ # From http://player.theplatform.com/p/7wvmTC/MSNBCEmbeddedOffSite?guid=n_hardb...
config_url.replace('onsite/', 'onsite/config/') config = self._download_json(config_url, video_id, 'Downloading config') if 'releaseUrl' in config: release_url = config['releaseUrl'] else: release_url = 'http://link.theplatform.com/s/%s?mbr=true' % pa...
256
256
1,029
10
245
andrew4699/Audis
_downloads/youtube_dl/extractor/theplatform.py
Python
ThePlatformFeedIE
ThePlatformFeedIE
309
397
309
309
641c1dce7e8f0812e3b8758b16163d4684d342ed
bigcode/the-stack
train
e925b398529b4e3358248904
train
class
class ThePlatformIE(ThePlatformBaseIE, AdobePassIE): _VALID_URL = r'''(?x) (?:https?://(?:link|player)\.theplatform\.com/[sp]/(?P<provider_id>[^/]+)/ (?:(?:(?:[^/]+/)+select/)?(?P<media>media/(?:guid/\d+/)?)?|(?P<config>(?:[^/\?]+/(?:swf|config)|onsite)/select/))? |theplatform:)(?P<id>[^...
class ThePlatformIE(ThePlatformBaseIE, AdobePassIE):
_VALID_URL = r'''(?x) (?:https?://(?:link|player)\.theplatform\.com/[sp]/(?P<provider_id>[^/]+)/ (?:(?:(?:[^/]+/)+select/)?(?P<media>media/(?:guid/\d+/)?)?|(?P<config>(?:[^/\?]+/(?:swf|config)|onsite)/select/))? |theplatform:)(?P<id>[^/\?&]+)''' _TESTS = [{ # from http://www...
(start_time, 1000) end_time = float_or_none(end_time, 1000) if start_time is None or end_time is None: return chapters.append({ 'start_time': start_time, 'end_time': end_time, }) for ...
256
256
2,266
13
243
andrew4699/Audis
_downloads/youtube_dl/extractor/theplatform.py
Python
ThePlatformIE
ThePlatformIE
117
306
117
117
a85ced67275aa5b35836b42f947deebf19d74bfd
bigcode/the-stack
train
332ce10d85c71f00bf97ea9f
train
class
class ThePlatformBaseIE(OnceIE): def _extract_theplatform_smil(self, smil_url, video_id, note='Downloading SMIL data'): meta = self._download_xml( smil_url, video_id, note=note, query={'format': 'SMIL'}, headers=self.geo_verification_headers()) error_element = find_xpath_attr...
class ThePlatformBaseIE(OnceIE):
def _extract_theplatform_smil(self, smil_url, video_id, note='Downloading SMIL data'): meta = self._download_xml( smil_url, video_id, note=note, query={'format': 'SMIL'}, headers=self.geo_verification_headers()) error_element = find_xpath_attr(meta, _x('.//smil:ref'), 'src') ...
# coding: utf-8 from __future__ import unicode_literals import re import time import hmac import binascii import hashlib from .once import OnceIE from .adobepass import AdobePassIE from ..compat import ( compat_parse_qs, compat_urllib_parse_urlparse, ) from ..utils import ( determine_ext, ExtractorEr...
172
241
806
9
163
andrew4699/Audis
_downloads/youtube_dl/extractor/theplatform.py
Python
ThePlatformBaseIE
ThePlatformBaseIE
34
114
34
34
e809e1fa83b607acdd7f62a13a235fd3927711c6
bigcode/the-stack
train
a88ed633465ca6491e727003
train
class
class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Speakerdeck' db.create_table('cmsplugin_speakerdeck', ( ('cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)), ('template'...
class Migration(SchemaMigration):
def forwards(self, orm): # Adding model 'Speakerdeck' db.create_table('cmsplugin_speakerdeck', ( ('cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)), ('template', self.gf('django.db.models.fields....
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration):
37
256
3,356
6
30
sternoru/goscalecms
goscale/plugins/presentations/migrations/0001_initial.py
Python
Migration
Migration
8
189
8
9
b1016a5960fdd9fa4102cf05f0fc3d0b3f7dcdd6
bigcode/the-stack
train
bb2d69464c8775943376a4cd
train
class
class SpentIndexTest(BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 4 def setup_network(self): self.nodes = [] # Nodes 0/1 are "wallet" nodes self.nodes.append(self.start_node(0, self.options.tmpdir, ...
class SpentIndexTest(BitcoinTestFramework):
def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 4 def setup_network(self): self.nodes = [] # Nodes 0/1 are "wallet" nodes self.nodes.append(self.start_node(0, self.options.tmpdir, ["-debug"])) self.nodes.append(self.s...
#!/usr/bin/env python3 # Copyright (c) 2014-2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test addressindex generation and fetching # import time from test_framework.test_framework import Bi...
106
256
1,693
10
95
kaboela/litecoinz
test/functional/spentindex.py
Python
SpentIndexTest
SpentIndexTest
17
138
17
18
ab9145b4037eee03546b0c03cf612f80cd5a66d3
bigcode/the-stack
train
2604a14d9dd9a242c8003629
train
function
def signal_handler(signal, frame): #Handle Ctrl+C here print("") sdnpwn.message("Stopping...", sdnpwn.NORMAL) return
def signal_handler(signal, frame): #Handle Ctrl+C here
print("") sdnpwn.message("Stopping...", sdnpwn.NORMAL) return
import signal from kamene.all import * import modules.sdnpwn_common as sdnpwn def signal_handler(signal, frame): #Handle Ctrl+C here
35
64
33
14
20
winston7568/sdnpwn
modules/detect_proxy_arp.py
Python
signal_handler
signal_handler
7
11
7
8
05d4c9676e3771170a99792091d7ac94af1475c6
bigcode/the-stack
train
cb623581a3b133e451683ea4
train
function
def usage(): sdnpwn.addUsage(["-i", "--iface"], "Interface to use (Default eth0)", False) sdnpwn.addUsage(["-v", "--verbose"], "Enable verbose output", False) return sdnpwn.getUsage()
def usage():
sdnpwn.addUsage(["-i", "--iface"], "Interface to use (Default eth0)", False) sdnpwn.addUsage(["-v", "--verbose"], "Enable verbose output", False) return sdnpwn.getUsage()
_common as sdnpwn def signal_handler(signal, frame): #Handle Ctrl+C here print("") sdnpwn.message("Stopping...", sdnpwn.NORMAL) return def info(): return "This module will check if an ARP proxy is running on the controller." def usage():
63
64
56
3
60
winston7568/sdnpwn
modules/detect_proxy_arp.py
Python
usage
usage
16
20
16
16
3ee9d5aa561ff8318da1febdbbe9975ba4fd0c7a
bigcode/the-stack
train
f02c3df3343c76856e8e59ac
train
function
def info(): return "This module will check if an ARP proxy is running on the controller."
def info():
return "This module will check if an ARP proxy is running on the controller."
import signal from kamene.all import * import modules.sdnpwn_common as sdnpwn def signal_handler(signal, frame): #Handle Ctrl+C here print("") sdnpwn.message("Stopping...", sdnpwn.NORMAL) return def info():
57
64
21
3
53
winston7568/sdnpwn
modules/detect_proxy_arp.py
Python
info
info
13
14
13
13
5a5d1815ba2416dcc3fab6858a816d3d03047d9d
bigcode/the-stack
train
4f1a7c406f337f1bf469b000
train
function
def run(params): signal.signal(signal.SIGINT, signal_handler) # Assign the signal handler iface = sdnpwn.getArg(["-i", "--iface"], params, "eth0") verbose = sdnpwn.checkArg(["-v", "--verbose"], params) try: if(verbose): sdnpwn.printVerbose("Getting MAC and IP address for interface " + iface) ...
def run(params):
signal.signal(signal.SIGINT, signal_handler) # Assign the signal handler iface = sdnpwn.getArg(["-i", "--iface"], params, "eth0") verbose = sdnpwn.checkArg(["-v", "--verbose"], params) try: if(verbose): sdnpwn.printVerbose("Getting MAC and IP address for interface " + iface) ifaceIP =...
npwn_common as sdnpwn def signal_handler(signal, frame): #Handle Ctrl+C here print("") sdnpwn.message("Stopping...", sdnpwn.NORMAL) return def info(): return "This module will check if an ARP proxy is running on the controller." def usage(): sdnpwn.addUsage(["-i", "--iface"], "Interface to use (Default...
124
124
416
5
119
winston7568/sdnpwn
modules/detect_proxy_arp.py
Python
run
run
22
59
22
23
be84b7e6f58796a4893acb704b4cb909240dc24f
bigcode/the-stack
train
d83b9de9c147ba1f4fdcee79
train
class
class Migration(migrations.Migration): dependencies = [ ('users', '0007_auto_20190623_0957'), ] operations = [ migrations.AddField( model_name='historicalwhitelisthistory', name='reason', field=models.CharField(blank=True, max_length=255, verbose_name='R...
class Migration(migrations.Migration):
dependencies = [ ('users', '0007_auto_20190623_0957'), ] operations = [ migrations.AddField( model_name='historicalwhitelisthistory', name='reason', field=models.CharField(blank=True, max_length=255, verbose_name='Raison'), ), migrations.A...
# Generated by Django 2.1 on 2019-06-23 09:05 from django.db import migrations, models class Migration(migrations.Migration):
36
64
119
7
28
nanoy42/coope
users/migrations/0008_auto_20190623_1105.py
Python
Migration
Migration
6
23
6
7
e2833336097daa61c4ee6145c05566ae31955dd9
bigcode/the-stack
train
edae0e7e58cb88142ee53da4
train
function
def cn_PnPoly(P, V): cn = 0 # the crossing number counter # repeat the first vertex at end V = tuple(V[:])+(V[0],) # loop through all edges of the polygon for i in range(len(V)-1): # edge from V[i] to V[i+1] if ((V[i][1] <= P[1] and V[i+1][1] > P[1]) # an upward crossing ...
def cn_PnPoly(P, V):
cn = 0 # the crossing number counter # repeat the first vertex at end V = tuple(V[:])+(V[0],) # loop through all edges of the polygon for i in range(len(V)-1): # edge from V[i] to V[i+1] if ((V[i][1] <= P[1] and V[i+1][1] > P[1]) # an upward crossing or (V[i][1] > P[1] a...
#=================================================================== # cn_PnPoly(): crossing number test for a point in a polygon # Input: P = a point, # V[] = vertex points of a polygon # Return: 0 = outside, 1 = inside # This code is patterned after [Franklin, 2000] def cn_PnPoly(P, V):
78
78
263
9
69
mChataign/smileCompletion
Code/point_in_polygon.py
Python
cn_PnPoly
cn_PnPoly
37
52
37
37
6a30beeaecae9b3b63dcab496e0767575968facf
bigcode/the-stack
train
836620cae645e747532ac008
train
function
def wn_PnPoly(P, V): wn = 0 # the winding number counter # repeat the first vertex at end V = tuple(V[:]) + (V[0],) # loop through all edges of the polygon for i in range(len(V)-1): # edge from V[i] to V[i+1] if V[i][1] <= P[1]: # start y <= P[1] if V[i+1][1] > P[1...
def wn_PnPoly(P, V):
wn = 0 # the winding number counter # repeat the first vertex at end V = tuple(V[:]) + (V[0],) # loop through all edges of the polygon for i in range(len(V)-1): # edge from V[i] to V[i+1] if V[i][1] <= P[1]: # start y <= P[1] if V[i+1][1] > P[1]: # an upward cr...
a polygon # Input: P = a point, # V[] = vertex points of a polygon # Return: wn = the winding number (=0 only if P is outside V[]) otherwise -1 or 1 if inside the polygon or -2 on the boundary #Personal modification : Modified to return -2 on the boundary (i.e. inside the polygon) def wn_PnPoly(P...
88
88
296
9
79
mChataign/smileCompletion
Code/point_in_polygon.py
Python
wn_PnPoly
wn_PnPoly
69
93
69
69
eb64d73a0748850aa611bbf55ddee8925440d1f9
bigcode/the-stack
train
22e505f9016f3e8f4b1706e0
train
function
def is_left(P0, P1, P2): return (P1[0] - P0[0]) * (P2[1] - P0[1]) - (P2[0] - P0[0]) * (P1[1] - P0[1])
def is_left(P0, P1, P2):
return (P1[0] - P0[0]) * (P2[1] - P0[1]) - (P2[0] - P0[0]) * (P1[1] - P0[1])
P1 # =0 for P2 on the line # <0 for P2 right of the line # See: the January 2001 Algorithm "Area of 2D and 3D Triangles and Polygons" def is_left(P0, P1, P2):
64
64
65
12
52
mChataign/smileCompletion
Code/point_in_polygon.py
Python
is_left
is_left
26
27
26
26
26fe24347fdf2c83ff11965762f729e516afeabe
bigcode/the-stack
train
4a95e3c07eb5e9e27d13027a
train
function
def isInsideHorizontalEdge(V1,V2,P): isHorizontalEdge = (V1[1] == V2[1]) and (V1[1] == P[1]) #same y isBetweenXAxis = (P[0] <= max(V1[0],V2[0])) and (P[0] >= min(V1[0],V2[0])) # x in [xMin,xMax] return (isHorizontalEdge and isBetweenXAxis)
def isInsideHorizontalEdge(V1,V2,P):
isHorizontalEdge = (V1[1] == V2[1]) and (V1[1] == P[1]) #same y isBetweenXAxis = (P[0] <= max(V1[0],V2[0])) and (P[0] >= min(V1[0],V2[0])) # x in [xMin,xMax] return (isHorizontalEdge and isBetweenXAxis)
a valid crossing of y=P[1] right of P[0] return cn % 2 # 0 if even (out), and 1 if odd (in) #=================================================================== #Check that a point lies on an horizontal edge def isInsideHorizontalEdge(V1,V2,P):
64
64
104
11
52
mChataign/smileCompletion
Code/point_in_polygon.py
Python
isInsideHorizontalEdge
isInsideHorizontalEdge
57
60
57
57
074d9af15ebe3dce68e2f0aa6c7d3a418f670f90
bigcode/the-stack
train
a30a68ff5be9240519a44798
train
class
@pytest.mark.skip(reason="Not being used yet") class Test_Routes(MultipleBrowserTest): drivers = [] def get_urls(self, method): links = [] for rule in app.url_map.iter_rules(): if method in rule.methods and has_no_empty_params(rule): #url = url...
@pytest.mark.skip(reason="Not being used yet") class Test_Routes(MultipleBrowserTest):
drivers = [] def get_urls(self, method): links = [] for rule in app.url_map.iter_rules(): if method in rule.methods and has_no_empty_params(rule): #url = url_for(rule.endpoint, **(rule.defaults or {})) url = rule.rule ...
app def has_no_empty_params(rule): defaults = rule.defaults if rule.defaults is not None else () arguments = rule.arguments if rule.arguments is not None else () return len(defaults) >= len(arguments) @pytest.mark.skip(reason="Not being used yet") class Test_Routes(MultipleBrowserTest):
64
64
205
19
45
tylerpar99/celts
tests/ui/functional_test.py
Python
Test_Routes
Test_Routes
15
39
15
16
3dfba9ea0d3ff393b8565d2dd33b97faeb2216db
bigcode/the-stack
train
30e3c3a55fb8396375ed0dd1
train
function
def has_no_empty_params(rule): defaults = rule.defaults if rule.defaults is not None else () arguments = rule.arguments if rule.arguments is not None else () return len(defaults) >= len(arguments)
def has_no_empty_params(rule):
defaults = rule.defaults if rule.defaults is not None else () arguments = rule.arguments if rule.arguments is not None else () return len(defaults) >= len(arguments)
# Import the modules that are required for execution import pytest from conftest import MultipleBrowserTest import colorama import urllib.request from app import app def has_no_empty_params(rule):
42
64
43
7
34
tylerpar99/celts
tests/ui/functional_test.py
Python
has_no_empty_params
has_no_empty_params
10
13
10
10
0cb4b60a76c9ea2368d5c30f928047212ed4cb3a
bigcode/the-stack
train
e2ee0db3fe8fa86cb97019ee
train
function
def batchfy_by_frame( sorted_data, max_frames_in, max_frames_out, max_frames_inout, num_batches=0, min_batch_size=1, shortest_first=False, ikey="input", okey="output", ): """Make variable batch set, which maximizes the number of frames to max_b...
def batchfy_by_frame( sorted_data, max_frames_in, max_frames_out, max_frames_inout, num_batches=0, min_batch_size=1, shortest_first=False, ikey="input", okey="output", ):
"""Make variable batch set, which maximizes the number of frames to max_batch_frame. :param List[(str, Dict[str, Any])] sorteddata: dictionary loaded from data.json :param int max_frames_in: Maximum input frames of a batch :param int max_frames_out: Maximum output frames of a batch :param int max_f...
- len(minibatches[i]) if -i == len(minibatches): minibatches[i + 1].extend(minibatches[i]) minibatches = minibatches[1:] break else: minibatches[i].extend(minibatches[i - 1][:missing]) minibatches[i - 1] = minibatch...
256
256
1,046
57
198
qq1440837150/DeepSpeech
deepspeech/io/batchfy.py
Python
batchfy_by_frame
batchfy_by_frame
184
277
184
193
9f5b81763f72b4da61beb34a81c677941a38491a
bigcode/the-stack
train
41d693188970064ab8edba9d
train
function
def batchfy_shuffle(data, batch_size, min_batch_size, num_batches, shortest_first): import random logger.info("use shuffled batch.") sorted_data = random.sample(data.items(), len(data.items())) logger.info("# utts: " + str(len(sorted_data))) # make list of minibatches miniba...
def batchfy_shuffle(data, batch_size, min_batch_size, num_batches, shortest_first):
import random logger.info("use shuffled batch.") sorted_data = random.sample(data.items(), len(data.items())) logger.info("# utts: " + str(len(sorted_data))) # make list of minibatches minibatches = [] start = 0 while True: end = min(len(sorted_data), start + batch_size) ...
logger.info( str(len(minibatches)) + " batches containing from " + str(min(lengths)) + " to " + str(max(lengths)) + " samples" + "(avg " + str( int(np.mean(lengths))) + " samples).") return minibatches def batchfy_shuffle(data, batch_size, min_batch_size, num_batches, ...
81
81
271
20
60
qq1440837150/DeepSpeech
deepspeech/io/batchfy.py
Python
batchfy_shuffle
batchfy_shuffle
280
313
280
281
2eebd3938e869ad118fcbfdc350cccd47e024463
bigcode/the-stack
train
850ef9a73cb9d6faf8db8297
train
function
def make_batchset( data, batch_size=0, max_length_in=float("inf"), max_length_out=float("inf"), num_batches=0, min_batch_size=1, shortest_first=False, batch_sort_key="input", count="auto", batch_bins=0, batch_frames_in=0, ba...
def make_batchset( data, batch_size=0, max_length_in=float("inf"), max_length_out=float("inf"), num_batches=0, min_batch_size=1, shortest_first=False, batch_sort_key="input", count="auto", batch_bins=0, batch_frames_in=0, ba...
"""Make batch set from json dictionary if utts have "category" value, >>> data = [{'category': 'A', 'input': ..., 'utt':'utt1'}, ... {'category': 'B', 'input': ..., 'utt':'utt2'}, ... {'category': 'B', 'input': ..., 'utt':'utt3'}, ... {'category': 'A', '...
min_batch_size additional_minibatch = [ sorted_data[i] for i in np.random.randint(0, start, mod) ] if shortest_first: additional_minibatch.reverse() minibatch.extend(additional_minibatch) minibatches.append(minibatch) if en...
255
256
1,437
101
154
qq1440837150/DeepSpeech
deepspeech/io/batchfy.py
Python
make_batchset
make_batchset
320
469
320
335
73bcd6e86480e434949ba458d599e5edd4e0d6e2
bigcode/the-stack
train
35412b55cd7d00cb19053c6c
train
function
def batchfy_by_bin( sorted_data, batch_bins, num_batches=0, min_batch_size=1, shortest_first=False, ikey="input", okey="output", ): """Make variably sized batch set, which maximizes the number of bins up to `batch_bins`. :param List[(str, Dict[str, A...
def batchfy_by_bin( sorted_data, batch_bins, num_batches=0, min_batch_size=1, shortest_first=False, ikey="input", okey="output", ):
"""Make variably sized batch set, which maximizes the number of bins up to `batch_bins`. :param List[(str, Dict[str, Any])] sorted_data: dictionary loaded from data.json :param int batch_bins: Maximum frames of a batch :param int num_batches: # number of batches to use (for debug) :param int m...
size / 2 # and max(min_batches, .) avoids batchsize = 0 bs = max(min_batch_size, int(batch_size / (1 + factor))) end = min(len(sorted_data), start + bs) minibatch = sorted_data[start:end] if shortest_first: minibatch.reverse() # check each batch is more than ...
246
246
821
45
200
qq1440837150/DeepSpeech
deepspeech/io/batchfy.py
Python
batchfy_by_bin
batchfy_by_bin
102
181
102
109
72f750dc6d1e686e44d3bb84a5869a575d66674b
bigcode/the-stack
train
7993a609b0b4328ed26fe75a
train
function
def batchfy_by_seq( sorted_data, batch_size, max_length_in, max_length_out, min_batch_size=1, shortest_first=False, ikey="input", iaxis=0, okey="output", oaxis=0, ): """Make batch set from json dictionary :param List[(str, Dict[str...
def batchfy_by_seq( sorted_data, batch_size, max_length_in, max_length_out, min_batch_size=1, shortest_first=False, ikey="input", iaxis=0, okey="output", oaxis=0, ):
"""Make batch set from json dictionary :param List[(str, Dict[str, Any])] sorted_data: dictionary loaded from data.json :param int batch_size: batch size :param int max_length_in: maximum length of input to decide adaptive batch size :param int max_length_out: maximum length of output to decide ada...
1 PaddlePaddle 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 applicable law or agreed...
226
226
755
61
165
qq1440837150/DeepSpeech
deepspeech/io/batchfy.py
Python
batchfy_by_seq
batchfy_by_seq
25
99
25
35
ad54898e49a9992d8ede72f2377fe26805c395b7
bigcode/the-stack
train
20bf29ee2c855bcd6cf91ec1
train
class
class ControlFlowStatement(Node): """A base class for Control Flow statements.""" def __init__(self): raise NotImplementedError("Base Class ControlFlowStatement not implemented!")
class ControlFlowStatement(Node):
"""A base class for Control Flow statements.""" def __init__(self): raise NotImplementedError("Base Class ControlFlowStatement not implemented!")
x.GetSExp()) def ToStr(self): return S.WriteToScheme(self) def GetXMLAttributes(self): return self.GetAttributes() def GetJSONAttributes(self): return self.GetAttributes() def GetDotAttributes(self): return self.GetAttributes() class ControlFlowStatement(Node):
64
64
37
6
58
JordanMilne/Redhawk
redhawk/common/_node_header.py
Python
ControlFlowStatement
ControlFlowStatement
157
160
157
157
509301f6de912750b14d9a8af7c1b529c368e17d
bigcode/the-stack
train
e5124f40ddb2d644ee706dd7
train
class
class Node: """A Parse Tree Node.""" def __init__(self): raise NotImplementedError("Node is an Abstract Class.") return def __repr__(self): return self.GetName() def __str__(self): return self.GetName() def GetSExp(self): """ This function is not to be called directly. Code for this fun...
class Node:
"""A Parse Tree Node.""" def __init__(self): raise NotImplementedError("Node is an Abstract Class.") return def __repr__(self): return self.GetName() def __str__(self): return self.GetName() def GetSExp(self): """ This function is not to be called directly. Code for this function is ...
follows: For element e in the list, li: * If e is a list, call ExpandList(li, f) recursively. * If e is a Node, expand it (into a list), by calling ExpandList(f(e), f)""" if type(li) is not list: return for (i, e) in enumerate(li): if type(e) is list: li[i] ...
141
141
470
3
137
JordanMilne/Redhawk
redhawk/common/_node_header.py
Python
Node
Node
85
154
85
85
589938e31c46185da98dfa399374fc04b7683dff
bigcode/the-stack
train
9aae49eed5fa156e0fd7d8e1
train
function
def ExpandList(li, f): """ Recursively expands a list li as follows: For element e in the list, li: * If e is a list, call ExpandList(li, f) recursively. * If e is a Node, expand it (into a list), by calling ExpandList(f(e), f)""" if type(li) is not list: return for ...
def ExpandList(li, f):
""" Recursively expands a list li as follows: For element e in the list, li: * If e is a list, call ExpandList(li, f) recursively. * If e is a Node, expand it (into a list), by calling ExpandList(f(e), f)""" if type(li) is not list: return for (i, e) in enumerate(li)...
2) ,'ARROW' : ('->', 2) ,'TYPE_CAST' : ('cast', 2) # An Indexing operator (dictionaries and lists) ,'INDEX_INTO' : ('index-into', 2) } def ExpandList(li, f):
64
64
154
7
57
JordanMilne/Redhawk
redhawk/common/_node_header.py
Python
ExpandList
ExpandList
66
82
66
66
ff07bfa5c998284486822549125260892c797cdd
bigcode/the-stack
train
6df437bfde51886bcd34c8ec
train
class
class ExceptionsStatement(Node): """A base class for Exceptions Related statements.""" def __init__(self): raise NotImplementedError("Base Class ExceptionsStatement not implemented!")
class ExceptionsStatement(Node):
"""A base class for Exceptions Related statements.""" def __init__(self): raise NotImplementedError("Base Class ExceptionsStatement not implemented!")
Attributes(self): return self.GetAttributes() def GetDotAttributes(self): return self.GetAttributes() class ControlFlowStatement(Node): """A base class for Control Flow statements.""" def __init__(self): raise NotImplementedError("Base Class ControlFlowStatement not implemented!") class ExceptionsS...
64
64
35
5
59
JordanMilne/Redhawk
redhawk/common/_node_header.py
Python
ExceptionsStatement
ExceptionsStatement
162
165
162
162
1c40ef497e3d1ec2cdc44aaa58bd4272c4e5f4e4
bigcode/the-stack
train
afe15184d88cff6714a422a8
train
function
def find_limit(subset, data_set, items_of_interest): """ Find the minimum number of similarity ratings to use as a limit. Look only at the given subset of the given data_set concerning the given set of items_of_interest. """ limit = 1000 for idx1, item1 in enumerate(items_of_interest): ...
def find_limit(subset, data_set, items_of_interest):
""" Find the minimum number of similarity ratings to use as a limit. Look only at the given subset of the given data_set concerning the given set of items_of_interest. """ limit = 1000 for idx1, item1 in enumerate(items_of_interest): for idx2, item2 in enumerate(items_of_interes...
corresponding list of item names items = list(items_of_interest) items_of_interest = [] for category in categories_of_interest: for item in data_set['categories'][category]['items']: if item in items: items_of_interest.append(item) return items_of_interest, cate...
78
78
260
13
64
lbechberger/LearningPsychologicalSpaces
code/mds/preprocessing/preprocess_Shapes.py
Python
find_limit
find_limit
117
144
117
117
e1f127adcdbbad23bd3df2d2e3248909bc8fd951
bigcode/the-stack
train
0d0ff9f190726a574b52bdbc
train
function
def select_data_subset(subset, data_set): """ Select a subset of the given data set. The parameter 'subset' can have the following values: 'all', 'between', 'within', 'cats'. Returns a triple of lists: items_of_interest, item_names, and categories_of_interest. """ category_names = data...
def select_data_subset(subset, data_set):
""" Select a subset of the given data set. The parameter 'subset' can have the following values: 'all', 'between', 'within', 'cats'. Returns a triple of lists: items_of_interest, item_names, and categories_of_interest. """ category_names = data_set['category_names'] # sort ite...
help = 'CSV file containing an ordered list of categories and their desired names') parser.add_argument('items_file', help = 'CSV file containing a mapping of item names') parser.add_argument('output_pickle_file', help = 'path to the output pickle file') parser.add_argument('output_csv_file', help = 'path to the outpu...
229
229
764
10
219
lbechberger/LearningPsychologicalSpaces
code/mds/preprocessing/preprocess_Shapes.py
Python
select_data_subset
select_data_subset
31
115
31
31
ed9aa7d294a9f9ddfc840283628f270db851bca5
bigcode/the-stack
train
d59236487d52cac41c7f9df8
train
class
class TestNthLastChild(util.TestCase): """Test `nth` last child selectors.""" def test_nth_last_child(self): """Test `nth` last child.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></s...
class TestNthLastChild(util.TestCase):
"""Test `nth` last child selectors.""" def test_nth_last_child(self): """Test `nth` last child.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> ...
"""Test `nth` last child selectors.""" from .. import util class TestNthLastChild(util.TestCase):
23
110
369
9
13
kianmeng/soupsieve
tests/test_level3/test_nth_last_child.py
Python
TestNthLastChild
TestNthLastChild
5
60
5
5
0c018fbc2b5fef7cae4d39dfe6ce9ab92c5cbacb
bigcode/the-stack
train
5e2c9744a3d07527f5898820
train
class
class ConanfileToolsTest(unittest.TestCase): def test_untar(self): tmp_dir = temp_folder() file_path = os.path.join(tmp_dir, "example.txt") save(file_path, "Hello world!") tar_path = os.path.join(tmp_dir, "sample.tar") try: old_path = os.getcwd() os.c...
class ConanfileToolsTest(unittest.TestCase):
def test_untar(self): tmp_dir = temp_folder() file_path = os.path.join(tmp_dir, "example.txt") save(file_path, "Hello world!") tar_path = os.path.join(tmp_dir, "sample.tar") try: old_path = os.getcwd() os.chdir(tmp_dir) import tarfile ...
import unittest import os from conans.util.files import save, load from conans.client.loader import ConanFileLoader from conans.model.settings import Settings from conans.test.utils.test_files import temp_folder from conans import tools from parameterized.parameterized import parameterized from conans.test.utils.tools ...
141
256
1,266
9
132
wahlm/conan
conans/test/util/conanfile_tools_test.py
Python
ConanfileToolsTest
ConanfileToolsTest
24
159
24
25
758c9071d84cfaf260dc5d9c4ca451caf5073337
bigcode/the-stack
train
ba8cfe1f9d1f8a94c3e3b2eb
train
function
def get_city_data() -> pd.DataFrame: """Return DataFrame with example city data. The countries, names, population, and coordinates of 47,966 cities. Subset of the Kaggle world cities database. https://www.kaggle.com/max-mind/world-cities-database This database was downloaded from MaxMind. The lice...
def get_city_data() -> pd.DataFrame:
"""Return DataFrame with example city data. The countries, names, population, and coordinates of 47,966 cities. Subset of the Kaggle world cities database. https://www.kaggle.com/max-mind/world-cities-database This database was downloaded from MaxMind. The license follows: OPEN DATA LICEN...
data = pd.read_pickle(data_path) return data def get_galaxy_data() -> pd.DataFrame: """Return DataFrame with example galaxy data. 100,000 galaxies from the Buzzard simulation [1], with redshifts in the range (0,2.3) and photometry in the LSST ugrizy bands. References ---------- [1] J...
189
189
633
10
178
jfcrenshaw/pzflow
pzflow/examples/examples.py
Python
get_city_data
get_city_data
38
93
38
38
a847ebad8baa5e224071db508ed208f318ef545c
bigcode/the-stack
train
d4003d129c42d61f11e8b8ff
train
function
def get_twomoons_data() -> pd.DataFrame: """Return DataFrame with two moons example data. Two moons data originally from scikit-learn, i.e., `sklearn.datasets.make_moons`. """ this_dir, _ = os.path.split(__file__) data_path = os.path.join(this_dir, "two-moons-data.pkl") data = pd.read_pickl...
def get_twomoons_data() -> pd.DataFrame:
"""Return DataFrame with two moons example data. Two moons data originally from scikit-learn, i.e., `sklearn.datasets.make_moons`. """ this_dir, _ = os.path.split(__file__) data_path = os.path.join(this_dir, "two-moons-data.pkl") data = pd.read_pickle(data_path) return data
import os import pandas as pd from pzflow import Flow def get_twomoons_data() -> pd.DataFrame:
27
64
90
12
14
jfcrenshaw/pzflow
pzflow/examples/examples.py
Python
get_twomoons_data
get_twomoons_data
8
17
8
8
78193cb8e9e511d72b574787f5a0ea377d2081f1
bigcode/the-stack
train
129abeb2402d8c4d432c3b31
train
function
def get_example_flow() -> Flow: """Return a normalizing flow that was trained on galaxy data. This flow was trained in the `redshift_example.ipynb` Jupyter notebook, on the example data available in `pzflow.examples.galaxy_data`. For more info: `print(example_flow().info)`. """ this_dir, _ = os...
def get_example_flow() -> Flow:
"""Return a normalizing flow that was trained on galaxy data. This flow was trained in the `redshift_example.ipynb` Jupyter notebook, on the example data available in `pzflow.examples.galaxy_data`. For more info: `print(example_flow().info)`. """ this_dir, _ = os.path.split(__file__) flow_p...
DATABASE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ this_dir, _ = os.path.split(__file__) data_path = os.path.join(this_dir, "city-data.pkl") data = pd.read_pickle(data_path) return data def get_example_flow() -> Flow:
64
64
112
8
55
jfcrenshaw/pzflow
pzflow/examples/examples.py
Python
get_example_flow
get_example_flow
96
106
96
96
8e6b76d26ce5a533179e730ebf59e42169d9c2e3
bigcode/the-stack
train
689ddb58cb2b5621c277a699
train
function
def get_galaxy_data() -> pd.DataFrame: """Return DataFrame with example galaxy data. 100,000 galaxies from the Buzzard simulation [1], with redshifts in the range (0,2.3) and photometry in the LSST ugrizy bands. References ---------- [1] Joseph DeRose et al. The Buzzard Flock: Dark Energy Surv...
def get_galaxy_data() -> pd.DataFrame:
"""Return DataFrame with example galaxy data. 100,000 galaxies from the Buzzard simulation [1], with redshifts in the range (0,2.3) and photometry in the LSST ugrizy bands. References ---------- [1] Joseph DeRose et al. The Buzzard Flock: Dark Energy Survey Synthetic Sky Catalogs. arXiv:19...
`sklearn.datasets.make_moons`. """ this_dir, _ = os.path.split(__file__) data_path = os.path.join(this_dir, "two-moons-data.pkl") data = pd.read_pickle(data_path) return data def get_galaxy_data() -> pd.DataFrame:
64
64
166
12
51
jfcrenshaw/pzflow
pzflow/examples/examples.py
Python
get_galaxy_data
get_galaxy_data
20
35
20
20
73190ed9f78ba9df7793f1d2e0d76c1d2066979d
bigcode/the-stack
train
99fb2decc4d329e47a8b8f70
train
class
class FabcoinIgnoreMPOSParticipantRewardTest(FabcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def remove_from_staking_prevouts(self, remove_prevout): for j in range(len(self.staking_prevouts)): prevout = self.staking_prevouts...
class FabcoinIgnoreMPOSParticipantRewardTest(FabcoinTestFramework):
def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def remove_from_staking_prevouts(self, remove_prevout): for j in range(len(self.staking_prevouts)): prevout = self.staking_prevouts[j] if prevout[0].serialize() == remove_prevout.serializ...
#!/usr/bin/env python3 from test_framework.test_framework import FabcoinTestFramework from test_framework.util import * from test_framework.script import * from test_framework.mininode import * from test_framework.address import * from test_framework.fabcoin import * import sys import random import time class FabcoinI...
75
256
998
15
59
XianlinGong/fabcoinsc-dev
test/functional/fabcoin-ignore-mpos-participant-reward.py
Python
FabcoinIgnoreMPOSParticipantRewardTest
FabcoinIgnoreMPOSParticipantRewardTest
13
91
13
13
93ea27de7f0ea529ef8385229e3a4260ed40cf4b
bigcode/the-stack
train
5d1ea6fa39a725c0d2eba154
train
class
class CoopConfig(AppConfig): name = 'coop'
class CoopConfig(AppConfig):
name = 'coop'
from django.apps import AppConfig class CoopConfig(AppConfig):
13
64
12
6
6
mySPITECH/live_e-cop
coop/apps.py
Python
CoopConfig
CoopConfig
4
5
4
4
3edb7019631ed5b7e1b47e367c32b296035f55b6
bigcode/the-stack
train
fa152d90646822dbd71933d3
train
function
def main(): """ Buying demonstration. """ drink_price: Dict[Type[Drink], int] = {Cola: 120, RedBull: 200} drink_box = DrinkBox( {Cola: [Cola(), Cola(), Cola()], RedBull: [RedBull(), RedBull(), RedBull()]} ) vending_machine = VendingMachine(drink_box, drink_price) vending_machine...
def main():
""" Buying demonstration. """ drink_price: Dict[Type[Drink], int] = {Cola: 120, RedBull: 200} drink_box = DrinkBox( {Cola: [Cola(), Cola(), Cola()], RedBull: [RedBull(), RedBull(), RedBull()]} ) vending_machine = VendingMachine(drink_box, drink_price) vending_machine.insert(Mone...
""" Main """ from typing import Dict, Type from vending_machine.drink import Cola, Drink, RedBull from vending_machine.drink_box import DrinkBox from vending_machine.money import Money from vending_machine.vending_machine import VendingMachine def main():
55
64
135
3
51
AtsushiOzawa/tdd_vending-machine
main.py
Python
main
main
12
24
12
12
662b0b6b27ba3586d6163c76d867455918f0f63c
bigcode/the-stack
train
37b3b2cfe56866ad9eb64bd9
train
function
def main(args): #list all the files from directory and sort them baseo in numerical order list = sorted(os.listdir(args['location'])) list.sort(key=lambda f:int(''.join(filter(str.isdigit, f)))) #Parameters for MTCNN sess = tf.Session() pnet, rnet, onet = detect_face.create_mtcnn(sess, None) ...
def main(args): #list all the files from directory and sort them baseo in numerical order
list = sorted(os.listdir(args['location'])) list.sort(key=lambda f:int(''.join(filter(str.isdigit, f)))) #Parameters for MTCNN sess = tf.Session() pnet, rnet, onet = detect_face.create_mtcnn(sess, None) minsize = 40 # minimum size of face threshold = [0.6, 0.7, 0.9] # three steps's thresh...
3.get the coordinates 4.draw bounding box on face 5.write the image 6.store the time in seperate text file ,image name, count of faces, dimension, time log for each image. The below code is used for checking detecting faces and recording how fast does it detect, and can also be used in conjuntion with Face Tracker Alg...
130
130
435
21
108
SSusantAchary/FaceDetection-counting-using-MTCNN
MTCNNDetector.py
Python
main
main
29
58
29
31
9493203f077873c3cce379c492a7f5014dfcaccd
bigcode/the-stack
train
2c95f5705d03ed3993daa390
train
class
class DateExamples: def __init__(self, date, answer): self.date = date self.answer = answer
class DateExamples:
def __init__(self, date, answer): self.date = date self.answer = answer
class DateExamples:
4
64
27
4
0
dmitrii1991/AppBotSheduler
app/tests/utils.py
Python
DateExamples
DateExamples
1
4
1
1
cb70e32959aa30c5e10e188e1f84819c0115612a
bigcode/the-stack
train
bf7343b4710987ec81745404
train
function
def is_builtin(var): if var == Builtin: return True if hasattr(var, '__bases__'): return any(is_builtin(base) for base in var.__bases__) return False
def is_builtin(var):
if var == Builtin: return True if hasattr(var, '__bases__'): return any(is_builtin(base) for base in var.__bases__) return False
, specialfunctions, scoping, strings, structure, system, tensors, xmlformat, optimization] if ENABLE_FILES_MODULE: from mathics.builtin import files, importexport modules += [files, importexport] builtins = [] builtins_by_module = {} def is_builtin(var):
63
64
43
5
58
JoseCarlosGarcia95/Mathics
mathics/builtin/__init__.py
Python
is_builtin
is_builtin
34
39
34
34
83c3938a8af783fdb2b819f8ea69435523ce3160
bigcode/the-stack
train
e932389c6264038e40eb746b
train
function
def get_module_doc(module): doc = module.__doc__ if doc is not None: doc = doc.strip() if doc: title = doc.splitlines()[0] text = '\n'.join(doc.splitlines()[1:]) else: title = module.__name__ for prefix in ('mathics.builtin.', 'mathics.optional.'): if ...
def get_module_doc(module):
doc = module.__doc__ if doc is not None: doc = doc.strip() if doc: title = doc.splitlines()[0] text = '\n'.join(doc.splitlines()[1:]) else: title = module.__name__ for prefix in ('mathics.builtin.', 'mathics.optional.'): if title.startswith(prefix): ...
cedence[name] = builtin.precedence if isinstance(builtin, PatternObject): pattern_objects[name] = builtin.__class__ builtins.update(dict(new_builtins)) new_builtins = builtins builtins = {} add_builtins(new_builtins) def get_module_doc(module):
64
64
108
6
58
JoseCarlosGarcia95/Mathics
mathics/builtin/__init__.py
Python
get_module_doc
get_module_doc
89
103
89
89
ff4307b68bc3283d16bed2e280019f997f7c747a
bigcode/the-stack
train
c8d041da3418d795f3699004
train
function
def contribute(definitions): # let MakeBoxes contribute first builtins['System`MakeBoxes'].contribute(definitions) for name, item in builtins.items(): if name != 'System`MakeBoxes': item.contribute(definitions) # Is there another way to Unprotect these symbols at initialization? ...
def contribute(definitions): # let MakeBoxes contribute first
builtins['System`MakeBoxes'].contribute(definitions) for name, item in builtins.items(): if name != 'System`MakeBoxes': item.contribute(definitions) # Is there another way to Unprotect these symbols at initialization? definitions.get_attributes('System`$PreRead').clear() definit...
()[1:]) else: title = module.__name__ for prefix in ('mathics.builtin.', 'mathics.optional.'): if title.startswith(prefix): title = title[len(prefix):] title = title.capitalize() text = '' return title, text def contribute(definitions): # let MakeB...
72
72
241
13
58
JoseCarlosGarcia95/Mathics
mathics/builtin/__init__.py
Python
contribute
contribute
107
132
107
108
5f2f25f15c377516f62fe0260cf11cfbdc65fee0
bigcode/the-stack
train
47ae6b88adb7add9f5027935
train
function
def add_builtins(new_builtins): for var_name, builtin in new_builtins: name = builtin.get_name() if isinstance(builtin, SympyObject): mathics_to_sympy[name] = builtin for sympy_name in builtin.get_sympy_names(): sympy_to_mathics[sympy_name] = builtin i...
def add_builtins(new_builtins):
for var_name, builtin in new_builtins: name = builtin.get_name() if isinstance(builtin, SympyObject): mathics_to_sympy[name] = builtin for sympy_name in builtin.get_sympy_names(): sympy_to_mathics[sympy_name] = builtin if isinstance(builtin, BoxConstru...
instance)) builtins_by_module[module.__name__].append(instance) # builtins = dict(builtins) mathics_to_sympy = {} sympy_to_mathics = {} box_constructs = {} pattern_objects = {} builtins_precedence = {} def add_builtins(new_builtins):
63
64
143
10
53
JoseCarlosGarcia95/Mathics
mathics/builtin/__init__.py
Python
add_builtins
add_builtins
69
82
69
69
f26961169161dd0caa95726458140973a023e18c
bigcode/the-stack
train
852b01b8335237fa76dfb106
train
class
class PngStream(RangeStream): """ As for RangeStream, but if `scan_ihdr` is True, then immediately call :meth:`~range_streams.codecs.png.PngStream.scan_ihdr` on initialisation (which will perform the necessary range request to read PNG metadata from its IHDR chunk), setting various attributes on the...
class PngStream(RangeStream):
""" As for RangeStream, but if `scan_ihdr` is True, then immediately call :meth:`~range_streams.codecs.png.PngStream.scan_ihdr` on initialisation (which will perform the necessary range request to read PNG metadata from its IHDR chunk), setting various attributes on the :attr:`~range_streams.cod...
from __future__ import annotations import struct import zlib from ranges import Range from ...stream import RangeStream from .data import PngChunkInfo, PngData from .reconstruct import reconstruct_idat __all__ = ["PngStream"] class PngStream(RangeStream):
65
256
4,019
8
57
lmmx/range-streams
src/range_streams/codecs/png/stream.py
Python
PngStream
PngStream
15
367
15
15
a2816cc063afc911478364723ab5fb2e55f7f8d2
bigcode/the-stack
train
96cb6c64a2e97666b674092f
train
function
def bisect_left(a, x, lo=0, hi=None): """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e < x, and all e in a[i:] have e >= x. So if x already appears in the list, a.insert(x) will insert just before the leftmost x already th...
def bisect_left(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e < x, and all e in a[i:] have e >= x. So if x already appears in the list, a.insert(x) will insert just before the leftmost x already there. Optional args lo (default 0) ...
def bisect_left(a, x, lo=0, hi=None):
15
64
195
15
0
G-MontaG/leetcode
binarySearch/bisectLeft.py
Python
bisect_left
bisect_left
1
18
1
1
86db4e317e42403577107c5a43bc10661af82eca
bigcode/the-stack
train
7c197367559a079804b98881
train
function
def test_amber_read_butane(): fname = eex_find_files.get_example_filename( "amber", "alkanes", "trappe_butane_single_molecule.prmtop") dl = eex.datalayer.DataLayer("test_amber_read", backend="memory") data = eex.translators.amber.read_amber_file(dl, fname) assert dl.get_atom_count() == 4 as...
def test_amber_read_butane():
fname = eex_find_files.get_example_filename( "amber", "alkanes", "trappe_butane_single_molecule.prmtop") dl = eex.datalayer.DataLayer("test_amber_read", backend="memory") data = eex.translators.amber.read_amber_file(dl, fname) assert dl.get_atom_count() == 4 assert dl.get_bond_count() == 3 ...
648 assert dl.get_term_count(2, "total") == 648 assert set(np.unique(bonds["term_index"])) == {1, 2} assert set(dl.get_term_count(2)) == {1, 2, "total"} def test_amber_read_butane():
64
65
219
8
56
MolSSI/EEX
eex/tests/test_amber.py
Python
test_amber_read_butane
test_amber_read_butane
90
118
90
90
50225197d41b6799897e7d8a8f5fa4a1a8eb90f5
bigcode/the-stack
train
7b69f8c45a380241e600d8f2
train
function
def test_amber_spce_read_data(spce_dl): data, dl = spce_dl assert data["VERSION"] == "V0001.000"
def test_amber_spce_read_data(spce_dl):
data, dl = spce_dl assert data["VERSION"] == "V0001.000"
_read", backend=request.param) data = eex.translators.amber.read_amber_file(dl, fname, blocksize=55) # print("-- Built AMBER SPCE DL --") yield (data, dl) dl.close() def test_amber_spce_read_data(spce_dl):
64
64
35
12
52
MolSSI/EEX
eex/tests/test_amber.py
Python
test_amber_spce_read_data
test_amber_spce_read_data
24
26
24
24
22ce0f805b300139d84ba9d9ff6975793f48f7d9
bigcode/the-stack
train
633895202848632d99a13f42
train
function
def test_amber_compatibility_check_mixing_rule(butane_dl): # Get butane topology dl = butane_dl(nb=True) oname = eex_find_files.get_scratch_directory("dl_compatibility.prmtop") # Check to make sure that mixing rule will be applied by compatibility check eex.translators.amber.write_amber_file(dl, ...
def test_amber_compatibility_check_mixing_rule(butane_dl): # Get butane topology
dl = butane_dl(nb=True) oname = eex_find_files.get_scratch_directory("dl_compatibility.prmtop") # Check to make sure that mixing rule will be applied by compatibility check eex.translators.amber.write_amber_file(dl, oname) # Make sure we're getting pair parameters from DL nb_pairs = dl.list_n...
= eex_find_files.get_scratch_directory("dl_compatibility.prmtop") with pytest.raises(KeyError): eex.translators.amber.write_amber_file(dl, oname) def test_amber_compatibility_check_mixing_rule(butane_dl): # Get butane topology
64
64
132
22
42
MolSSI/EEX
eex/tests/test_amber.py
Python
test_amber_compatibility_check_mixing_rule
test_amber_compatibility_check_mixing_rule
191
204
191
193
772329a69563568c343a8031054f9afbdf29d2e5
bigcode/the-stack
train
4dc5ff064b641a7c8ef2afa1
train
function
def test_amber_compatibility_scaling(butane_dl): dl = butane_dl(scale=False) oname = eex_find_files.get_scratch_directory("dl_compatibility.prmtop") # Set with noncompatible scale13 scaling_factors = { "coul": { "scale12": 0.0, "scale13": 0.50, "scale14": 0...
def test_amber_compatibility_scaling(butane_dl):
dl = butane_dl(scale=False) oname = eex_find_files.get_scratch_directory("dl_compatibility.prmtop") # Set with noncompatible scale13 scaling_factors = { "coul": { "scale12": 0.0, "scale13": 0.50, "scale14": 0.75, }, "vdw": { "scal...
ene", { "K": 1, "R0": 1, "epsilon": 1, "sigma": 1, }) eex.translators.amber.write_amber_file(dl, oname) def test_amber_compatibility_scaling(butane_dl):
64
64
173
13
51
MolSSI/EEX
eex/tests/test_amber.py
Python
test_amber_compatibility_scaling
test_amber_compatibility_scaling
224
247
224
225
2040d6e4466c88ed85c087f593bb3c9a0cf533c1
bigcode/the-stack
train
22ef07266a3a7e326df6e47d
train
function
def test_amber_compatibility_no_scaling(butane_dl): dl = butane_dl(scale=False) oname = eex_find_files.get_scratch_directory("dl_compatibility.prmtop") with pytest.raises(ValueError): eex.translators.amber.write_amber_file(dl, oname)
def test_amber_compatibility_no_scaling(butane_dl):
dl = butane_dl(scale=False) oname = eex_find_files.get_scratch_directory("dl_compatibility.prmtop") with pytest.raises(ValueError): eex.translators.amber.write_amber_file(dl, oname)
"scale14": 0.75, } } dl.set_nb_scaling_factors(scaling_factors) with pytest.raises(ValueError): eex.translators.amber.write_amber_file(dl, oname) def test_amber_compatibility_no_scaling(butane_dl):
64
64
68
14
50
MolSSI/EEX
eex/tests/test_amber.py
Python
test_amber_compatibility_no_scaling
test_amber_compatibility_no_scaling
250
257
250
251
025c14ed3839597cb8f0b57275c6ad7cbd0b0694
bigcode/the-stack
train
76f2096fb3a1f3a8729827c9
train
function
def test_amber_compatibility_NB_number(butane_dl): dl = butane_dl(nb=False) oname = eex_find_files.get_scratch_directory("dl_compatibility.prmtop") dl.add_nb_parameter( atom_type=1, atom_type2=2, nb_name="LJ", nb_model="epsilon/sigma", nb_parameters={ '...
def test_amber_compatibility_NB_number(butane_dl):
dl = butane_dl(nb=False) oname = eex_find_files.get_scratch_directory("dl_compatibility.prmtop") dl.add_nb_parameter( atom_type=1, atom_type2=2, nb_name="LJ", nb_model="epsilon/sigma", nb_parameters={ 'sigma': 3.75, 'epsilon': 0.1947460018 ...
from datalayer and compare assert (dl.list_stored_nb_types() == ["LJ"]) assert (dl.list_nb_parameters(nb_name="LJ") == dl_new.list_nb_parameters( nb_name="LJ")) def test_amber_compatibility_NB_number(butane_dl):
63
64
155
14
49
MolSSI/EEX
eex/tests/test_amber.py
Python
test_amber_compatibility_NB_number
test_amber_compatibility_NB_number
151
172
151
152
14efc0128e7fc3c440c9cfce16f1f3b9e982ad00
bigcode/the-stack
train
f8b5e1f42e2301e5e0146d40
train
function
def test_amber_spce_read_atoms_value(spce_dl): data, dl = spce_dl atoms = dl.get_atoms([ "atom_name", "charge", "atomic_number", "mass", "residue_name", "residue_index", "xyz" ], by_value=True) assert atoms.shape[0] == 648 assert dl.get_atom_count() == 648 ...
def test_amber_spce_read_atoms_value(spce_dl):
data, dl = spce_dl atoms = dl.get_atoms([ "atom_name", "charge", "atomic_number", "mass", "residue_name", "residue_index", "xyz" ], by_value=True) assert atoms.shape[0] == 648 assert dl.get_atom_count() == 648 assert dl.get_atom_count("charge") == 648 ...
= eex.translators.amber.read_amber_file(dl, fname, blocksize=55) # print("-- Built AMBER SPCE DL --") yield (data, dl) dl.close() def test_amber_spce_read_data(spce_dl): data, dl = spce_dl assert data["VERSION"] == "V0001.000" # Test AMBER read by_value def test_amber_spce_read_atoms_value(spc...
100
100
334
13
86
MolSSI/EEX
eex/tests/test_amber.py
Python
test_amber_spce_read_atoms_value
test_amber_spce_read_atoms_value
30
53
30
30
478c5ca3538b7ab69cccadcac5223e15564b0b8a
bigcode/the-stack
train
cc533c6947308fc3bf8b2ce8
train
function
@pytest.mark.parametrize("backend", ["HDF5", "Memory"]) @pytest.mark.parametrize("molecule", [ "trappe_butane_single_molecule.prmtop", "trappe_propane_single_molecule.prmtop", "trappe_ethane_single_molecule.prmtop", ]) def test_amber_writer(molecule, backend): fname = eex_find_files.get_example_filename...
@pytest.mark.parametrize("backend", ["HDF5", "Memory"]) @pytest.mark.parametrize("molecule", [ "trappe_butane_single_molecule.prmtop", "trappe_propane_single_molecule.prmtop", "trappe_ethane_single_molecule.prmtop", ]) def test_amber_writer(molecule, backend):
fname = eex_find_files.get_example_filename("amber", "alkanes", molecule) # Read in the data dl = eex.datalayer.DataLayer(molecule, backend=backend) data = eex.translators.amber.read_amber_file(dl, fname) # Write out the data oname = eex_find_files.get_scratch_directory(molecule) eex.trans...
90 } assert eex.testing.dict_compare(box_info, ref_box) @pytest.mark.parametrize("backend", ["HDF5", "Memory"]) @pytest.mark.parametrize("molecule", [ "trappe_butane_single_molecule.prmtop", "trappe_propane_single_molecule.prmtop", "trappe_ethane_single_molecule.prmtop", ]) def test_amber_writer(mo...
89
89
297
72
17
MolSSI/EEX
eex/tests/test_amber.py
Python
test_amber_writer
test_amber_writer
121
148
121
127
1695362a597f28ce03640604a07b48771b686281
bigcode/the-stack
train
8879fa8050cd0475c36bd067
train
function
def test_amber_compatibility_functional_form(butane_dl): dl = butane_dl(ff=False) oname = eex_find_files.get_scratch_directory("dl_compatibility.prmtop") # Add incompatible functional form with pytest.raises(TypeError): dl.add_term_parameter(2, "fene", { "K": 1, "R0": ...
def test_amber_compatibility_functional_form(butane_dl):
dl = butane_dl(ff=False) oname = eex_find_files.get_scratch_directory("dl_compatibility.prmtop") # Add incompatible functional form with pytest.raises(TypeError): dl.add_term_parameter(2, "fene", { "K": 1, "R0": 1, "epsilon": 1, "sigma": 1, ...
oname) # Make sure we're getting pair parameters from DL nb_pairs = dl.list_nb_parameters(nb_name="LJ", nb_model="AB", itype="pair") assert (len(nb_pairs.keys()) == 3) def test_amber_compatibility_functional_form(butane_dl):
64
64
119
14
50
MolSSI/EEX
eex/tests/test_amber.py
Python
test_amber_compatibility_functional_form
test_amber_compatibility_functional_form
207
221
207
208
ad9e1b27162b7e037da5eac41999c5cbf1488fe3
bigcode/the-stack
train
104084f51e66457cb41fafb6
train
function
def test_amber_compatibility_NB_type(butane_dl): dl = butane_dl(nb=False) dl.add_nb_parameter( atom_type=1, nb_name="Buckingham", nb_model=None, nb_parameters=[1.0, 1.0, 1.0]) oname = eex_find_files.get_scratch_directory("dl_compatibility.prmtop") with pytest.raises(K...
def test_amber_compatibility_NB_type(butane_dl):
dl = butane_dl(nb=False) dl.add_nb_parameter( atom_type=1, nb_name="Buckingham", nb_model=None, nb_parameters=[1.0, 1.0, 1.0]) oname = eex_find_files.get_scratch_directory("dl_compatibility.prmtop") with pytest.raises(KeyError): eex.translators.amber.write_ambe...
utype={ 'sigma': 'angstrom', 'epsilon': 'kcal * mol ** -1' }) with pytest.raises(ValueError): eex.translators.amber.write_amber_file(dl, oname) def test_amber_compatibility_NB_type(butane_dl):
64
64
110
14
50
MolSSI/EEX
eex/tests/test_amber.py
Python
test_amber_compatibility_NB_type
test_amber_compatibility_NB_type
175
188
175
176
6afd6c1cc07ec92f01efc9b4e13b7f8ccf41a95d
bigcode/the-stack
train
2551482cb48b88098aa8a67a
train
function
def test_amber_spce_read_atoms_index(spce_dl): data, dl = spce_dl atoms = dl.get_atoms([ "atom_name", "charge", "atomic_number", "mass", "residue_name", "residue_index", "xyz" ], by_value=False) assert atoms.shape[0] == 648 assert set(np.unique(atoms["atom_n...
def test_amber_spce_read_atoms_index(spce_dl):
data, dl = spce_dl atoms = dl.get_atoms([ "atom_name", "charge", "atomic_number", "mass", "residue_name", "residue_index", "xyz" ], by_value=False) assert atoms.shape[0] == 648 assert set(np.unique(atoms["atom_name"])) == {"H1", "H2", "O"} assert np.allc...
"Z"]].min(), [-0.757235, -0.519927, -0.872856]) assert np.allclose(atoms[["X", "Y", "Z"]].max(), [19.388333, 19.213448, 19.423807]) # Test AMBER read by_index def test_amber_spce_read_atoms_index(spce_dl):
85
85
286
13
71
MolSSI/EEX
eex/tests/test_amber.py
Python
test_amber_spce_read_atoms_index
test_amber_spce_read_atoms_index
57
76
57
57
5e6d28ddf92422f130b5023d391361c52f9608ed
bigcode/the-stack
train
25c7f99c0f3b5eb14aefedfc
train
function
def test_amber_spce_read_bonds(spce_dl): data, dl = spce_dl # Test bond df bonds = dl.get_bonds() assert bonds.shape[0] == 648 assert dl.get_term_count(2, "total") == 648 assert set(np.unique(bonds["term_index"])) == {1, 2} assert set(dl.get_term_count(2)) == {1, 2, "total"}
def test_amber_spce_read_bonds(spce_dl):
data, dl = spce_dl # Test bond df bonds = dl.get_bonds() assert bonds.shape[0] == 648 assert dl.get_term_count(2, "total") == 648 assert set(np.unique(bonds["term_index"])) == {1, 2} assert set(dl.get_term_count(2)) == {1, 2, "total"}
-0.519927, -0.872856]) assert np.allclose(atoms[["X", "Y", "Z"]].max(), [19.388333, 19.213448, 19.423807]) def test_amber_spce_read_bonds(spce_dl):
64
64
101
13
51
MolSSI/EEX
eex/tests/test_amber.py
Python
test_amber_spce_read_bonds
test_amber_spce_read_bonds
79
87
79
79
81d8777c4c33cf6cc84ce3c15abc26a4f11b83f3
bigcode/the-stack
train
2279b81766fa7c65a84c28ee
train
function
@pytest.fixture(scope="module", params=["HDF5", "Memory"]) def spce_dl(request): fname = eex_find_files.get_example_filename("amber", "water", "spce.prmtop") dl = eex.datalayer.DataLayer("test_amber_read", backend=request.param) data = eex.translators.amber.re...
@pytest.fixture(scope="module", params=["HDF5", "Memory"]) def spce_dl(request):
fname = eex_find_files.get_example_filename("amber", "water", "spce.prmtop") dl = eex.datalayer.DataLayer("test_amber_read", backend=request.param) data = eex.translators.amber.read_amber_file(dl, fname, blocksize=55) # print("-- Built AMBER SPCE DL --") ...
""" Tests for LAMMPS IO """ import eex import numpy as np import pytest import pandas as pd import copy from . import eex_find_files @pytest.fixture(scope="module", params=["HDF5", "Memory"]) def spce_dl(request):
59
64
111
21
37
MolSSI/EEX
eex/tests/test_amber.py
Python
spce_dl
spce_dl
12
21
12
13
e74d6d42de7948126b9ee003cf56e656d348d429
bigcode/the-stack
train
6cf2fae3d7aec80ba1e51056
train
class
@pulumi.output_type class GetApiManagementServiceResult: """ A single API Management service resource in List or Get response. """ def __init__(__self__, additional_locations=None, certificates=None, created_at_utc=None, custom_properties=None, developer_portal_url=None, enable_client_certificate=None, ...
@pulumi.output_type class GetApiManagementServiceResult:
""" A single API Management service resource in List or Get response. """ def __init__(__self__, additional_locations=None, certificates=None, created_at_utc=None, custom_properties=None, developer_portal_url=None, enable_client_certificate=None, etag=None, gateway_regional_url=None, gateway_url=None, h...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
123
256
3,612
13
110
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/apimanagement/v20190101/get_api_management_service.py
Python
GetApiManagementServiceResult
GetApiManagementServiceResult
18
342
18
19
851a4f0e9f7e58106f79f7d70bfe51cc7650e323
bigcode/the-stack
train
6a1072d6edbcefd9ae675bdc
train
function
def get_api_management_service(resource_group_name: Optional[str] = None, service_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetApiManagementServiceResult: """ A single API Management service resource in List...
def get_api_management_service(resource_group_name: Optional[str] = None, service_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetApiManagementServiceResult:
""" A single API Management service resource in List or Get response. :param str resource_group_name: The name of the resource group. :param str service_name: The name of the API Management service. """ __args__ = dict() __args__['resourceGroupName'] = resource_group_name __args__['ser...
_email=self.notification_sender_email, portal_url=self.portal_url, private_ip_addresses=self.private_ip_addresses, provisioning_state=self.provisioning_state, public_ip_addresses=self.public_ip_addresses, publisher_email=self.publisher_email, publi...
156
156
520
47
109
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/apimanagement/v20190101/get_api_management_service.py
Python
get_api_management_service
get_api_management_service
382
430
382
384
6979e1b5645412cba2ea0e9e8277c5456fbee9b2
bigcode/the-stack
train
7d5ea3aab3f7e08468f7d542
train
class
class AwaitableGetApiManagementServiceResult(GetApiManagementServiceResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetApiManagementServiceResult( additional_locations=self.additional_locations, certificates=self...
class AwaitableGetApiManagementServiceResult(GetApiManagementServiceResult): # pylint: disable=using-constant-test
def __await__(self): if False: yield self return GetApiManagementServiceResult( additional_locations=self.additional_locations, certificates=self.certificates, created_at_utc=self.created_at_utc, custom_properties=self.custom_properties, ...
Virtual Network, External means the API Management deployment is set up inside a Virtual Network having an Internet Facing Endpoint, and Internal means that API Management deployment is setup inside a Virtual Network having an Intranet Facing Endpoint only. """ return pulumi.get(self, "virtual_network_...
82
82
275
25
57
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/apimanagement/v20190101/get_api_management_service.py
Python
AwaitableGetApiManagementServiceResult
AwaitableGetApiManagementServiceResult
345
379
345
346
952f369419e49c2821b53895b1696874a158d5a1
bigcode/the-stack
train
522e9fec4438787ed65fddbf
train
function
def mul_by_3(num): return num*3
def mul_by_3(num):
return num*3
def mul_by_2(num): return num*2 def mul_by_3(num):
20
64
13
7
12
Trigition/pypeline
tests/utils.py
Python
mul_by_3
mul_by_3
5
6
5
5
563c61f17e6161690d37e3e0b5e9328c72578db2
bigcode/the-stack
train
9271d01079f1c029e60704b9
train
function
def mul_by_2(num): return num*2
def mul_by_2(num):
return num*2
def mul_by_2(num):
7
64
13
7
0
Trigition/pypeline
tests/utils.py
Python
mul_by_2
mul_by_2
1
2
1
1
af79e3691b7def93db2fdb51acdb087f27a377db
bigcode/the-stack
train
9d2f31d2185bbda8a85d0b8a
train
function
def sentence_gen(corpus, size=7): if not size: size = random.randint(1, 15) m = MarkovGenerator(corpus) sentence = m.generate_markov_text(size) return sentence
def sentence_gen(corpus, size=7):
if not size: size = random.randint(1, 15) m = MarkovGenerator(corpus) sentence = m.generate_markov_text(size) return sentence
next_word gen_words = [] for i in range(size): gen_words.append(w1) w1, w2 = w2, random.choice(self.cache[w2]) gen_words.append(w2) return ' '.join(gen_words) def sentence_gen(corpus, size=7):
64
64
48
10
54
MLH-Fellowship/standupSummary
standupSummary/server/words/sentence_gen.py
Python
sentence_gen
sentence_gen
50
55
50
50
43502f0c5a5afab8e062b0d31e697716510e538d
bigcode/the-stack
train
6661726f5f2c7411e2d6c8c7
train
class
class MarkovGenerator(): """ Use a markov chain to generate the next word randomly from bigrams. """ def __init__(self, corpus): self.cache = {} self.corpus = corpus self.words = self.file_to_words() self.word_size = len(self.words) self.database() def file_...
class MarkovGenerator():
""" Use a markov chain to generate the next word randomly from bigrams. """ def __init__(self, corpus): self.cache = {} self.corpus = corpus self.words = self.file_to_words() self.word_size = len(self.words) self.database() def file_to_words(self): w...
import random class MarkovGenerator():
8
95
317
5
2
MLH-Fellowship/standupSummary
standupSummary/server/words/sentence_gen.py
Python
MarkovGenerator
MarkovGenerator
3
47
3
3
b0697cb0c01c359e505e930e2b16ce5a296c44e7
bigcode/the-stack
train
2442cd538ac1f16e89cac481
train
class
class TimeService(Service): def exposed_get_time(self): return time.ctime()
class TimeService(Service):
def exposed_get_time(self): return time.ctime()
import time from rpyc import Service from rpyc.utils.server import ThreadedServer class TimeService(Service):
26
64
18
5
20
hardikp/service_demo
rpyc/server.py
Python
TimeService
TimeService
7
9
7
7
6fc185ff3948231ee034878eabf555de93576620
bigcode/the-stack
train
c6b4c7065529378536e22d83
train
class
class PlacementMeshImplInputReader(object): """Handles input pipeline for PlacementMeshImpl.""" def __init__(self, placement_mesh_impl, ds_creator, mtf_input_shapes, ds_prefetch_size=tf.data.experimental.AUTOTUNE, is_eval_mode=False): ...
class PlacementMeshImplInputReader(object):
"""Handles input pipeline for PlacementMeshImpl.""" def __init__(self, placement_mesh_impl, ds_creator, mtf_input_shapes, ds_prefetch_size=tf.data.experimental.AUTOTUNE, is_eval_mode=False): self._placement_mesh_impl = placement_mesh_i...
tuple_types=[x.dtype for x in laidout_tensors0], tuple_shapes=[x.shape for x in laidout_tensors0]) enqueue_ops = infeed_queue.generate_enqueue_ops( all_laidout_tensors, tpu_ordinal_function=_tpu_ordinal_function_impl, placement_function=_placement_function_impl) return i...
88
88
295
8
79
doc22940/mesh
mesh_tensorflow/experimental/input_reader.py
Python
PlacementMeshImplInputReader
PlacementMeshImplInputReader
519
553
519
519
87fb38b3a5bdee2311b52259a48c5cd4f18c3cb7
bigcode/the-stack
train
35820cc6bfb6e7500ec54fe1
train
function
def _host_device_to_id(device_str): assert isinstance(device_str, str) id_string = device_str.lower().split("/task:")[1].split("/device:")[0] id_int = int(id_string) assert str(id_int) == id_string return id_int
def _host_device_to_id(device_str):
assert isinstance(device_str, str) id_string = device_str.lower().split("/task:")[1].split("/device:")[0] id_int = int(id_string) assert str(id_int) == id_string return id_int
import time import numpy as np import tensorflow.compat.v1 as tf # pylint: disable=g-direct-tensorflow-import from tensorflow.python.framework import ops from tensorflow.python.tpu import tpu_feed _NONE_PNUM = None _NO_DATA = None def _host_device_to_id(device_str):
64
64
62
9
54
doc22940/mesh
mesh_tensorflow/experimental/input_reader.py
Python
_host_device_to_id
_host_device_to_id
78
83
78
78
49432a26939700e8b68f295aa4a610e054dffcaf
bigcode/the-stack
train
bd428c9e65ca668831c5d4b3
train
class
class SubBatchSlicer(object): """Reads and distributes a sub-batch on a host.""" def __init__(self, sub_batch_ds_creator, host_id, all_sub_batch_pnums, simd_mesh_impl, mtf_input_shapes, external_worker, global_batch): self._host_id = host_id self._all_sub_batch_pnums = all_sub_batch_pnums ...
class SubBatchSlicer(object):
"""Reads and distributes a sub-batch on a host.""" def __init__(self, sub_batch_ds_creator, host_id, all_sub_batch_pnums, simd_mesh_impl, mtf_input_shapes, external_worker, global_batch): self._host_id = host_id self._all_sub_batch_pnums = all_sub_batch_pnums self._simd_mesh_impl = simd_...
future__ import absolute_import from __future__ import division from __future__ import print_function import collections import threading import time import numpy as np import tensorflow.compat.v1 as tf # pylint: disable=g-direct-tensorflow-import from tensorflow.python.framework import ops from tensorflow.python.tpu...
216
216
722
7
209
doc22940/mesh
mesh_tensorflow/experimental/input_reader.py
Python
SubBatchSlicer
SubBatchSlicer
94
169
94
94
f5f3b2812afaaaa2f77225b07c90c1d4717c81cc
bigcode/the-stack
train
e9954db3699e97babb23ce80
train
function
def _host_id_to_tf_device(host_id, external_worker): assert isinstance(host_id, int) if external_worker: return "/job:tpu_worker/task:{}/device:CPU:0".format(host_id) else: return "/task:{}/device:CPU:0".format(host_id)
def _host_id_to_tf_device(host_id, external_worker):
assert isinstance(host_id, int) if external_worker: return "/job:tpu_worker/task:{}/device:CPU:0".format(host_id) else: return "/task:{}/device:CPU:0".format(host_id)
isinstance(device_str, str) id_string = device_str.lower().split("/task:")[1].split("/device:")[0] id_int = int(id_string) assert str(id_int) == id_string return id_int def _host_id_to_tf_device(host_id, external_worker):
64
64
65
13
50
doc22940/mesh
mesh_tensorflow/experimental/input_reader.py
Python
_host_id_to_tf_device
_host_id_to_tf_device
86
91
86
86
304f41e3bf5791c53f095d6f1962d9ce68ac6959
bigcode/the-stack
train
f6ffbfb3163b90550bcd8cee
train
class
class ProcessDevices(object): """An utility class that maps between pnum to devices.""" def __init__(self, simd_mesh_impl): """Init tpu and host devices in logical order.""" self._num_cores = simd_mesh_impl.device_assignment.num_replicas self._ordered_ordinals = [] self._ordered_tpus = [] self...
class ProcessDevices(object):
"""An utility class that maps between pnum to devices.""" def __init__(self, simd_mesh_impl): """Init tpu and host devices in logical order.""" self._num_cores = simd_mesh_impl.device_assignment.num_replicas self._ordered_ordinals = [] self._ordered_tpus = [] self._ordered_hosts = [] self....
, input_tensor, mtf_input_shape, pnum): """Slice input_tensor according to mtf_input_shape and pnum.""" s_begin = self._simd_mesh_impl.slice_begin(mtf_input_shape, pnum) if not self._global_batch: # Always slice from 0 in the first dimension (batch dimension), since # input_tensor a sub-batch te...
171
171
570
5
165
doc22940/mesh
mesh_tensorflow/experimental/input_reader.py
Python
ProcessDevices
ProcessDevices
172
244
172
172
8b93d48fce446967f01bc62d55afb756df36b7f5
bigcode/the-stack
train
d58083f45c5876a3eab9bff7
train
class
class SimdMeshImplInputReader(object): """Handles input pipeline for SimdMeshImpl.""" def __init__(self, simd_mesh_impl, ds_creator, mtf_input_shapes, ds_prefetch_size=tf.data.experimental.AUTOTUNE, external_worker=True, is_e...
class SimdMeshImplInputReader(object):
"""Handles input pipeline for SimdMeshImpl.""" def __init__(self, simd_mesh_impl, ds_creator, mtf_input_shapes, ds_prefetch_size=tf.data.experimental.AUTOTUNE, external_worker=True, is_eval_mode=False): """Input pipeline ...
._num_hosts * self._num_cores_per_host tf.logging.info("Process Devices " "ordered_ordinals: {}, " "ordered_tpus: {}, " "ordered_hosts: {}, " "host_id_to_its_pnums: {}.".format( self.ordered_ordinals, ...
256
256
2,687
9
246
doc22940/mesh
mesh_tensorflow/experimental/input_reader.py
Python
SimdMeshImplInputReader
SimdMeshImplInputReader
247
516
247
247
aed974ff459c1574c80fba51e7d5de58b678c201
bigcode/the-stack
train
7fde30ac0ad56a8e17503c5f
train
class
class MetaPoeTask(type): """ This metaclass makes all decendents of PoeTask (task types) register themselves on declaration and validates that they include the expected class attributes. """ def __init__(cls, *args): super().__init__(*args) if cls.__name__ == "PoeTask": ...
class MetaPoeTask(type):
""" This metaclass makes all decendents of PoeTask (task types) register themselves on declaration and validates that they include the expected class attributes. """ def __init__(cls, *args): super().__init__(*args) if cls.__name__ == "PoeTask": return assert isi...
..config import PoeConfig from ..ui import PoeUi TaskDef = Union[str, Dict[str, Any], List[Union[str, Dict[str, Any]]]] _TASK_NAME_PATTERN = re.compile(r"^\w[\w\d\-\_\+\:]*$") class MetaPoeTask(type):
63
64
122
7
57
Parnassius/poethepoet
poethepoet/task/base.py
Python
MetaPoeTask
MetaPoeTask
33
45
33
33
417131e2866ddbd81d678996e7e113228d03bd23
bigcode/the-stack
train
80b142782ef42eb71e96ea95
train
class
class PoeTask(metaclass=MetaPoeTask): name: str content: TaskContent options: Dict[str, Any] __options__: Dict[str, Union[Type, Tuple[Type, ...]]] = {} __content_type__: Type = str __base_options: Dict[str, Union[Type, Tuple[Type, ...]]] = { "args": (dict, list), "capture_stdout...
class PoeTask(metaclass=MetaPoeTask):
name: str content: TaskContent options: Dict[str, Any] __options__: Dict[str, Union[Type, Tuple[Type, ...]]] = {} __content_type__: Type = str __base_options: Dict[str, Union[Type, Tuple[Type, ...]]] = { "args": (dict, list), "capture_stdout": (str), "deps": list, ...
.args import PoeTaskArgs from ..exceptions import PoeException from ..helpers import is_valid_env_var from ..helpers.env import resolve_envvars if TYPE_CHECKING: from ..context import RunContext from ..config import PoeConfig from ..ui import PoeUi TaskDef = Union[str, Dict[str, Any], List[Union[str, Di...
255
256
2,866
12
243
Parnassius/poethepoet
poethepoet/task/base.py
Python
PoeTask
PoeTask
51
435
51
51
aa573c63a3161be643cf5c8d01541ef6b0ce7371
bigcode/the-stack
train
5d9ed86f7f0c2bb663313310
train
class
class BaggingDeepEnsemble(DeepEnsemble): """Class for deep ensembles with bagging.""" def __init__(self, model, n_members, input_shape=None, weights_list=None): """Initialize a Bagging[1] Deep Ensemble that uses bootstrap resampled data. [1] Breiman, Leo. "Bagging predictors." Machine learning 24.2 (1996)...
class BaggingDeepEnsemble(DeepEnsemble):
"""Class for deep ensembles with bagging.""" def __init__(self, model, n_members, input_shape=None, weights_list=None): """Initialize a Bagging[1] Deep Ensemble that uses bootstrap resampled data. [1] Breiman, Leo. "Bagging predictors." Machine learning 24.2 (1996). Args: model: tf.keras.models...
dataset_in, y_in = dataset else: dataset_in, y_in = dataset, None model.fit( dataset_in, y_in, epochs=epoch + 1, initial_epoch=epoch, verbose=fit_verbose, **fit_kwargs) self.weights...
256
256
1,553
11
244
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
BaggingDeepEnsemble
BaggingDeepEnsemble
1,112
1,272
1,112
1,112
a3436316be59ca2b628044aa5d69ca66be64afc1
bigcode/the-stack
train
e23dacfb2ce784baa17b28d2
train
function
def _statistics_to_ordered_tuple(statistics, key_order): """Turn inputs into an ordered tuple. Note: facilitates single, multi-output or named multi-output Keras model API. Args: statistics: instance, tuple or dict of (named) statistics. key_order: in case of dict args, implied order. Returns: or...
def _statistics_to_ordered_tuple(statistics, key_order):
"""Turn inputs into an ordered tuple. Note: facilitates single, multi-output or named multi-output Keras model API. Args: statistics: instance, tuple or dict of (named) statistics. key_order: in case of dict args, implied order. Returns: ordered tuple of statistics. """ if statistics is None:...
instance. result = [] elif (isinstance(example, (tuple, list)) and isinstance(example[0], (tuple, list))): result = args else: result = args[0] return result def _statistics_to_ordered_tuple(statistics, key_order):
64
64
210
13
50
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
_statistics_to_ordered_tuple
_statistics_to_ordered_tuple
332
357
332
332
b0c04f3efb212eb5780f66d5d0c17c478f307338
bigcode/the-stack
train
2b6074380497a7a572f55531
train
class
class VBEnsemble(Ensemble): """Ensemble where each member is sampled from a tf.keras.models.Model. This ensemble assumes that the tf.keras.models.Model given in the constructor is a Variational Bayes (VB) model where an ensemble member is sampled each time a forward pass through the model is taken. """ de...
class VBEnsemble(Ensemble):
"""Ensemble where each member is sampled from a tf.keras.models.Model. This ensemble assumes that the tf.keras.models.Model given in the constructor is a Variational Bayes (VB) model where an ensemble member is sampled each time a forward pass through the model is taken. """ def __init__(self, model, n_me...
] self.weights_list.append(weights) def iter_members(self): """Iterate over ensemble members, handles weight swapping. Yields: `tf.keras.Model` for each member to be used for prediction. """ backup_weights = self.model.get_weights() try: for weight in self.weights_list: ...
99
99
330
8
91
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
VBEnsemble
VBEnsemble
576
622
576
576
86ad5a1714fada3a97db9e2e042e03162fcbd46c
bigcode/the-stack
train
d114e173ea7521e19e796364
train
function
def _process_dataset(dataset, output_names): """Turns dataset into keras-compatible inputs, and collated targets. Args: dataset: tf.data.Dataset, tuple(inputs,outputs), inputs output_names: in case of implied order of targets. Returns: inputs, ordered_targets. """ if isinstance(dataset, tuple):...
def _process_dataset(dataset, output_names):
"""Turns dataset into keras-compatible inputs, and collated targets. Args: dataset: tf.data.Dataset, tuple(inputs,outputs), inputs output_names: in case of implied order of targets. Returns: inputs, ordered_targets. """ if isinstance(dataset, tuple): if len(dataset) == 1: ordered_targ...
# pylint: disable=g-explicit-tensorflow-version-import import tensorflow_datasets as tfds from tqdm import tqdm from cold_posterior_bnn.core import model as bnnmodel from cold_posterior_bnn.core import statistics as stats def _process_dataset(dataset, output_names):
64
64
209
9
54
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
_process_dataset
_process_dataset
43
73
43
43
0471f9061b905ef2f449681b0896a847df57a504
bigcode/the-stack
train
acaa0ed7543af2a78f759503
train
class
class FreshReservoirIterator(object): """Iterator class for iterating over fresh items in the reservoir.""" def __init__(self, res, pos=0): self.res = res self.pos = pos def __iter__(self): return self def __next__(self): fresh_pos = self.res.fresh_position() while self.pos < len(self.res...
class FreshReservoirIterator(object):
"""Iterator class for iterating over fresh items in the reservoir.""" def __init__(self, res, pos=0): self.res = res self.pos = pos def __iter__(self): return self def __next__(self): fresh_pos = self.res.fresh_position() while self.pos < len(self.res.reservoir): if self.res.reservo...
outputs. """ outputs = model(inputs) return outputs def iter_members(self): for _ in range(len(self)): # self.model is expected to handle stochasticity. yield self.model def __len__(self): return self.n_members class FreshReservoirIterator(object):
64
64
163
7
56
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
FreshReservoirIterator
FreshReservoirIterator
625
650
625
625
fce4d77ab1ec90d021277b0c5610169097757f28
bigcode/the-stack
train
4e148ea11781e3f87b872ea6
train
class
class Ensemble(object): """Ensemble base class suitable for evaluation and prediction.""" def reset(self): """Clears the ensemble . E.g. an empirical ensemble will clear its members. Returns: """ raise NotImplementedError() def predict_ensemble(self, dataset): """Predict using all memb...
class Ensemble(object):
"""Ensemble base class suitable for evaluation and prediction.""" def reset(self): """Clears the ensemble . E.g. an empirical ensemble will clear its members. Returns: """ raise NotImplementedError() def predict_ensemble(self, dataset): """Predict using all members of ensemble. Ar...
-import import tensorflow_datasets as tfds from tqdm import tqdm from cold_posterior_bnn.core import model as bnnmodel from cold_posterior_bnn.core import statistics as stats def _process_dataset(dataset, output_names): """Turns dataset into keras-compatible inputs, and collated targets. Args: dataset: tf.d...
256
256
1,927
4
251
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
Ensemble
Ensemble
76
303
76
76
bb83ea03d908745e3e9507f885acfdabb476afa2
bigcode/the-stack
train
d8abf1ae326d8dad25177d35
train
class
class EmpiricalEnsemble(Ensemble): """Ensemble with each member defined by a set of weights for the same model. This ensemble can be created in a number of ways, including non-Bayesian ensembles; for example, we can use a collection of models obtained from multiple training runs started from scratch. """ ...
class EmpiricalEnsemble(Ensemble):
"""Ensemble with each member defined by a set of weights for the same model. This ensemble can be created in a number of ways, including non-Bayesian ensembles; for example, we can use a collection of models obtained from multiple training runs started from scratch. """ def __init__(self, m...
ordered_stats = (statistics,) return ordered_stats def _collate_tensor(all_tensors, key_order, func=np.concatenate): """Combines iterable of groups of tensors using `func` along first dimension. Args: all_tensors: iterable of dicts, tuples or single instances. key_order: keys of model output order. ...
256
256
1,315
9
246
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
EmpiricalEnsemble
EmpiricalEnsemble
390
573
390
390
e55d832a40c200ff635151bbfa559ab225bfe591
bigcode/the-stack
train
5d52a0f2c0bac6a4b7ba38c2
train
function
def _format_like_example(args, example, key_order): """Returns args as instance, ordered list or dict, following `example` format. Note: facilitates single, multi-output or named multi-output Keras model API. Args: args: ordered tuple of arguments. example: example of format to follow: single instance, ...
def _format_like_example(args, example, key_order):
"""Returns args as instance, ordered list or dict, following `example` format. Note: facilitates single, multi-output or named multi-output Keras model API. Args: args: ordered tuple of arguments. example: example of format to follow: single instance, tuple or dict. key_order: keys for arguments in ...
path to ensemble weights. """ raise NotImplementedError() def load_ensemble(self, ensemble_dir): """Load model(s) and weights. Args: ensemble_dir: path to ensemble weights. """ raise NotImplementedError() def _format_like_example(args, example, key_order):
64
64
200
12
52
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
_format_like_example
_format_like_example
306
329
306
306
098ae94c3cdf2ecc2da5ff8c69fcbe8fc471591c
bigcode/the-stack
train
8cb8618cf5c9b9c6bf77f4fe
train
class
class FreshReservoirEnsemble(EmpiricalEnsemble): """Fresh reservoir ensemble which dynamically subsamples ensemble members. This ensemble can dynamically grow using the `append` method and can be called throughout MCMC sampling to keep models. """ def __init__(self, model, inpu...
class FreshReservoirEnsemble(EmpiricalEnsemble):
"""Fresh reservoir ensemble which dynamically subsamples ensemble members. This ensemble can dynamically grow using the `append` method and can be called throughout MCMC sampling to keep models. """ def __init__(self, model, input_shape, capacity=20, ...
count = 0 fresh_pos = self.fresh_position() for item in self.reservoir: if item is not None: if item[0] < fresh_pos: continue count += 1 return count def __iter__(self): """Iterator over all fresh items in the reservoir.""" return FreshReservoirIterator(self)...
92
92
307
12
80
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
FreshReservoirEnsemble
FreshReservoirEnsemble
736
775
736
736
cb52b77e429ff8d3ed71d43214c4be9bd7904c55
bigcode/the-stack
train
2b1f3b3190d414d92e72afab
train
class
class FreshReservoir(object): """Fresh reservoir sampling. [Reservoir sampling](https://en.wikipedia.org/wiki/Reservoir_sampling) is an algorithm to obtain a set of items uniformly sampled from a stream of items. A _fresh_ reservoir is a reservoir which allows selection over a given fraction of the last item...
class FreshReservoir(object):
"""Fresh reservoir sampling. [Reservoir sampling](https://en.wikipedia.org/wiki/Reservoir_sampling) is an algorithm to obtain a set of items uniformly sampled from a stream of items. A _fresh_ reservoir is a reservoir which allows selection over a given fraction of the last items seen. As an example, in t...
# self.model is expected to handle stochasticity. yield self.model def __len__(self): return self.n_members class FreshReservoirIterator(object): """Iterator class for iterating over fresh items in the reservoir.""" def __init__(self, res, pos=0): self.res = res self.pos = pos def _...
198
199
666
6
192
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
FreshReservoir
FreshReservoir
653
733
653
653
1356c82ae2eb7c3c67ed0ed02ee40f5a09e3c3a9
bigcode/the-stack
train
c14dc033df296a984b3dbabf
train
function
def _collate_tensor(all_tensors, key_order, func=np.concatenate): """Combines iterable of groups of tensors using `func` along first dimension. Args: all_tensors: iterable of dicts, tuples or single instances. key_order: keys of model output order. func: function to use for combination of elements. ...
def _collate_tensor(all_tensors, key_order, func=np.concatenate):
"""Combines iterable of groups of tensors using `func` along first dimension. Args: all_tensors: iterable of dicts, tuples or single instances. key_order: keys of model output order. func: function to use for combination of elements. Returns: ordered_targets: Unzipped tensors with structure of `...
in key_order) elif isinstance(statistics, (tuple, list)) and len(statistics) and isinstance( statistics[0], (tuple, list)): ordered_stats = statistics else: ordered_stats = (statistics,) return ordered_stats def _collate_tensor(all_tensors, key_order, func=np.concatenate):
70
70
236
16
53
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
_collate_tensor
_collate_tensor
360
387
360
360
fd3b45455f8556398f78b154696b4d4bf0b24e8a
bigcode/the-stack
train
be2dfa4562440661eb794a3d
train
class
class FreshReservoirSamplingEnsemble(FreshReservoirEnsemble): """Fresh reservoir ensemble which dynamically subsamples ensemble members. A custom sampling function must be provided by the user to iterate over the fresh reservoir. This ensemble can dynamically grow using the `append[_maybe]` methods and can ...
class FreshReservoirSamplingEnsemble(FreshReservoirEnsemble):
"""Fresh reservoir ensemble which dynamically subsamples ensemble members. A custom sampling function must be provided by the user to iterate over the fresh reservoir. This ensemble can dynamically grow using the `append[_maybe]` methods and can be called throughout MCMC sampling to keep models. """ de...
, reservoir, clone_model) def append_maybe(self, get_weights_fn): """Add a member to the ensemble. Allows for lazy copy of weights. Args: get_weights_fn: function that returns set of weights. Returns: Insertion index in case item was ins...
98
98
327
14
84
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
FreshReservoirSamplingEnsemble
FreshReservoirSamplingEnsemble
778
817
778
778
908012ad024133e431bb21844b2605bc6a04b541
bigcode/the-stack
train
3e5e42384d9e8b652370c2a4
train
class
class DeepEnsemble(EmpiricalEnsemble): """An empirical ensemble that enables training of Deep Ensembles [1, 2]. Note: DeepEnsemble.fit() is experimental. A deep ensemble combines copies of the same deep neural network, each trained from scratch using different initializations. It is an effective baseline for ...
class DeepEnsemble(EmpiricalEnsemble):
"""An empirical ensemble that enables training of Deep Ensembles [1, 2]. Note: DeepEnsemble.fit() is experimental. A deep ensemble combines copies of the same deep neural network, each trained from scratch using different initializations. It is an effective baseline for model uncertainty. References: ...
__(self, model, input_shape, sampler, capacity=20, freshness=50.0): """Initialize a fresh reservoir ensemble. Args: model: tf.keras.Model input_shape: tf.keras.models.Model input_shape to be used with Model.build sampler: function that accepts self as an argument and iterates over wei...
256
256
2,567
10
246
deepneuralmachine/google-research
cold_posterior_bnn/core/ensemble.py
Python
DeepEnsemble
DeepEnsemble
820
1,109
820
820
d0a1a17d5c9b1c5ad09e1f1358fce4fab013d15a
bigcode/the-stack
train
d0b1557771e59d05db5b6016
train
function
def zip_entry_exists(zipf, name): try: # Trick ZipInfo into sanitizing the name for us so this awful module stops spewing warnings. zinfo = zipfile.ZipInfo.from_file("Resources", name) zipf.getinfo(zinfo.filename) except KeyError: return False return True
def zip_entry_exists(zipf, name):
try: # Trick ZipInfo into sanitizing the name for us so this awful module stops spewing warnings. zinfo = zipfile.ZipInfo.from_file("Resources", name) zipf.getinfo(zinfo.filename) except KeyError: return False return True
if filename in ignore_set: continue path = p(source, filename) target_path = filename if os.path.isdir(path): copy_dir_into_zip(path, target_path, zipf) else: zipf.write(path, target_path) def zip_entry_exists(zipf, name):
64
64
70
9
55
Phantom-Lily/space-station-14
Tools/package_client_build.py
Python
zip_entry_exists
zip_entry_exists
132
139
132
132
e53d29fd3cd9c8565477163dc77c2cd769511de6
bigcode/the-stack
train
036239ad076bdc50cc1db2f8
train
function
def copy_dir_into_zip(directory, basepath, zipf): if basepath and not zip_entry_exists(zipf, basepath): zipf.write(directory, basepath) for root, _, files in os.walk(directory): relpath = os.path.relpath(root, directory) if relpath != "." and not zip_entry_exists(zipf, p(basepath, relpa...
def copy_dir_into_zip(directory, basepath, zipf):
if basepath and not zip_entry_exists(zipf, basepath): zipf.write(directory, basepath) for root, _, files in os.walk(directory): relpath = os.path.relpath(root, directory) if relpath != "." and not zip_entry_exists(zipf, p(basepath, relpath)): zipf.write(root, p(basepath, rel...
izing the name for us so this awful module stops spewing warnings. zinfo = zipfile.ZipInfo.from_file("Resources", name) zipf.getinfo(zinfo.filename) except KeyError: return False return True def copy_dir_into_zip(directory, basepath, zipf):
64
64
214
13
50
Phantom-Lily/space-station-14
Tools/package_client_build.py
Python
copy_dir_into_zip
copy_dir_into_zip
142
163
142
142
0d3fc5b6c6e730e5120135a4b1bb6f8ebe08b556
bigcode/the-stack
train
0832821f227060cdf4f8fa72
train
function
def build(skip_build: bool) -> None: # Run a full build. print(Fore.GREEN + "Building project..." + Style.RESET_ALL) if not skip_build: subprocess.run([ "dotnet", "build", p("Content.Client", "Content.Client.csproj"), "-c", "Release", "--n...
def build(skip_build: bool) -> None: # Run a full build.
print(Fore.GREEN + "Building project..." + Style.RESET_ALL) if not skip_build: subprocess.run([ "dotnet", "build", p("Content.Client", "Content.Client.csproj"), "-c", "Release", "--nologo", "/v:m", "/t:Rebuild", ...
old build artifacts (if any)..." + Style.RESET_ALL) if os.path.exists("bin"): shutil.rmtree("bin") # Be advised this is called from package_server_build during a Hybrid-ACZ build. def build(skip_build: bool) -> None: # Run a full build.
64
64
185
17
47
Phantom-Lily/space-station-14
Tools/package_client_build.py
Python
build
build
83
109
83
84
f7fe5126652e2b46b52f45c0e972c4e1135173c8
bigcode/the-stack
train
f316835b0eaa60ee06e367f8
train
function
def do_resource_copy(source, zipf, ignore_set): for filename in os.listdir(source): if filename in ignore_set: continue path = p(source, filename) target_path = filename if os.path.isdir(path): copy_dir_into_zip(path, target_path, zipf) else: ...
def do_resource_copy(source, zipf, ignore_set):
for filename in os.listdir(source): if filename in ignore_set: continue path = p(source, filename) target_path = filename if os.path.isdir(path): copy_dir_into_zip(path, target_path, zipf) else: zipf.write(path, target_path)
# Cool we're done. client_zip.close() def copy_resources(zipf): ignore_set = SHARED_IGNORED_RESOURCES.union(CLIENT_IGNORED_RESOURCES) do_resource_copy("Resources", zipf, ignore_set) def do_resource_copy(source, zipf, ignore_set):
64
64
76
12
52
Phantom-Lily/space-station-14
Tools/package_client_build.py
Python
do_resource_copy
do_resource_copy
118
129
118
118
9cb38158b8273ac5e4fba4687f0ecfdfe2203f56
bigcode/the-stack
train
43ca97bb57c3d4dd438e7f4a
train
function
def copy_content_assemblies(target, zipf): files = [] source_dir = p("bin", "Content.Client") base_assemblies = CLIENT_CONTENT_ASSEMBLIES # Include content assemblies. for asm in base_assemblies: files.append(asm + ".dll") # If PDB available, include it aswell. pdb_path = a...
def copy_content_assemblies(target, zipf):
files = [] source_dir = p("bin", "Content.Client") base_assemblies = CLIENT_CONTENT_ASSEMBLIES # Include content assemblies. for asm in base_assemblies: files.append(asm + ".dll") # If PDB available, include it aswell. pdb_path = asm + ".pdb" if os.path.exists(p(sou...
Style.DIM, diskroot=directory, ziproot=zipf.filename, zipfile=os.path.normpath(zippath)) print(Fore.CYAN + message + Style.RESET_ALL) zipf.write(filepath, zippath) def copy_content_assemblies(target, zipf):
64
64
153
11
53
Phantom-Lily/space-station-14
Tools/package_client_build.py
Python
copy_content_assemblies
copy_content_assemblies
166
185
166
166
62d5c8c5ec52615f66c1587c9248d39ff2adbe59
bigcode/the-stack
train
9eb2d67399db3856ec2d2d79
train
function
def wipe_bin(): print(Fore.BLUE + Style.DIM + "Clearing old build artifacts (if any)..." + Style.RESET_ALL) if os.path.exists("bin"): shutil.rmtree("bin")
def wipe_bin():
print(Fore.BLUE + Style.DIM + "Clearing old build artifacts (if any)..." + Style.RESET_ALL) if os.path.exists("bin"): shutil.rmtree("bin")
print(Fore.BLUE + Style.DIM + # "Cleaning old release packages (release/)..." + Style.RESET_ALL) # shutil.rmtree("release") else: os.mkdir("release") if not skip_build: wipe_bin() build(skip_build) def wipe_bin():
64
64
47
4
60
Phantom-Lily/space-station-14
Tools/package_client_build.py
Python
wipe_bin
wipe_bin
75
80
75
75
3ec2a9de6cb278f0de3928bbc2fac044008d2de7
bigcode/the-stack
train
e94d73fefa730b9bd49c3520
train
function
def main() -> None: parser = argparse.ArgumentParser( description="Packages the SS14 client.") parser.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS) args = parser.parse_args() skip_build = args.skip_build if os.pat...
def main() -> None:
parser = argparse.ArgumentParser( description="Packages the SS14 client.") parser.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS) args = parser.parse_args() skip_build = args.skip_build if os.path.exists("release"):...
directory", ".DS_Store" } CLIENT_IGNORED_RESOURCES = { "Maps", "emotes.xml", "Groups" } CLIENT_CONTENT_ASSEMBLIES = [ "Content.Client", "Content.Shared", "Content.Shared.Database" ] def main() -> None:
64
64
134
6
58
Phantom-Lily/space-station-14
Tools/package_client_build.py
Python
main
main
50
72
50
50
9548ded74335e85a7bed2189b90c491ffc8c16de
bigcode/the-stack
train
f13dc4b267319e4d8b024a2c
train
function
def copy_resources(zipf): ignore_set = SHARED_IGNORED_RESOURCES.union(CLIENT_IGNORED_RESOURCES) do_resource_copy("Resources", zipf, ignore_set)
def copy_resources(zipf):
ignore_set = SHARED_IGNORED_RESOURCES.union(CLIENT_IGNORED_RESOURCES) do_resource_copy("Resources", zipf, ignore_set)
.ZipFile( p("release", "SS14.Client.zip"), "w", compression=zipfile.ZIP_DEFLATED) copy_resources(client_zip) copy_content_assemblies("Assemblies", client_zip) # Cool we're done. client_zip.close() def copy_resources(zipf):
64
64
41
6
58
Phantom-Lily/space-station-14
Tools/package_client_build.py
Python
copy_resources
copy_resources
112
115
112
112
7741df34f7fdf9f6417e6e27cefb70bde3f55c37
bigcode/the-stack
train
c9f97cf8fe2b95d5cab4411a
train
function
@app.task(max_retries=3, throw=False) def update_associated_submissions(database_name, form_model_id, deleted_question_codes): try: manager = get_db_manager(database_name) #update_submissions_for_form_code_change(manager, new_form_code, old_form_code) remove_deleted_questions_from_submission...
@app.task(max_retries=3, throw=False) def update_associated_submissions(database_name, form_model_id, deleted_question_codes):
try: manager = get_db_manager(database_name) #update_submissions_for_form_code_change(manager, new_form_code, old_form_code) remove_deleted_questions_from_submissions(manager, form_model_id, deleted_question_codes) except Exception as e: current.retry(exc=e)
_model_id) for survey_response in survey_responses: for code in deleted_question_codes: survey_response._doc.values.pop(code, None) survey_response.save() @app.task(max_retries=3, throw=False) def update_associated_submissions(database_name, form_model_id, deleted_questio...
64
64
88
28
36
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
update_associated_submissions
update_associated_submissions
360
367
360
361
a6ca70513fae34e5cfea66ab4557274ff0f6da88
bigcode/the-stack
train
3432be1ea9cd147310d3977e
train
function
@login_required @session_not_expired @is_datasender @csrf_exempt @is_not_expired @is_project_exist def edit_project(request, project_id): manager = get_database_manager(request.user) dashboard_page = settings.HOME_PAGE + "?deleted=true" questionnaire = Project.get(manager, project_id) if questionnaire.i...
@login_required @session_not_expired @is_datasender @csrf_exempt @is_not_expired @is_project_exist def edit_project(request, project_id):
manager = get_database_manager(request.user) dashboard_page = settings.HOME_PAGE + "?deleted=true" questionnaire = Project.get(manager, project_id) if questionnaire.is_void(): return HttpResponseRedirect(dashboard_page) if request.method == 'GET': return render_to_response('project/c...
': template.get('form_code'), 'existing_questions': json.dumps(template.get('json_fields'), default=field_to_json)} return HttpResponse(json.dumps(template_details), content_type='application/json') def _get_deleted_question_codes(new_codes, old_codes): diff = set(old_codes) - set(new_...
164
164
548
38
125
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
edit_project
edit_project
119
172
119
125
4c67a7c3c5e4d97f5792cd4d6e9aefbf905acacb
bigcode/the-stack
train