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
911a49278a3cc616335a4b51
train
class
class Conv2D(Layer): """Convolution The binary Convolution Layer uses HWMC instead of HWCM layout. The weights and outputs are packed into ints of size binary_word_size. The binary Convolution Layer only allows for weights and inputs -1 (False) and 1 (True). It works as follows: x = popcount(c...
class Conv2D(Layer):
"""Convolution The binary Convolution Layer uses HWMC instead of HWCM layout. The weights and outputs are packed into ints of size binary_word_size. The binary Convolution Layer only allows for weights and inputs -1 (False) and 1 (True). It works as follows: x = popcount(convolution_weight xno...
from .Layer import Layer #from fastinference.Util import render, get_initializer, get_attribute import fastinference.Util class Conv2D(Layer):
33
146
487
7
25
njru8cjo/fastinference
fastinference/models/nn/Conv2D.py
Python
Conv2D
Conv2D
5
40
5
5
e6fafd713d63458048b3497aa4cafb552dee3263
bigcode/the-stack
train
9c2433a37348f8b806b700ea
train
class
class KojiPlugin(PreBuildPlugin): key = "koji" is_allowed_to_fail = False def __init__(self, tasker, workflow, target=None, proxy=None): """ constructor :param tasker: ContainerTasker instance :param workflow: DockerBuildWorkflow instance :param target: string, koji...
class KojiPlugin(PreBuildPlugin):
key = "koji" is_allowed_to_fail = False def __init__(self, tasker, workflow, target=None, proxy=None): """ constructor :param tasker: ContainerTasker instance :param workflow: DockerBuildWorkflow instance :param target: string, koji target to use as a source ...
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. Pre build plugin for koji build system """ import os from atomic_reactor.plugin import PreBuildPlugin from atomic_reactor.constants import YUM_R...
135
209
699
9
126
SalatskySal/atomic-reactor
atomic_reactor/plugins/pre_koji.py
Python
KojiPlugin
KojiPlugin
20
101
20
20
30c7e83b12408af3b0c4c56a3a95f26378beb282
bigcode/the-stack
train
d8514b42252b610e46007855
train
function
@register(pattern=r".uploadas(stream|vn|all) (.*)", outgoing=True) async def uploadas(uas_event): """ For .uploadas command, allows you to specify some arguments for upload. """ await uas_event.edit("Processing ...") type_of_upload = uas_event.pattern_match.group(1) supports_streaming = False ...
@register(pattern=r".uploadas(stream|vn|all) (.*)", outgoing=True) async def uploadas(uas_event):
""" For .uploadas command, allows you to specify some arguments for upload. """ await uas_event.edit("Processing ...") type_of_upload = uas_event.pattern_match.group(1) supports_streaming = False round_message = False spam_big_messages = False if type_of_upload == "stream": su...
_h(file): """ Get width and height of media """ command_to_run = [ "ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", file, ] # https://stackoverflow.com/a/11236144/4723940 try: t_r...
195
195
653
27
167
Evenix20/sempakk
userbot/modules/upload_download.py
Python
uploadas
uploadas
259
348
259
260
1be6af2a85d7d387c6edc5c29d040eaac01cfeb4
bigcode/the-stack
train
303803b87ff0a10a9aecd5bd
train
function
@register(pattern=r".download(?: |$)(.*)", outgoing=True) async def download(target_file): """ For .download command, download files to the userbot's server. """ await target_file.edit("Processing ...") input_str = target_file.pattern_match.group(1) if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): ...
@register(pattern=r".download(?: |$)(.*)", outgoing=True) async def download(target_file):
""" For .download command, download files to the userbot's server. """ await target_file.edit("Processing ...") input_str = target_file.pattern_match.group(1) if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) if "|" in input_str: url, file_name...
) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.d (the "License"); # you may not use this file except in compliance with the License. # # The entire source code is OSSRPL except # 'download, uploadir, uploadas, upload' which is MPL # License: MPL and OSSRPL """...
212
212
709
21
190
Evenix20/sempakk
userbot/modules/upload_download.py
Python
download
download
29
103
29
30
0ba26b9a392d10681dd01cbf0bc325722e96e658
bigcode/the-stack
train
ca9b76e1f5b74514294981d7
train
function
@register(pattern=r".upload (.*)", outgoing=True) async def upload(u_event): """ For .upload command, allows you to upload a file from the userbot's server """ await u_event.edit("Processing ...") input_str = u_event.pattern_match.group(1) if input_str in ("userbot.session", "config.env"): ...
@register(pattern=r".upload (.*)", outgoing=True) async def upload(u_event):
""" For .upload command, allows you to upload a file from the userbot's server """ await u_event.edit("Processing ...") input_str = u_event.pattern_match.group(1) if input_str in ("userbot.session", "config.env"): return await u_event.edit("`That's a dangerous operation! Not Permitted!`") ...
.remove(single_file) uploaded = uploaded + 1 await udir_event.edit("Uploaded {} files successfully !!".format(uploaded)) else: await udir_event.edit("404: Directory Not Found") @register(pattern=r".upload (.*)", outgoing=True) async def upload(u_event):
63
64
206
18
45
Evenix20/sempakk
userbot/modules/upload_download.py
Python
upload
upload
183
204
183
184
3fd949fc4607ae0b75d2a0bca8b126cdd7b25c09
bigcode/the-stack
train
ff5c13834801badcab9db96d
train
function
def get_video_thumb(file, output=None, width=90): """ Get video thumbnail """ metadata = extractMetadata(createParser(file)) popen = subprocess.Popen( [ "ffmpeg", "-i", file, "-ss", str( int((0, metadata.get("durat...
def get_video_thumb(file, output=None, width=90):
""" Get video thumbnail """ metadata = extractMetadata(createParser(file)) popen = subprocess.Popen( [ "ffmpeg", "-i", file, "-ss", str( int((0, metadata.get("duration").seconds)[metadata.has("duration")] / 2) ...
create_task( progress(d, t, u_event, c_time, "[UPLOAD]", input_str) ), ) await u_event.edit("Uploaded successfully !!") else: await u_event.edit("404: File Not Found") def get_video_thumb(file, output=None, width=90):
63
64
148
13
50
Evenix20/sempakk
userbot/modules/upload_download.py
Python
get_video_thumb
get_video_thumb
207
231
207
207
b151e7235aa7b7b969cf42091cf2a0eec3b25513
bigcode/the-stack
train
e7b583ecec06ce92982bfb33
train
function
def extract_w_h(file): """ Get width and height of media """ command_to_run = [ "ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", file, ] # https://stackoverflow.com/a/11236144/4723940 try:...
def extract_w_h(file):
""" Get width and height of media """ command_to_run = [ "ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", file, ] # https://stackoverflow.com/a/11236144/4723940 try: t_response = s...
".format(width), "-vframes", "1", output, ], shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, ) if not popen.returncode and os.path.lexists(file): return output return None def extract_w_h(file):
64
64
171
6
57
Evenix20/sempakk
userbot/modules/upload_download.py
Python
extract_w_h
extract_w_h
234
256
234
234
0d64d0e89515c9f258fd8855688f613395a6cbb0
bigcode/the-stack
train
79d88f6af1f1599b99625b7c
train
function
@register(pattern=r".uploadir (.*)", outgoing=True) async def uploadir(udir_event): """ For .uploadir command, allows you to upload everything from a folder in the server""" input_str = udir_event.pattern_match.group(1) if os.path.exists(input_str): await udir_event.edit("Processing ...") ...
@register(pattern=r".uploadir (.*)", outgoing=True) async def uploadir(udir_event):
""" For .uploadir command, allows you to upload everything from a folder in the server""" input_str = udir_event.pattern_match.group(1) if os.path.exists(input_str): await udir_event.edit("Processing ...") lst_of_files = [] for r, d, f in os.walk(input_str): for fil...
Incorrect URL\n{}".format(url)) elif target_file.reply_to_msg_id: try: c_time = time.time() downloaded_file_name = await target_file.client.download_media( await target_file.get_reply_message(), TEMP_DOWNLOAD_DIRECTORY, progress_...
179
180
600
21
158
Evenix20/sempakk
userbot/modules/upload_download.py
Python
uploadir
uploadir
106
180
106
107
40f81c6db741d7d1614ac7379019001f91fac0b5
bigcode/the-stack
train
2298e568b42f90749a9ab2d5
train
class
class BitcoinRPC: def __init__(self, host, port, username, password): authpair = "%s:%s" % (username, password) authpair = authpair.encode('utf-8') self.authhdr = b"Basic " + base64.b64encode(authpair) self.conn = HTTPConnection(host, port=port, timeout=30) def execute(self, obj...
class BitcoinRPC:
def __init__(self, host, port, username, password): authpair = "%s:%s" % (username, password) authpair = authpair.encode('utf-8') self.authhdr = b"Basic " + base64.b64encode(authpair) self.conn = HTTPConnection(host, port=port, timeout=30) def execute(self, obj): try: ...
Connection import json import re import base64 import sys import os import os.path settings = {} def hex_switchEndian(s): """ Switches the endianness of a hex string (in pairs of hex chars) """ pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)] return b''.join(pairList[::-1]).decode() class Bitco...
93
93
310
4
89
Overdrive5/yumekawa
contrib/linearize/linearize-hashes.py
Python
BitcoinRPC
BitcoinRPC
25
64
25
25
6c327b7e1cb52b34fa20dc035a538686533b2c8d
bigcode/the-stack
train
d899d39189d5d7842bcae4d8
train
function
def hex_switchEndian(s): """ Switches the endianness of a hex string (in pairs of hex chars) """ pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)] return b''.join(pairList[::-1]).decode()
def hex_switchEndian(s):
""" Switches the endianness of a hex string (in pairs of hex chars) """ pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)] return b''.join(pairList[::-1]).decode()
# Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from http.client import HTTPConnection import json import re import base64 import sys import os import os.path settings = {} def hex_switchEndian(s):
64
64
64
6
58
Overdrive5/yumekawa
contrib/linearize/linearize-hashes.py
Python
hex_switchEndian
hex_switchEndian
20
23
20
20
000513da2e66249a1e9e49e9cf3629b47de7e6d3
bigcode/the-stack
train
f720cb2f17b08703eaeeb626
train
function
def get_rpc_cookie(): # Open the cookie file with open(os.path.join(os.path.expanduser(settings['datadir']), '.cookie'), 'r', encoding="ascii") as f: combined = f.readline() combined_split = combined.split(":") settings['rpcuser'] = combined_split[0] settings['rpcpassword'] = com...
def get_rpc_cookie(): # Open the cookie file
with open(os.path.join(os.path.expanduser(settings['datadir']), '.cookie'), 'r', encoding="ascii") as f: combined = f.readline() combined_split = combined.split(":") settings['rpcuser'] = combined_split[0] settings['rpcpassword'] = combined_split[1]
'] == x) # assume replies are in-sequence if settings['rev_hash_bytes'] == 'true': resp_obj['result'] = hex_switchEndian(resp_obj['result']) print(resp_obj['result']) height += num_blocks def get_rpc_cookie(): # Open the cookie file
64
64
78
12
51
Overdrive5/yumekawa
contrib/linearize/linearize-hashes.py
Python
get_rpc_cookie
get_rpc_cookie
93
99
93
94
f00d6d3dcb6c0fa30ec1af5986071abbb9d21338
bigcode/the-stack
train
7ccd904b6847934c69a5d35c
train
function
def get_block_hashes(settings, max_blocks_per_call=10000): rpc = BitcoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpassword']) height = settings['min_height'] while height < settings['max_height']+1: num_blocks = min(settings['max_height']+1-height, max_b...
def get_block_hashes(settings, max_blocks_per_call=10000):
rpc = BitcoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpassword']) height = settings['min_height'] while height < settings['max_height']+1: num_blocks = min(settings['max_height']+1-height, max_blocks_per_call) batch = [] for x in range(n...
if params is None: obj['params'] = [] else: obj['params'] = params return obj @staticmethod def response_is_error(resp_obj): return 'error' in resp_obj and resp_obj['error'] is not None def get_block_hashes(settings, max_blocks_per_call=10000):
73
73
244
15
57
Overdrive5/yumekawa
contrib/linearize/linearize-hashes.py
Python
get_block_hashes
get_block_hashes
66
91
66
66
2f99a4b8a1d6db9f229d896070a4c711bee50c76
bigcode/the-stack
train
edc04eb503bcf5ab66823754
train
class
class FilterableStatement(Statement): """A statement to be used with filterable statements. Args: target (object): The target database object, it can be :class:`mysqlx.Collection` or :class:`mysqlx.Table`. doc_based (Optional[bool]): `True` if it is document based ...
class FilterableStatement(Statement):
"""A statement to be used with filterable statements. Args: target (object): The target database object, it can be :class:`mysqlx.Collection` or :class:`mysqlx.Table`. doc_based (Optional[bool]): `True` if it is document based (defaul...
[0].strip(quote), temp[-1].strip(quote),) class Statement(object): """Provides base functionality for statement objects. Args: target (object): The target database object, it can be :class:`mysqlx.Collection` or :class:`mysqlx.Table`. doc_based (bool): `Tr...
256
256
1,911
7
248
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
FilterableStatement
FilterableStatement
169
479
169
169
d3343f5dd41aeb25fecb00a1fe718a6d6537557d
bigcode/the-stack
train
2dc3fa6078f93430470d7cda
train
function
def parse_table_name(default_schema, table_name, sql_mode=""): """Parse table name. Args: default_schema (str): The default schema. table_name (str): The table name. sql_mode(Optional[str]): The SQL mode. Returns: str: The parsed table name. """ quote = '"' if "ANSI...
def parse_table_name(default_schema, table_name, sql_mode=""):
"""Parse table name. Args: default_schema (str): The default schema. table_name (str): The table name. sql_mode(Optional[str]): The SQL mode. Returns: str: The parsed table name. """ quote = '"' if "ANSI_QUOTES" in sql_mode else "`" delimiter = ".{0}".format(quo...
to quote. sql_mode (Optional[string]): SQL mode. Returns: A string with the multi-part identifier quoted with backticks. """ return ".".join([quote_identifier(identifier, sql_mode) for identifier in identifiers]) def parse_table_name(default_schema, table_name, sql_mod...
64
64
143
14
50
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
parse_table_name
parse_table_name
111
126
111
111
cffdd7f3d74f7ae24ef8e4d82d3290a4678f27c2
bigcode/the-stack
train
a723d7ec0ef332cd07d3d5b1
train
class
class Statement(object): """Provides base functionality for statement objects. Args: target (object): The target database object, it can be :class:`mysqlx.Collection` or :class:`mysqlx.Table`. doc_based (bool): `True` if it is document based. """ def __init__(se...
class Statement(object):
"""Provides base functionality for statement objects. Args: target (object): The target database object, it can be :class:`mysqlx.Collection` or :class:`mysqlx.Table`. doc_based (bool): `True` if it is document based. """ def __init__(self, target, doc_based=Tru...
else "`" delimiter = ".{0}".format(quote) if quote in table_name else "." temp = table_name.split(delimiter, 1) return (default_schema if len(temp) is 1 else temp[0].strip(quote), temp[-1].strip(quote),) class Statement(object):
69
69
232
4
65
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
Statement
Statement
129
166
129
129
dce18461de131a0bcbe2037c67f75889e49ac5c5
bigcode/the-stack
train
9fcad33d5a829c48874d7197
train
function
def flexible_params(*values): """Parse flexible parameters.""" if len(values) == 1 and isinstance(values[0], (list, tuple,)): return values[0] return values
def flexible_params(*values):
"""Parse flexible parameters.""" if len(values) == 1 and isinstance(values[0], (list, tuple,)): return values[0] return values
from .result import SqlResult, Result from .protobuf import mysqlxpb_enum ERR_INVALID_INDEX_NAME = 'The given index name "{}" is not valid' class Expr(object): """Expression wrapper.""" def __init__(self, expr): self.expr = expr def flexible_params(*values):
64
64
42
6
57
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
flexible_params
flexible_params
53
57
53
53
c9452d7adb86eb1d8945b38e0e90a32b27a4f303
bigcode/the-stack
train
795446cf5cfbe9ab97ba143e
train
class
class InsertStatement(WriteStatement): """A statement for insert operations on Table. Args: table (mysqlx.Table): The Table object. *fields: The fields to be inserted. """ def __init__(self, table, *fields): super(InsertStatement, self).__init__(table, False) self._field...
class InsertStatement(WriteStatement):
"""A statement for insert operations on Table. Args: table (mysqlx.Table): The Table object. *fields: The fields to be inserted. """ def __init__(self, table, *fields): super(InsertStatement, self).__init__(table, False) self._fields = flexible_params(*fields) def v...
having}" "{order}{limit}".format(select=self._projection_str or "*", schema=self.schema.name, table=self.target.name, limit=limit, where=where, group=group_by, ...
64
64
176
7
56
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
InsertStatement
InsertStatement
989
1,018
989
989
3a7b3d2ff95c0145ae09c8f262cc34c713bb7395
bigcode/the-stack
train
17165854d4eeddd016e28223
train
class
class ReadStatement(FilterableStatement): """Provide base functionality for Read operations Args: target (object): The target database object, it can be :class:`mysqlx.Collection` or :class:`mysqlx.Table`. doc_based (Optional[bool]): `True` if it is document based ...
class ReadStatement(FilterableStatement):
"""Provide base functionality for Read operations Args: target (object): The target database object, it can be :class:`mysqlx.Collection` or :class:`mysqlx.Table`. doc_based (Optional[bool]): `True` if it is document based (default: `...
mysqlx.DbDoc`, string JSON format or a dict with the changes and applies it on all matching documents. Args: doc (object): A generic document (DbDoc), string in JSON format or dict, with the changes to apply to the matching documents. ...
228
228
762
7
221
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
ReadStatement
ReadStatement
780
891
780
780
878287222b80a00068cd21bf37b7505fb7edc552
bigcode/the-stack
train
7fcb39bc0f60fe51206af5f0
train
function
def quote_identifier(identifier, sql_mode=""): """Quote the given identifier with backticks, converting backticks (`) in the identifier name with the correct escape sequence (``) unless the identifier is quoted (") as in sql_mode set to ANSI_QUOTES. Args: identifier (string): Identifier to quot...
def quote_identifier(identifier, sql_mode=""):
"""Quote the given identifier with backticks, converting backticks (`) in the identifier name with the correct escape sequence (``) unless the identifier is quoted (") as in sql_mode set to ANSI_QUOTES. Args: identifier (string): Identifier to quote. sql_mode (Optional[string]): SQL mod...
_mode: return ((identifier[0] == "`" and identifier[-1] == "`") or (identifier[0] == '"' and identifier[-1] == '"')) return identifier[0] == "`" and identifier[-1] == "`" def quote_identifier(identifier, sql_mode=""):
64
64
164
9
55
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
quote_identifier
quote_identifier
76
94
76
76
183ea78700b6834de4cbca5f60f46728ccffb37a
bigcode/the-stack
train
29296f1de6eb4802ffaf8375
train
class
class ModifyStatement(FilterableStatement): """A statement for document update operations on a Collection. Args: collection (mysqlx.Collection): The Collection object. condition (str): Sets the search condition to identify the documents to be modified. .. versionch...
class ModifyStatement(FilterableStatement):
"""A statement for document update operations on a Collection. Args: collection (mysqlx.Collection): The Collection object. condition (str): Sets the search condition to identify the documents to be modified. .. versionchanged:: 8.0.12 The ``condition`` para...
== 0: return Result() return self._connection.send_insert(self) class UpdateSpec(object): """Update specification class implementation. Args: update_type (int): The update type. source (str): The source. value (Optional[str]): The value. """ def __init__(...
256
256
1,041
7
248
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
ModifyStatement
ModifyStatement
620
777
620
620
6ae095a395affe2ef174b8c0f9a5651dd0bf8967
bigcode/the-stack
train
1ba4d2d602092e0a94a70fea
train
class
class RemoveStatement(FilterableStatement): """A statement for document removal from a collection. Args: collection (mysqlx.Collection): The Collection object. condition (str): Sets the search condition to identify the documents to be removed. .. versionchanged:: 8...
class RemoveStatement(FilterableStatement):
"""A statement for document removal from a collection. Args: collection (mysqlx.Collection): The Collection object. condition (str): Sets the search condition to identify the documents to be removed. .. versionchanged:: 8.0.12 The ``condition`` parameter was...
): """Execute the statement. Returns: mysqlx.Result: Result object Raises: ProgrammingError: If condition was not set. """ if not self.has_where: raise ProgrammingError("No condition was found for update") return self._connection.upda...
67
67
224
7
60
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
RemoveStatement
RemoveStatement
1,093
1,130
1,093
1,093
90d3df838e890c969a181c854c5a78485aab7d3e
bigcode/the-stack
train
c8e1246e9aace0755eac5b49
train
class
class UpdateStatement(FilterableStatement): """A statement for record update operations on a Table. Args: table (mysqlx.Table): The Table object. .. versionchanged:: 8.0.12 The ``fields`` parameters were removed. """ def __init__(self, table): super(UpdateStatement, self).__...
class UpdateStatement(FilterableStatement):
"""A statement for record update operations on a Table. Args: table (mysqlx.Table): The Table object. .. versionchanged:: 8.0.12 The ``fields`` parameters were removed. """ def __init__(self, table): super(UpdateStatement, self).__init__(target=table, doc_based=False) ...
).__init__(table, False) self._fields = flexible_params(*fields) def values(self, *values): """Set the values to be inserted. Args: *values: The values of the columns to be inserted. Returns: mysqlx.InsertStatement: InsertStatement object. """ ...
121
121
405
7
114
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
UpdateStatement
UpdateStatement
1,021
1,090
1,021
1,021
ac7c04764ab0e7d752b61af46752ee4535c4f18d
bigcode/the-stack
train
115512152698a1e6546acb57
train
class
class WriteStatement(Statement): """Provide common write operation attributes. """ def __init__(self, target, doc_based): super(WriteStatement, self).__init__(target, doc_based) self._values = [] def get_values(self): """Returns the list of values. Returns: ...
class WriteStatement(Statement):
"""Provide common write operation attributes. """ def __init__(self, target, doc_based): super(WriteStatement, self).__init__(target, doc_based) self._values = [] def get_values(self): """Returns the list of values. Returns: `list`: The list of values. ...
self._connection = connection self._sql = sql def execute(self): """Execute the statement. Returns: mysqlx.SqlResult: SqlResult object. """ self._connection.send_sql(self._sql) return SqlResult(self._connection) class WriteStatement(Statement):
64
64
116
6
58
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
WriteStatement
WriteStatement
504
525
504
504
c6a7a11305c440dfd650ae1b58322ea0e87fc4d7
bigcode/the-stack
train
3ea3491fab16c115b6a7f243
train
class
class SelectStatement(ReadStatement): """A statement for record retrieval operations on a Table. Args: table (mysqlx.Table): The Table object. *fields: The fields to be retrieved. """ def __init__(self, table, *fields): super(SelectStatement, self).__init__(table, False) ...
class SelectStatement(ReadStatement):
"""A statement for record retrieval operations on a Table. Args: table (mysqlx.Table): The Table object. *fields: The fields to be retrieved. """ def __init__(self, table, *fields): super(SelectStatement, self).__init__(table, False) self._set_projection(*fields) d...
, condition) def fields(self, *fields): """Sets a document field filter. Args: *fields: The string expressions identifying the fields to be extracted. Returns: mysqlx.FindStatement: FindStatement object. """ return self._set_pro...
124
124
416
6
118
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
SelectStatement
SelectStatement
931
986
931
931
ec11654dd04ffa123d75b423b686eb31baa0330f
bigcode/the-stack
train
750725988e8a7eaf8cc6a1bf
train
class
class DeleteStatement(FilterableStatement): """A statement that drops a table. Args: table (mysqlx.Table): The Table object. .. versionchanged:: 8.0.12 The ``condition`` parameter was removed. """ def __init__(self, table): super(DeleteStatement, self).__init__(target=table,...
class DeleteStatement(FilterableStatement):
"""A statement that drops a table. Args: table (mysqlx.Table): The Table object. .. versionchanged:: 8.0.12 The ``condition`` parameter was removed. """ def __init__(self, table): super(DeleteStatement, self).__init__(target=table, doc_based=False) def where(self, condi...
._sort(*clauses) def execute(self): """Execute the statement. Returns: mysqlx.Result: Result object. Raises: ProgrammingError: If condition was not set. """ if not self.has_where: raise ProgrammingError("No condition was found for remove...
77
77
257
7
70
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
DeleteStatement
DeleteStatement
1,133
1,178
1,133
1,133
964723c9783de9fdcaee62361a4a51d628906b8a
bigcode/the-stack
train
20310939ef9eb6baf3998e3d
train
class
class AddStatement(WriteStatement): """A statement for document addition on a collection. Args: collection (mysqlx.Collection): The Collection object. """ def __init__(self, collection): super(AddStatement, self).__init__(collection, True) self._upsert = False self.ids =...
class AddStatement(WriteStatement):
"""A statement for document addition on a collection. Args: collection (mysqlx.Collection): The Collection object. """ def __init__(self, collection): super(AddStatement, self).__init__(collection, True) self._upsert = False self.ids = [] def is_upsert(self): ...
_based): super(WriteStatement, self).__init__(target, doc_based) self._values = [] def get_values(self): """Returns the list of values. Returns: `list`: The list of values. """ return self._values def execute(self): """Execute the statement....
97
97
325
7
89
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
AddStatement
AddStatement
528
583
528
528
f5de711a78e1825a2b3bf9ec1f6cc4d2eaf886a0
bigcode/the-stack
train
9bfb775b7de6f9a8fd316dc5
train
class
class CreateCollectionIndexStatement(Statement): """A statement that creates an index on a collection. Args: collection (mysqlx.Collection): Collection. index_name (string): Index name. index_desc (dict): A dictionary containing the fields members that constra...
class CreateCollectionIndexStatement(Statement):
"""A statement that creates an index on a collection. Args: collection (mysqlx.Collection): Collection. index_name (string): Index name. index_desc (dict): A dictionary containing the fields members that constraints the index to be created. It must have ...
A statement that drops a table. Args: table (mysqlx.Table): The Table object. .. versionchanged:: 8.0.12 The ``condition`` parameter was removed. """ def __init__(self, table): super(DeleteStatement, self).__init__(target=table, doc_based=False) def where(self, condition): ...
256
256
1,166
8
248
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
CreateCollectionIndexStatement
CreateCollectionIndexStatement
1,181
1,316
1,181
1,181
4d60cd2c75940f944a465ed1c25a775dfeb85671
bigcode/the-stack
train
cee1bc90a3d4fda73922d711
train
class
class Expr(object): """Expression wrapper.""" def __init__(self, expr): self.expr = expr
class Expr(object):
"""Expression wrapper.""" def __init__(self, expr): self.expr = expr
, STRING_TYPES from .constants import LockContention from .dbdoc import DbDoc from .helpers import deprecated from .result import SqlResult, Result from .protobuf import mysqlxpb_enum ERR_INVALID_INDEX_NAME = 'The given index name "{}" is not valid' class Expr(object):
64
64
24
4
60
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
Expr
Expr
47
50
47
47
53755ea76dfa85cd63ce30903e3e4a37143e6cbd
bigcode/the-stack
train
9af876acdc3d0edb9417b4de
train
class
class UpdateSpec(object): """Update specification class implementation. Args: update_type (int): The update type. source (str): The source. value (Optional[str]): The value. """ def __init__(self, update_type, source, value=None): if update_type == mysqlxpb_enum( ...
class UpdateSpec(object):
"""Update specification class implementation. Args: update_type (int): The update type. source (str): The source. value (Optional[str]): The value. """ def __init__(self, update_type, source, value=None): if update_type == mysqlxpb_enum( "Mysqlx.Crud.Upda...
else: self._values.append(DbDoc(val)) return self def execute(self): """Execute the statement. Returns: mysqlx.Result: Result object. """ if len(self._values) == 0: return Result() return self._connection.send_ins...
69
69
232
5
64
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
UpdateSpec
UpdateSpec
586
617
586
586
b9047d0e224760c1dc1f96d42552e64777ceae3f
bigcode/the-stack
train
be3ab7e1bd3454d187b271ee
train
class
class SqlStatement(Statement): """A statement for SQL execution. Args: connection (mysqlx.connection.Connection): Connection object. sql (string): The sql statement to be executed. """ def __init__(self, connection, sql): super(SqlStatement, self).__init__(target=None, doc_based...
class SqlStatement(Statement):
"""A statement for SQL execution. Args: connection (mysqlx.connection.Connection): Connection object. sql (string): The sql statement to be executed. """ def __init__(self, connection, sql): super(SqlStatement, self).__init__(target=None, doc_based=False) self._connectio...
: self._bindings.append({"name": args[0], "value": args[1]}) return self def execute(self): """Execute the statement. Raises: NotImplementedError: This method must be implemented. """ raise NotImplementedError class SqlStatement(Statement):
64
64
127
6
57
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
SqlStatement
SqlStatement
482
501
482
482
b028c3b5be6a0dfa2371ac8ba805dfc8deb82a42
bigcode/the-stack
train
b8bbfb499e977a2b1156eba9
train
class
class FindStatement(ReadStatement): """A statement document selection on a Collection. Args: collection (mysqlx.Collection): The Collection object. condition (Optional[str]): An optional expression to identify the documents to be retrieved. If not specified ...
class FindStatement(ReadStatement):
"""A statement document selection on a Collection. Args: collection (mysqlx.Collection): The Collection object. condition (Optional[str]): An optional expression to identify the documents to be retrieved. If not specified all...
Returns: mysqlx.ReadStatement: ReadStatement object. """ self._set_having(condition) return self def execute(self): """Execute the statement. Returns: mysqlx.Result: Result object. """ return self._connection.find(self) class FindSta...
64
64
216
6
58
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
FindStatement
FindStatement
894
928
894
894
492f7ec8ee9de63238075da4a8ebd2611e04a2e6
bigcode/the-stack
train
ee820e70b9d556e4821d24c1
train
function
def quote_multipart_identifier(identifiers, sql_mode=""): """Quote the given multi-part identifier with backticks. Args: identifiers (iterable): List of identifiers to quote. sql_mode (Optional[string]): SQL mode. Returns: A string with the multi-part identifier quoted with backtic...
def quote_multipart_identifier(identifiers, sql_mode=""):
"""Quote the given multi-part identifier with backticks. Args: identifiers (iterable): List of identifiers to quote. sql_mode (Optional[string]): SQL mode. Returns: A string with the multi-part identifier quoted with backticks. """ return ".".join([quote_identifier(identifi...
(identifier, sql_mode): return identifier if "ANSI_QUOTES" in sql_mode: return '"{0}"'.format(identifier.replace('"', '""')) return "`{0}`".format(identifier.replace("`", "``")) def quote_multipart_identifier(identifiers, sql_mode=""):
63
64
87
13
50
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
quote_multipart_identifier
quote_multipart_identifier
97
108
97
97
f8bec28da9792590d4937bbf977dceb3ea4e3dbd
bigcode/the-stack
train
59af5d93c39515202d5db4cb
train
function
def is_quoted_identifier(identifier, sql_mode=""): """Check if the given identifier is quoted. Args: identifier (string): Identifier to check. sql_mode (Optional[string]): SQL mode. Returns: `True` if the identifier has backtick quotes, and False otherwise. """ if "ANSI_QUO...
def is_quoted_identifier(identifier, sql_mode=""):
"""Check if the given identifier is quoted. Args: identifier (string): Identifier to check. sql_mode (Optional[string]): SQL mode. Returns: `True` if the identifier has backtick quotes, and False otherwise. """ if "ANSI_QUOTES" in sql_mode: return ((identifier[0] ==...
__(self, expr): self.expr = expr def flexible_params(*values): """Parse flexible parameters.""" if len(values) == 1 and isinstance(values[0], (list, tuple,)): return values[0] return values def is_quoted_identifier(identifier, sql_mode=""):
64
64
127
11
52
meikomeik/mysql-connector-python
lib/mysqlx/statement.py
Python
is_quoted_identifier
is_quoted_identifier
60
73
60
60
3906d5d730d587de3e180ba68d8f47aa35a132cf
bigcode/the-stack
train
6c8fc07fc03cf724edc621f9
train
function
def close_db(e=None): db = g.pop("db", None) if db is not None: db.close()
def close_db(e=None):
db = g.pop("db", None) if db is not None: db.close()
from flask import g def close_db(e=None):
11
64
27
6
4
pekingPow/us-congress-pizza-flag-tracker
src/init_app_close_db.py
Python
close_db
close_db
3
7
3
3
1daab11e46258a2855ea22633fa2dd2c163b550e
bigcode/the-stack
train
fb8f87bbe5cde79ae7cc10ff
train
function
def init_app(app): app.teardown_appcontext(close_db)
def init_app(app):
app.teardown_appcontext(close_db)
from flask import g def close_db(e=None): db = g.pop("db", None) if db is not None: db.close() def init_app(app):
37
64
14
5
32
pekingPow/us-congress-pizza-flag-tracker
src/init_app_close_db.py
Python
init_app
init_app
9
10
9
9
23254b9de7e23b4f8d3f75e9fcf5147abe33032c
bigcode/the-stack
train
fc07df2820739e354d8610d8
train
class
class ValuehoverformatValidator(_plotly_utils.basevalidators.StringValidator): def __init__(self, plotly_name="valuehoverformat", parent_name="volume", **kwargs): super(ValuehoverformatValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=...
class ValuehoverformatValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="valuehoverformat", parent_name="volume", **kwargs): super(ValuehoverformatValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), **kwargs, )
import _plotly_utils.basevalidators class ValuehoverformatValidator(_plotly_utils.basevalidators.StringValidator):
22
64
83
14
7
mastermind88/plotly.py
packages/python/plotly/plotly/validators/volume/_valuehoverformat.py
Python
ValuehoverformatValidator
ValuehoverformatValidator
4
11
4
4
1b70a70bc54e80f08204fb26247522ac5deaf893
bigcode/the-stack
train
9645b3a909f58e92f8029a37
train
class
class DockerComponentUnhealthy(Exception): def __init__(self, component): self.component = component super().__init__("Unhealthy component: {} - " "Check the Docker container logs".format(component))
class DockerComponentUnhealthy(Exception):
def __init__(self, component): self.component = component super().__init__("Unhealthy component: {} - " "Check the Docker container logs".format(component))
for all the different components that the charm is managing. :param name: Name of the component :type name: str """ def __init__(self, name): self.name = name def __repr__(self): return self.name class DockerComponentUnhealthy(Exception):
64
64
45
7
56
elastisys/layer-charmscaler-base
reactive/component.py
Python
DockerComponentUnhealthy
DockerComponentUnhealthy
38
42
38
38
938219735b5e59089e62795815289695c568abfa
bigcode/the-stack
train
b55e47af790538ac0ff75372
train
class
class DockerComponentStarting(Exception): def __init__(self, component): self.component = component super().__init__("Component timed out while starting up: {} - " "Check the Docker container logs".format(component))
class DockerComponentStarting(Exception):
def __init__(self, component): self.component = component super().__init__("Component timed out while starting up: {} - " "Check the Docker container logs".format(component))
def __repr__(self): return self.name class DockerComponentUnhealthy(Exception): def __init__(self, component): self.component = component super().__init__("Unhealthy component: {} - " "Check the Docker container logs".format(component)) class DockerComponentS...
64
64
47
6
58
elastisys/layer-charmscaler-base
reactive/component.py
Python
DockerComponentStarting
DockerComponentStarting
45
49
45
45
44f5415638c5ec25ddcc957fd0509fdf24355cd7
bigcode/the-stack
train
5df2efb559c4f275664cd441
train
class
class HTTPComponent(Component): """ Components with a HTTP REST API. :param name: Name of the component :type name: str :param port: The port the component is supposed to listen on :type port: int :param paths: The REST API URL paths. The paths are dependent on which opera...
class HTTPComponent(Component):
""" Components with a HTTP REST API. :param name: Name of the component :type name: str :param port: The port the component is supposed to listen on :type port: int :param paths: The REST API URL paths. The paths are dependent on which operations the component is capable o...
", "common", "{}/.env".format(self.name)) if not compose_env.exists(): compose_env.extend(lambda: {"name": "charmscaler"}) compose_env.render() self.compose_config.render() # TODO This will show up even though a restart might not have occured. msg = "(Re)startin...
162
162
540
5
157
elastisys/layer-charmscaler-base
reactive/component.py
Python
HTTPComponent
HTTPComponent
149
218
149
149
bb37680caff5d32ff1b8c8bcbc26679b12d06403
bigcode/the-stack
train
b0e2040cbd437d8ddf434d2c
train
class
class ConfigComponent(HTTPComponent): """ A config component have the capabilities of generating and rendering a configuration file from a specific template file. :param name: Name of the component :type name: str :param port: The port the component is supposed to listen on :type port: int ...
class ConfigComponent(HTTPComponent):
""" A config component have the capabilities of generating and rendering a configuration file from a specific template file. :param name: Name of the component :type name: str :param port: The port the component is supposed to listen on :type port: int :param paths: The REST API URL pat...
._session.post(url, headers=headers, data=data) else: raise Exception("Unhandeled data type: {}".format(data_type)) else: raise Exception("Unhandeled REST API verb: {}".format(method)) hookenv.log("Request URL: {}".format(url), level=hookenv.DEBUG) hooken...
105
105
350
7
97
elastisys/layer-charmscaler-base
reactive/component.py
Python
ConfigComponent
ConfigComponent
221
265
221
221
caa463cbd0eb675c301369eeefed7efed5ebce2d
bigcode/the-stack
train
14f6f0f26202d7b9ad030e4e
train
class
class Component: """ Base class for all the different components that the charm is managing. :param name: Name of the component :type name: str """ def __init__(self, name): self.name = name def __repr__(self): return self.name
class Component:
""" Base class for all the different components that the charm is managing. :param name: Name of the component :type name: str """ def __init__(self, name): self.name = name def __repr__(self): return self.name
a container to become healthy at startup. HEALTH_STARTUP_RETRY_LIMIT = 60 # Maximum number of seconds for a container to become healthy at runtime. HEALTH_RUNTIME_RETRY_LIMIT = 10 # Number of retries for a failed HTTP request. HTTP_RETRY_LIMIT = 5 class Component:
64
64
65
3
60
elastisys/layer-charmscaler-base
reactive/component.py
Python
Component
Component
24
35
24
24
8b6ae7d7f533a4cc9721a8fd098862ee436ea0a5
bigcode/the-stack
train
962bb0330e975421e706a60b
train
class
class DockerComponent(Component): """ A Docker component is used for software which is executed as Docker images. With it you can generate a Docker Compose yaml-manifest and then start the Docker Compose services. :param name: Name of the component :type name: str :param tag: Docker image t...
class DockerComponent(Component):
""" A Docker component is used for software which is executed as Docker images. With it you can generate a Docker Compose yaml-manifest and then start the Docker Compose services. :param name: Name of the component :type name: str :param tag: Docker image tag :type tag: str :var com...
Maximum number of seconds for a container to become healthy at startup. HEALTH_STARTUP_RETRY_LIMIT = 60 # Maximum number of seconds for a container to become healthy at runtime. HEALTH_RUNTIME_RETRY_LIMIT = 10 # Number of retries for a failed HTTP request. HTTP_RETRY_LIMIT = 5 class Component: """ Base cla...
228
228
762
5
223
elastisys/layer-charmscaler-base
reactive/component.py
Python
DockerComponent
DockerComponent
52
146
52
52
541c4eded7f6deb3dd9450bc93898a3870f34ee7
bigcode/the-stack
train
8e6640be8282c4a9c8dc85f1
train
function
def test_data_by_sequence(): for txid in seqs: expected_ivc = known_juncs.get(txid[0], None) if expected_ivc is not None: for query_ivc in query_juncs[txid]: yield check_data_by_sequence, expected_ivc, query_ivc
def test_data_by_sequence():
for txid in seqs: expected_ivc = known_juncs.get(txid[0], None) if expected_ivc is not None: for query_ivc in query_juncs[txid]: yield check_data_by_sequence, expected_ivc, query_ivc
c.get_sequence(seqs) test_seq = test_ivc.get_sequence(seqs) assert_equal( expected_seq, test_seq, "Sequences don't match in test dataset for %s and %s." % (expected_seq.get_name(), test_seq.get_name()) ) def test_data_by_sequence():
64
64
69
6
58
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
test_data_by_sequence
test_data_by_sequence
44
49
44
44
0ef7c82986a91ddb3b0711c4d26a32e652c278a4
bigcode/the-stack
train
7b8300a95c1e476c6a8606b4
train
function
def check_find_repetitive_in_range(query_junc, minus_range, plus_range, expected): """Find repetitive blocks that overlap splice junctions Parameters ---------- query_junc : SegmentChain splice junction expected : bool Whether or not ``query_junc`` overlaps a repetitive f...
def check_find_repetitive_in_range(query_junc, minus_range, plus_range, expected):
"""Find repetitive blocks that overlap splice junctions Parameters ---------- query_junc : SegmentChain splice junction expected : bool Whether or not ``query_junc`` overlaps a repetitive feature """ assert_equal(covered_by_repetitive(query_junc, minus_range, plus...
, query_junc, minus_range, plus_range, False # make sure we found a bunch of each type assert_greater(pos, 0) assert_greater(neg, 0) def check_find_repetitive_in_range(query_junc, minus_range, plus_range, expected):
64
64
95
20
44
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
check_find_repetitive_in_range
check_find_repetitive_in_range
216
227
216
216
780fc620ec469afbade35cd1c7fadffb13d36fd5
bigcode/the-stack
train
6d365e7316ce97b31f1e96d3
train
function
@attr(test="unit") def test_find_canonicals_in_range(): for txid in seqs: juncs = noncan_juncs.get(txid, []) for my_junc in juncs: yield check_find_canonicals_in_range, my_junc
@attr(test="unit") def test_find_canonicals_in_range():
for txid in seqs: juncs = noncan_juncs.get(txid, []) for my_junc in juncs: yield check_find_canonicals_in_range, my_junc
Expected %s\n " +\ "Got %s\n match range: (%s,%s)") % (txid, str(query_junc), expected, ...
64
64
62
15
49
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
test_find_canonicals_in_range
test_find_canonicals_in_range
160
165
160
161
a9d54103d52f58b81c3a422c390d8268d50de4e5
bigcode/the-stack
train
fb585c4013a6a5bb21f2b2f0
train
function
def check_find_none_when_none_known_in_range(query_junc): minus_range, plus_range = find_match_range(query_junc, seqs, 20) found_known = find_known_in_range(query_junc, minus_range, plus_range, all_known_juncs) found_known = set([str(X) for X in found_known]) assert_set_equal(found_known, set([]))
def check_find_none_when_none_known_in_range(query_junc):
minus_range, plus_range = find_match_range(query_junc, seqs, 20) found_known = find_known_in_range(query_junc, minus_range, plus_range, all_known_juncs) found_known = set([str(X) for X in found_known]) assert_set_equal(found_known, set([]))
known in plus range plus strand for txid in seqs: juncs = query_juncs.get(txid, []) for my_junc in juncs: yield check_find_known_in_range, my_junc def check_find_none_when_none_known_in_range(query_junc):
64
64
82
13
50
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
check_find_none_when_none_known_in_range
check_find_none_when_none_known_in_range
123
127
123
123
57d2af6a74c53e647c68da107f3b689b67fb2e88
bigcode/the-stack
train
3d5c8ecf9704caad6b6642b9
train
function
def check_find_none_when_none_canonical_in_range(query_junc): minus_range, plus_range = find_match_range(query_junc, seqs, 20) found_known = find_canonicals_in_range( query_junc, minus_range, plus_range, seqs, canonicals[query_junc.strand] ) found_known = set([str(X) for X in found_known]) a...
def check_find_none_when_none_canonical_in_range(query_junc):
minus_range, plus_range = find_match_range(query_junc, seqs, 20) found_known = find_canonicals_in_range( query_junc, minus_range, plus_range, seqs, canonicals[query_junc.strand] ) found_known = set([str(X) for X in found_known]) assert_set_equal(found_known, set([]))
_in_range(): for txid in seqs: juncs = noncan_juncs.get(txid, []) for my_junc in juncs: yield check_find_canonicals_in_range, my_junc def check_find_none_when_none_canonical_in_range(query_junc):
64
64
95
14
49
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
check_find_none_when_none_canonical_in_range
check_find_none_when_none_canonical_in_range
168
174
168
168
0c4e0d5076cb447d14780da1649d81bc5ab3e483
bigcode/the-stack
train
e5929173fea7c3ad5a7fcfd2
train
function
def check_find_match_range(txid, max_slide): """Check output of :py:func:`find_match_range` against known data Parameters ---------- txid : str ID of transcript to check """ my_juncs = known_juncs.get(txid, []) for n, my_junc in enumerate(my_juncs): ref_minus, ref_plus =...
def check_find_match_range(txid, max_slide):
"""Check output of :py:func:`find_match_range` against known data Parameters ---------- txid : str ID of transcript to check """ my_juncs = known_juncs.get(txid, []) for n, my_junc in enumerate(my_juncs): ref_minus, ref_plus = match_ranges[txid][n] ref_minus = ma...
) if expected_ivc is not None: for query_ivc in query_juncs[txid]: yield check_data_by_sequence, expected_ivc, query_ivc #=============================================================================== # INDEX: testing match range #==================================================...
63
64
213
11
52
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
check_find_match_range
check_find_match_range
57
78
57
57
e21023efa657023b8be1f5258c4c79666a7e9c19
bigcode/the-stack
train
9e693045caef6a34203cf6b6
train
function
@attr(test="unit") def test_find_known_in_range(): # test case, has known in plus range plus strand for txid in seqs: juncs = query_juncs.get(txid, []) for my_junc in juncs: yield check_find_known_in_range, my_junc
@attr(test="unit") def test_find_known_in_range(): # test case, has known in plus range plus strand
for txid in seqs: juncs = query_juncs.get(txid, []) for my_junc in juncs: yield check_find_known_in_range, my_junc
%s\n match range: (%s,%s)") % (txid, str(query_junc), expected, found_known,...
64
64
70
26
38
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
test_find_known_in_range
test_find_known_in_range
114
120
114
116
e267d3dd0ad2017c3410524b6be6640365105482
bigcode/the-stack
train
4ce5088181689a04d9443ad4
train
function
@attr(test="unit") def test_find_none_when_none_canonical_in_range(): for junc in unmatched_noncan_query_juncs: yield check_find_none_when_none_canonical_in_range, junc
@attr(test="unit") def test_find_none_when_none_canonical_in_range():
for junc in unmatched_noncan_query_juncs: yield check_find_none_when_none_canonical_in_range, junc
unc, minus_range, plus_range, seqs, canonicals[query_junc.strand] ) found_known = set([str(X) for X in found_known]) assert_set_equal(found_known, set([])) @attr(test="unit") def test_find_none_when_none_canonical_in_range():
64
64
45
17
47
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
test_find_none_when_none_canonical_in_range
test_find_none_when_none_canonical_in_range
177
180
177
178
c353b44ba6725afc3241bd83f3be2ec7c464a4f8
bigcode/the-stack
train
dcb9720df14886d70ed8a7a6
train
function
def check_find_known_in_range(query_junc): txid = query_junc.chrom minus_range, plus_range = find_match_range(query_junc, seqs, 20) found_known = find_known_in_range(query_junc, minus_range, plus_range, all_known_juncs) expected = set([str(X) for X in known_juncs.get(txid, [])]) found_known = set([...
def check_find_known_in_range(query_junc):
txid = query_junc.chrom minus_range, plus_range = find_match_range(query_junc, seqs, 20) found_known = find_known_in_range(query_junc, minus_range, plus_range, all_known_juncs) expected = set([str(X) for X in known_juncs.get(txid, [])]) found_known = set([str(X) for X in found_known]) assert_se...
txid in seqs: for max_slide in (2, 4, 20): yield check_find_match_range, txid, max_slide #=============================================================================== # INDEX: find known junctions within match range only when present #===========================================================...
63
64
176
10
53
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
check_find_known_in_range
check_find_known_in_range
97
111
97
97
f6a8de4480a173aa0ed8f663693b2d10715b1dce
bigcode/the-stack
train
ea23ebc640a4b1c1d4eb420a
train
function
@attr(test="unit") def test_find_repetitive_in_range(): pos = 0 neg = 0 # some should be positive, others negative for txid in known_juncs: expected = txid in cross_hash_seqs if expected == True: pos += 1 else: neg += 1 my_query_juncs = query_juncs...
@attr(test="unit") def test_find_repetitive_in_range():
pos = 0 neg = 0 # some should be positive, others negative for txid in known_juncs: expected = txid in cross_hash_seqs if expected == True: pos += 1 else: neg += 1 my_query_juncs = query_juncs.get(txid, []) for query_junc in my_query_juncs:...
attr(test="unit") def test_find_none_when_none_canonical_in_range(): for junc in unmatched_noncan_query_juncs: yield check_find_none_when_none_canonical_in_range, junc #=============================================================================== # INDEX: find repetitive junctions within match range onl...
79
80
267
15
64
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
test_find_repetitive_in_range
test_find_repetitive_in_range
188
213
188
189
9224a1ba727e7e5d8f794dcf5b486f1cce1cc469
bigcode/the-stack
train
fd1ea9d3254c3419492792d9
train
function
@attr(test="unit") def test_find_match_range(): # test case, plus strand has match range plus # test case, plus strand has no match range plus # test case, minus strand has match range plus # test case, minus strand has no match range plus for txid in seqs: for max_slide in (2, 4, 20): ...
@attr(test="unit") def test_find_match_range(): # test case, plus strand has match range plus # test case, plus strand has no match range plus # test case, minus strand has match range plus # test case, minus strand has no match range plus
for txid in seqs: for max_slide in (2, 4, 20): yield check_find_match_range, txid, max_slide
) @attr(test="unit") def test_find_match_range(): # test case, plus strand has match range plus # test case, plus strand has no match range plus # test case, minus strand has match range plus # test case, minus strand has no match range plus
64
64
97
62
2
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
test_find_match_range
test_find_match_range
81
89
81
86
dea54cd69333267d63b9d17e8002302f0ae47c68
bigcode/the-stack
train
2f30e47e691e7aaec922bdf1
train
function
def check_data_by_sequence(expected_ivc, test_ivc): """Verify that two junctions produce identical sequence Parameters ---------- expected_ivc : SegmentChain SegmentChain corresponding to known splice junction test_ivc : SegmentChain SegmentChain corresponding to test splic...
def check_data_by_sequence(expected_ivc, test_ivc):
"""Verify that two junctions produce identical sequence Parameters ---------- expected_ivc : SegmentChain SegmentChain corresponding to known splice junction test_ivc : SegmentChain SegmentChain corresponding to test splice junction that is sequence-consistant with ...
, ) from plastid.genomics.roitools import SegmentChain, GenomicSegment from plastid.genomics.genome_hash import GenomeHash #=============================================================================== # INDEX: verify test data above in case it got bungled #===========================================================...
63
64
142
13
50
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
check_data_by_sequence
check_data_by_sequence
24
41
24
24
88a39c5f527e8f828b1f1747e3cf549e15d71ab7
bigcode/the-stack
train
b0f78f6061335c3b0e5f75ee
train
function
@attr(test="unit") def test_find_none_when_none_known_in_range(): for _, v in unmatched_query_juncs.items(): for junc in v: yield check_find_none_when_none_known_in_range, junc
@attr(test="unit") def test_find_none_when_none_known_in_range():
for _, v in unmatched_query_juncs.items(): for junc in v: yield check_find_none_when_none_known_in_range, junc
found_known = find_known_in_range(query_junc, minus_range, plus_range, all_known_juncs) found_known = set([str(X) for X in found_known]) assert_set_equal(found_known, set([])) @attr(test="unit") def test_find_none_when_none_known_in_range():
64
64
49
16
48
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
test_find_none_when_none_known_in_range
test_find_none_when_none_known_in_range
130
134
130
131
415551a35554c11d7817e4e705888769247500c3
bigcode/the-stack
train
beb6489a12899095235c00e9
train
function
def check_find_canonicals_in_range(query_junc): txid = query_junc.chrom minus_range, plus_range = find_match_range(query_junc, seqs, 20) found_can = find_canonicals_in_range( query_junc, minus_range, plus_range, seqs, canonicals[query_junc.strand] ) found_can = set([str(X) for X in found_can...
def check_find_canonicals_in_range(query_junc):
txid = query_junc.chrom minus_range, plus_range = find_match_range(query_junc, seqs, 20) found_can = find_canonicals_in_range( query_junc, minus_range, plus_range, seqs, canonicals[query_junc.strand] ) found_can = set([str(X) for X in found_can]) expected = set([str(X) for X in known_jun...
_, v in unmatched_query_juncs.items(): for junc in v: yield check_find_none_when_none_known_in_range, junc #=============================================================================== # INDEX: find canonical junctions within match range only when present #=====================================...
63
64
190
12
51
joshuagryphon/plastid
plastid/test/unit/bin/test_slidejuncs.py
Python
check_find_canonicals_in_range
check_find_canonicals_in_range
142
157
142
142
bf0986373b0f6e9f823b9df2c8e243c334d964e0
bigcode/the-stack
train
8a5e3e801edce31a1262861c
train
class
class Migration(migrations.Migration): dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.AlterField( model_name='recipe', name='description', field=models.TextField(verbose_name='Description'), ), migrations.AlterField...
class Migration(migrations.Migration):
dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.AlterField( model_name='recipe', name='description', field=models.TextField(verbose_name='Description'), ), migrations.AlterField( model_name='recipe', ...
# Generated by Django 4.0.1 on 2022-01-30 12:55 from django.db import migrations, models class Migration(migrations.Migration):
38
64
183
7
30
M0673N/Python-Web-Basics
Mock-exams/04-Mock-exam/recipes/recipes/app/migrations/0002_alter_recipe_description_alter_recipe_image_url_and_more.py
Python
Migration
Migration
6
38
6
7
d81630bcca8d1718cd0053f07b5c5133b75ca8e2
bigcode/the-stack
train
d6b279270907309f8dde3206
train
class
class Bullet(): x = 0 y = 0 speed = 0 damage = 0 x_v = 0 y_v = 0 def __init__(self,x,y,t_x,t_y,speed,damage): self.x = x self.y = y self.speed = speed self.damage = damage a_x = t_x a_y = y if(t_x==x): ...
class Bullet():
x = 0 y = 0 speed = 0 damage = 0 x_v = 0 y_v = 0 def __init__(self,x,y,t_x,t_y,speed,damage): self.x = x self.y = y self.speed = speed self.damage = damage a_x = t_x a_y = y if(t_x==x): if(y > t_y): ...
from Player import * import Crash import math class Bullet():
13
101
337
3
9
kjmin622/ERICA_Game_DevilInvade
src/Bullet.py
Python
Bullet
Bullet
5
58
5
5
646662649123734dd3a5dfc483117efa82f320a2
bigcode/the-stack
train
94b6b2ce9fe6e14231a69d58
train
class
class ItemsPanel (ExportPanel): def __init__(self, *args, **kwargs): super(ItemsPanel, self).__init__(pageName = _("Items"), *args, **kwargs) self.buffer_label = wx.StaticText(self, label = _("Buffer")) self._first = self.buffer = wx.ComboBox(self, style = wx.CB_READONLY | wx.CB_SORT) self.buffer.SetSizer...
class ItemsPanel (ExportPanel):
def __init__(self, *args, **kwargs): super(ItemsPanel, self).__init__(pageName = _("Items"), *args, **kwargs) self.buffer_label = wx.StaticText(self, label = _("Buffer")) self._first = self.buffer = wx.ComboBox(self, style = wx.CB_READONLY | wx.CB_SORT) self.buffer.SetSizerProps(expand = True) self.buff...
import wx from core.sessions.buffers.gui.export import ExportPanel import sessions from core.sessions.buffers.exporter.exporters import RANGE_ALL, RANGE_ALL_REVERSED, RANGE_CUSTOM import signals from pydispatch import dispatcher class ItemsPanel (ExportPanel):
57
256
2,005
7
49
Oire/TheQube
src/core/sessions/buffers/gui/export/panels/items_panel.py
Python
ItemsPanel
ItemsPanel
8
204
8
8
4acb1c3df351bb3558c643f3658f258fa95cc227
bigcode/the-stack
train
99ebc2a9f3e8005e475e47c6
train
function
@require_previewer @login_and_domain_required def upload_message_bank(request, domain): if request.method == "POST": form = MessageBankForm(request.POST, request.FILES) if form.is_valid(): current_bank = get_message_bank(domain) message_id_map = {} for message in ...
@require_previewer @login_and_domain_required def upload_message_bank(request, domain):
if request.method == "POST": form = MessageBankForm(request.POST, request.FILES) if form.is_valid(): current_bank = get_message_bank(domain) message_id_map = {} for message in current_bank: message_id_map[message.fri_id.upper()] = message ...
MessageBankMessage from corehq.apps.reports.dispatcher import CustomProjectReportDispatcher from corehq.apps.domain.decorators import require_previewer, login_and_domain_required from django.http import HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from django.contrib import messages from d...
92
92
308
18
73
dslowikowski/commcare-hq
custom/fri/views.py
Python
upload_message_bank
upload_message_bank
12
45
12
14
3ea2d48b47e951d72e0ce804080ffb5daf6fc3fa
bigcode/the-stack
train
5c8dd5263a0ddbf9f9f47886
train
class
class Input: HASH = "hash"
class Input:
HASH = "hash"
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Input:
20
64
9
3
16
xhennessy-r7/insightconnect-plugins
anomali_threatstream/komand_anomali_threatstream/actions/lookup_hash/schema.py
Python
Input
Input
6
7
6
6
1eab8ef4ea5836a8d5bdcf450fcf052dd05522f2
bigcode/the-stack
train
19e9763ccd7c0887536cd0dd
train
class
class Output: RESULTS = "results"
class Output:
RESULTS = "results"
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Input: HASH = "hash" class Output:
29
64
9
3
26
xhennessy-r7/insightconnect-plugins
anomali_threatstream/komand_anomali_threatstream/actions/lookup_hash/schema.py
Python
Output
Output
10
11
10
10
b623a0edb4daf201b91330d4f73359785a622bc1
bigcode/the-stack
train
057cd836a87d119e978e958e
train
class
class LookupHashInput(komand.Input): schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "hash": { "type": "string", "title": "Hash", "description": "Hash", "order": 1 } } } """) def __init__(self): super(self.__class__, self)...
class LookupHashInput(komand.Input):
schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "hash": { "type": "string", "title": "Hash", "description": "Hash", "order": 1 } } } """) def __init__(self): super(self.__class__, self).__init__(self.schema)
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Input: HASH = "hash" class Output: RESULTS = "results" class LookupHashInput(komand.Input):
45
64
97
9
36
xhennessy-r7/insightconnect-plugins
anomali_threatstream/komand_anomali_threatstream/actions/lookup_hash/schema.py
Python
LookupHashInput
LookupHashInput
14
31
14
14
f18192a74e760b04e9fa5dfbe672181412e3c7ae
bigcode/the-stack
train
7e53c6aecd8144aff397c217
train
class
class LookupHashOutput(komand.Output): schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "results": { "type": "array", "title": "Results", "description": "Results returned", "items": { "$ref": "#/definitions/result" }, "order":...
class LookupHashOutput(komand.Output):
schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "results": { "type": "array", "title": "Results", "description": "Results returned", "items": { "$ref": "#/definitions/result" }, "order": 1 } }, "definitions": { "r...
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Input: HASH = "hash" class Output: RESULTS = "results" class LookupHashInput(komand.Input): schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "hash": { "type": "string", ...
143
256
987
9
134
xhennessy-r7/insightconnect-plugins
anomali_threatstream/komand_anomali_threatstream/actions/lookup_hash/schema.py
Python
LookupHashOutput
LookupHashOutput
34
200
34
34
5cc2c57523594c5af5d04ecc2d47edc61db300e6
bigcode/the-stack
train
86dfb166af24e9527cd1a260
train
function
def delete_object(obj): raise Exception("Delete object not implemented in the current scheduler")
def delete_object(obj):
raise Exception("Delete object not implemented in the current scheduler")
__(self, f): raise Exception( "Exaqute task call code not implemented in the current scheduler") def get_value_from_remote(obj): raise Exception("Get value not implemented in the current scheduler") def barrier(): raise Exception("Barrier not implemented in the current scheduler") def de...
64
64
18
5
59
ramonamela/compss
compss/programming_model/bindings/python/src/exaqute/ExaquteTask.py
Python
delete_object
delete_object
39
40
39
39
ee88bbba93b5fd8e202b6318fd55e0b1d368de75
bigcode/the-stack
train
f767bd8352c5f997cb8df8e1
train
function
def from_args_to_vector(obj): print("FROM ARGS TO VECTOR") index = [i for i, x in enumerate(obj) if x == "#"] print(index) print(list(enumerate(obj))) if len(index) == 0: return obj new_vector = [] new_vector.append(list(obj[0:index[0]])) for i in range(len(index) - 1): n...
def from_args_to_vector(obj):
print("FROM ARGS TO VECTOR") index = [i for i, x in enumerate(obj) if x == "#"] print(index) print(list(enumerate(obj))) if len(index) == 0: return obj new_vector = [] new_vector.append(list(obj[0:index[0]])) for i in range(len(index) - 1): new_vector.append(list(obj[(ind...
value not implemented in the current scheduler") def barrier(): raise Exception("Barrier not implemented in the current scheduler") def delete_object(obj): raise Exception("Delete object not implemented in the current scheduler") def compute(obj): raise Exception("Compute not implemented in the curre...
64
64
144
7
57
ramonamela/compss
compss/programming_model/bindings/python/src/exaqute/ExaquteTask.py
Python
from_args_to_vector
from_args_to_vector
46
60
46
46
7a4a25f304984827005ea1775f31bdb3cec563f8
bigcode/the-stack
train
0caa0eba3908fc59549e3bfb
train
function
def from_vector_to_args(obj): new_vector = [] new_vector.extend(obj[0]) for i in range(1, len(obj)): new_vector.append("#") new_vector.extend(obj[1]) return new_vector
def from_vector_to_args(obj):
new_vector = [] new_vector.extend(obj[0]) for i in range(1, len(obj)): new_vector.append("#") new_vector.extend(obj[1]) return new_vector
1): new_vector.append(list(obj[(index[i] + 1):index[i + 1]])) new_vector.append(list(obj[(index[-1] + 1):len(obj)])) print("Return:") print(new_vector) return new_vector def from_vector_to_args(obj):
64
64
50
7
56
ramonamela/compss
compss/programming_model/bindings/python/src/exaqute/ExaquteTask.py
Python
from_vector_to_args
from_vector_to_args
63
69
63
63
b4e9f492c9c3ca2bed9fcfe4aa965d46262f0b23
bigcode/the-stack
train
9695425667f52ae7ad0f277b
train
function
def compute(obj): raise Exception("Compute not implemented in the current scheduler")
def compute(obj):
raise Exception("Compute not implemented in the current scheduler")
not implemented in the current scheduler") def get_value_from_remote(obj): raise Exception("Get value not implemented in the current scheduler") def barrier(): raise Exception("Barrier not implemented in the current scheduler") def delete_object(obj): raise Exception("Delete object not implemented in...
64
64
16
4
60
ramonamela/compss
compss/programming_model/bindings/python/src/exaqute/ExaquteTask.py
Python
compute
compute
43
44
43
43
322325969b12200dfe361ca8cac09f6e1ca25cf1
bigcode/the-stack
train
8a93c7779b7600790bc64974
train
function
def get_value_from_remote(obj): raise Exception("Get value not implemented in the current scheduler")
def get_value_from_remote(obj):
raise Exception("Get value not implemented in the current scheduler")
__init__(self, *args, **kwargs): raise Exception( "Exaqute task decorator not implemented in the current scheduler") def __call__(self, f): raise Exception( "Exaqute task call code not implemented in the current scheduler") def get_value_from_remote(obj):
64
64
20
7
57
ramonamela/compss
compss/programming_model/bindings/python/src/exaqute/ExaquteTask.py
Python
get_value_from_remote
get_value_from_remote
31
32
31
31
0e571cb822389d5061f3aabb230dcfe34a6dfff2
bigcode/the-stack
train
4974024a1941680721e304ee
train
class
class ExaquteTask(object): def __init__(self, *args, **kwargs): raise Exception( "Exaqute task decorator not implemented in the current scheduler") def __call__(self, f): raise Exception( "Exaqute task call code not implemented in the current scheduler")
class ExaquteTask(object):
def __init__(self, *args, **kwargs): raise Exception( "Exaqute task decorator not implemented in the current scheduler") def __call__(self, f): raise Exception( "Exaqute task call code not implemented in the current scheduler")
License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from exaqute.ExaquteParameter import * class ExaquteTask(object):
64
64
66
7
57
ramonamela/compss
compss/programming_model/bindings/python/src/exaqute/ExaquteTask.py
Python
ExaquteTask
ExaquteTask
20
28
20
21
8faf635b17c162354e7eb862049112d085d4b02a
bigcode/the-stack
train
92073f515a2ecc60ccebb933
train
function
def barrier(): raise Exception("Barrier not implemented in the current scheduler")
def barrier():
raise Exception("Barrier not implemented in the current scheduler")
"Exaqute task decorator not implemented in the current scheduler") def __call__(self, f): raise Exception( "Exaqute task call code not implemented in the current scheduler") def get_value_from_remote(obj): raise Exception("Get value not implemented in the current scheduler") def barrier(...
64
64
15
3
61
ramonamela/compss
compss/programming_model/bindings/python/src/exaqute/ExaquteTask.py
Python
barrier
barrier
35
36
35
35
b70ad379c20daac6333bfdbf3c8046613331e07d
bigcode/the-stack
train
94e1c53f5c3883a159ad0a17
train
class
class AgeGenderAdapter(Adapter): __provider__ = 'age_gender' prediction_types = (ClassificationPrediction, RegressionPrediction, ) @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'age_out': StringField(description="Output layer name fo...
class AgeGenderAdapter(Adapter):
__provider__ = 'age_gender' prediction_types = (ClassificationPrediction, RegressionPrediction, ) @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'age_out': StringField(description="Output layer name for age recognition."), ...
_out') self.type_out = self.get_value_from_config('type_out') def process(self, raw, identifiers=None, frame_meta=None): res = [] raw_output = self._extract_predictions(raw, frame_meta) for identifier, colors, types in zip(identifiers, raw_output[self.color_out], raw_output[self.typ...
117
117
390
6
110
AnthonyQuantum/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/attributes_recognition.py
Python
AgeGenderAdapter
AgeGenderAdapter
121
169
121
121
e67e73f7d3f4b55b35f8e13c9b1eb988201280a2
bigcode/the-stack
train
4947f548c9c45f7c44b81999
train
class
class GazeEstimationAdapter(Adapter): __provider__ = 'gaze_estimation' prediction_types = (GazeVectorPrediction, ) def process(self, raw, identifiers=None, frame_meta=None): result = [] raw_output = self._extract_predictions(raw, frame_meta) for identifier, output in zip(identifiers...
class GazeEstimationAdapter(Adapter):
__provider__ = 'gaze_estimation' prediction_types = (GazeVectorPrediction, ) def process(self, raw, identifiers=None, frame_meta=None): result = [] raw_output = self._extract_predictions(raw, frame_meta) for identifier, output in zip(identifiers, raw_output[self.output_blob]): ...
_recognition_out]): multi_label[multi_label > 0.5] = 1. multi_label[multi_label <= 0.5] = 0. result.append(MultiLabelRecognitionPrediction(identifier, multi_label.reshape(-1))) return result class GazeEstimationAdapter(Adapter):
64
64
93
8
55
AnthonyQuantum/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/attributes_recognition.py
Python
GazeEstimationAdapter
GazeEstimationAdapter
219
229
219
219
a65df25f0daba12f8fbd656b3435d158ff3b34d2
bigcode/the-stack
train
1b3e17621936059b60d0d20a
train
class
class PersonAttributesAdapter(Adapter): __provider__ = 'person_attributes' prediction_types = (MultiLabelRecognitionPrediction, ) @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'attributes_recognition_out': StringField( ...
class PersonAttributesAdapter(Adapter):
__provider__ = 'person_attributes' prediction_types = (MultiLabelRecognitionPrediction, ) @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'attributes_recognition_out': StringField( description="Output layer name for att...
extract_predictions(raw, frame_meta) for identifier, values in zip(identifiers, raw_output[self.output_blob]): x_values, y_values = values[::2], values[1::2] res.append(FacialLandmarksPrediction(identifier, x_values.reshape(-1), y_values.reshape(-1))) return res class PersonAttr...
74
74
247
6
67
AnthonyQuantum/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/attributes_recognition.py
Python
PersonAttributesAdapter
PersonAttributesAdapter
186
216
186
186
5f8817af8a37f7e0885bac59c861534dfacdc238
bigcode/the-stack
train
ba8fe3198eb91f15c899ef5a
train
class
class LandmarksRegressionAdapter(Adapter): __provider__ = 'landmarks_regression' prediction_types = (FacialLandmarksPrediction, ) def process(self, raw, identifiers=None, frame_meta=None): res = [] raw_output = self._extract_predictions(raw, frame_meta) for identifier, values in zip...
class LandmarksRegressionAdapter(Adapter):
__provider__ = 'landmarks_regression' prediction_types = (FacialLandmarksPrediction, ) def process(self, raw, identifiers=None, frame_meta=None): res = [] raw_output = self._extract_predictions(raw, frame_meta) for identifier, values in zip(identifiers, raw_output[self.output_blob])...
Prediction(identifier, self.get_age_scores(age)) age_error_rep = RegressionPrediction(identifier, age) result.append(ContainerPrediction({ 'gender': gender_rep, 'age_classification': age_class_rep, 'age_error': age_error_rep })) return result class LandmarksR...
64
64
122
7
56
AnthonyQuantum/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/attributes_recognition.py
Python
LandmarksRegressionAdapter
LandmarksRegressionAdapter
172
183
172
172
58bc2f78edeef2cb1512a43cf6cd5a0a3bff7267
bigcode/the-stack
train
d567b56d288b49584c1142cf
train
class
class VehicleAttributesRecognitionAdapter(Adapter): __provider__ = 'vehicle_attributes' prediction_types = (ClassificationPrediction,) @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'color_out': StringField(description="Vehicle color ...
class VehicleAttributesRecognitionAdapter(Adapter):
__provider__ = 'vehicle_attributes' prediction_types = (ClassificationPrediction,) @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'color_out': StringField(description="Vehicle color attribute output layer name."), 'type_ou...
raw_output[self.angle_roll] ): prediction = ContainerPrediction({ 'angle_yaw': RegressionPrediction(identifier, yaw[0]), 'angle_pitch': RegressionPrediction(identifier, pitch[0]), 'angle_roll': RegressionPrediction(identifier, roll[0]) }) ...
73
73
244
7
65
AnthonyQuantum/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/attributes_recognition.py
Python
VehicleAttributesRecognitionAdapter
VehicleAttributesRecognitionAdapter
86
118
86
86
2be606c5cbc0050c74b188b511990454b677d370
bigcode/the-stack
train
727b0e0f8a038d3bf1676b5d
train
class
class HeadPoseEstimatorAdapter(Adapter): """ Class for converting output of HeadPoseEstimator to HeadPosePrediction representation """ __provider__ = 'head_pose' prediction_types = (RegressionPrediction, ) @classmethod def parameters(cls): parameters = super().parameters() p...
class HeadPoseEstimatorAdapter(Adapter):
""" Class for converting output of HeadPoseEstimator to HeadPosePrediction representation """ __provider__ = 'head_pose' prediction_types = (RegressionPrediction, ) @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'angle_yaw...
, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import numpy as np from ..adapters import Adapter from ..config i...
112
112
374
7
105
AnthonyQuantum/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/attributes_recognition.py
Python
HeadPoseEstimatorAdapter
HeadPoseEstimatorAdapter
31
83
31
31
ff6fde19aa0cfebb4b14618e39c139531b6da662
bigcode/the-stack
train
ff22e68a9aad8a0cc4ff0353
train
class
class Twitch(TwitchAPI, commands.Cog): """ Get twitch user information and post when a user gets new followers """ __author__ = ["TrustyJAID"] __version__ = "1.3.1" def __init__(self, bot): self.bot = bot self.config = Config.get_conf(self, 1543454673) global_defaults =...
class Twitch(TwitchAPI, commands.Cog):
""" Get twitch user information and post when a user gets new followers """ __author__ = ["TrustyJAID"] __version__ = "1.3.1" def __init__(self, bot): self.bot = bot self.config = Config.get_conf(self, 1543454673) global_defaults = { "access_token": {}, ...
import asyncio import logging from datetime import datetime from typing import Literal, Optional import aiohttp import discord from redbot.core import Config, checks, commands from redbot.core.commands import Context from redbot.core.utils.menus import DEFAULT_CONTROLS, menu from .errors import TwitchError from .twit...
133
256
3,640
10
123
LyssyT/Trusty-cogs
twitch/twitch.py
Python
Twitch
Twitch
22
483
22
22
40bd79c45fd9211e603dd66ab2fcc392233b5730
bigcode/the-stack
train
2c41c469f4fa1c92702f3878
train
function
def detection(vid): with tf.Session(graph=graph) as sess: return_value, frame = vid.read() if return_value: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(frame) else: raise ValueError("No image!") frame_size = frame.shap...
def detection(vid):
with tf.Session(graph=graph) as sess: return_value, frame = vid.read() if return_value: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(frame) else: raise ValueError("No image!") frame_size = frame.shape[:2] image_...
othbrush"] return_elements = ["input/input_data:0", "pred_sbbox/concat_2:0", "pred_mbbox/concat_2:0", "pred_lbbox/concat_2:0"] pb_file = "./yolov3_coco.pb" # video_path = "./docs/images/road.mp4" video_path = 0 num_classes = 80 input_size = 416 graph = tf.Graph() return_tensors = ...
132
132
443
5
127
Daredevil5053728/traffic
webcam_detection.py
Python
detection
detection
20
71
20
20
517de397c6e791eafe09fdb268f631e4c9e89675
bigcode/the-stack
train
1ad79ee80e6073684e7010a0
train
class
class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True, null = False) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = tinymce_models.HTMLField(blank=True) # comment_count = models.IntegerField(default = 0...
class Post(models.Model):
title = models.CharField(max_length=100) slug = models.SlugField(unique=True, null = False) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = tinymce_models.HTMLField(blank=True) # comment_count = models.IntegerField(default = 0) # view_count = model...
return self.user.username class Category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Tags(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Comment(models.Model): user = model...
137
137
459
5
131
praveensinghml/pkarticle
posts/models.py
Python
Post
Post
53
118
53
53
e7974eb417310bcd0c93bbf245d837bd96eab20a
bigcode/the-stack
train
a042339b6cea1a64c01b790d
train
class
class Category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title
class Category(models.Model):
title = models.CharField(max_length=20) def __str__(self): return self.title
name = models.CharField(max_length=100) aboutme = models.CharField(max_length=300) desination = models.CharField(max_length=100) profile_picture = models.ImageField(blank=True,null=True) def __str__(self): return self.user.username class Category(models.Model):
64
64
28
5
58
praveensinghml/pkarticle
posts/models.py
Python
Category
Category
30
34
30
30
cc6dd24224765f4c46586eb7ce020d8a5e8ebe76
bigcode/the-stack
train
21a46c3fc110244772d4881a
train
class
class PostView(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) def __str__(self): return self.user.username
class PostView(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) def __str__(self): return self.user.username
from tinymce.models import HTMLField from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse from django.template.defaultfilters import slugify from tinymce import models as tinymce_models User = get_user_model() class PostView(models.Model):
60
64
46
6
54
praveensinghml/pkarticle
posts/models.py
Python
PostView
PostView
11
16
11
11
6cc2b26dec3c796623467a01f265235842f6f6c3
bigcode/the-stack
train
3fdd8510a96ee995b77edcb5
train
class
class Tags(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title
class Tags(models.Model):
title = models.CharField(max_length=20) def __str__(self): return self.title
Field(max_length=100) profile_picture = models.ImageField(blank=True,null=True) def __str__(self): return self.user.username class Category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Tags(models.Model):
64
64
28
5
58
praveensinghml/pkarticle
posts/models.py
Python
Tags
Tags
36
40
36
36
6a16cd5a6b2948b99a50587af60dffb9d1dab5d2
bigcode/the-stack
train
a21c28b834ded1b78211fd15
train
class
class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField() post = models.ForeignKey( 'Post', related_name='comments', on_delete=models.CASCADE) def __str__(self): return self....
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField() post = models.ForeignKey( 'Post', related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.user.username
.user.username class Category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Tags(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Comment(models.Model):
64
64
71
5
58
praveensinghml/pkarticle
posts/models.py
Python
Comment
Comment
42
50
42
42
231387b8bf26068f74940132c85527a3092efccc
bigcode/the-stack
train
0f4cd4dad4a983b888fc61d5
train
class
class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) authorname = models.CharField(max_length=100) aboutme = models.CharField(max_length=300) desination = models.CharField(max_length=100) profile_picture = models.ImageField(blank=True,null=True) def __str__(s...
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE) authorname = models.CharField(max_length=100) aboutme = models.CharField(max_length=300) desination = models.CharField(max_length=100) profile_picture = models.ImageField(blank=True,null=True) def __str__(self): return self.us...
import models as tinymce_models User = get_user_model() class PostView(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) def __str__(self): return self.user.username class Author(models.Model):
64
64
81
5
58
praveensinghml/pkarticle
posts/models.py
Python
Author
Author
18
27
18
18
da74f89a6d27d429d7b94f2cc5996262d9cb8968
bigcode/the-stack
train
16d6d0a69bb14deea4b5615b
train
function
def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories): out = {} stack = [(convert_path(where), '', package)] while stack: where, prefix, package = stack.pop(0) for name in os.listdir(where): fn = os.path.join(wher...
def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories):
out = {} stack = [(convert_path(where), '', package)] while stack: where, prefix, package = stack.pop(0) for name in os.listdir(where): fn = os.path.join(where, name) if os.path.isdir(fn): bad_name = False for pattern in exclude_directo...
('*.pyc', '*~', '.*', '*.bak', '*.swp*') standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info') def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories):
78
78
262
25
53
mill0791/docassemble-mill0791
setup.py
Python
find_package_data
find_package_data
9
43
9
9
cddfe10269388297eff0333cc45cea57c7ba5f85
bigcode/the-stack
train
1c7735e7407699c72a6ab91f
train
function
def define_G(input_nc, output_nc, ngf, netG, norm='batch', dilation_order=0, use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]): """Create a generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in o...
def define_G(input_nc, output_nc, ngf, netG, norm='batch', dilation_order=0, use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]):
"""Create a generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images ngf (int) -- the number of filters in the last conv layer netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks ...
a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights Parameters: net (network) -- the network to be initialized init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal gain (float) -- scaling ...
228
228
761
45
182
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
define_G
define_G
120
169
120
121
485125b39769bd2cf12aea3c272e42b3c95b7d03
bigcode/the-stack
train
b88713bdd2c8b1a9176f6a7d
train
function
def define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[]): """Create a discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the first conv layer netD (str...
def define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[]):
"""Create a discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the first conv layer netD (str) -- the architecture's name: basic | n_layers | pixel n_layers_D (int) -- the number of conv...
=norm_layer, use_dropout=use_dropout) elif netG == 'unet_128': net = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout) elif netG == 'unet_256': net = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout) else: ...
168
168
560
38
130
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
define_D
define_D
172
213
172
172
8e80bc784f0db36d79521b894fc35671eacde6ee
bigcode/the-stack
train
8bb7b057abb221bc309d932c
train
function
def get_scheduler(optimizer, opt): """Return a learning rate scheduler Parameters: optimizer -- the optimizer of the network opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions.  opt.lr_policy is the name of learnin...
def get_scheduler(optimizer, opt):
"""Return a learning rate scheduler Parameters: optimizer -- the optimizer of the network opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions.  opt.lr_policy is the name of learning rate policy: linear | step | plat...
if norm_type == 'batch': norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True) elif norm_type == 'instance': norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False) elif norm_type == 'none': def norm_layer(x): return ...
109
109
364
8
100
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
get_scheduler
get_scheduler
39
65
39
39
af7984303851b9271988fc4601fa54273dbde283
bigcode/the-stack
train
502d0278e5b7d1a1639b1c78
train
class
class UnetGenerator(nn.Module): """Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels in input images ...
class UnetGenerator(nn.Module):
"""Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number...
if padding_type == 'reflect': conv_block += [nn.ReflectionPad2d(1)] elif padding_type == 'replicate': conv_block += [nn.ReplicationPad2d(1)] elif padding_type == 'zero': p = 1 else: raise NotImplementedError('padding [%s] is not implemented...
162
162
540
7
154
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
UnetGenerator
UnetGenerator
456
485
456
456
581d8d671bd7eaff2f6d0495f421f0a5c746e645
bigcode/the-stack
train
6809916e2ab4c13a3f713bb7
train
function
def init_weights(net, init_type='normal', init_gain=0.02): """Initialize network weights. Parameters: net (network) -- network to be initialized init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal init_gain (float) -- scaling factor for n...
def init_weights(net, init_type='normal', init_gain=0.02):
"""Initialize network weights. Parameters: net (network) -- network to be initialized init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal init_gain (float) -- scaling factor for normal, xavier and orthogonal. We use 'normal' in the o...
elif opt.lr_policy == 'plateau': scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5) elif opt.lr_policy == 'cosine': scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.n_epochs, eta_min=0) else: return NotImplementedErro...
123
123
413
17
105
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
init_weights
init_weights
68
99
68
68
e1046b79ad4c28f4571a31e95d5ee8acc5062927
bigcode/the-stack
train
d99959dbf079d10852dfa90e
train
class
class UnetSkipConnectionBlock(nn.Module): """Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, oute...
class UnetSkipConnectionBlock(nn.Module):
"""Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, innermost=False, norm_layer=n...
of filters from ngf * 8 to ngf unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlo...
204
204
681
9
195
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
UnetSkipConnectionBlock
UnetSkipConnectionBlock
488
555
488
488
01e84954fb02c8df222e5350ca6fd70d03e502ec
bigcode/the-stack
train
747d8a11bd2a39a620f60334
train
class
class PixelDiscriminator(nn.Module): """Defines a 1x1 PatchGAN discriminator (pixelGAN)""" def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d): """Construct a 1x1 PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input images nd...
class PixelDiscriminator(nn.Module):
"""Defines a 1x1 PatchGAN discriminator (pixelGAN)""" def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d): """Construct a 1x1 PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filter...
norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True) ] sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map self.model = nn.Sequential(*sequence) def forward(self, input): """Standard forward.""" ...
98
98
329
7
91
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
PixelDiscriminator
PixelDiscriminator
606
635
606
606
fb042baf85c889f64c01a9cca49cf47aa7cc7a2d
bigcode/the-stack
train
1bb6245fc8193482b6461881
train
function
def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]): """Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights Parameters: net (network) -- the network to be initialized init_type (str) -- the name of an initialization m...
def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):
"""Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights Parameters: net (network) -- the network to be initialized init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal gain (float) ...
) init.constant_(m.bias.data, 0.0) print('initialize network with %s' % init_type) net.apply(init_func) # apply the initialization function <init_func> def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):
64
64
207
21
43
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
init_net
init_net
102
117
102
102
fab8597b71d7a000d068aa65f4c164b8533eb17f
bigcode/the-stack
train
57b3088bb0e11174b2948bdb
train
function
def cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0): """Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028 Arguments: netD (network) -- discriminator network real_data (tensor array) --...
def cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0):
"""Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028 Arguments: netD (network) -- discriminator network real_data (tensor array) -- real images fake_data (tensor array) -- generated images from the generator device (st...
the prediction output from a discriminator target_is_real (bool) - - if the ground truth label is for real images or fake images Returns: the calculated loss. """ if self.gan_mode in ['lsgan', 'vanilla']: target_tensor = self.get_target_tensor(prediction, ta...
152
152
509
33
118
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
cal_gradient_penalty
cal_gradient_penalty
288
322
288
288
524be8a973781ba86629f15cbcedd298f604d1c2
bigcode/the-stack
train
762a1dd6396584c2694a75e8
train
class
class ResnetGenerator(nn.Module): """Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init__(self, input_nc,...
class ResnetGenerator(nn.Module):
"""Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn....
1, device=device) alpha = alpha.expand(real_data.shape[0], real_data.nelement() // real_data.shape[0]).contiguous().view(*real_data.shape) interpolatesv = alpha * real_data + ((1 - alpha) * fake_data) else: raise NotImplementedError('{} not implemented'.format(type)) ...
232
232
776
7
224
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
ResnetGenerator
ResnetGenerator
325
392
325
325
2a4cb368570168f50c9218bf09142ec1805a309c
bigcode/the-stack
train
082e2e077be4c29dd0b4cf0f
train
class
class ResnetBlock(nn.Module): """Define a Resnet block""" def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias, dilation): """Initialize the Resnet block A resnet block is a conv block with skip connections We construct a conv block with build_conv_block function, ...
class ResnetBlock(nn.Module):
"""Define a Resnet block""" def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias, dilation): """Initialize the Resnet block A resnet block is a conv block with skip connections We construct a conv block with build_conv_block function, and implement skip conne...
in range(n_downsampling): # add upsampling layers mult = 2 ** (n_downsampling - i) model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1, output_padding=1, ...
178
178
595
7
171
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
ResnetBlock
ResnetBlock
395
453
395
395
4337e2b958984b41b8a5027dc422f3568ae6d457
bigcode/the-stack
train
75cdca6f9739452bcde12368
train
class
class NLayerDiscriminator(nn.Module): """Defines a PatchGAN discriminator""" def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d): """Construct a PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int...
class NLayerDiscriminator(nn.Module):
"""Defines a PatchGAN discriminator""" def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d): """Construct a PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in th...
* 2, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) down = [downrelu, downconv, downnorm] up = [uprelu, upconv, upnorm] if use_dropout: model = down + [submodule] + up + [n...
153
153
512
8
145
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
NLayerDiscriminator
NLayerDiscriminator
558
603
558
558
a2672c9ffd15f8569735b2f43b3524ccf3048070
bigcode/the-stack
train
ebd553465eb337ed2d89d6ae
train
function
def get_norm_layer(norm_type='instance'): """Return a normalization layer Parameters: norm_type (str) -- the name of the normalization layer: batch | instance | none For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev). For InstanceNorm, we do not use le...
def get_norm_layer(norm_type='instance'):
"""Return a normalization layer Parameters: norm_type (str) -- the name of the normalization layer: batch | instance | none For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev). For InstanceNorm, we do not use learnable affine parameters. We do not track...
import torch import torch.nn as nn import numpy as np from torch.nn import init import functools from torch.optim import lr_scheduler ############################################################################### # Helper Functions ############################################################################### cla...
64
64
183
9
54
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
get_norm_layer
get_norm_layer
19
36
19
19
bab9a0024f0a3cac2e588bab5ff4877f5c85c6c4
bigcode/the-stack
train
e4304fd00846dc2d3e7ac5ca
train
class
class Identity(nn.Module): def forward(self, x): return x
class Identity(nn.Module):
def forward(self, x): return x
import torch import torch.nn as nn import numpy as np from torch.nn import init import functools from torch.optim import lr_scheduler ############################################################################### # Helper Functions ############################################################################### class...
43
64
16
5
38
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
Identity
Identity
14
16
14
14
97123a44f4920759f9eece6c61ddb7a814bb1783
bigcode/the-stack
train