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
9523581793791eec9d11e9b2
train
class
class SaveFigures: def __init__(self, resultsName, resultsPath, figures): figures.Overview.figure.savefig( join(resultsPath, 'plot_Overview.png'), bbox_inches='tight') figures.GFPSummary.figure.savefig( join(resultsPath, 'plot_GFP_Summary.png'), bbox_inches='tight') ...
class SaveFigures:
def __init__(self, resultsName, resultsPath, figures): figures.Overview.figure.savefig( join(resultsPath, 'plot_Overview.png'), bbox_inches='tight') figures.GFPSummary.figure.savefig( join(resultsPath, 'plot_GFP_Summary.png'), bbox_inches='tight') figures.GFPDetail.f...
Epoch marker file filename += '.mrk' with open(join(resultsPath, filename), 'w') as f: f.writelines( 'TL02\n{:>12}\t{:>12}\t"Origin"\n'.format(preFrame, preFrame)) class SaveFigures:
64
64
159
4
60
miykael/LINEViewer
lineviewer/FileHandler.py
Python
SaveFigures
SaveFigures
329
345
329
330
964233b1d900605fd82c0ff7722552610b590f5a
bigcode/the-stack
train
bf7e54349bb53cf560deb410
train
class
class TestBlockchain(unittest.TestCase): def setUp(self): self.tearDown() blockchain_repo.session.add_all(TestVariables().blockchain) blockchain_repo.session.commit() @patch("common.utils.Utils.report_slack") def test_get_all_blockchain(self, mock_report_slack): success_res...
class TestBlockchain(unittest.TestCase):
def setUp(self): self.tearDown() blockchain_repo.session.add_all(TestVariables().blockchain) blockchain_repo.session.commit() @patch("common.utils.Utils.report_slack") def test_get_all_blockchain(self, mock_report_slack): success_response_1 = {'status': 'success', 'data': [ ...
import json import unittest from unittest.mock import patch from application.handler.blockchain_handlers import get_all_blockchain from infrastructure.models import BlockChainDBModel, TransactionDBModel, ConversionTransactionDBModel, \ ConversionDBModel, WalletPairDBModel, TokenPairDBModel, ConversionFeeDBModel, T...
109
176
589
7
102
singnet/snet-converter-services
testcases/functional_testcases/test_blockchain_handlers.py
Python
TestBlockchain
TestBlockchain
14
66
14
15
552428665bac87d69bf279a431b926bb289305de
bigcode/the-stack
train
78a7a3728d709bbf30983a14
train
class
class NewsCategoriesSitemap(Sitemap): changefreq = "never" priority = 0.5 def items(self): return Category.objects.all()
class NewsCategoriesSitemap(Sitemap):
changefreq = "never" priority = 0.5 def items(self): return Category.objects.all()
# -*- coding: utf-8 -*- from django.contrib.sitemaps import Sitemap from ..models import Category, News class NewsCategoriesSitemap(Sitemap):
33
64
34
8
24
conformist-mw/aldryn-news
aldryn_news/sitemaps/sitemap.py
Python
NewsCategoriesSitemap
NewsCategoriesSitemap
7
12
7
7
58fa33eabf3ecd4c0bb037efd6bb36b8b20b13e4
bigcode/the-stack
train
928f135a4913c6d4abe0e5f4
train
class
class NewsSitemap(Sitemap): changefreq = "yearly" priority = 0.5 def items(self): return News.published.all() def lastmod(self, obj): return obj.publication_start
class NewsSitemap(Sitemap):
changefreq = "yearly" priority = 0.5 def items(self): return News.published.all() def lastmod(self, obj): return obj.publication_start
coding: utf-8 -*- from django.contrib.sitemaps import Sitemap from ..models import Category, News class NewsCategoriesSitemap(Sitemap): changefreq = "never" priority = 0.5 def items(self): return Category.objects.all() class NewsSitemap(Sitemap):
64
64
50
7
57
conformist-mw/aldryn-news
aldryn_news/sitemaps/sitemap.py
Python
NewsSitemap
NewsSitemap
15
23
15
15
53da77a91f532ead749fb47fd54973c8a760b7fe
bigcode/the-stack
train
ce59a16e0178c346403bd260
train
function
def imwrite_uint16_png(image_path, image, alignratio_path): """ This function writes the hdr image as a uint16 png and stores its related align_ratio value in the specified paths. Args: image_path (str): Write path to the uint16 png image (needs to finish in .png, e.g. 0000.png) ima...
def imwrite_uint16_png(image_path, image, alignratio_path):
""" This function writes the hdr image as a uint16 png and stores its related align_ratio value in the specified paths. Args: image_path (str): Write path to the uint16 png image (needs to finish in .png, e.g. 0000.png) image (np.ndarray): HDR image in float format. alig...
).astype(np.float32) # Load image without changing bit depth and normalize by align ratio return cv2.cvtColor(cv2.imread(image_path, cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB) / align_ratio def imwrite_uint16_png(image_path, image, alignratio_path):
66
66
220
15
50
LingkaiZhu1999/Evaluation
data_io.py
Python
imwrite_uint16_png
imwrite_uint16_png
22
38
22
22
b995c7a32e2eddef2a57046acf0e76370634cb72
bigcode/the-stack
train
2fce4f362fd2e9b3d93aec0d
train
function
def imread_uint16_png(image_path, alignratio_path): """ This function loads a uint16 png image from the specified path and restore its original image range with the ratio stored in the specified alignratio.npy respective path. Args: image_path (str): Path to the uint16 png image alignratio...
def imread_uint16_png(image_path, alignratio_path):
""" This function loads a uint16 png image from the specified path and restore its original image range with the ratio stored in the specified alignratio.npy respective path. Args: image_path (str): Path to the uint16 png image alignratio_path (str): Path to the alignratio.npy file corresp...
import cv2 import numpy as np def imread_uint16_png(image_path, alignratio_path):
22
64
190
13
8
LingkaiZhu1999/Evaluation
data_io.py
Python
imread_uint16_png
imread_uint16_png
4
20
4
4
1da9969c95240214012ef5c803cd448474b14b58
bigcode/the-stack
train
06121a46e327c2368b308a05
train
function
def archive_screenshot(userid, filename, data): if not os.path.exists("archive/%s/" % userid): os.makedirs("archive/%s/" % userid) if not os.path.exists("archive/%s/%s" % (userid, filename)): with open("archive/%s/%s" % (userid, filename), 'wb') as f: f.write(data)
def archive_screenshot(userid, filename, data):
if not os.path.exists("archive/%s/" % userid): os.makedirs("archive/%s/" % userid) if not os.path.exists("archive/%s/%s" % (userid, filename)): with open("archive/%s/%s" % (userid, filename), 'wb') as f: f.write(data)
w') as f: json.dump(obj, f) except IOError as ex: print("[JSON] Exception occured saving %s!\n%s" % (filename, ex)) else: print("[JSON] Saved %s successfully." % filename) def archive_screenshot(userid, filename, data):
64
64
81
10
54
cyberkitsune/DDRBot
DDRBot.py
Python
archive_screenshot
archive_screenshot
49
55
49
49
f9145d02b50d4c5f9db8cb3df09dc52ddc435fc5
bigcode/the-stack
train
9992e9766c47e30b034b5469
train
function
def divide_chunks(l, n): # looping till length l for i in range(0, len(l), n): yield l[i:i + n]
def divide_chunks(l, n): # looping till length l
for i in range(0, len(l), n): yield l[i:i + n]
, IIDXScore, DBTaskWorkItem from DDRGenie.DDRDataTypes import DDRParsedData, DDRScreenshot from DDRGenie.IIDXDataTypes import IIDXParsedData, IIDXScreenshot db.connect() def divide_chunks(l, n): # looping till length l
64
64
35
14
50
cyberkitsune/DDRBot
DDRBot.py
Python
divide_chunks
divide_chunks
21
24
21
22
ee64b57cef05ad6e676984213eb3c49d4fafa7db
bigcode/the-stack
train
ac4f3b6b6bde8c1265af1891
train
function
def load_json(filename): try: with open(filename, 'r') as f: obj = json.load(f) except IOError as ex: print("[JSON] Exception occured loading %s!\n%s" % (filename, ex)) return None else: print("[JSON] Loaded %s successfully." % filename) return obj
def load_json(filename):
try: with open(filename, 'r') as f: obj = json.load(f) except IOError as ex: print("[JSON] Exception occured loading %s!\n%s" % (filename, ex)) return None else: print("[JSON] Loaded %s successfully." % filename) return obj
userid): os.makedirs("archive/%s/" % userid) if not os.path.exists("archive/%s/%s" % (userid, filename)): with open("archive/%s/%s" % (userid, filename), 'wb') as f: f.write(data) def load_json(filename):
64
64
76
5
59
cyberkitsune/DDRBot
DDRBot.py
Python
load_json
load_json
58
67
58
58
a276d332c1d52a3e2bda288c8705450f1b791138
bigcode/the-stack
train
302a2c2f869e88d0d24ecb8a
train
function
def generate_itg_embed(groovestats_data, song_info): """ :type groovestats_data: GSScoreEntry :type song_info: GSSongInfo """ emb = discord.Embed() emb.title = "<:ddr_arrow:687073061039505454> %s by %s (%sSP %s)" % (song_info.song_name, song_info.song_artist, groovestats_data.difficult...
def generate_itg_embed(groovestats_data, song_info):
""" :type groovestats_data: GSScoreEntry :type song_info: GSSongInfo """ emb = discord.Embed() emb.title = "<:ddr_arrow:687073061039505454> %s by %s (%sSP %s)" % (song_info.song_name, song_info.song_artist, groovestats_data.difficulty[0], song_info.song_level) emb.description = "Pl...
)" % (score_data.good_count, good_percent), inline=True) emb.add_field(name="<:eming:572201816792629267> Miss", value="%s (%0.2f%%)" % (score_data.miss_count, miss_percent), inline=True) emb.add_field(name="<:emiok:572201794982248452> OK", value="%s" % score_data.OK_count, inline=True) emb.set_footer(text="...
206
206
689
15
190
cyberkitsune/DDRBot
DDRBot.py
Python
generate_itg_embed
generate_itg_embed
226
277
226
226
29af76d15fafbf29feff893aa5b85ceecb1d102a
bigcode/the-stack
train
67f51039e9afd3cb5cacd2aa
train
function
def harvest_cover(ss, pd): """ Harvests an album cover if it's needed. :type ss: DDRScreenshot :type pd: DDRParsedData """ if os.path.exists("covers/"): if not os.path.exists("covers/%s.png" % pd.song_title.value.strip()): print("[CoverScrape] Harvesting for %s" % pd.song_tit...
def harvest_cover(ss, pd):
""" Harvests an album cover if it's needed. :type ss: DDRScreenshot :type pd: DDRParsedData """ if os.path.exists("covers/"): if not os.path.exists("covers/%s.png" % pd.song_title.value.strip()): print("[CoverScrape] Harvesting for %s" % pd.song_title) ss.album_ar...
from DDRGenie.IIDXDataTypes import IIDXParsedData, IIDXScreenshot db.connect() def divide_chunks(l, n): # looping till length l for i in range(0, len(l), n): yield l[i:i + n] def harvest_cover(ss, pd):
64
64
106
7
57
cyberkitsune/DDRBot
DDRBot.py
Python
harvest_cover
harvest_cover
27
36
27
27
e201c0cecccec4f5357b6958527c210880af157a
bigcode/the-stack
train
5deab852a1b7f09943dd945b
train
function
def generate_embed_iidx(score_data, score_player): """ :type score_data: IIDXParsedData """ emb = discord.Embed() emb.title = "<:iidx:540794989316145162> %s by %s [%s %s]" % (score_data.song_title, score_data.song_artist, score_data.chart_play_mode, score_data....
def generate_embed_iidx(score_data, score_player):
""" :type score_data: IIDXParsedData """ emb = discord.Embed() emb.title = "<:iidx:540794989316145162> %s by %s [%s %s]" % (score_data.song_title, score_data.song_artist, score_data.chart_play_mode, score_data.chart_difficulty) emb.description = "Played by ...
982248452> OK", value="%s" % score_data.score_OK_count, inline=True) emb.set_footer(text="DDR-Genie [β] - C: %i%%" % int(score_data.title_conf * 100)) if os.path.exists("covers/%s.png" % score_data.song_title.value.strip()): emb.set_thumbnail(url="https://assets.cyberkitsune.net/ddr_cover/%s.png" % urll...
135
135
452
11
123
cyberkitsune/DDRBot
DDRBot.py
Python
generate_embed_iidx
generate_embed_iidx
122
146
122
122
016239d90549a0c3abce1b8347c21323e815bd33
bigcode/the-stack
train
e26b7f651183b2d4153d4a9a
train
function
def save_json(filename, obj): try: with open(filename, 'w') as f: json.dump(obj, f) except IOError as ex: print("[JSON] Exception occured saving %s!\n%s" % (filename, ex)) else: print("[JSON] Saved %s successfully." % filename)
def save_json(filename, obj):
try: with open(filename, 'w') as f: json.dump(obj, f) except IOError as ex: print("[JSON] Exception occured saving %s!\n%s" % (filename, ex)) else: print("[JSON] Saved %s successfully." % filename)
not os.path.exists("covers/%s.png" % pd.song_title.value.strip()): print("[CoverScrape] Harvesting for %s" % pd.song_title) ss.album_art.save("covers/%s.png" % pd.song_title.value.strip(), format='PNG') def save_json(filename, obj):
64
64
70
7
57
cyberkitsune/DDRBot
DDRBot.py
Python
save_json
save_json
39
46
39
39
4dc28bd713a183a2ba4e02b38facb0e81b386e36
bigcode/the-stack
train
45e2dc3bd258e23741a55e09
train
function
def update_songdb(): if not os.path.exists("DDRGenie/genie_assets/a20_songlist.json"): print("[GENIE] Updating DDR song DB from Konami") ddrapi = DDRApi(EAGate()) songs = ddrapi.get_ddr_songs() out_json = json.dumps(songs) with open("DDRGenie/genie_assets/a20_songlist.json", ...
def update_songdb():
if not os.path.exists("DDRGenie/genie_assets/a20_songlist.json"): print("[GENIE] Updating DDR song DB from Konami") ddrapi = DDRApi(EAGate()) songs = ddrapi.get_ddr_songs() out_json = json.dumps(songs) with open("DDRGenie/genie_assets/a20_songlist.json", 'w') as f: ...
: r1 = await session.get(js['output_url']) c = await r1.read() reqdata = io.BytesIO(c) return reqdata else: raise Exception("DeepAI didn't return an upscaled image...\nOutput: %s", js) def update_songdb()...
64
64
107
5
59
cyberkitsune/DDRBot
DDRBot.py
Python
update_songdb
update_songdb
1,716
1,724
1,716
1,716
15c6de9ce66a2b11b31020e4f9a63daeab487dce
bigcode/the-stack
train
07ef1ffe17e370e9636a8fcc
train
class
class YeetException(Exception): pass
class YeetException(Exception):
pass
not submitted with judgement data. " emb.set_footer(text=footer) if song_info.cover_url is not None: emb.set_thumbnail(url="https://assets.cyberkitsune.net/gstats_proxy/%s" % urllib.parse.quote(song_info.cover_url)) return emb class YeetException(Exception):
64
64
9
6
57
cyberkitsune/DDRBot
DDRBot.py
Python
YeetException
YeetException
280
281
280
280
c5eeae4a0595103e46931423a1726737eb7f2b1d
bigcode/the-stack
train
f4ccad9bf1250d5fe848f8da
train
function
def generate_embed_iidx_db(score_data, score_player, verified=False, cmd_prefix='k!'): """ :type score_data: IIDXScore """ if verified: v = '<:verified:680629672735670352>' else: v = '' emb = discord.Embed() emb.title = "<:iidx:540794989316145162> %s by %s [%s %s]" % (score...
def generate_embed_iidx_db(score_data, score_player, verified=False, cmd_prefix='k!'):
""" :type score_data: IIDXScore """ if verified: v = '<:verified:680629672735670352>' else: v = '' emb = discord.Embed() emb.title = "<:iidx:540794989316145162> %s by %s [%s %s]" % (score_data.song_title, score_data.song_artist, 'DP' if...
_count, inline=True) emb.add_field(name="⛓ Combo Break", value="%s" % score_data.score_combo_break, inline=True) emb.add_field(name="🥕 Fast", value="%s" % score_data.score_fast_count, inline=True) emb.add_field(name="🐢 Slow", value="%s" % score_data.score_slow_count, inline=True) emb.set_footer(text="...
153
153
513
21
131
cyberkitsune/DDRBot
DDRBot.py
Python
generate_embed_iidx_db
generate_embed_iidx_db
149
178
149
149
275bef2b9dc449edfb667d0dbe600805e3b5e784
bigcode/the-stack
train
27a66255e76f2a107a8611c9
train
class
class DDRBotClient(discord.Client): admin_users = ['109500246106587136'] command_handlers = {} command_prefix = 'k!' authorized_channels = {} linked_eamuse = {} shown_screenshots = {} memes = {} generic_eamuse_session = None task_created = False lastrun = None auto_task_creat...
class DDRBotClient(discord.Client):
admin_users = ['109500246106587136'] command_handlers = {} command_prefix = 'k!' authorized_channels = {} linked_eamuse = {} shown_screenshots = {} memes = {} generic_eamuse_session = None task_created = False lastrun = None auto_task_created = False auto_users = {} g...
😠 Decent", value="%s (%0.2f%%)" % (extended.decent, desc_percent), inline=True) emb.add_field(name="<:CautionDDR:636661438085333002> Wayoff", value="%s (%0.2f%%)" % (extended.wayoff, wo_percent), inline=True) else: footer += "No Decent/WO. " ...
256
256
15,154
8
247
cyberkitsune/DDRBot
DDRBot.py
Python
DDRBotClient
DDRBotClient
284
1,713
284
284
b7ec57c27310c0e791a3b16ce0dc9a8bf7c017a8
bigcode/the-stack
train
db20465ccfae53abbabbb4d4
train
function
def get_emoji_for_fc(fc_text): if 'MFC' in fc_text: return '<:mfc:472191264796966926>' elif 'PFC' in fc_text: return '<:pfc:472191264402702347>' elif 'GFC' in fc_text: return '<:gfc:844785257852960778>' elif 'FC' in fc_text: return '<:fc:844785257164701708>' else: ...
def get_emoji_for_fc(fc_text):
if 'MFC' in fc_text: return '<:mfc:472191264796966926>' elif 'PFC' in fc_text: return '<:pfc:472191264402702347>' elif 'GFC' in fc_text: return '<:gfc:844785257852960778>' elif 'FC' in fc_text: return '<:fc:844785257164701708>' else: return ''
= json.load(f) except IOError as ex: print("[JSON] Exception occured loading %s!\n%s" % (filename, ex)) return None else: print("[JSON] Loaded %s successfully." % filename) return obj def get_emoji_for_fc(fc_text):
64
64
109
9
54
cyberkitsune/DDRBot
DDRBot.py
Python
get_emoji_for_fc
get_emoji_for_fc
70
80
70
70
416c7c5db61cad67e177f2e51d34c28b6887d1a1
bigcode/the-stack
train
b74ac5d116376e8ec6b35069
train
function
def generate_embed_from_db(score_data, score_player, verified=False, cmd_prefix='k!'): """ :type score_data: Score """ if isinstance(score_data, IIDXScore): return generate_embed_iidx_db(score_data, score_player, verified, cmd_prefix) emb = discord.Embed() if score_data.doubles_play: ...
def generate_embed_from_db(score_data, score_player, verified=False, cmd_prefix='k!'):
""" :type score_data: Score """ if isinstance(score_data, IIDXScore): return generate_embed_iidx_db(score_data, score_player, verified, cmd_prefix) emb = discord.Embed() if score_data.doubles_play: first_mode = 'D' else: first_mode = 'S' if verified: v = '...
", value="%s" % score_data.great_count, inline=True) emb.add_field(name="😐 Good", value="%s" % score_data.good_count, inline=True) emb.add_field(name="👎 Bad", value="%s" % score_data.bad_count, inline=True) emb.add_field(name="🆖 Poor", value="%s" % score_data.poor_count, inline=True) emb.add_field(na...
243
243
810
20
222
cyberkitsune/DDRBot
DDRBot.py
Python
generate_embed_from_db
generate_embed_from_db
181
223
181
181
e581be946d6284b72562b08fc61eae7550037300
bigcode/the-stack
train
7367139194776b6af21fe78a
train
function
def generate_embed(score_data, score_player): """ :type score_data: DDRParsedData """ emb = discord.Embed() first_mode = score_data.chart_play_mode.value[0] if first_mode == "V": first_mode = 'S' total_notes = int(score_data.score_marv_count.value) + int(score_data.score_perfect_cou...
def generate_embed(score_data, score_player):
""" :type score_data: DDRParsedData """ emb = discord.Embed() first_mode = score_data.chart_play_mode.value[0] if first_mode == "V": first_mode = 'S' total_notes = int(score_data.score_marv_count.value) + int(score_data.score_perfect_count.value) + int(score_data.score_great_count.v...
" % (userid, filename)): with open("archive/%s/%s" % (userid, filename), 'wb') as f: f.write(data) def load_json(filename): try: with open(filename, 'r') as f: obj = json.load(f) except IOError as ex: print("[JSON] Exception occured loading %s!\n%s" % (filename,...
228
229
766
9
219
cyberkitsune/DDRBot
DDRBot.py
Python
generate_embed
generate_embed
83
119
83
83
a8e0983d0517d8ca53a1ac45a5a6f14e944756ad
bigcode/the-stack
train
9449dd87d9183e3baf480e53
train
function
def activation(x): """ Sigmoid activation function Arguments --------- x: torch.Tensor """ return 1/(1 + torch.exp(-x))
def activation(x):
""" Sigmoid activation function Arguments --------- x: torch.Tensor """ return 1/(1 + torch.exp(-x))
import torch def activation(x):
7
64
39
4
2
johncurcio/facebook-secure-private-ai
lesson 2/01_tensors.py
Python
activation
activation
3
11
3
3
ba22289e72eaeafcd005745473b1281385b8d5eb
bigcode/the-stack
train
26b5db9b87572a6fbcc47893
train
class
class _Markdown: @staticmethod def _convert( string: str, base_path: Optional[Union[str, pathlib.Path]] = None ) -> str: """ https://facelessuser.github.io/pymdown-extensions/ """ md = _markdown.Markdown( extensions=[ "nl2br", "sane_lists"...
class _Markdown: @staticmethod
def _convert( string: str, base_path: Optional[Union[str, pathlib.Path]] = None ) -> str: """ https://facelessuser.github.io/pymdown-extensions/ """ md = _markdown.Markdown( extensions=[ "nl2br", "sane_lists", "pymdownx.pathcon...
import os import pathlib from typing import Optional, Union import markdown as _markdown from .globals import Globals from .helpers import Utils class _Markdown: @staticmethod
39
142
476
8
30
tnahs/easel
src/easel/site/markdown.py
Python
_Markdown
_Markdown
11
80
11
12
17bdb472c0fc7d58ec93bbe7a4acdeeb61be6972
bigcode/the-stack
train
0bb61f2797760cb3ada60af6
train
function
def testeParametroOpcional(texto, opcional = True): return f'{texto} {opcional}'
def testeParametroOpcional(texto, opcional = True):
return f'{texto} {opcional}'
# %% [markdown] ## Parâmetros opcionais def testeParametroOpcional(texto, opcional = True):
25
64
23
13
11
VictorMello1993/CursoPythonUdemy
Funcoes/ParametrosOpcionais.py
Python
testeParametroOpcional
testeParametroOpcional
5
6
5
5
668cea20af69761caf0bded33a760740a89d1733
bigcode/the-stack
train
e46e55a6f72142ce5c265fd0
train
class
class Rectangle: def __init__(self, top_left, bottom_right): self.top_left = top_left self.bottom_right = bottom_right def intersect(self, other_rect): top_left = np.max(np.array([self.top_left, other_rect.top_left]), axis=0) bottom_right = np.min( np.array([self.bot...
class Rectangle:
def __init__(self, top_left, bottom_right): self.top_left = top_left self.bottom_right = bottom_right def intersect(self, other_rect): top_left = np.max(np.array([self.top_left, other_rect.top_left]), axis=0) bottom_right = np.min( np.array([self.bottom_right, other_...
import numpy as np class Rectangle:
8
79
266
3
4
symbench/scm
circuit_recognizer/circuit_recognizer/connect/rectangle.py
Python
Rectangle
Rectangle
4
29
4
4
d59a595a5baaf68f841ccc40eeab6a313f845865
bigcode/the-stack
train
7103b5b800f9fa9fb7916d93
train
function
def report(step, episode, epoch, loss, win_count, position, action): print("Step {} Epoch {:03d}/{:03d} | Loss {:.4f} | Win count {} | Pos {:.3f} | Act {}". format(step, episode, (epoch - 1), loss, win_count, position, action))
def report(step, episode, epoch, loss, win_count, position, action):
print("Step {} Epoch {:03d}/{:03d} | Loss {:.4f} | Win count {} | Pos {:.3f} | Act {}". format(step, episode, (epoch - 1), loss, win_count, position, action))
import json import numpy as np import matplotlib.pyplot as plt from random import random from keras.models import Sequential from keras.layers.core import Dense from keras.optimizers import Adam from MountainCar import MountainCar def report(step, episode, epoch, loss, win_count, position, action):
64
64
72
17
46
erdenbatuhan/Mountain-Car
extras/DQN.py
Python
report
report
12
14
12
12
75d5b67c3f04138b784fd35b67eba6b26c27bc6e
bigcode/the-stack
train
32cb32aec434ce7ff6431a68
train
class
class DQN(object): def __init__(self, env, num_actions=3, max_memory=500): self.env = env self.num_actions = num_actions self.max_memory = max_memory self.memory, self.model, self.episodes = [], [], [] self.build_model() def build_model(self, hidden_size=200, input_siz...
class DQN(object):
def __init__(self, env, num_actions=3, max_memory=500): self.env = env self.num_actions = num_actions self.max_memory = max_memory self.memory, self.model, self.episodes = [], [], [] self.build_model() def build_model(self, hidden_size=200, input_size=2, learning_rate=....
import time import json import numpy as np import matplotlib.pyplot as plt from random import random from keras.models import Sequential from keras.layers.core import Dense from keras.optimizers import Adam from MountainCar import MountainCar def report(step, episode, epoch, loss, win_count, position, action): pr...
126
231
772
5
121
erdenbatuhan/Mountain-Car
extras/DQN.py
Python
DQN
DQN
17
114
17
18
04a693245755a0e9c0f7dc0476a166e5286b74d7
bigcode/the-stack
train
22a96c60908aba25744c58c3
train
function
def main(): start = [-.5, 0.] goal = [.45] Xrange = [-1.5, .55] Vrange = [-2., 2.] env = MountainCar(start, goal, Xrange, Vrange) dqn = DQN(env) # If you want to continue training from a previous model, just uncomment the line bellow # dqn.model.load_weights("dqn-model.h5") dqn.tr...
def main():
start = [-.5, 0.] goal = [.45] Xrange = [-1.5, .55] Vrange = [-2., 2.] env = MountainCar(start, goal, Xrange, Vrange) dqn = DQN(env) # If you want to continue training from a previous model, just uncomment the line bellow # dqn.model.load_weights("dqn-model.h5") dqn.train() dq...
.ylabel("Length of Episode") plt.show() @staticmethod def print_time_passed(start_time): print("Time passed:", end=" ") time_passed = time.time() - start_time time.strftime("%H:%M:%S", time.gmtime(time_passed)) def main():
64
64
168
3
61
erdenbatuhan/Mountain-Car
extras/DQN.py
Python
main
main
117
135
117
117
0a8edb5313f5a6f1c97cbc6afce02e74c70a4d5d
bigcode/the-stack
train
6f9730d54dd1490e10f6e8a7
train
class
class Token: def __init__(self, token_type, contents, position=None, lineno=None): """ A token representing a string from the template. token_type One of TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK, or TOKEN_COMMENT. contents The token source string. positio...
class Token:
def __init__(self, token_type, contents, position=None, lineno=None): """ A token representing a string from the template. token_type One of TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK, or TOKEN_COMMENT. contents The token source string. position ...
, 'line': line, 'name': self.origin.name, 'start': start, 'end': end, } def linebreak_iter(template_source): yield 0 p = template_source.find('\n') while p >= 0: yield p + 1 p = template_source.find('\n', p + 1) yield len(template...
91
91
305
3
87
kkoralsky/django
django/template/base.py
Python
Token
Token
306
348
306
306
7384344ab4d1cd72f7c34b309fe78291f26c389a
bigcode/the-stack
train
406eb358e8945ba4f12a825d
train
class
class TemplateEncodingError(Exception): pass
class TemplateEncodingError(Exception):
pass
% (re.escape(BLOCK_TAG_START), re.escape(BLOCK_TAG_END), re.escape(VARIABLE_TAG_START), re.escape(VARIABLE_TAG_END), re.escape(COMMENT_TAG_START), re.escape(COMMENT_TAG_END)))) logger = logging.getLogger('django.template') class TemplateEncodingError(Exception):
64
64
9
6
58
kkoralsky/django
django/template/base.py
Python
TemplateEncodingError
TemplateEncodingError
111
112
111
111
c2223eb6e678c5ebdb8d2afefc2bb979aa989e4d
bigcode/the-stack
train
bcee798aa666346e17ed75eb
train
class
class VariableNode(Node): def __init__(self, filter_expression): self.filter_expression = filter_expression def __repr__(self): return "<Variable Node: %s>" % self.filter_expression def render(self, context): try: output = self.filter_expression.resolve(context) ...
class VariableNode(Node):
def __init__(self, filter_expression): self.filter_expression = filter_expression def __repr__(self): return "<Variable Node: %s>" % self.filter_expression def render(self, context): try: output = self.filter_expression.resolve(context) except UnicodeDecodeError...
value = template_localtime(value, use_tz=context.use_tz) value = localize(value, use_l10n=context.use_l10n) value = force_text(value) if context.autoescape: return conditional_escape(value) else: return value class VariableNode(Node):
64
64
116
5
58
kkoralsky/django
django/template/base.py
Python
VariableNode
VariableNode
997
1,012
997
997
977f631b680a1d66bf283357de231d6dd5c12820
bigcode/the-stack
train
d7617a0dbb67ba95d9b2bd35
train
class
class Template: def __init__(self, template_string, origin=None, name=None, engine=None): try: template_string = force_text(template_string) except UnicodeDecodeError: raise TemplateEncodingError( "Templates can only be constructed from strings or UTF-8 " ...
class Template:
def __init__(self, template_string, origin=None, name=None, engine=None): try: template_string = force_text(template_string) except UnicodeDecodeError: raise TemplateEncodingError( "Templates can only be constructed from strings or UTF-8 " "byt...
re.escape(BLOCK_TAG_START), re.escape(BLOCK_TAG_END), re.escape(VARIABLE_TAG_START), re.escape(VARIABLE_TAG_END), re.escape(COMMENT_TAG_START), re.escape(COMMENT_TAG_END)))) logger = logging.getLogger('django.template') class TemplateEncodingError(Exception): pass class VariableDoesNotExi...
256
256
961
3
253
kkoralsky/django
django/template/base.py
Python
Template
Template
151
294
151
151
1b7fddbdf5453f12ac1c7e0c70d09ab9554e0143
bigcode/the-stack
train
9c7a522a15098b8b0f539ba6
train
class
class Parser: def __init__(self, tokens, libraries=None, builtins=None, origin=None): self.tokens = tokens self.tags = {} self.filters = {} self.command_stack = [] if libraries is None: libraries = {} if builtins is None: builtins = [] ...
class Parser:
def __init__(self, tokens, libraries=None, builtins=None, origin=None): self.tokens = tokens self.tags = {} self.filters = {} self.command_stack = [] if libraries is None: libraries = {} if builtins is None: builtins = [] self.librari...
, position, lineno) return token class DebugLexer(Lexer): def tokenize(self): """ Split a template string into tokens and annotates each token with its start and end position in the source. This is slower than the default lexer so we only use it when debug is True. ...
256
256
1,295
3
252
kkoralsky/django
django/template/base.py
Python
Parser
Parser
428
588
428
428
955fad4ae908f001430b1df9d467bccaf5951a5b
bigcode/the-stack
train
5cec4aa91d0dfb9baf840348
train
function
def render_value_in_context(value, context): """ Converts any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a string. If value is a string, it's expected to already be translated. """ value = template_localtime(value, use_tz=context....
def render_value_in_context(value, context):
""" Converts any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a string. If value is a string, it's expected to already be translated. """ value = template_localtime(value, use_tz=context.use_tz) value = localize(value, use_l10n=...
def __init__(self, s): self.s = s def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.s[:25]) def render(self, context): return self.s def render_value_in_context(value, context):
64
64
117
9
54
kkoralsky/django
django/template/base.py
Python
render_value_in_context
render_value_in_context
982
994
982
982
357ea273c13fe4a33444c38de12697c5d674bf26
bigcode/the-stack
train
beb3c189cf83e07537ca067a
train
class
class DebugLexer(Lexer): def tokenize(self): """ Split a template string into tokens and annotates each token with its start and end position in the source. This is slower than the default lexer so we only use it when debug is True. """ lineno = 1 result = [] ...
class DebugLexer(Lexer):
def tokenize(self): """ Split a template string into tokens and annotates each token with its start and end position in the source. This is slower than the default lexer so we only use it when debug is True. """ lineno = 1 result = [] upto = 0 ...
content = '' if token_string.find(TRANSLATOR_COMMENT_MARK): content = token_string[2:-2].strip() token = Token(TOKEN_COMMENT, content, position, lineno) else: token = Token(TOKEN_TEXT, token_string, position, lineno) return token class Deb...
72
72
243
7
64
kkoralsky/django
django/template/base.py
Python
DebugLexer
DebugLexer
401
425
401
401
724bc6e46c9c7c559ccd1a44c22642d43d88284d
bigcode/the-stack
train
7d58d304d459d83b9b089af1
train
class
class VariableDoesNotExist(Exception): def __init__(self, msg, params=()): self.msg = msg self.params = params def __str__(self): return self.msg % tuple(force_text(p, errors='replace') for p in self.params)
class VariableDoesNotExist(Exception):
def __init__(self, msg, params=()): self.msg = msg self.params = params def __str__(self): return self.msg % tuple(force_text(p, errors='replace') for p in self.params)
re.escape(BLOCK_TAG_END), re.escape(VARIABLE_TAG_START), re.escape(VARIABLE_TAG_END), re.escape(COMMENT_TAG_START), re.escape(COMMENT_TAG_END)))) logger = logging.getLogger('django.template') class TemplateEncodingError(Exception): pass class VariableDoesNotExist(Exception):
64
64
58
7
56
kkoralsky/django
django/template/base.py
Python
VariableDoesNotExist
VariableDoesNotExist
115
122
115
116
f7271c03cb0139b157b05c3f0c3ce2a307442a81
bigcode/the-stack
train
775c08c551cc9f64c39349eb
train
class
class TextNode(Node): def __init__(self, s): self.s = s def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.s[:25]) def render(self, context): return self.s
class TextNode(Node):
def __init__(self, s): self.s = s def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.s[:25]) def render(self, context): return self.s
return mark_safe(''.join(bits)) def get_nodes_by_type(self, nodetype): "Return a list of all nodes of the given type" nodes = [] for node in self: nodes.extend(node.get_nodes_by_type(nodetype)) return nodes class TextNode(Node):
64
64
61
5
58
kkoralsky/django
django/template/base.py
Python
TextNode
TextNode
971
979
971
971
8761c959d282b4e2ca1c0f4011d3306338719de3
bigcode/the-stack
train
40fba423fd54f16e691d02ed
train
class
class NodeList(list): # Set to True the first time a non-TextNode is inserted by # extend_nodelist(). contains_nontext = False def render(self, context): bits = [] for node in self: if isinstance(node, Node): bit = node.render_annotated(context) e...
class NodeList(list): # Set to True the first time a non-TextNode is inserted by # extend_nodelist().
contains_nontext = False def render(self, context): bits = [] for node in self: if isinstance(node, Node): bit = node.render_annotated(context) else: bit = node bits.append(force_text(bit)) return mark_safe(''.join(bits...
nodelist = getattr(self, attr, None) if nodelist: nodes.extend(nodelist.get_nodes_by_type(nodetype)) return nodes class NodeList(list): # Set to True the first time a non-TextNode is inserted by # extend_nodelist().
64
64
144
29
34
kkoralsky/django
django/template/base.py
Python
NodeList
NodeList
948
968
948
950
f276e73243e5cfe63654b10aada9797586de6748
bigcode/the-stack
train
1a8aba02d5cdbd01022b4174
train
class
class Variable: """ A template variable, resolvable against a given context. The variable may be a hard-coded string (if it begins and ends with single or double quote marks):: >>> c = {'article': {'section':'News'}} >>> Variable('article.section').resolve(c) 'News' >>> ...
class Variable:
""" A template variable, resolvable against a given context. The variable may be a hard-coded string (if it begins and ends with single or double quote marks):: >>> c = {'article': {'section':'News'}} >>> Variable('article.section').resolve(c) 'News' >>> Variable('articl...
if getattr(func, 'needs_autoescape', False): new_obj = func(obj, autoescape=context.autoescape, *arg_vals) else: new_obj = func(obj, *arg_vals) if getattr(func, 'is_safe', False) and isinstance(obj, SafeData): obj = mark_safe(new_obj) ...
256
256
1,269
3
252
kkoralsky/django
django/template/base.py
Python
Variable
Variable
746
900
746
746
b1d7b2c62ce2ad3798ad03e57010903d5e4c5f57
bigcode/the-stack
train
04b47b2df88c0256ce9ae4df
train
class
class FilterExpression: """ Parses a variable token and its optional filters (all as a single string), and return a list of tuples of the filter name and arguments. Sample:: >>> token = 'variable|default:"Default value"|date:"Y-m-d"' >>> p = Parser('') >>> fe = FilterExpression(...
class FilterExpression:
""" Parses a variable token and its optional filters (all as a single string), and return a list of tuples of the filter name and arguments. Sample:: >>> token = 'variable|default:"Default value"|date:"Y-m-d"' >>> p = Parser('') >>> fe = FilterExpression(token, p) >>> le...
"\\]*)*"', # double-quoted string 'strsq': r"'[^'\\]*(?:\\.[^'\\]*)*'", # single-quoted string 'i18n_open': re.escape("_("), 'i18n_close': re.escape(")"), } constant_string = constant_string.replace("\n", "") filter_raw_string = r""" ^(?P<constant>%(constant)s)| ^(?P<var>[%(var_chars)s]+|%(num)s)| (?:\s...
256
256
887
4
252
kkoralsky/django
django/template/base.py
Python
FilterExpression
FilterExpression
629
743
629
629
2949722fc63cd346f8285cb39940809df6296383
bigcode/the-stack
train
7d4c8cbb9358c29a2e0b42a4
train
class
class Node: # Set this to True for nodes that must be first in the template (although # they can be preceded by text nodes. must_be_first = False child_nodelists = ('nodelist',) token = None def render(self, context): """ Return the node rendered as a string. """ ...
class Node: # Set this to True for nodes that must be first in the template (although # they can be preceded by text nodes.
must_be_first = False child_nodelists = ('nodelist',) token = None def render(self, context): """ Return the node rendered as a string. """ pass def render_annotated(self, context): """ Render the node. If debug is True and an exception occurs during...
"Exception while resolving variable '%s' in template '%s'.", bit, template_name, exc_info=True, ) if getattr(e, 'silent_variable_failure', False): current = context.template.engine.string_if_invalid else: ...
91
91
305
31
59
kkoralsky/django
django/template/base.py
Python
Node
Node
903
945
903
905
7842a50f4c42488a967603671c21f2349ee05311
bigcode/the-stack
train
9c2876724e1453d396b26c33
train
function
def token_kwargs(bits, parser, support_legacy=False): """ A utility method for parsing token keyword arguments. :param bits: A list containing remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments will be removed from this list. :param support_le...
def token_kwargs(bits, parser, support_legacy=False):
""" A utility method for parsing token keyword arguments. :param bits: A list containing remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments will be removed from this list. :param support_legacy: If set to true ``True``, the legacy format ...
def render(self, context): try: output = self.filter_expression.resolve(context) except UnicodeDecodeError: # Unicode conversion can fail sometimes for reasons out of our # control (e.g. exception rendering). In that case, we fail # quietly. ...
110
111
373
12
98
kkoralsky/django
django/template/base.py
Python
token_kwargs
token_kwargs
1,019
1,066
1,019
1,019
20303ce3503e6d30453c24c7b98b6621ee8f8ead
bigcode/the-stack
train
b350ddb4f6b1769d105e9e5d
train
class
class Origin: def __init__(self, name, template_name=None, loader=None): self.name = name self.template_name = template_name self.loader = loader def __str__(self): return self.name def __eq__(self, other): if not isinstance(other, Origin): return False ...
class Origin:
def __init__(self, name, template_name=None, loader=None): self.name = name self.template_name = template_name self.loader = loader def __str__(self): return self.name def __eq__(self, other): if not isinstance(other, Origin): return False retur...
pass class VariableDoesNotExist(Exception): def __init__(self, msg, params=()): self.msg = msg self.params = params def __str__(self): return self.msg % tuple(force_text(p, errors='replace') for p in self.params) class Origin:
64
64
131
3
61
kkoralsky/django
django/template/base.py
Python
Origin
Origin
125
148
125
125
5a206f49d1c216ba2dbba55938e12e0a698c404c
bigcode/the-stack
train
fbc709d28a5b65e6d91bb8b3
train
function
def linebreak_iter(template_source): yield 0 p = template_source.find('\n') while p >= 0: yield p + 1 p = template_source.find('\n', p + 1) yield len(template_source) + 1
def linebreak_iter(template_source):
yield 0 p = template_source.find('\n') while p >= 0: yield p + 1 p = template_source.find('\n', p + 1) yield len(template_source) + 1
'during': during, 'after': after, 'top': top, 'bottom': bottom, 'total': total, 'line': line, 'name': self.origin.name, 'start': start, 'end': end, } def linebreak_iter(template_source):
64
64
59
7
57
kkoralsky/django
django/template/base.py
Python
linebreak_iter
linebreak_iter
297
303
297
297
57badb9b586392e638f79e556e3e27f79966a69d
bigcode/the-stack
train
b84465318c7ba9076bd9a552
train
class
class Lexer: def __init__(self, template_string): self.template_string = template_string self.verbatim = False def tokenize(self): """ Return a list of tokens from a given template_string. """ in_tag = False lineno = 1 result = [] for bit ...
class Lexer:
def __init__(self, template_string): self.template_string = template_string self.verbatim = False def tokenize(self): """ Return a list of tokens from a given template_string. """ in_tag = False lineno = 1 result = [] for bit in tag_re.spl...
TOKEN_MAPPING[self.token_type] return ('<%s token: "%s...">' % (token_name, self.contents[:20].replace('\n', ''))) def split_contents(self): split = [] bits = iter(smart_split(self.contents)) for bit in bits: # Handle translation-marked template pieces ...
141
141
473
3
137
kkoralsky/django
django/template/base.py
Python
Lexer
Lexer
351
398
351
351
8a41de0f49d83a6646c4241adace04f8ed5c3eaa
bigcode/the-stack
train
05ec4d11e91b6787a77c609f
train
class
class AmiraSpatialGraph(Amira): def __init__(self, path): super().__init__(path) sid_ranges = self._extract_sid_ranges() arrays = dict() for sid, (start, end) in sid_ranges: # find data type name, dtype = None, None for _name, (_sid, sh...
class AmiraSpatialGraph(Amira):
def __init__(self, path): super().__init__(path) sid_ranges = self._extract_sid_ranges() arrays = dict() for sid, (start, end) in sid_ranges: # find data type name, dtype = None, None for _name, (_sid, shape, _dtype) in self.data.items()...
import logging from pprint import pprint import numpy as np from utoolbox.data.io.amira.base import Amira __all__ = ["AmiraSpatialGraph"] logger = logging.getLogger(__name__) class AmiraSpatialGraph(Amira):
54
155
519
9
45
thhsieh00/utoolbox-core
src/utoolbox/io/encdec/amira/spatialgraph.py
Python
AmiraSpatialGraph
AmiraSpatialGraph
13
78
13
13
ca8a7eeb47bf299390075b4494b53daa3f42819d
bigcode/the-stack
train
f7af0d326d46e8fe6fa97e67
train
function
def extract_case_control_assignments(samples): sample_status = {} for sample in samples: sample_status[sample.id] = sample.status return sample_status
def extract_case_control_assignments(samples):
sample_status = {} for sample in samples: sample_status[sample.id] = sample.status return sample_status
.Region(chrom, start, end) overlaps_target_region = any( regiontools.compute_distance(region, target) == 0 for target in target_regions ) if overlaps_target_region: filtered_count_table.append(row) return filtered_count_table def extract_case_control_ass...
64
64
35
8
55
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
extract_case_control_assignments
extract_case_control_assignments
92
96
92
92
ef4ad82929a61ee0c40011e44ec0a338761a9ff6
bigcode/the-stack
train
a86d6a8174d1b051fc52e2ed
train
function
def generate_table_with_irr_pair_counts(combined_counts): count_table = [] for unit, rec in combined_counts.items(): if "IrrPairCounts" not in rec: continue sample_counts = rec["IrrPairCounts"] table_row = {"unit": unit, "sample_counts": sample_counts} count_table.ap...
def generate_table_with_irr_pair_counts(combined_counts):
count_table = [] for unit, rec in combined_counts.items(): if "IrrPairCounts" not in rec: continue sample_counts = rec["IrrPairCounts"] table_row = {"unit": unit, "sample_counts": sample_counts} count_table.append(table_row) return count_table
count_table): depths = sample_stats["Depths"] for row in count_table: row["sample_counts"] = { s: normalize_count(depths[s], c) for s, c in row["sample_counts"].items() } def generate_table_with_irr_pair_counts(combined_counts):
64
64
81
12
52
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
generate_table_with_irr_pair_counts
generate_table_with_irr_pair_counts
143
153
143
143
a1911292d4dc54095432792b8167b2298bc3d19d
bigcode/the-stack
train
12e9c917b8bc9bf00c5395a9
train
function
def depth_normalize_counts(sample_stats, count_table): depths = sample_stats["Depths"] for row in count_table: row["sample_counts"] = { s: normalize_count(depths[s], c) for s, c in row["sample_counts"].items() }
def depth_normalize_counts(sample_stats, count_table):
depths = sample_stats["Depths"] for row in count_table: row["sample_counts"] = { s: normalize_count(depths[s], c) for s, c in row["sample_counts"].items() }
for row in count_table: row["bonf_pvalue"] = min(row["pvalue"] * num_tests, 1.0) def normalize_count(sample_depth, count, target_depth=40): return target_depth * count / sample_depth def depth_normalize_counts(sample_stats, count_table):
64
64
60
11
52
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
depth_normalize_counts
depth_normalize_counts
135
140
135
135
479d002b7dd1eb84750a03e4ef553882314e62b6
bigcode/the-stack
train
562f5de44627e880203b2136
train
function
def filter_counts_by_magnitude(count_table, count_cutoff): filtered_count_table = [] for row in count_table: max_count = max(count for _, count in row["sample_counts"].items()) if max_count >= count_cutoff: filtered_count_table.append(row) return filtered_count_table
def filter_counts_by_magnitude(count_table, count_cutoff):
filtered_count_table = [] for row in count_table: max_count = max(count for _, count in row["sample_counts"].items()) if max_count >= count_cutoff: filtered_count_table.append(row) return filtered_count_table
be either "case" or "control";' ' instead got "{}"' ) raise Exception(message.format(status)) sample = Sample(id=sample_id, status=status, path=path) samples.append(sample) return samples def filter_counts_by_magnitude(count_table, count_...
64
64
65
13
50
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
filter_counts_by_magnitude
filter_counts_by_magnitude
63
70
63
63
67237df6c803f866e18da34f5e170ad995a4bfcc
bigcode/the-stack
train
12e5d1cf71022a34aea3691a
train
function
def compare_counts(test_params, sample_status, count_table): for row in count_table: # Generate counts before testing pvalue = test_samples(test_params, sample_status, row["sample_counts"]) row["pvalue"] = pvalue
def compare_counts(test_params, sample_status, count_table):
for row in count_table: # Generate counts before testing pvalue = test_samples(test_params, sample_status, row["sample_counts"]) row["pvalue"] = pvalue
control_samples ] case_counts = [sample_counts[s] if s in sample_counts else 0 for s in case_samples] pvalue = wilcoxon_rank_sum_test(test_params, case_counts, control_counts) return pvalue def compare_counts(test_params, sample_status, count_table):
64
64
53
12
51
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
compare_counts
compare_counts
118
122
118
118
20184f63df2ad248d57d6e69093a4c8d048fbeb7
bigcode/the-stack
train
6b88e410968b03b4c2734b69
train
function
def normalize_count(sample_depth, count, target_depth=40): return target_depth * count / sample_depth
def normalize_count(sample_depth, count, target_depth=40):
return target_depth * count / sample_depth
"] = pvalue def correct_pvalues(count_table): num_tests = len(count_table) for row in count_table: row["bonf_pvalue"] = min(row["pvalue"] * num_tests, 1.0) def normalize_count(sample_depth, count, target_depth=40):
64
64
23
13
51
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
normalize_count
normalize_count
131
132
131
131
c732f0ed3503d500286cc3c96890a2cba9faf7b0
bigcode/the-stack
train
389580cbfe906c3a44386ea7
train
function
def load_manifest(manifest_path): """Extract sample information from a manifest file. """ # pylint: disable=I0011,C0103 Sample = collections.namedtuple("Sample", "id status path") samples = [] with open(manifest_path, "r") as manifest_file: for line in manifest_file: sampl...
def load_manifest(manifest_path):
"""Extract sample information from a manifest file. """ # pylint: disable=I0011,C0103 Sample = collections.namedtuple("Sample", "id status path") samples = [] with open(manifest_path, "r") as manifest_file: for line in manifest_file: sample_id, status, path = line.split() ...
import json import scipy.stats as stats import numpy as np from . import regiontools from .wilcoxontest import wilcoxon_rank_sum_test def init_logger(): logging.basicConfig(format="%(asctime)s: %(message)s", level=logging.INFO) def load_manifest(manifest_path):
64
64
153
7
57
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
load_manifest
load_manifest
38
60
38
38
e3acf567032fd388284da784610b2608bc45928f
bigcode/the-stack
train
52ad9dbabf2faa7b050a862d
train
function
def test_samples(test_params, sample_status, sample_counts): control_samples = [ sample for sample, status in sample_status.items() if status == "control" ] case_samples = [ sample for sample, status in sample_status.items() if status == "case" ] control_counts = [ sample_co...
def test_samples(test_params, sample_status, sample_counts):
control_samples = [ sample for sample, status in sample_status.items() if status == "control" ] case_samples = [ sample for sample, status in sample_status.items() if status == "case" ] control_counts = [ sample_counts[s] if s in sample_counts else 0 for s in control_samples...
overlaps_target_region: filtered_count_table.append(row) return filtered_count_table def extract_case_control_assignments(samples): sample_status = {} for sample in samples: sample_status[sample.id] = sample.status return sample_status def test_samples(test_params, sample_status,...
64
64
133
12
51
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
test_samples
test_samples
99
115
99
99
0b59caa42e2940ff0b1eb64cba71be43c985d3ef
bigcode/the-stack
train
200cb056fbff8f5dc175bbc5
train
function
def filter_counts_by_region(count_table, target_regions): filtered_count_table = [] for row in count_table: region_encoding = row["region"] chrom, coords = region_encoding.rsplit(":", 1) start, end = coords.split("-") start, end = int(start), int(end) region = regiontools...
def filter_counts_by_region(count_table, target_regions):
filtered_count_table = [] for row in count_table: region_encoding = row["region"] chrom, coords = region_encoding.rsplit(":", 1) start, end = coords.split("-") start, end = int(start), int(end) region = regiontools.Region(chrom, start, end) overlaps_target_region ...
): filtered_count_table = [] for row in count_table: max_count = max(count for _, count in row["sample_counts"].items()) if max_count >= count_cutoff: filtered_count_table.append(row) return filtered_count_table def filter_counts_by_region(count_table, target_regions):
64
64
127
11
52
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
filter_counts_by_region
filter_counts_by_region
73
89
73
73
8fc076704d415438e454dda4e69bd44f9ebf742c
bigcode/the-stack
train
897acb75c10cd3bb7f5f3400
train
function
def resample_quantiles(counts, num_resamples, target_quantile_value): resamples = np.random.choice(counts, len(counts) * num_resamples) resamples = np.split(resamples, num_resamples) resampled_quantiles = [] for resample in resamples: quantile = np.quantile(resample, target_quantile_value) ...
def resample_quantiles(counts, num_resamples, target_quantile_value):
resamples = np.random.choice(counts, len(counts) * num_resamples) resamples = np.split(resamples, num_resamples) resampled_quantiles = [] for resample in resamples: quantile = np.quantile(resample, target_quantile_value) resampled_quantiles.append(quantile) return resampled_quantil...
" not in rec: continue sample_counts = rec["IrrPairCounts"] table_row = {"unit": unit, "sample_counts": sample_counts} count_table.append(table_row) return count_table def resample_quantiles(counts, num_resamples, target_quantile_value):
64
64
96
17
46
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
resample_quantiles
resample_quantiles
156
165
156
156
8280d8f5051ab44e02136523db729c0ea52ced1d
bigcode/the-stack
train
2cc03c57e6f840e11fc5120d
train
function
def run_zscore_analysis(sample_status, sample_counts): raw_counts = [sample_counts.get(sample, 0) for sample, _ in sample_status.items()] quantiles = resample_quantiles(raw_counts, 100, 0.95) (mu, sigma) = stats.norm.fit(quantiles) sigma = max(sigma, 1) case_counts = { sample: sample_counts...
def run_zscore_analysis(sample_status, sample_counts):
raw_counts = [sample_counts.get(sample, 0) for sample, _ in sample_status.items()] quantiles = resample_quantiles(raw_counts, 100, 0.95) (mu, sigma) = stats.norm.fit(quantiles) sigma = max(sigma, 1) case_counts = { sample: sample_counts.get(sample, 0) for sample, status in sample_st...
amples, num_resamples) resampled_quantiles = [] for resample in resamples: quantile = np.quantile(resample, target_quantile_value) resampled_quantiles.append(quantile) return resampled_quantiles def run_zscore_analysis(sample_status, sample_counts):
64
64
213
11
52
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
run_zscore_analysis
run_zscore_analysis
168
191
168
168
e7d0c2a1db33120eef8512b3700c7c2eb9358b16
bigcode/the-stack
train
e460cf17670a06d5592973c3
train
function
def correct_pvalues(count_table): num_tests = len(count_table) for row in count_table: row["bonf_pvalue"] = min(row["pvalue"] * num_tests, 1.0)
def correct_pvalues(count_table):
num_tests = len(count_table) for row in count_table: row["bonf_pvalue"] = min(row["pvalue"] * num_tests, 1.0)
return pvalue def compare_counts(test_params, sample_status, count_table): for row in count_table: # Generate counts before testing pvalue = test_samples(test_params, sample_status, row["sample_counts"]) row["pvalue"] = pvalue def correct_pvalues(count_table):
64
64
46
7
56
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
correct_pvalues
correct_pvalues
125
128
125
125
09f8fc06bf2ab921c9bd73e740e0a3204a81d716
bigcode/the-stack
train
565012c63bbf8c793b9f3a8c
train
function
def init_logger(): logging.basicConfig(format="%(asctime)s: %(message)s", level=logging.INFO)
def init_logger():
logging.basicConfig(format="%(asctime)s: %(message)s", level=logging.INFO)
# See the License for the specific language governing permissions and # limitations under the License. # # import collections import logging import json import scipy.stats as stats import numpy as np from . import regiontools from .wilcoxontest import wilcoxon_rank_sum_test def init_logger():
64
64
23
4
59
christopher-schroeder/dna-seq-strling
workflow/external/ehdn/scripts/core/common.py
Python
init_logger
init_logger
34
35
34
34
2c8c9dd2063944e6aa427088866569385c221d2f
bigcode/the-stack
train
ab758616c3b1567434d59c94
train
class
class Solution: def canJump(self, nums: List[int]) -> bool: k = 0 for i in range(len(nums)): if i > k: return False k = max(k, i + nums[i]) return True
class Solution:
def canJump(self, nums: List[int]) -> bool: k = 0 for i in range(len(nums)): if i > k: return False k = max(k, i + nums[i]) return True
from typing import List # 跳跃游戏 class Solution:
14
64
56
3
10
googege/algo-learn
python/greedy/jump_game.py
Python
Solution
Solution
6
14
6
7
4e91c93d00b6660280cbc05d22da009d1c07b676
bigcode/the-stack
train
33166d26b5b97cc3e56a6695
train
function
def is_psycopg2_exists(): try: import psycopg2 # noqa return True except ImportError: return False
def is_psycopg2_exists():
try: import psycopg2 # noqa return True except ImportError: return False
elif value == '0': ext_modules = list(set(ext_modules) - {module}) else: raise ValueError( f"Flag {key} should be '0' or '1', but {repr(value)} got.") return ext_modules def is_psycopg2_exists():
64
64
35
9
54
jiechic/vnpy
setup.py
Python
is_psycopg2_exists
is_psycopg2_exists
48
53
48
48
41ccbff5912477092f4b2e697e75923d08a16685
bigcode/the-stack
train
6d57d59b5335f4bd0b8686d0
train
function
def check_extension_build_flag(ext_modules, key: str, module: Extension): value = os.environ.get(key, None) if value is not None: if value == '1': ext_modules = list(set(ext_modules) | {module}) elif value == '0': ext_modules = list(set(ext_modules) - {module}) el...
def check_extension_build_flag(ext_modules, key: str, module: Extension):
value = os.environ.get(key, None) if value is not None: if value == '1': ext_modules = list(set(ext_modules) | {module}) elif value == '0': ext_modules = list(set(ext_modules) - {module}) else: raise ValueError( f"Flag {key} should be '...
filenames: filebase, ext = os.path.splitext(filename) if ext == ".cpp" and filebase.startswith("generated_functions_"): path = os.path.join(root, filename) fs.append(path) return fs def check_extension_build_flag(ext_modules, key: str, module: Extension):
64
64
109
16
47
jiechic/vnpy
setup.py
Python
check_extension_build_flag
check_extension_build_flag
35
45
35
35
264f13bfdc95dd80b349c45ba0483cd612705b14
bigcode/the-stack
train
1a99cca00b1a181ba341eb17
train
function
def get_ext_modules(): if platform.uname().system == "Windows": compiler_flags = [ "/MP", "/std:c++17", # standard "/O2", "/Ob2", "/Oi", "/Ot", "/Oy", "/GL", # Optimization "/bigobj", # Better compatibility "/wd4819", # 936 code page "/D_CRT_SE...
def get_ext_modules():
if platform.uname().system == "Windows": compiler_flags = [ "/MP", "/std:c++17", # standard "/O2", "/Ob2", "/Oi", "/Ot", "/Oy", "/GL", # Optimization "/bigobj", # Better compatibility "/wd4819", # 936 code page "/D_CRT_SECURE_NO_WARNINGS", ...
(value)} got.") return ext_modules def is_psycopg2_exists(): try: import psycopg2 # noqa return True except ImportError: return False def get_install_requires(): install_requires = [ "PyQt5", "qdarkstyle", "requests", "websocket-client", ...
256
256
2,550
5
251
jiechic/vnpy
setup.py
Python
get_ext_modules
get_ext_modules
90
369
90
90
4cbd085156a90115c7ee402a70577cf6443e02a0
bigcode/the-stack
train
a6fba1167735b559e02b149f
train
function
def get_version_string(): global version with open("vnpy/__init__.py", "rb") as f: version_line = re.search( r"__version__\s+=\s+(.*)", f.read().decode("utf-8") ).group(1) return str(ast.literal_eval(version_line))
def get_version_string():
global version with open("vnpy/__init__.py", "rb") as f: version_line = re.search( r"__version__\s+=\s+(.*)", f.read().decode("utf-8") ).group(1) return str(ast.literal_eval(version_line))
q", "QScintilla" ] if not is_psycopg2_exists(): install_requires.append("psycopg2-binary") if sys.version_info.minor < 7: install_requires.append("dataclasses") return install_requires def get_version_string():
64
64
71
5
58
jiechic/vnpy
setup.py
Python
get_version_string
get_version_string
81
87
81
81
5748fce9772794dd29b4ce57da824b0f8ff6e838
bigcode/the-stack
train
de635c1e36bf2dc0030f06fc
train
function
def get_install_requires(): install_requires = [ "PyQt5", "qdarkstyle", "requests", "websocket-client", "peewee", "numpy", "pandas", "matplotlib", "seaborn", "rqdatac", "ta-lib", "deap", "pyzmq", "QScinti...
def get_install_requires():
install_requires = [ "PyQt5", "qdarkstyle", "requests", "websocket-client", "peewee", "numpy", "pandas", "matplotlib", "seaborn", "rqdatac", "ta-lib", "deap", "pyzmq", "QScintilla" ] if not is_psy...
{key} should be '0' or '1', but {repr(value)} got.") return ext_modules def is_psycopg2_exists(): try: import psycopg2 # noqa return True except ImportError: return False def get_install_requires():
64
64
136
5
58
jiechic/vnpy
setup.py
Python
get_install_requires
get_install_requires
56
78
56
56
2510e9749d320e952c2e571ee61d6427632cae83
bigcode/the-stack
train
3a107bda38ff021790c75438
train
function
def gather_autocxxpy_generated_files(root: str): fs = [os.path.join(root, "module.cpp")] for root, dirs, filenames in os.walk(root): for filename in filenames: filebase, ext = os.path.splitext(filename) if ext == ".cpp" and filebase.startswith("generated_functions_"): ...
def gather_autocxxpy_generated_files(root: str):
fs = [os.path.join(root, "module.cpp")] for root, dirs, filenames in os.walk(root): for filename in filenames: filebase, ext = os.path.splitext(filename) if ext == ".cpp" and filebase.startswith("generated_functions_"): path = os.path.join(root, filename) ...
, and automatically route their orders to the most desired destinations, including equity, commodity, forex and many other financial markets. """ import ast import os import platform import re import sys from setuptools import Extension, find_packages, setup def gather_autocxxpy_generated_files(root: str):
64
64
89
12
51
jiechic/vnpy
setup.py
Python
gather_autocxxpy_generated_files
gather_autocxxpy_generated_files
24
32
24
24
eefc862e1d81597dc98fbbad67ac9cf79c254996
bigcode/the-stack
train
b68e960ec9abb803c4e61957
train
class
class MinStack: def __init__(self): """ initialize your data structure here. """ self.stack = [] self.mins = [] def push(self, x: int) -> None: self.stack.append(x) if not self.mins or x <= self.mins[-1]: self.mins.append(x) def pop(self)...
class MinStack:
def __init__(self): """ initialize your data structure here. """ self.stack = [] self.mins = [] def push(self, x: int) -> None: self.stack.append(x) if not self.mins or x <= self.mins[-1]: self.mins.append(x) def pop(self) -> None: ...
-*- # @Time: 2020/6/7 21:36 # @Author: GraceKoo # @File: interview_20.py # @Desc: https://leetcode-cn.com/problems/ # bao-han-minhan-shu-de-zhan-lcof/ class MinStack:
64
64
156
4
60
liuxiaohui1221/algorithm
Codes/gracekoo/interview_20.py
Python
MinStack
MinStack
9
33
9
9
6d084f5b336612a1d349d9c49c128c70c3f332b1
bigcode/the-stack
train
b721ef725e6d873512dbfb5c
train
function
def video_processing(infile, outpath): # 初始化一个VideoCapture对象 cap = cv2.VideoCapture() if cap.open(infile): colorbar = list() # 获取视频帧数 fps, n_frames = (int(cap.get(cv2.CAP_PROP_FPS)), int(cap.get(cv2.CAP_PROP_FRAME_COUNT))) # 对每帧HSV处理 for n_frame in range(n_frames): ...
def video_processing(infile, outpath): # 初始化一个VideoCapture对象
cap = cv2.VideoCapture() if cap.open(infile): colorbar = list() # 获取视频帧数 fps, n_frames = (int(cap.get(cv2.CAP_PROP_FPS)), int(cap.get(cv2.CAP_PROP_FRAME_COUNT))) # 对每帧HSV处理 for n_frame in range(n_frames): if n_frame % int(n_frames/10) == 0: cap...
if frameshot.content[key][i] != 0.0: sh += -frameshot.content[key][i] * math.log(frameshot.content[key][i], 2) for i in range(12, 17): if frameshot.content[key][i] != 0.0: ss += -frameshot.content[key][i] * math.log(frameshot.content[key][i], 2) for i in rang...
253
253
845
17
236
ihoung/video_classification
keyframe_test/keyframe_extraction_1.py
Python
video_processing
video_processing
50
135
50
51
308266927bc744e4f657352acf242747ae4b47f4
bigcode/the-stack
train
8532477446995bb1c1057e71
train
class
class FrameShot: content = dict() center = np.zeros((22,), dtype=np.float)
class FrameShot:
content = dict() center = np.zeros((22,), dtype=np.float)
import numpy as np import math import cv2 import os class FrameShot:
19
64
21
4
14
ihoung/video_classification
keyframe_test/keyframe_extraction_1.py
Python
FrameShot
FrameShot
7
9
7
7
8009eb48fbc703c914d85c337f569f290796377e
bigcode/the-stack
train
b3a3d99b37089f31a8fc5de9
train
function
def find_max_entropy_id(frameshot): n_id = 0 for key in frameshot.content.keys(): sh = ss = sv = smax = 0.0 for i in range(12): if frameshot.content[key][i] != 0.0: sh += -frameshot.content[key][i] * math.log(frameshot.content[key][i], 2) for i in range(12, 17...
def find_max_entropy_id(frameshot):
n_id = 0 for key in frameshot.content.keys(): sh = ss = sv = smax = 0.0 for i in range(12): if frameshot.content[key][i] != 0.0: sh += -frameshot.content[key][i] * math.log(frameshot.content[key][i], 2) for i in range(12, 17): if frameshot.content[...
for i in range(12, 17): ss += min(x1[i], x2[i]) for i in range(17, 22): sv += min(x1[i], x2[i]) return sh*alpha_h + ss*alpha_s + sv*alpha_v def find_max_entropy_id(frameshot):
71
71
238
9
61
ihoung/video_classification
keyframe_test/keyframe_extraction_1.py
Python
find_max_entropy_id
find_max_entropy_id
24
41
24
24
229a9006a15472f7de30fffe68f78959768f3c8e
bigcode/the-stack
train
284a7a9a87d2d1b40a5e6a3f
train
function
def similarity(x1, x2): sh = ss = sv = 0 alpha_h, alpha_s, alpha_v = (0.5, 0.3, 0.2) for i in range(12): sh += min(x1[i], x2[i]) for i in range(12, 17): ss += min(x1[i], x2[i]) for i in range(17, 22): sv += min(x1[i], x2[i]) return sh*alpha_h + ss*alpha_s + sv*alpha_v
def similarity(x1, x2):
sh = ss = sv = 0 alpha_h, alpha_s, alpha_v = (0.5, 0.3, 0.2) for i in range(12): sh += min(x1[i], x2[i]) for i in range(12, 17): ss += min(x1[i], x2[i]) for i in range(17, 22): sv += min(x1[i], x2[i]) return sh*alpha_h + ss*alpha_s + sv*alpha_v
import numpy as np import math import cv2 import os class FrameShot: content = dict() center = np.zeros((22,), dtype=np.float) def similarity(x1, x2):
44
64
126
8
36
ihoung/video_classification
keyframe_test/keyframe_extraction_1.py
Python
similarity
similarity
12
21
12
12
8f7b9712df0b75f84fd90f968717d313b021477b
bigcode/the-stack
train
8d4c415b7a1e1db95edddb0c
train
function
def combine(shotlist, i, j): for key in shotlist[j].content.keys(): shotlist[i].content[key] = shotlist[j].content.get(key) shotlist.remove(shotlist[j])
def combine(shotlist, i, j):
for key in shotlist[j].content.keys(): shotlist[i].content[key] = shotlist[j].content.get(key) shotlist.remove(shotlist[j])
][i], 2) s = 0.5*sh + 0.3*ss + 0.2*sv if s > smax: smax = s n_id = key return n_id def combine(shotlist, i, j):
64
64
47
10
53
ihoung/video_classification
keyframe_test/keyframe_extraction_1.py
Python
combine
combine
44
47
44
44
5c7b229495a8c52ea3ba51f117464da5cf2d06d2
bigcode/the-stack
train
94308e294911362b22f7c09b
train
class
class TestDomain(BaseTest): """ Unit tests for the domain module. """ def setUp(self): self.a = Variable(name='a') self.x = Variable(2, name='x') self.y = Variable(2, name='y') self.z = Variable(3, name='z') self.A = Variable((2,2), name='A') self.B = Variable(...
class TestDomain(BaseTest):
""" Unit tests for the domain module. """ def setUp(self): self.a = Variable(name='a') self.x = Variable(2, name='x') self.y = Variable(2, name='y') self.z = Variable(3, name='z') self.A = Variable((2,2), name='A') self.B = Variable((2,2), name='B') sel...
""" Copyright 2013 Steven Diamond This file is part of CVXPY. CVXPY is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CVXPY is distributed i...
248
256
1,459
6
241
NunoEdgarGFlowHub/cvxpy
cvxpy/tests/test_domain.py
Python
TestDomain
TestDomain
33
189
33
33
5384e48e36f0fdcde356474a23c30de36b6f0efb
bigcode/the-stack
train
8536ba86240c6cee86258d2b
train
function
def aggregateSSRsByDate(dates, ssrs, skillset, rating, res, iter, dayIndex): ''' Calculate Skillset Rating for a selected Skillset given a list of Top SSR Values However, this will only calculate for the dates in the given list. Those dates must correspond to existent SSR Values in the given SSR list ...
def aggregateSSRsByDate(dates, ssrs, skillset, rating, res, iter, dayIndex):
''' Calculate Skillset Rating for a selected Skillset given a list of Top SSR Values However, this will only calculate for the dates in the given list. Those dates must correspond to existent SSR Values in the given SSR list ''' sum = 0 while True: sum = 0 rating += res ...
break if iter == 11: return rating return aggregateSSRs(skillset, rating - res, res / 2, iter + 1, topssrs) def aggregateSSRsByDate(dates, ssrs, skillset, rating, res, iter, dayIndex):
64
64
211
24
40
poco0317/EtternaScripts
XMLAnalyzer/calc.py
Python
aggregateSSRsByDate
aggregateSSRsByDate
26
43
26
26
11462d5644542fc39f6e1725c6cc577bdcafa235
bigcode/the-stack
train
8c7de034ecc955c58f3baa07
train
function
def get_scores(charts, skillset, advanced_filter = False, ssrnorm = False, requiredAcc = 0, no_limits = False): ''' Get the full list of scores according to the given Skillset and set of charts ''' failed = 0 skipped = 0 SkillsetsWithDates = [] for chart in charts: for scoresAtRate i...
def get_scores(charts, skillset, advanced_filter = False, ssrnorm = False, requiredAcc = 0, no_limits = False):
''' Get the full list of scores according to the given Skillset and set of charts ''' failed = 0 skipped = 0 SkillsetsWithDates = [] for chart in charts: for scoresAtRate in list(chart): for score in scoresAtRate: try: if not fitsAcc(sc...
self.overall = skillsetdict["Overall"] self.stream = skillsetdict["Stream"] self.jumpstream = skillsetdict["Jumpstream"] self.handstream = skillsetdict["Handstream"] self.stamina = skillsetdict["Stamina"] self.jackspeed = skillsetdict["JackSpeed"] self.chordjack = skills...
210
210
700
31
179
poco0317/EtternaScripts
XMLAnalyzer/calc.py
Python
get_scores
get_scores
203
284
203
203
aa21f8470c57e10fa9229236e3d5fe9a6fa5f2e0
bigcode/the-stack
train
814d59a5f4e8c4715643ae18
train
function
def fitsAcc(score, requiredAcc, ssrnorm): try: if ssrnorm: for x in score.findall("SSRNormPercent"): if float(" ".join(x.itertext())) * 100 >= requiredAcc: return True else: for x in score.findall("WifeScore"): if float(" "....
def fitsAcc(score, requiredAcc, ssrnorm):
try: if ssrnorm: for x in score.findall("SSRNormPercent"): if float(" ".join(x.itertext())) * 100 >= requiredAcc: return True else: for x in score.findall("WifeScore"): if float(" ".join(x.itertext())) * 100 >= requiredAcc: ...
"): if " ".join(x.itertext()) == "0": return False for x in score.findall("NoChordCohesion"): if " ".join(x.itertext()) == "0": return False return True def fitsAcc(score, requiredAcc, ssrnorm):
64
64
99
12
51
poco0317/EtternaScripts
XMLAnalyzer/calc.py
Python
fitsAcc
fitsAcc
169
181
169
169
384f3f3514688cac4be06bf9ef95aa0381866f78
bigcode/the-stack
train
34dc8316a007a6e9288234b9
train
function
def getPBs(charts, skillset, advanced_filter = False, ssrnorm = False, requiredAcc = 0, no_limits = False): ''' Given the skillset, get the pbs returns a tuple of (dates, values) , {grade : (dates, values) } ''' import matplotlib pbmap = {} failed = 0 AAAAAkeys = set() AAAAkeys = se...
def getPBs(charts, skillset, advanced_filter = False, ssrnorm = False, requiredAcc = 0, no_limits = False):
''' Given the skillset, get the pbs returns a tuple of (dates, values) , {grade : (dates, values) } ''' import matplotlib pbmap = {} failed = 0 AAAAAkeys = set() AAAAkeys = set() AAAkeys = set() AAkeys = set() for chart in charts: stuff = list(chart) for ...
.99955: return "AAAA" elif num >= .997: return "AAA" elif num >= .93: return "AA" elif num >= .80: return "A" elif num >= .70: return "B" elif num >= .60: return "C" elif num >= 0: return...
256
256
1,218
32
223
poco0317/EtternaScripts
XMLAnalyzer/calc.py
Python
getPBs
getPBs
286
409
286
286
7a4771ce7190fe507356aefa50655c8466fc12b5
bigcode/the-stack
train
1adac8328ece1e349b6f878f
train
function
def isValid(score, no_limits = False): if no_limits: return True for x in score.findall("EtternaValid"): if " ".join(x.itertext()) == "0": return False for x in score.findall("NoChordCohesion"): if " ".join(x.itertext()) == "0": return False return True
def isValid(score, no_limits = False):
if no_limits: return True for x in score.findall("EtternaValid"): if " ".join(x.itertext()) == "0": return False for x in score.findall("NoChordCohesion"): if " ".join(x.itertext()) == "0": return False return True
usually complains about the ssr section missing for k,v in topssrs.items(): topssrs[k] = sorted(v, key = lambda x: x[1]) return topssrs #print("Failed score count", failed) def isValid(score, no_limits = False):
64
64
81
10
54
poco0317/EtternaScripts
XMLAnalyzer/calc.py
Python
isValid
isValid
158
167
158
158
f1bd564db0b8e529f02bbbb12939185fbd6fe3c4
bigcode/the-stack
train
397b8cca70e19ae1b7f7e91d
train
class
class InfoHolder: def __init__(self, date, skillsetdict, percent, name="", grade=""): self.date = date self.skillsets = skillsetdict self.overall = skillsetdict["Overall"] self.stream = skillsetdict["Stream"] self.jumpstream = skillsetdict["Jumpstream"] self.handstrea...
class InfoHolder:
def __init__(self, date, skillsetdict, percent, name="", grade=""): self.date = date self.skillsets = skillsetdict self.overall = skillsetdict["Overall"] self.stream = skillsetdict["Stream"] self.jumpstream = skillsetdict["Jumpstream"] self.handstream = skillsetdict["...
(x.itertext())) * 100 >= requiredAcc: return True else: for x in score.findall("WifeScore"): if float(" ".join(x.itertext())) * 100 >= requiredAcc: return True return False except: return False class InfoHolder:
65
65
219
4
60
poco0317/EtternaScripts
XMLAnalyzer/calc.py
Python
InfoHolder
InfoHolder
183
201
183
183
a4090fef05c5e6c6a49b3a12eebafd4db71c518e
bigcode/the-stack
train
b1ccdb1c7cc8ee63d7c18b6f
train
function
def aggregateSSRs(skillset, rating, res, iter, topssrs): ''' Calculate Skillset Rating for a selected Skillset given a list of Top SSR Values ''' sum = 0 while True: sum = 0 rating += res for i in range(len(topssrs[skillset])): sum += max(0, 2 / math.erfc(0.1 * (t...
def aggregateSSRs(skillset, rating, res, iter, topssrs):
''' Calculate Skillset Rating for a selected Skillset given a list of Top SSR Values ''' sum = 0 while True: sum = 0 rating += res for i in range(len(topssrs[skillset])): sum += max(0, 2 / math.erfc(0.1 * (topssrs[skillset][i][0] - rating)) - 2) if 2 ** (r...
import time import datetime import traceback from multiprocessing import Pool skillset_consts = ["Overall", "Stream", "Jumpstream", "Handstream", "JackSpeed", "Chordjack", "Technical", "Stamina"] def aggregateSSRs(skillset, rating, res, iter, topssrs):
64
64
166
17
47
poco0317/EtternaScripts
XMLAnalyzer/calc.py
Python
aggregateSSRs
aggregateSSRs
10
24
10
10
5711eb14a391f5048b7742ce9de98bb47cdf402d
bigcode/the-stack
train
62478c5ec7fd9fadad880684
train
function
def calcRatingByDate(ssrs, no_limits = False): ''' Given a list of SSRs to work with, calculate the Skillset Ratings for every day of those SSRs Return a dict mapping those dates to the Skillsets ''' listOfRatingsByDate = {ss: {} for ss in skillset_consts} SSRsByDates = {} # gather a list o...
def calcRatingByDate(ssrs, no_limits = False):
''' Given a list of SSRs to work with, calculate the Skillset Ratings for every day of those SSRs Return a dict mapping those dates to the Skillsets ''' listOfRatingsByDate = {ss: {} for ss in skillset_consts} SSRsByDates = {} # gather a list of ratings by date and attach a readable datetim...
SSRs ''' skillz = {} output = {} for ss in skillset_consts[1:]: output[ss] = aggregateSSRs(ss, 0, 10.24, 1, ssrs) * 1.04 skillz[ss] = output[ss] skills = sorted(list(skillz.values()))[1:] return {"Overall": sum(skills) / 6, "Stream" : skillz["Stream"], "Jumpstrea...
187
187
625
13
174
poco0317/EtternaScripts
XMLAnalyzer/calc.py
Python
calcRatingByDate
calcRatingByDate
65
125
65
65
1256090988947e9bd5c848cec55ec3175f098454
bigcode/the-stack
train
4ae4f1578100c9d3294775b9
train
function
def setAllTopSSRs(charts, ssrnorm, requiredAcc = 0, no_limits = False): ''' Get all valid PB SSRs for the profile. Must be CC Off. Returns a dict mapping skillsets to big lists of SSR values Each list of SSR values is sorted ''' failed = 0 topssrs = {} for chart in charts: for sc...
def setAllTopSSRs(charts, ssrnorm, requiredAcc = 0, no_limits = False):
''' Get all valid PB SSRs for the profile. Must be CC Off. Returns a dict mapping skillsets to big lists of SSR values Each list of SSR values is sorted ''' failed = 0 topssrs = {} for chart in charts: for scores_at_rate in list(chart): pbkey = scores_at_rate.get("PBK...
(f"Queued the process pool. There are {total} days to calculate. Up to {os.cpu_count()} processes may spawn.") pool.close() # stop the pool pool.join() # block until the pool finishes j2 = time.time() print(f"Full run took {j2-j1} seconds") return SSRsByDates def setAllTopSSRs(charts, ssrnorm, requ...
100
100
334
24
75
poco0317/EtternaScripts
XMLAnalyzer/calc.py
Python
setAllTopSSRs
setAllTopSSRs
127
155
127
127
2c73f6eb6d83568be36349b1b59a6c4edfe1beed
bigcode/the-stack
train
95fc1b4dc39cc173938a19df
train
function
def calcRating(ssrs): ''' Shortcut to grab a dict of all Skillset Ratings given a full list of SSRs ''' skillz = {} output = {} for ss in skillset_consts[1:]: output[ss] = aggregateSSRs(ss, 0, 10.24, 1, ssrs) * 1.04 skillz[ss] = output[ss] skills = sorted(list(skillz.values()...
def calcRating(ssrs):
''' Shortcut to grab a dict of all Skillset Ratings given a full list of SSRs ''' skillz = {} output = {} for ss in skillset_consts[1:]: output[ss] = aggregateSSRs(ss, 0, 10.24, 1, ssrs) * 1.04 skillz[ss] = output[ss] skills = sorted(list(skillz.values()))[1:] return {"Ov...
1) >= sum: break if iter == 11: return rating, skillset, dayIndex return aggregateSSRsByDate(dates, ssrs, skillset, rating - res, res / 2, iter + 1, dayIndex) def calcRating(ssrs):
64
64
198
6
58
poco0317/EtternaScripts
XMLAnalyzer/calc.py
Python
calcRating
calcRating
45
63
45
45
d0d6c9546bcef02832a6103b77152fa7cc5c9b8a
bigcode/the-stack
train
6df86c704e49bbbfe16bcbf7
train
function
def parse_alias(alias): if "&&" not in alias: if alias.startswith('"') and alias.endswith('"'): return [alias[1:-1]] return [alias] buffer = "" cmd = [] try: for token in shlex.shlex(alias, punctuation_chars="&"): if token != "&&": buffer ...
def parse_alias(alias):
if "&&" not in alias: if alias.startswith('"') and alias.endswith('"'): return [alias[1:-1]] return [alias] buffer = "" cmd = [] try: for token in shlex.shlex(alias, punctuation_chars="&"): if token != "&&": buffer += " " + token ...
.capitalize()} `{word}` cannot be found.**", ) val = get_close_matches(word, possibilities, n=n, cutoff=cutoff) if val: embed.description += "\nHowever, perhaps you meant...\n" + "\n".join(val) return embed def parse_alias(alias):
64
64
172
5
58
AbbeG/modmail
core/utils.py
Python
parse_alias
parse_alias
215
244
215
215
e49c95891dd1f980ffca027a2336905ea2c1af6d
bigcode/the-stack
train
523ac66e21a7611831610900
train
function
async def ignore(coro): try: await coro except Exception: pass
async def ignore(coro):
try: await coro except Exception: pass
The user ID if found. Otherwise, -1. """ match = re.search(r"\bUser ID: (\d{17,21})\b", text) if match is not None: return int(match.group(1)) return -1 async def ignore(coro):
64
64
20
6
57
AbbeG/modmail
core/utils.py
Python
ignore
ignore
197
201
197
197
837f5d84c420134f05fe248fd98e09a0846a1a27
bigcode/the-stack
train
e840541e87d91e2343ae93fa
train
function
def match_user_id(text: str) -> int: """ Matches a user ID in the format of "User ID: 12345". Parameters ---------- text : str The text of the user ID. Returns ------- int The user ID if found. Otherwise, -1. """ match = re.search(r"\bUser ID: (\d{17,21})\b", te...
def match_user_id(text: str) -> int:
""" Matches a user ID in the format of "User ID: 12345". Parameters ---------- text : str The text of the user ID. Returns ------- int The user ID if found. Otherwise, -1. """ match = re.search(r"\bUser ID: (\d{17,21})\b", text) if match is not None: ...
""" # remove ```py\n``` if content.startswith("```") and content.endswith("```"): return "\n".join(content.split("\n")[1:-1]) # remove `foo` return content.strip("` \n") def match_user_id(text: str) -> int:
64
64
113
11
53
AbbeG/modmail
core/utils.py
Python
match_user_id
match_user_id
177
194
177
177
25d00df9c1ec62508b2eb0b677ef80b409ed3958
bigcode/the-stack
train
9b00922e5aff520d772be6e5
train
function
def human_join(strings): if len(strings) <= 2: return " or ".join(strings) return ", ".join(strings[: len(strings) - 1]) + " or " + strings[-1]
def human_join(strings):
if len(strings) <= 2: return " or ".join(strings) return ", ".join(strings[: len(strings) - 1]) + " or " + strings[-1]
", ".gif", ".jpeg", ".webp"] url = parse.urlsplit(url) if any(url.path.lower().endswith(i) for i in types): return parse.urlunsplit((*url[:3], "size=128", url[-1])) return "" def human_join(strings):
63
64
45
5
58
AbbeG/modmail
core/utils.py
Python
human_join
human_join
129
132
129
129
81aefbb178a46235770c46644dbbc40833601c53
bigcode/the-stack
train
f921ce563f602a1fed7e2da7
train
function
def format_preview(messages: typing.List[typing.Dict[str, typing.Any]]): """ Used to format previews. Parameters ---------- messages : List[Dict[str, Any]] A list of messages. Returns ------- str A formatted string preview. """ messages = messages[:3] out = ...
def format_preview(messages: typing.List[typing.Dict[str, typing.Any]]):
""" Used to format previews. Parameters ---------- messages : List[Dict[str, Any]] A list of messages. Returns ------- str A formatted string preview. """ messages = messages[:3] out = "" for message in messages: if message.get("type") in {"note"...
to 50. Returns ------- str The truncated text. """ text = text.strip() return text[: max - 3].strip() + "..." if len(text) > max else text def format_preview(messages: typing.List[typing.Dict[str, typing.Any]]):
64
64
180
16
47
AbbeG/modmail
core/utils.py
Python
format_preview
format_preview
62
87
62
62
bb5d4768a476a44cfde9a59e746f96736eb31ada
bigcode/the-stack
train
45d9ed4843c82a309de4cb9e
train
function
def parse_image_url(url: str) -> str: """ Convert the image URL into a sized Discord avatar. Parameters ---------- url : str The URL to convert. Returns ------- str The converted URL, or '' if the URL isn't in the proper format. """ types = [".png", ".jpg", ".gi...
def parse_image_url(url: str) -> str:
""" Convert the image URL into a sized Discord avatar. Parameters ---------- url : str The URL to convert. Returns ------- str The converted URL, or '' if the URL isn't in the proper format. """ types = [".png", ".jpg", ".gif", ".jpeg", ".webp"] url = parse....
if the URL is pointing to an image. Parameters ---------- url : str The URL to check. Returns ------- bool Whether the URL is a valid image URL. """ return bool(parse_image_url(url)) def parse_image_url(url: str) -> str:
64
64
133
11
53
AbbeG/modmail
core/utils.py
Python
parse_image_url
parse_image_url
107
126
107
107
a8844a8b2b3c8b0bdd6ab518f6e9e95de429aa01
bigcode/the-stack
train
8acbb1dfa85ce8dd9be7d6b2
train
function
def cleanup_code(content: str) -> str: """ Automatically removes code blocks from the code. Parameters ---------- content : str The content to be cleaned. Returns ------- str The cleaned content. """ # remove ```py\n``` if content.startswith("```") and conte...
def cleanup_code(content: str) -> str:
""" Automatically removes code blocks from the code. Parameters ---------- content : str The content to be cleaned. Returns ------- str The cleaned content. """ # remove ```py\n``` if content.startswith("```") and content.endswith("```"): return "\n"...
A formatted string of the number of days passed. """ day = int(day) if day == 0: return "**today**" return f"{day} day ago" if day == 1 else f"{day} days ago" def cleanup_code(content: str) -> str:
64
64
104
10
54
AbbeG/modmail
core/utils.py
Python
cleanup_code
cleanup_code
155
174
155
155
f11783bb49e71d986930aa50e3c2a4ee7f11f0b4
bigcode/the-stack
train
e69bf69aeef78fc5badaeb32
train
function
def is_image_url(url: str) -> bool: """ Check if the URL is pointing to an image. Parameters ---------- url : str The URL to check. Returns ------- bool Whether the URL is a valid image URL. """ return bool(parse_image_url(url))
def is_image_url(url: str) -> bool:
""" Check if the URL is pointing to an image. Parameters ---------- url : str The URL to check. Returns ------- bool Whether the URL is a valid image URL. """ return bool(parse_image_url(url))
str(author["discriminator"]) prefix = "[M]" if author["mod"] else "[R]" out += truncate(f"`{prefix} {name}:` {content}", max=75) + "\n" return out or "No Messages" def is_image_url(url: str) -> bool:
64
64
68
11
53
AbbeG/modmail
core/utils.py
Python
is_image_url
is_image_url
90
104
90
90
564e56ae6dd98ad8de58d82d80926df7cee00982
bigcode/the-stack
train
55d566622cf6afaa901ad8d3
train
function
def format_description(i, names): return "\n".join( ": ".join((str(a + i * 15), b)) for a, b in enumerate(takewhile(lambda x: x is not None, names), start=1) )
def format_description(i, names):
return "\n".join( ": ".join((str(a + i * 15), b)) for a, b in enumerate(takewhile(lambda x: x is not None, names), start=1) )
buffer = "" except ValueError: return [] buffer = buffer.strip() if buffer.startswith('"') and buffer.endswith('"'): buffer = buffer[1:-1] cmd += [buffer] if not all(cmd): return [] return cmd def format_description(i, names):
64
64
55
7
56
AbbeG/modmail
core/utils.py
Python
format_description
format_description
247
251
247
247
54ec8d2c71416b45661e14cbbcdf1ad87da52a01
bigcode/the-stack
train
3335bc80a5f0a22321e64437
train
class
class User(commands.IDConverter): """ A custom discord.py `Converter` that supports `Member`, `User`, and string ID's. """ # noinspection PyCallByClass,PyTypeChecker async def convert(self, ctx, argument): try: return await commands.MemberConverter.convert(self, ctx, argumen...
class User(commands.IDConverter):
""" A custom discord.py `Converter` that supports `Member`, `User`, and string ID's. """ # noinspection PyCallByClass,PyTypeChecker async def convert(self, ctx, argument): try: return await commands.MemberConverter.convert(self, ctx, argument) except commands.BadArgu...
_stb # pylint: disable=import-error from itertools import takewhile from urllib import parse import discord from discord.ext import commands def strtobool(val): if isinstance(val, bool): return val return _stb(str(val)) class User(commands.IDConverter):
64
64
147
6
58
AbbeG/modmail
core/utils.py
Python
User
User
19
38
19
19
e3fea1b15915edd3cc512a12c238dfd60626db1f
bigcode/the-stack
train
46ab0c8f62f56f4e8acc8626
train
function
def truncate(text: str, max: int = 50) -> str: # pylint: disable=redefined-builtin """ Reduces the string to `max` length, by trimming the message into "...". Parameters ---------- text : str The text to trim. max : int, optional The max length of the text. Defaults to ...
def truncate(text: str, max: int = 50) -> str: # pylint: disable=redefined-builtin
""" Reduces the string to `max` length, by trimming the message into "...". Parameters ---------- text : str The text to trim. max : int, optional The max length of the text. Defaults to 50. Returns ------- str The truncated text. """ text = ...
._get_id_match(argument) if match is None: raise commands.BadArgument('User "{}" not found'.format(argument)) return discord.Object(int(match.group(1))) def truncate(text: str, max: int = 50) -> str: # pylint: disable=redefined-builtin
63
64
127
26
37
AbbeG/modmail
core/utils.py
Python
truncate
truncate
41
59
41
41
3e35b2d9d4a359931f045523ad30ff30dca78ba5
bigcode/the-stack
train
eeb56bd4d40754b174485d2c
train
function
def days(day: typing.Union[str, int]) -> str: """ Humanize the number of days. Parameters ---------- day: Union[int, str] The number of days passed. Returns ------- str A formatted string of the number of days passed. """ day = int(day) if day == 0: ...
def days(day: typing.Union[str, int]) -> str:
""" Humanize the number of days. Parameters ---------- day: Union[int, str] The number of days passed. Returns ------- str A formatted string of the number of days passed. """ day = int(day) if day == 0: return "**today**" return f"{day} day ago"...
])) return "" def human_join(strings): if len(strings) <= 2: return " or ".join(strings) return ", ".join(strings[: len(strings) - 1]) + " or " + strings[-1] def days(day: typing.Union[str, int]) -> str:
64
64
106
14
50
AbbeG/modmail
core/utils.py
Python
days
days
135
152
135
135
dc35ad4767c382e0c28ad50768a9e7417bb77e41
bigcode/the-stack
train
8af83e0bd64b04b65053ce58
train
function
def strtobool(val): if isinstance(val, bool): return val return _stb(str(val))
def strtobool(val):
if isinstance(val, bool): return val return _stb(str(val))
shlex import typing from difflib import get_close_matches from distutils.util import strtobool as _stb # pylint: disable=import-error from itertools import takewhile from urllib import parse import discord from discord.ext import commands def strtobool(val):
64
64
26
7
56
AbbeG/modmail
core/utils.py
Python
strtobool
strtobool
13
16
13
13
6b5da5e24362b78729599a277b2b5b0acf760188
bigcode/the-stack
train
9b0bec77195cfcace703fd86
train
function
def create_not_found_embed(word, possibilities, name, n=2, cutoff=0.6) -> discord.Embed: embed = discord.Embed( color=discord.Color.red(), description=f"**{name.capitalize()} `{word}` cannot be found.**", ) val = get_close_matches(word, possibilities, n=n, cutoff=cutoff) if val: ...
def create_not_found_embed(word, possibilities, name, n=2, cutoff=0.6) -> discord.Embed:
embed = discord.Embed( color=discord.Color.red(), description=f"**{name.capitalize()} `{word}` cannot be found.**", ) val = get_close_matches(word, possibilities, n=n, cutoff=cutoff) if val: embed.description += "\nHowever, perhaps you meant...\n" + "\n".join(val) return embe...
match is not None: return int(match.group(1)) return -1 async def ignore(coro): try: await coro except Exception: pass def create_not_found_embed(word, possibilities, name, n=2, cutoff=0.6) -> discord.Embed:
64
64
106
26
37
AbbeG/modmail
core/utils.py
Python
create_not_found_embed
create_not_found_embed
204
212
204
204
3939fc0f6ab01476143213b9cdb934ae72def6d1
bigcode/the-stack
train
edd277e0f9f3c4b5b543cf9c
train
function
def test_inhibition_multiple_rescue_entries_not_present(monkeypatch): """Tests whether the upgrade process is not inhibited when multiple rescue boot entries are not present.""" monkeypatch.setattr(reporting, 'create_report', create_report_mocked()) boot_entries = [ BootEntry(title='entry_1', kerne...
def test_inhibition_multiple_rescue_entries_not_present(monkeypatch):
"""Tests whether the upgrade process is not inhibited when multiple rescue boot entries are not present.""" monkeypatch.setattr(reporting, 'create_report', create_report_mocked()) boot_entries = [ BootEntry(title='entry_1', kernel_image="img"), BootEntry(title='entry_2', kernel_image="img")...
-ver2.3']: assert expected_rescue_entry in report_summary, fail_description fail_description = 'Upgrade should be inhibited on multiple rescue entries.' assert 'inhibitor' in mocked_report.report_fields['flags'], fail_description def test_inhibition_multiple_rescue_entries_not_present(monkeypatch):
64
64
148
14
49
tmds/leapp-repository
repos/system_upgrade/el7toel8/actors/ziplcheckbootentries/tests/test_ziplcheckbootentries.py
Python
test_inhibition_multiple_rescue_entries_not_present
test_inhibition_multiple_rescue_entries_not_present
44
56
44
44
099453b8b913dd2aac92ff13dad7ffd1411e7e28
bigcode/the-stack
train
3fce509b6ac5277c5eefd306
train
function
@pytest.mark.parametrize( ('boot_entries',), [([BootEntry(title='Linux0', kernel_image='/boot/vmlinuz-4.18.0-240.1.1.el8_3.x86_64'), BootEntry(title='Linux1', kernel_image='/boot/4.18.0-240.1.1.el8_3.x86_64')],), ([BootEntry(title='Linux0', kernel_image='/boot/vmlinuz-4.18.0-240.1.1.el8_3.x86_64'), ...
@pytest.mark.parametrize( ('boot_entries',), [([BootEntry(title='Linux0', kernel_image='/boot/vmlinuz-4.18.0-240.1.1.el8_3.x86_64'), BootEntry(title='Linux1', kernel_image='/boot/4.18.0-240.1.1.el8_3.x86_64')],), ([BootEntry(title='Linux0', kernel_image='/boot/vmlinuz-4.18.0-240.1.1.el8_3.x86_64'), ...
"""Tests whether the IPU gets inhibited when there are kernel images shared between boot entries.""" monkeypatch.setattr(reporting, 'create_report', create_report_mocked()) inhibit_if_entries_share_kernel_version(SourceBootLoaderConfiguration(entries=boot_entries)) assert reporting.create_report.call...
@pytest.mark.parametrize( ('boot_entries',), [([BootEntry(title='Linux0', kernel_image='/boot/vmlinuz-4.18.0-240.1.1.el8_3.x86_64'), BootEntry(title='Linux1', kernel_image='/boot/4.18.0-240.1.1.el8_3.x86_64')],), ([BootEntry(title='Linux0', kernel_image='/boot/vmlinuz-4.18.0-240.1.1.el8_3.x86_64'), ...
174
90
302
174
0
tmds/leapp-repository
repos/system_upgrade/el7toel8/actors/ziplcheckbootentries/tests/test_ziplcheckbootentries.py
Python
test_inhibit_when_entries_share_kernel_image
test_inhibit_when_entries_share_kernel_image
71
88
71
77
2dc1bf55ab894b9aacaa291af8d646e374db2351
bigcode/the-stack
train
21c420b7b657c95cea64541e
train
function
def test_extract_kernel_version(): # Manually generated via experimentation with the zipl-switch-to-blscfg versions_from_img_paths = [ ('/boot/vmlinuz-4.18.0-240.1.1.el8_3.x86_64', '4.18.0-240.1.1.el8_3.x86_64'), ('/boot/4.18.0-240.1.1.el8_3.x86_64', '4.18.0-240.1.1.el8_3.x86_64'), ('/bo...
def test_extract_kernel_version(): # Manually generated via experimentation with the zipl-switch-to-blscfg
versions_from_img_paths = [ ('/boot/vmlinuz-4.18.0-240.1.1.el8_3.x86_64', '4.18.0-240.1.1.el8_3.x86_64'), ('/boot/4.18.0-240.1.1.el8_3.x86_64', '4.18.0-240.1.1.el8_3.x86_64'), ('/boot/patched-4.18.0-240.1.1.el8_3.x86_64', 'patched-4.18.0-240.1.1.el8_3.x86_64'), ('patched-4.18.0-240.1...
assert bool(reporting.create_report.called) == should_perform, fail_description if should_perform: inhibitor_description = 'contains boot entries sharing the same kernel version' assert inhibitor_description in reporting.create_report.report_fields['summary'] def test_extract_kernel_version(): ...
73
73
245
23
50
tmds/leapp-repository
repos/system_upgrade/el7toel8/actors/ziplcheckbootentries/tests/test_ziplcheckbootentries.py
Python
test_extract_kernel_version
test_extract_kernel_version
146
156
146
147
d3cc5316637c24eca5ef29d809e19d32d5eb14ab
bigcode/the-stack
train
cfb5bd7e562325c6fa9a206f
train
function
def test_inhibition_when_entries_do_not_share_kernel_image(monkeypatch): """Tests whether the IPU is not inhibited when there are no kernel images shared between boot entries.""" entries = [ BootEntry(title='Linux#0', kernel_image='/boot/vmlinuz-4.17.0-240.1.1.el8_3.x86_64'), BootEntry(title='Li...
def test_inhibition_when_entries_do_not_share_kernel_image(monkeypatch):
"""Tests whether the IPU is not inhibited when there are no kernel images shared between boot entries.""" entries = [ BootEntry(title='Linux#0', kernel_image='/boot/vmlinuz-4.17.0-240.1.1.el8_3.x86_64'), BootEntry(title='Linux#1', kernel_image='/boot/vmlinuz-4.18.0-240.1.1.el8_3.x86_64') ] ...
="img_rescue"), ] inhibit_if_multiple_zipl_rescue_entries_present(SourceBootLoaderConfiguration(entries=boot_entries)) assert not reporting.create_report.called, 'Report was created, even if multiple rescue entries were not present.' def test_inhibition_when_entries_do_not_share_kernel_image(monkeypatch):...
63
64
156
15
48
tmds/leapp-repository
repos/system_upgrade/el7toel8/actors/ziplcheckbootentries/tests/test_ziplcheckbootentries.py
Python
test_inhibition_when_entries_do_not_share_kernel_image
test_inhibition_when_entries_do_not_share_kernel_image
59
68
59
59
2436da160946db4e95d9c8e11985809467342e6f
bigcode/the-stack
train