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
91950d90a96c4ba9aa7a4a96
train
function
def generateEmails(emailAdresses: List[EmailAddress], spammerAdresses=[], spam_rate=0.0, flood_rate=0.0, *, email_amount=0): emails = [] if random() < flood_rate: emails.extend(generateFloodEmail( spammerAdresses, email_amount)) # randint(0, email_amount) else: email_amount_left...
def generateEmails(emailAdresses: List[EmailAddress], spammerAdresses=[], spam_rate=0.0, flood_rate=0.0, *, email_amount=0):
emails = [] if random() < flood_rate: emails.extend(generateFloodEmail( spammerAdresses, email_amount)) # randint(0, email_amount) else: email_amount_left = email_amount - len(emails) emails.extend((generateSimpleEmail(emailAdresses=emailAdresses, spammerAdresses=spammer...
SimpleEmail(emailAdresses, from_sender=flooder_adress, with_body=body) for _ in range(emailGeneratedCount)) def generateEmails(emailAdresses: List[EmailAddress], spammerAdresses=[], spam_rate=0.0, flood_rate=0.0, *, email_amount=0):
64
64
132
37
27
johannchopin/htw-m1-softwarearchitecture
src/entry/fakeEmails.py
Python
generateEmails
generateEmails
92
101
92
92
bf48bc05ca23fac33b42ca6a2bc693ef52ff692d
bigcode/the-stack
train
42be6f9a7fd290d121611509
train
function
def getTimestamp(precision_after_second=3): """ Helper that return a timestamp, with additional seconds if provided The returned timestamp is in ms (10^-3s) """ shift_after_seconds = 10**precision_after_second return int(time() * shift_after_seconds)
def getTimestamp(precision_after_second=3):
""" Helper that return a timestamp, with additional seconds if provided The returned timestamp is in ms (10^-3s) """ shift_after_seconds = 10**precision_after_second return int(time() * shift_after_seconds)
paragraph_amount = range(randint(1, nb_max_paragraph)) return '\n'.join((FAKE.paragraph( nb_sentences=nb_max_sentences_per_paragraph, variable_nb_sentences=True ) for _ in paragraph_amount)) def getTimestamp(precision_after_second=3):
64
64
62
10
54
johannchopin/htw-m1-softwarearchitecture
src/entry/fakeEmails.py
Python
getTimestamp
getTimestamp
52
58
52
52
da8881e91fa1bde3fa5c80c7d4a65f352758d8c9
bigcode/the-stack
train
02d3a124f1016423683aa9bf
train
class
class EmailJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Email): return obj.__dict__ # Base class default() raises TypeError: return json.JSONEncoder.default(self, obj)
class EmailJsonEncoder(json.JSONEncoder):
def default(self, obj): if isinstance(obj, Email): return obj.__dict__ # Base class default() raises TypeError: return json.JSONEncoder.default(self, obj)
AM_WORDLIST_SOURCE)] EmailAddress = NewType('EmailAdress', str) @dataclass class Email: """ Structure of an email """ sender: EmailAddress receiver: EmailAddress timestamp: int subject: str body: str class EmailJsonEncoder(json.JSONEncoder):
64
64
48
8
55
johannchopin/htw-m1-softwarearchitecture
src/entry/fakeEmails.py
Python
EmailJsonEncoder
EmailJsonEncoder
31
36
31
31
57cefd0eb828ec0ef7dd8ebce886880396da0142
bigcode/the-stack
train
c0325f3202207841ea62f706
train
function
def generateEmailBody(nb_max_paragraph=3, nb_max_sentences_per_paragraph=10) -> str: """ Generate the body of an email, i.e. the message """ paragraph_amount = range(randint(1, nb_max_paragraph)) return '\n'.join((FAKE.paragraph( nb_sentences=nb_max_sentences_per_paragraph, variable_nb_sente...
def generateEmailBody(nb_max_paragraph=3, nb_max_sentences_per_paragraph=10) -> str:
""" Generate the body of an email, i.e. the message """ paragraph_amount = range(randint(1, nb_max_paragraph)) return '\n'.join((FAKE.paragraph( nb_sentences=nb_max_sentences_per_paragraph, variable_nb_sentences=True ) for _ in paragraph_amount))
: return json.JSONEncoder.default(self, obj) def generateEmailAdresses(amount: int) -> List[EmailAddress]: return [FAKE.email() for _ in range(amount)] def generateEmailBody(nb_max_paragraph=3, nb_max_sentences_per_paragraph=10) -> str:
63
64
94
24
39
johannchopin/htw-m1-softwarearchitecture
src/entry/fakeEmails.py
Python
generateEmailBody
generateEmailBody
43
49
43
43
95d03d0e8a6d7f9c12eab822acac1ffbd0c51b8a
bigcode/the-stack
train
2855573a84d39418a5464997
train
function
def generateFloodEmail(emailAdresses, emailGeneratedCount): flooder_adress = choice(emailAdresses) body = generateEmailBody(nb_max_paragraph=5) return (generateSimpleEmail(emailAdresses, from_sender=flooder_adress, with_body=body) for _ in range(emailGeneratedCount))
def generateFloodEmail(emailAdresses, emailGeneratedCount):
flooder_adress = choice(emailAdresses) body = generateEmailBody(nb_max_paragraph=5) return (generateSimpleEmail(emailAdresses, from_sender=flooder_adress, with_body=body) for _ in range(emailGeneratedCount))
_max_paragraph=5) if not with_body else with_body if random() < spam_rate: sender = choice(spammerAdresses) body = generateSpamBody(body) return Email(sender, receiver, timestamp, subject, body) def generateFloodEmail(emailAdresses, emailGeneratedCount):
64
64
67
12
52
johannchopin/htw-m1-softwarearchitecture
src/entry/fakeEmails.py
Python
generateFloodEmail
generateFloodEmail
86
89
86
86
d5fc6b4cb241004048e5b1a72250bcb2e2cf6b60
bigcode/the-stack
train
d7511e9f11a5f910d12ea64d
train
function
def generateEmailAdresses(amount: int) -> List[EmailAddress]: return [FAKE.email() for _ in range(amount)]
def generateEmailAdresses(amount: int) -> List[EmailAddress]:
return [FAKE.email() for _ in range(amount)]
class EmailJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Email): return obj.__dict__ # Base class default() raises TypeError: return json.JSONEncoder.default(self, obj) def generateEmailAdresses(amount: int) -> List[EmailAddress]:
64
64
28
15
49
johannchopin/htw-m1-softwarearchitecture
src/entry/fakeEmails.py
Python
generateEmailAdresses
generateEmailAdresses
39
40
39
39
60de51fd1e61f45e1885b57f1b53927a0e90453f
bigcode/the-stack
train
9d5b4e45954c04758045a89c
train
class
class StatsStoreDataQueryTest(aff4_test_lib.AFF4ObjectTest): """Tests for StatsStoreDataQuery class.""" def setUp(self): super(StatsStoreDataQueryTest, self).setUp() self.process_id = "some_pid" self.stats_store = aff4.FACTORY.Create( None, stats_store.StatsStore, mode="w", token=self.token) ...
class StatsStoreDataQueryTest(aff4_test_lib.AFF4ObjectTest):
"""Tests for StatsStoreDataQuery class.""" def setUp(self): super(StatsStoreDataQueryTest, self).setUp() self.process_id = "some_pid" self.stats_store = aff4.FACTORY.Create( None, stats_store.StatsStore, mode="w", token=self.token) def testUsingInCallNarrowsQuerySpace(self): # Create sam...
_ids=["pid1", "pid2"]) self.assertFalse("counter" in metadata_by_id["pid1"].AsDict()) self.assertFalse("counter" in metadata_by_id["pid2"].AsDict()) # Write stats to the data store. Metadata should be # written as well. self.stats_store.WriteStats(process_id="pid1", timestamp=42) # Now metadat...
256
256
4,830
17
239
billstackpole/grr
grr/server/grr_response_server/aff4_objects/stats_store_test.py
Python
StatsStoreDataQueryTest
StatsStoreDataQueryTest
270
766
270
270
79b5e0d4f3649eba60bb2099223e857a0ac805e0
bigcode/the-stack
train
faaf0654ac5dfa597bbc6194
train
class
class StatsStoreTest(aff4_test_lib.AFF4ObjectTest): def setUp(self): super(StatsStoreTest, self).setUp() self.process_id = "some_pid" self.stats_store = aff4.FACTORY.Create( None, stats_store.StatsStore, mode="w", token=self.token) def testValuesAreFetchedCorrectly(self): stats.STATS.Regi...
class StatsStoreTest(aff4_test_lib.AFF4ObjectTest):
def setUp(self): super(StatsStoreTest, self).setUp() self.process_id = "some_pid" self.stats_store = aff4.FACTORY.Create( None, stats_store.StatsStore, mode="w", token=self.token) def testValuesAreFetchedCorrectly(self): stats.STATS.RegisterCounterMetric("counter") stats.STATS.Register...
#!/usr/bin/env python """Tests for the stats_store classes.""" from builtins import range # pylint: disable=redefined-builtin from future.utils import iterkeys from grr_response_core.lib import flags from grr_response_core.lib import rdfvalue from grr_response_core.lib import stats from grr_response_server import a...
130
256
2,539
15
114
billstackpole/grr
grr/server/grr_response_server/aff4_objects/stats_store_test.py
Python
StatsStoreTest
StatsStoreTest
19
267
19
20
f2f5603cdfc2a6d921f382d5f9af193c8bdd0bc8
bigcode/the-stack
train
6098cb6466515ac98f8e106c
train
function
def main(argv): test_lib.main(argv)
def main(argv):
test_lib.main(argv)
Read data back. stats_data = self.stats_store.ReadStats(process_id=self.process_id) # Get time series generated with TakeValue(). query = stats_store.StatsStoreDataQuery(stats_data) self.assertAlmostEqual(query.In("counter").TakeValue().Mean(), 3) def main(argv):
64
64
10
4
60
billstackpole/grr
grr/server/grr_response_server/aff4_objects/stats_store_test.py
Python
main
main
769
770
769
769
ecd94fc80a33de9e929d8f215b77bba11a49aa84
bigcode/the-stack
train
33e289b5960ac12217dbb218
train
class
class Websocket(KaitaiStruct): """The WebSocket protocol establishes a two-way communication channel via TCP. Messages are made up of one or more dataframes, and are delineated by frames with the `fin` bit set. """ class Opcode(Enum): continuation = 0 text = 1 binary = 2 ...
class Websocket(KaitaiStruct):
"""The WebSocket protocol establishes a two-way communication channel via TCP. Messages are made up of one or more dataframes, and are delineated by frames with the `fin` bit set. """ class Opcode(Enum): continuation = 0 text = 1 binary = 2 reserved_3 = 3 res...
apply to the Work or any use thereof, including without # limitation any person's Copyright and Related Rights in the Work. # Further, Affirmer disclaims responsibility for obtaining any necessary # consents, permissions or other rights required for any use of the # Work. # d. Affirmer understands and...
255
256
1,711
8
247
angea/pytai
pytai/kaitai/formats/websocket.py
Python
Websocket
Websocket
139
289
139
139
042b4c1377ba3ace09af54ea2954e4e0a5e38083
bigcode/the-stack
train
33f3162761bdef484fe8f92d
train
function
def test_badwords(): compare_extraction(dutch.badwords.revision.datasources.matches, BAD, OTHER) eq_(dutch.badwords, pickle.loads(pickle.dumps(dutch.badwords)))
def test_badwords():
compare_extraction(dutch.badwords.revision.datasources.matches, BAD, OTHER) eq_(dutch.badwords, pickle.loads(pickle.dumps(dutch.badwords)))
emd werden. Kerkorgels verschilden enorm van stemtoon. In de loop van de tijd is die variatie steeds kleiner geworden. Naarmate mensen steeds mobieler werden, ontstond ook de behoefte aan meer compatibiliteit van instrumenten. """ ] def test_badwords():
64
64
41
5
59
yafeunteun/wikipedia-spam-classifier
revscoring/revscoring/languages/tests/test_dutch.py
Python
test_badwords
test_badwords
136
139
136
136
03558730f84980e2add59820257c50dbcce03205
bigcode/the-stack
train
686f1770da936802066d6f96
train
function
def test_stopwords(): cache = {revision_oriented.revision.text: 'Door middel van een!'} eq_(solve(dutch.stopwords.revision.datasources.stopwords, cache=cache), ["Door", "van", "een"]) eq_(solve(dutch.stopwords.revision.datasources.non_stopwords, cache=cache), ["middel"]) eq_(dut...
def test_stopwords():
cache = {revision_oriented.revision.text: 'Door middel van een!'} eq_(solve(dutch.stopwords.revision.datasources.stopwords, cache=cache), ["Door", "van", "een"]) eq_(solve(dutch.stopwords.revision.datasources.non_stopwords, cache=cache), ["middel"]) eq_(dutch.stopwords, pickle.l...
=cache), ["Door", "middel", "van", "een"]) eq_(solve(dutch.dictionary.revision.datasources.non_dict_words, cache=cache), ["worngly"]) eq_(dutch.dictionary, pickle.loads(pickle.dumps(dutch.dictionary))) def test_stopwords():
63
64
95
5
58
yafeunteun/wikipedia-spam-classifier
revscoring/revscoring/languages/tests/test_dutch.py
Python
test_stopwords
test_stopwords
160
168
160
160
cbf74299ceed449a4ce628a090499b9102e94340
bigcode/the-stack
train
bf2eba971b79a7b213cbe97f
train
function
def test_stemmed(): cache = {revision_oriented.revision.text: 'Door middel van een!'} eq_(solve(dutch.stemmed.revision.datasources.stems, cache=cache), ["dor", "middel", "van", "een"]) eq_(dutch.stemmed, pickle.loads(pickle.dumps(dutch.stemmed)))
def test_stemmed():
cache = {revision_oriented.revision.text: 'Door middel van een!'} eq_(solve(dutch.stemmed.revision.datasources.stems, cache=cache), ["dor", "middel", "van", "een"]) eq_(dutch.stemmed, pickle.loads(pickle.dumps(dutch.stemmed)))
cache=cache), ["Door", "van", "een"]) eq_(solve(dutch.stopwords.revision.datasources.non_stopwords, cache=cache), ["middel"]) eq_(dutch.stopwords, pickle.loads(pickle.dumps(dutch.stopwords))) def test_stemmed():
63
64
77
6
57
yafeunteun/wikipedia-spam-classifier
revscoring/revscoring/languages/tests/test_dutch.py
Python
test_stemmed
test_stemmed
171
176
171
171
57721388ae7e93f0c003cff0e1520988e54bc48b
bigcode/the-stack
train
ce1474878eea1a19861a9013
train
function
def test_dictionary(): cache = {revision_oriented.revision.text: 'Door middel van een worngly.'} eq_(solve(dutch.dictionary.revision.datasources.dict_words, cache=cache), ["Door", "middel", "van", "een"]) eq_(solve(dutch.dictionary.revision.datasources.non_dict_words, cache=cache), ...
def test_dictionary():
cache = {revision_oriented.revision.text: 'Door middel van een worngly.'} eq_(solve(dutch.dictionary.revision.datasources.dict_words, cache=cache), ["Door", "middel", "van", "een"]) eq_(solve(dutch.dictionary.revision.datasources.non_dict_words, cache=cache), ["worngly"]) ...
, pickle.loads(pickle.dumps(dutch.badwords))) def test_informals(): compare_extraction(dutch.informals.revision.datasources.matches, INFORMAL, OTHER) eq_(dutch.informals, pickle.loads(pickle.dumps(dutch.informals))) def test_dictionary():
63
64
98
4
59
yafeunteun/wikipedia-spam-classifier
revscoring/revscoring/languages/tests/test_dutch.py
Python
test_dictionary
test_dictionary
149
157
149
149
656229203a68094539af1fe226f290f6f3ccd359
bigcode/the-stack
train
6c2b4dcd7c4ac3ead317d735
train
function
def test_informals(): compare_extraction(dutch.informals.revision.datasources.matches, INFORMAL, OTHER) eq_(dutch.informals, pickle.loads(pickle.dumps(dutch.informals)))
def test_informals():
compare_extraction(dutch.informals.revision.datasources.matches, INFORMAL, OTHER) eq_(dutch.informals, pickle.loads(pickle.dumps(dutch.informals)))
ook de behoefte aan meer compatibiliteit van instrumenten. """ ] def test_badwords(): compare_extraction(dutch.badwords.revision.datasources.matches, BAD, OTHER) eq_(dutch.badwords, pickle.loads(pickle.dumps(dutch.badwords))) def test_informals():
63
64
47
6
57
yafeunteun/wikipedia-spam-classifier
revscoring/revscoring/languages/tests/test_dutch.py
Python
test_informals
test_informals
142
146
142
142
87c0460368b7b4752c4780ecdf24fdbf4d18c917
bigcode/the-stack
train
9451b3e7ab27a6029bf9d75d
train
class
class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ["first_name", "last_name", "email", "address", "zip_code"] # "city"
class OrderCreateForm(forms.ModelForm):
class Meta: model = Order fields = ["first_name", "last_name", "email", "address", "zip_code"] # "city"
from django import forms from .models import Order class OrderCreateForm(forms.ModelForm):
19
64
43
8
10
dada00321/clothing_website
orders/forms.py
Python
OrderCreateForm
OrderCreateForm
4
8
4
4
6c07c1bb036bd47bcd3b432f0196e37982fe101a
bigcode/the-stack
train
bb06b3a48ebca1037f298588
train
class
class MemgraphConnection(Connection): def __init__(self, host: str, port: int, username: str, password: str, encrypted: bool, lazy: bool = True): super().__init__(host, port, username, password, encrypted) self.lazy = lazy self._connection = self._create_connection() def execute_query(s...
class MemgraphConnection(Connection):
def __init__(self, host: str, port: int, username: str, password: str, encrypted: bool, lazy: bool = True): super().__init__(host, port, username, password, encrypted) self.lazy = lazy self._connection = self._create_connection() def execute_query(self, query: str) -> None: """E...
def execute_and_fetch(self, query: str) -> Iterator[Dict[str, Any]]: """Executes Cypher query and returns iterator of results.""" pass @abstractmethod def is_active(self) -> bool: """Returns True if connection is active and can be used""" pass @staticmethod def cre...
94
94
315
6
88
memgraph/orbicon
backend/orbit_graph/database/connection.py
Python
MemgraphConnection
MemgraphConnection
38
73
38
38
965b910da14f860f56fd0c9fe02ed58a281c8d0a
bigcode/the-stack
train
9d8a3e8bb403cfbc5f014273
train
function
def _convert_memgraph_value(value: Any) -> Any: """Converts Memgraph objects to custom Node/Relationship objects""" if isinstance(value, mgclient.Relationship): return Relationship( rel_id=value.id, rel_type=value.type, start_node=value.start_id, end_node=...
def _convert_memgraph_value(value: Any) -> Any:
"""Converts Memgraph objects to custom Node/Relationship objects""" if isinstance(value, mgclient.Relationship): return Relationship( rel_id=value.id, rel_type=value.type, start_node=value.start_id, end_node=value.end_id, properties=value.prope...
.encrypted else mgclient.MG_SSLMODE_DISABLE return mgclient.connect( host=self.host, port=self.port, username=self.username, password=self.password, sslmode=sslmode, lazy=self.lazy, ) def _convert_memgraph_value(value: Any) -> Any:
64
64
103
13
51
memgraph/orbicon
backend/orbit_graph/database/connection.py
Python
_convert_memgraph_value
_convert_memgraph_value
76
90
76
76
c64a5b1dbb4033fc4479734fb23ceb52f00ca183
bigcode/the-stack
train
3586702fa7e547d8acd55641
train
class
class Connection(ABC): def __init__(self, host: str, port: int, username: str, password: str, encrypted: bool): self.host = host self.port = port self.username = username self.password = password self.encrypted = encrypted @abstractmethod def execute_query(self, quer...
class Connection(ABC):
def __init__(self, host: str, port: int, username: str, password: str, encrypted: bool): self.host = host self.port = port self.username = username self.password = password self.encrypted = encrypted @abstractmethod def execute_query(self, query: str) -> None: ...
from abc import ABC, abstractmethod from typing import Any, Dict, Iterator import mgclient from orbit_graph.database.models import Node, Relationship __all__ = ("Connection",) class Connection(ABC):
44
64
188
5
39
memgraph/orbicon
backend/orbit_graph/database/connection.py
Python
Connection
Connection
10
35
10
10
08aa87c67ebc4b14a843b3adca171e9fe9c40407
bigcode/the-stack
train
91219a0c1ab70a2abe55d5c1
train
class
class NonDynamicallyQuantizableLinear(Linear): def __init__(self, in_features: int, out_features: int, bias: bool = True, device=None, dtype=None) -> None: super().__init__(in_features, out_features, bias=bias, device=device, dtype=dtype)
class NonDynamicallyQuantizableLinear(Linear):
def __init__(self, in_features: int, out_features: int, bias: bool = True, device=None, dtype=None) -> None: super().__init__(in_features, out_features, bias=bias, device=device, dtype=dtype)
improperly quantized attention layer. See this issue for details: # https://github.com/pytorch/pytorch/issues/58969 # TODO: fail fast on quantization API usage error, then remove this class # and replace uses of it with plain Linear class NonDynamicallyQuantizableLinear(Linear):
64
64
67
11
52
eee4017/pytorch
torch/nn/modules/linear.py
Python
NonDynamicallyQuantizableLinear
NonDynamicallyQuantizableLinear
109
113
109
109
ba5efc89b75448e601959a2cf2378bb4065b7b58
bigcode/the-stack
train
8161da317ce959cdea01d731
train
class
class LazyLinear(LazyModuleMixin, Linear): r"""A :class:`torch.nn.Linear` module where `in_features` is inferred. In this module, the `weight` and `bias` are of :class:`torch.nn.UninitializedParameter` class. They will be initialized after the first call to ``forward`` is done and the module will becom...
class LazyLinear(LazyModuleMixin, Linear):
r"""A :class:`torch.nn.Linear` module where `in_features` is inferred. In this module, the `weight` and `bias` are of :class:`torch.nn.UninitializedParameter` class. They will be initialized after the first call to ``forward`` is done and the module will become a regular :class:`torch.nn.Linear` module...
self.bias = Parameter(torch.empty(out_features, **factory_kwargs)) else: self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self) -> None: bound = 1 / math.sqrt(self.weight.size(1)) init.uniform_(self.weight, -bound, bound) ...
183
183
611
10
173
eee4017/pytorch
torch/nn/modules/linear.py
Python
LazyLinear
LazyLinear
190
245
190
190
50f7962be3572b6820c52d1bebc90cc7c3578ab9
bigcode/the-stack
train
39680ffa6598d644859a9eab
train
class
class Identity(Module): r"""A placeholder identity operator that is argument-insensitive. Args: args: any argument (unused) kwargs: any keyword argument (unused) Examples:: >>> m = nn.Identity(54, unused_argument1=0.1, unused_argument2=False) >>> input = torch.randn(128, 2...
class Identity(Module):
r"""A placeholder identity operator that is argument-insensitive. Args: args: any argument (unused) kwargs: any keyword argument (unused) Examples:: >>> m = nn.Identity(54, unused_argument1=0.1, unused_argument2=False) >>> input = torch.randn(128, 20) >>> output = ...
import math import torch from torch import Tensor from torch.nn.parameter import Parameter, UninitializedParameter from .. import functional as F from .. import init from .module import Module from .lazy import LazyModuleMixin class Identity(Module):
52
64
136
4
47
eee4017/pytorch
torch/nn/modules/linear.py
Python
Identity
Identity
12
32
12
12
14cf89a58b4b693f65fdee45d5af14df31eafc85
bigcode/the-stack
train
af01fc754551793e60896fd4
train
class
class Linear(Module): r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b` This module supports :ref:`TensorFloat32<tf32_on_ampere>`. Args: in_features: size of each input sample out_features: size of each output sample bias: If set to ``False``, the layer...
class Linear(Module):
r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b` This module supports :ref:`TensorFloat32<tf32_on_ampere>`. Args: in_features: size of each input sample out_features: size of each output sample bias: If set to ``False``, the layer will not learn an add...
import math import torch from torch import Tensor from torch.nn.parameter import Parameter, UninitializedParameter from .. import functional as F from .. import init from .module import Module from .lazy import LazyModuleMixin class Identity(Module): r"""A placeholder identity operator that is argument-insensiti...
188
216
722
4
183
eee4017/pytorch
torch/nn/modules/linear.py
Python
Linear
Linear
35
101
35
35
8ce3f042496797863cf1675ecae070586f0342a3
bigcode/the-stack
train
cbe5984d0f06a8b4ed9c2593
train
class
class Bilinear(Module): r"""Applies a bilinear transformation to the incoming data: :math:`y = x_1^T A x_2 + b` Args: in1_features: size of each first input sample in2_features: size of each second input sample out_features: size of each output sample bias: If set to False, ...
class Bilinear(Module):
r"""Applies a bilinear transformation to the incoming data: :math:`y = x_1^T A x_2 + b` Args: in1_features: size of each first input sample in2_features: size of each second input sample out_features: size of each output sample bias: If set to False, the layer will not learn...
init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0 init.uniform_(self.bias, -bound, bound) def forward(self, input: Tensor) -> Tensor: return F.linear(input, self.weight, self.bias) def extra_repr(self) -> str: return 'in...
252
252
842
5
247
eee4017/pytorch
torch/nn/modules/linear.py
Python
Bilinear
Bilinear
116
187
116
116
f096c076d61186ce422572fd082780ade1179fcb
bigcode/the-stack
train
6a0732cf4de3938e79b5d7e6
train
function
def make_square_image(img, width, height, padVal): x, y = img.size fill_color=(padVal, padVal, padVal, padVal) min_size=224 size = max(min_size, x, y) new_img = Image.new('RGBA', (size, size), fill_color) new_img.paste(img, ((size - x) / 2, (size - y) / 2)) new_img = new_img.resize((width, h...
def make_square_image(img, width, height, padVal):
x, y = img.size fill_color=(padVal, padVal, padVal, padVal) min_size=224 size = max(min_size, x, y) new_img = Image.new('RGBA', (size, size), fill_color) new_img.paste(img, ((size - x) / 2, (size - y) / 2)) new_img = new_img.resize((width, height), Image.BILINEAR) new_img = new_img.conve...
import os import getopt import sys import re from PIL import Image def make_square_image(img, width, height, padVal):
30
64
129
13
16
rrawther/help
classificationLabelGenerator/scripts/step-1.py
Python
make_square_image
make_square_image
7
16
7
7
68bde3ec5907001c33ca010337de2e7ea8d4b50d
bigcode/the-stack
train
c058193d6880134eb99b22a3
train
function
def split_iso_gene(iso_gene): if '_chr' in iso_gene: splitchar = '_chr' elif '_XM' in iso_gene: splitchar = '_XM' elif '_XR' in iso_gene: splitchar = '_XR' elif '_NM' in iso_gene: splitchar = '_NM' elif '_NR' in iso_gene: splitchar = '_NR' elif '_R2_' in i...
def split_iso_gene(iso_gene):
if '_chr' in iso_gene: splitchar = '_chr' elif '_XM' in iso_gene: splitchar = '_XM' elif '_XR' in iso_gene: splitchar = '_XR' elif '_NM' in iso_gene: splitchar = '_NM' elif '_NR' in iso_gene: splitchar = '_NR' elif '_R2_' in iso_gene: splitchar = '...
')+2:] gene = gene[:gene.find('"')] # gene = re.search("(ENSG[^\.]+)", cols[-1]).group(1) starts.append((chrom,c1,c2,gene,".",strand)) return starts def split_iso_gene(iso_gene):
64
64
179
8
55
epistatic/flair
bin/predictProductivity.py
Python
split_iso_gene
split_iso_gene
131
150
131
131
48bfc731ab0d99c8149e02fe95f141eb42618622
bigcode/the-stack
train
f4b8db9f73b44c7b9827586e
train
function
def checkPTC(orfEndPos, exons, isoObj): ''' takes a transcript sequence position, and list of exon sizes to detemine if that position occurs more than 55nucleotides away from a splice junction. ptc = True if yes, ptc = False if not. the genomic position is also reported. ''' stopDistFromExon...
def checkPTC(orfEndPos, exons, isoObj):
''' takes a transcript sequence position, and list of exon sizes to detemine if that position occurs more than 55nucleotides away from a splice junction. ptc = True if yes, ptc = False if not. the genomic position is also reported. ''' stopDistFromExon = None exonWithStop = None ptc...
x[0] for x in exons] # First get start position relative to transcript sequence. if isoObj.strand == "+": relativeStart = genomicStartPos - exons[exonNum][0] + sum([x for x in isoObj.exonSizes[:exonNum]]) elif isoObj.strand == "-": relativeStart = len(isoObj.sequence) - (genomicStartPos - e...
141
141
473
15
125
epistatic/flair
bin/predictProductivity.py
Python
checkPTC
checkPTC
184
237
184
184
1c0fc04612e40dac32d1b9b9ac244b4eea8ef868
bigcode/the-stack
train
31e0335f41352ccfb424f91d
train
function
def main(): ''' maine ''' # Command Line Stuff... myCommandLine = CommandLine() bed = myCommandLine.args['input_isoforms'] genome = myCommandLine.args['genome_fasta'] gtf = myCommandLine.args['gtf'] extra_col = myCommandLine.args['append_column'] if myCommandLine.args['fi...
def main():
''' maine ''' # Command Line Stuff... myCommandLine = CommandLine() bed = myCommandLine.args['input_isoforms'] genome = myCommandLine.args['genome_fasta'] gtf = myCommandLine.args['gtf'] extra_col = myCommandLine.args['append_column'] if myCommandLine.args['firstTIS']: ...
exons[0][0], orfEndPos-relativeStart, relativeStart]) #o.orfs.append(["NST", startPos, exons[-1][-1] if o.strand == "+" else exons[0][0], relativeStart]) #else if a stop was reached... else: orfEndPos = len(fiveUTR)+i+3 di...
180
180
602
3
176
epistatic/flair
bin/predictProductivity.py
Python
main
main
304
368
304
304
114146c01521da8a95683001b7e5b8b43d0bfce4
bigcode/the-stack
train
6a90de44e67505f3d351ae7c
train
function
def getStartRelPos(genomicStartPos,exon, exons, isoObj): ''' is handed a genomic position, the exon it occurs in, all exons, and returns the position relative to all exons ''' exonNum = exons.index(exon) isoObj.exonSizes = [x[1]-x[0] for x in exons] # First get start position relative to tr...
def getStartRelPos(genomicStartPos,exon, exons, isoObj):
''' is handed a genomic position, the exon it occurs in, all exons, and returns the position relative to all exons ''' exonNum = exons.index(exon) isoObj.exonSizes = [x[1]-x[0] for x in exons] # First get start position relative to transcript sequence. if isoObj.strand == "+": r...
read,seq = entry.split() read = read.split("(")[0] if read not in isoDict: isoDict[read] = Isoform(read,seq) return isoDict def getStartRelPos(genomicStartPos,exon, exons, isoObj):
64
64
199
19
44
epistatic/flair
bin/predictProductivity.py
Python
getStartRelPos
getStartRelPos
167
181
167
167
1f916326e96e87b1fed36b1da9cd08b20313e553
bigcode/the-stack
train
4e08691bf33cb87731dac983
train
function
def predict(bed, starts, isoDict): bt = pybedtools.BedTool(bed) b6 = bt.bed6() st = pybedtools.BedTool(starts) bt_st = b6.intersect(st, s=True, split=True, wao=True) for intersection in bt_st: read = intersection[3] #iso,gene = read.split("_") overlap = intersection[-1] ...
def predict(bed, starts, isoDict):
bt = pybedtools.BedTool(bed) b6 = bt.bed6() st = pybedtools.BedTool(starts) bt_st = b6.intersect(st, s=True, split=True, wao=True) for intersection in bt_st: read = intersection[3] #iso,gene = read.split("_") overlap = intersection[-1] goStart = int(intersection[...
exon the stop codon is in to get genomic position elif orfEndPos<distance: distToJunc = distance - orfEndPos if exonWithStop == None: exonWithStop = num stopDistFromExon = int(distToJunc) if distToJunc>55: ptc=True ...
202
202
676
10
191
epistatic/flair
bin/predictProductivity.py
Python
predict
predict
240
302
240
241
f62106b2b5d1a4cb6acf5591e5f2369860d64745
bigcode/the-stack
train
b4568a799a608227c2055fdf
train
function
def getSeqs(bed, genome): isoDict = dict() bt = pybedtools.BedTool(bed) bt.sequence(fi=genome, tab=True, s=True, split=True, name=True) with open(bt.seqfn) as entries: for entry in entries: read,seq = entry.split() read = read.split("(")[0] if r...
def getSeqs(bed, genome):
isoDict = dict() bt = pybedtools.BedTool(bed) bt.sequence(fi=genome, tab=True, s=True, split=True, name=True) with open(bt.seqfn) as entries: for entry in entries: read,seq = entry.split() read = read.split("(")[0] if read not in isoDict: ...
itchar = '_NC_' else: splitchar = '_' iso = iso_gene[:iso_gene.rfind(splitchar)] gene = iso_gene[iso_gene.rfind(splitchar)+1:] return iso, gene def getSeqs(bed, genome):
64
64
108
9
54
epistatic/flair
bin/predictProductivity.py
Python
getSeqs
getSeqs
152
164
152
153
756b2f4c5ea51e13a23258ad33e333a4eb5f4c6e
bigcode/the-stack
train
c530a65d736c8ab0d9f20494
train
class
class Isoform(object) : ''' Object to handle isoform related data. attributes: methods: ''' def __init__(self, name=None, seq=None): self.name = name self.pro = "UNK" self.chrom = "" self.sequence = seq self.bed12 = None ...
class Isoform(object) :
''' Object to handle isoform related data. attributes: methods: ''' def __init__(self, name=None, seq=None): self.name = name self.pro = "UNK" self.chrom = "" self.sequence = seq self.bed12 = None self.exons = set() ...
', default = False, help = 'Defined ORFs by the longest open reading frame.') if inOpts is None : self.args = vars(self.parser.parse_args()) else : self.args = vars(self.parser.parse_args(inOpts)) ######################################################################## # Isofo...
64
64
145
6
57
epistatic/flair
bin/predictProductivity.py
Python
Isoform
Isoform
77
103
77
77
c530c8ae716472e140d63ed6a9a06d5301211ed6
bigcode/the-stack
train
2c3437893c64b6bc45dc0cc9
train
class
class CommandLine(object) : ''' Handle the command line, usage and help requests. CommandLine uses argparse, now standard in 2.7 and beyond. it implements a standard command line argument parser with various argument options, and a standard usage and help, attributes: myCommandLine.args is ...
class CommandLine(object) :
''' Handle the command line, usage and help requests. CommandLine uses argparse, now standard in 2.7 and beyond. it implements a standard command line argument parser with various argument options, and a standard usage and help, attributes: myCommandLine.args is a dictionary which includes ...
#!/usr/bin/env python3 from __future__ import print_function ######################################################################## # File: predictProductivity.py # executable: predictProductivity.py # Purpose: # # # Author: Cameron M. Soulette # History: cms 10/09/2018 Created # ##################...
112
145
486
6
105
epistatic/flair
bin/predictProductivity.py
Python
CommandLine
CommandLine
31
70
31
31
147633b1c40b84406a311fd75ae704c69e11be87
bigcode/the-stack
train
8da3c3ddbe142d39cd200c4f
train
function
def getStarts(gtf): starts = list() with open(gtf) as lines: for l in lines: if l[0] == "#": continue cols = l.rstrip().split("\t") chrom, c1, c2, strand = cols[0], int(cols[3])-1, int(cols[4]), cols[6] if cols[2] == "start_codon": gene = c...
def getStarts(gtf):
starts = list() with open(gtf) as lines: for l in lines: if l[0] == "#": continue cols = l.rstrip().split("\t") chrom, c1, c2, strand = cols[0], int(cols[3])-1, int(cols[4]), cols[6] if cols[2] == "start_codon": gene = cols[8][cols[8].find(...
sortORFs(self): self.orfs.sort(key=lambda x: x[-1]) #for i in self.orfs: # print(i,self.gid,self.tid) ######################################################################## # MAIN ######################################################################## def bed12ToExonRanges(cols): p...
64
64
167
6
57
epistatic/flair
bin/predictProductivity.py
Python
getStarts
getStarts
114
129
114
114
ab7684d1090fbe5ac586b1f8ecb105a9091c802d
bigcode/the-stack
train
74c55c1c8945e50534286622
train
function
def bed12ToExonRanges(cols): pass
def bed12ToExonRanges(cols):
pass
self.exonSizes = list() def sortORFs(self): self.orfs.sort(key=lambda x: x[-1]) #for i in self.orfs: # print(i,self.gid,self.tid) ######################################################################## # MAIN ######################################################################## de...
64
64
12
9
54
epistatic/flair
bin/predictProductivity.py
Python
bed12ToExonRanges
bed12ToExonRanges
111
112
111
111
38908670f768c59042ece8ebc46cd7e3842b5f87
bigcode/the-stack
train
b97330c9a8bd1f10ea68d1bc
train
class
class Solution: def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int: heap = [] for i in range(len(heights) - 1): d = heights[i + 1] - heights[i] if d > 0: heapq.heappush(heap, d) if len(heap) > ladders: ...
class Solution:
def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int: heap = [] for i in range(len(heights) - 1): d = heights[i + 1] - heights[i] if d > 0: heapq.heappush(heap, d) if len(heap) > ladders: bricks -= heapq....
class Solution:
3
64
116
3
0
nilax97/leetcode-solutions
solutions/Furthest Building You Can Reach/solution.py
Python
Solution
Solution
1
12
1
1
eca3e6029afe11ef613772643d02f32c67c1c2b0
bigcode/the-stack
train
2a310fbb3f9e1876e2baff0d
train
function
def configure_rider(pathToRider, bicycle, bicyclePar, measuredPar, draw): """ Returns the rider parameters, bicycle paramaters with a rider and a human object that is configured to sit on the bicycle. Parameters ---------- pathToRider : string Path to the rider's data folder. bicycl...
def configure_rider(pathToRider, bicycle, bicyclePar, measuredPar, draw):
""" Returns the rider parameters, bicycle paramaters with a rider and a human object that is configured to sit on the bicycle. Parameters ---------- pathToRider : string Path to the rider's data folder. bicycle : string The short name of the bicycle. bicyclePar : diction...
bb = measuredPar['hbb'] # chain stay length lcs = measuredPar['lcs'] # rear wheel radius rR = benchmarkPar['rR'] # seat post length lsp = measuredPar['lsp'] # seat tube length lst = measuredPar['lst'] # seat tube angle lambdast = measuredPar['lamst'] # bicycle origin to yead...
230
230
767
19
210
sandertyu/Simple-Geometry-Plot
bicycleparameters/rider.py
Python
configure_rider
configure_rider
68
145
68
68
10ed8a654408a3c2dea6dd2a43256e91c95f9c19
bigcode/the-stack
train
915879ab655adf8a8d868de6
train
function
def rider_on_bike(benchmarkPar, measuredPar, yeadonMeas, yeadonCFG, drawrider): """ Returns a yeadon human configured to sit on a bicycle. Parameters ---------- benchmarkPar : dictionary A dictionary containing the benchmark bicycle parameters. measuredPar : dictionary...
def rider_on_bike(benchmarkPar, measuredPar, yeadonMeas, yeadonCFG, drawrider):
""" Returns a yeadon human configured to sit on a bicycle. Parameters ---------- benchmarkPar : dictionary A dictionary containing the benchmark bicycle parameters. measuredPar : dictionary A dictionary containing the raw geometric measurements of the bicycle. yeadonMeas : s...
Par) # build a dictionary to store the inertial data riderPar = {'IBxx': human_inertia_in_bike_frame[0, 0], 'IByy': human_inertia_in_bike_frame[1, 1], 'IBzz': human_inertia_in_bike_frame[2, 2], 'IBxz': human_inertia_in_bike_frame[2, 0], ...
256
256
2,493
28
227
sandertyu/Simple-Geometry-Plot
bicycleparameters/rider.py
Python
rider_on_bike
rider_on_bike
148
361
148
149
59b5f4e32ed2f37a7a9a960a097aa566041387b6
bigcode/the-stack
train
3d0b87b34f8fa510429c23a7
train
function
def yeadon_vec_to_bicycle_vec(vector, measured_bicycle_par, benchmark_bicycle_par): """ Parameters ---------- vector : np.matrix, shape(3, 1) A vector from the Yeadon origin to a point expressed in the Yeadon reference frame. measured_bicycle_par : dicti...
def yeadon_vec_to_bicycle_vec(vector, measured_bicycle_par, benchmark_bicycle_par):
""" Parameters ---------- vector : np.matrix, shape(3, 1) A vector from the Yeadon origin to a point expressed in the Yeadon reference frame. measured_bicycle_par : dictionary The raw bicycle measurements. benchmark_bicycle_par : dictionary The Meijaard 2007 et. a...
#!/usr/bin/env python import os import numpy as np from numpy import sin, cos, sqrt from scipy.optimize import fsolve import yeadon from .io import remove_uncertainties from .inertia import combine_bike_rider def yeadon_vec_to_bicycle_vec(vector, measured_bicycle_par, benchmark_bicycle_p...
77
149
498
22
54
sandertyu/Simple-Geometry-Plot
bicycleparameters/rider.py
Python
yeadon_vec_to_bicycle_vec
yeadon_vec_to_bicycle_vec
13
65
13
14
9e621cd06a72d19053f72e3e1b2feefe55c6fd82
bigcode/the-stack
train
13ae0e04716c14001c6ce6e7
train
function
def find_between(s, start, end): try: return (s.split(start))[1].split(end)[0] except: return False
def find_between(s, start, end):
try: return (s.split(start))[1].split(end)[0] except: return False
import mido from mido import MidiFile, Message, tempo2bpm, MidiTrack,MetaMessage from neopixel import * import argparse import time import RPi.GPIO as GPIO def find_between(s, start, end):
51
64
33
9
41
arpyman/Piano-LED-Visualizer
tests/minilightkeys.py
Python
find_between
find_between
9
13
9
9
71041ea49212a09ee0b1915e92ab6790eacfdc14
bigcode/the-stack
train
06b10649f61e783c2f5518f5
train
function
def colorWipe(strip, color, wait_ms=50): """Wipe color across display a pixel at a time.""" for i in range(strip.numPixels()): strip.setPixelColor(i, color) strip.show() time.sleep(wait_ms/1000.0)
def colorWipe(strip, color, wait_ms=50):
"""Wipe color across display a pixel at a time.""" for i in range(strip.numPixels()): strip.setPixelColor(i, color) strip.show() time.sleep(wait_ms/1000.0)
from neopixel import * import argparse import time import RPi.GPIO as GPIO def find_between(s, start, end): try: return (s.split(start))[1].split(end)[0] except: return False def colorWipe(strip, color, wait_ms=50):
64
64
60
13
50
arpyman/Piano-LED-Visualizer
tests/minilightkeys.py
Python
colorWipe
colorWipe
14
19
14
14
d0f2c73d5bec5cbfcdd424f036d2aface80c0120
bigcode/the-stack
train
b52ddec0c8f8c56682ca8c71
train
function
def visibility_define(config): """Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty string).""" hide = '__attribute__((visibility("hidden")))' if config.check_gcc_function_attribute(hide, 'hideme'): return hide else: return ''
def visibility_define(config):
"""Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty string).""" hide = '__attribute__((visibility("hidden")))' if config.check_gcc_function_attribute(hide, 'hideme'): return hide else: return ''
_func("exp", libraries=libs, decl=True, call=True): mathlibs = libs break else: raise EnvironmentError("math library missing; rerun " "setup.py after setting the " "MATHLIB env variable") return mathlibs def visibility...
64
64
65
5
58
PacktPublishing/Supercharge-Your-Applications-with-GraalVM
Chapter08/python/ab-env/lib/python3.8/site-packages/numpy-1.16.4-py3.8-macosx-10.16-x86_64.egg/numpy/core/setup.py
Python
visibility_define
visibility_define
379
386
379
379
7bc6e98803a2000c5235ed9ab51c2fb4ffefacbd
bigcode/the-stack
train
c9350b1039c47b9736b8f2f7
train
function
def win32_checks(deflist): from numpy.distutils.misc_util import get_build_architecture a = get_build_architecture() # Distutils hack on AMD64 on windows print('BUILD_ARCHITECTURE: %r, os.name=%r, sys.platform=%r' % (a, os.name, sys.platform)) if a == 'AMD64': deflist.append('DIST...
def win32_checks(deflist):
from numpy.distutils.misc_util import get_build_architecture a = get_build_architecture() # Distutils hack on AMD64 on windows print('BUILD_ARCHITECTURE: %r, os.name=%r, sys.platform=%r' % (a, os.name, sys.platform)) if a == 'AMD64': deflist.append('DISTUTILS_USE_SDK') # On w...
# are actually multiple CPUS? -- but # threaded code can be nice even on a single # CPU so that long-calculating code doesn't # block. return 'NPY_NOSMP' in os.environ def win32_checks(deflist):
64
64
161
7
56
PacktPublishing/Supercharge-Your-Applications-with-GraalVM
Chapter08/python/ab-env/lib/python3.8/site-packages/numpy-1.16.4-py3.8-macosx-10.16-x86_64.egg/numpy/core/setup.py
Python
win32_checks
win32_checks
92
106
92
92
52deaf02c635cddbc653b1649926832aecad2ee9
bigcode/the-stack
train
a5814e627f92d0264860a9f3
train
function
def is_npy_no_signal(): """Return True if the NPY_NO_SIGNAL symbol must be defined in configuration header.""" return sys.platform == 'win32'
def is_npy_no_signal():
"""Return True if the NPY_NO_SIGNAL symbol must be defined in configuration header.""" return sys.platform == 'win32'
.loads(self._check_complex)) return out def pythonlib_dir(): """return path where libpython* is.""" if sys.platform == 'win32': return os.path.join(sys.prefix, "libs") else: return get_config_var('LIBDIR') def is_npy_no_signal():
64
64
36
7
57
PacktPublishing/Supercharge-Your-Applications-with-GraalVM
Chapter08/python/ab-env/lib/python3.8/site-packages/numpy-1.16.4-py3.8-macosx-10.16-x86_64.egg/numpy/core/setup.py
Python
is_npy_no_signal
is_npy_no_signal
76
79
76
76
774ceacf10c775d5dacbf8b9c77a16c7a415cb40
bigcode/the-stack
train
ef7743be60077ea38e5b2d6d
train
function
def pythonlib_dir(): """return path where libpython* is.""" if sys.platform == 'win32': return os.path.join(sys.prefix, "libs") else: return get_config_var('LIBDIR')
def pythonlib_dir():
"""return path where libpython* is.""" if sys.platform == 'win32': return os.path.join(sys.prefix, "libs") else: return get_config_var('LIBDIR')
_complex(self, *a, **kw): if self._check_complex is None: out = check_complex(*a, **kw) self._check_complex = pickle.dumps(out) else: out = copy.deepcopy(pickle.loads(self._check_complex)) return out def pythonlib_dir():
64
64
47
5
58
PacktPublishing/Supercharge-Your-Applications-with-GraalVM
Chapter08/python/ab-env/lib/python3.8/site-packages/numpy-1.16.4-py3.8-macosx-10.16-x86_64.egg/numpy/core/setup.py
Python
pythonlib_dir
pythonlib_dir
69
74
69
69
56e30d0836b1b70a8fe2f0bd8a43003e5cfb3f63
bigcode/the-stack
train
ede63cbcd9650c1d9d5521de
train
function
def check_complex(config, mathlibs): priv = [] pub = [] try: if os.uname()[0] == "Interix": warnings.warn("Disabling broken complex support. See #1365", stacklevel=2) return priv, pub except Exception: # os.uname not available on all platforms. blanket except ugl...
def check_complex(config, mathlibs):
priv = [] pub = [] try: if os.uname()[0] == "Interix": warnings.warn("Disabling broken complex support. See #1365", stacklevel=2) return priv, pub except Exception: # os.uname not available on all platforms. blanket except ugly but safe pass # Check ...
moredefs.append((fname2def(fn), 1)) for fn in OPTIONAL_VARIABLE_ATTRIBUTES: if config.check_gcc_variable_attribute(fn): m = fn.replace("(", "_").replace(")", "_") moredefs.append((fname2def(m), 1)) # C99 functions: float and long double versions check_funcs(C99_FUNCS_SINGL...
96
96
322
8
88
PacktPublishing/Supercharge-Your-Applications-with-GraalVM
Chapter08/python/ab-env/lib/python3.8/site-packages/numpy-1.16.4-py3.8-macosx-10.16-x86_64.egg/numpy/core/setup.py
Python
check_complex
check_complex
183
222
183
183
e1a84f9b44afbf9fd417780dbd7697903800d557
bigcode/the-stack
train
656b4e7662f76338944c949b
train
function
def check_ieee_macros(config): priv = [] pub = [] macros = [] def _add_decl(f): priv.append(fname2def("decl_%s" % f)) pub.append('NPY_%s' % fname2def("decl_%s" % f)) # XXX: hack to circumvent cpp pollution from python: python put its # config.h in the public namespace, so we h...
def check_ieee_macros(config):
priv = [] pub = [] macros = [] def _add_decl(f): priv.append(fname2def("decl_%s" % f)) pub.append('NPY_%s' % fname2def("decl_%s" % f)) # XXX: hack to circumvent cpp pollution from python: python put its # config.h in the public namespace, so we have a clash for the common ...
list, call=decl, decl=decl, libraries=mathlibs): for f in flist: if config.check_func(f, call=True, decl=True, libraries=mathlibs): priv.append((fname2def(f), 1)) e...
105
105
351
8
96
PacktPublishing/Supercharge-Your-Applications-with-GraalVM
Chapter08/python/ab-env/lib/python3.8/site-packages/numpy-1.16.4-py3.8-macosx-10.16-x86_64.egg/numpy/core/setup.py
Python
check_ieee_macros
check_ieee_macros
224
259
224
224
2b8ebed18708889a8a07ce95bed5cf1c1da0eef7
bigcode/the-stack
train
0a72ba7b9079d15891151970
train
function
def check_mathlib(config_cmd): # Testing the C math library mathlibs = [] mathlibs_choices = [[], ['m'], ['cpml']] mathlib = os.environ.get('MATHLIB') if mathlib: mathlibs_choices.insert(0, mathlib.split(',')) for libs in mathlibs_choices: if config_cmd.check_func("exp", librarie...
def check_mathlib(config_cmd): # Testing the C math library
mathlibs = [] mathlibs_choices = [[], ['m'], ['cpml']] mathlib = os.environ.get('MATHLIB') if mathlib: mathlibs_choices.insert(0, mathlib.split(',')) for libs in mathlibs_choices: if config_cmd.check_func("exp", libraries=libs, decl=True, call=True): mathlibs = libs ...
if not config_cmd.check_decl('CHAR_BIT', headers=['Python.h']): raise RuntimeError( "Config wo CHAR_BIT is not supported" ", please contact the maintainers") return private_defines, public_defines def check_mathlib(config_cmd): # Testing the C math library
64
64
136
15
48
PacktPublishing/Supercharge-Your-Applications-with-GraalVM
Chapter08/python/ab-env/lib/python3.8/site-packages/numpy-1.16.4-py3.8-macosx-10.16-x86_64.egg/numpy/core/setup.py
Python
check_mathlib
check_mathlib
362
377
362
363
6da802b14610ea4ae45d8ad7d3a1d4d377b901d1
bigcode/the-stack
train
4fd79cde6bea3502cc731e66
train
class
class CallOnceOnly(object): def __init__(self): self._check_types = None self._check_ieee_macros = None self._check_complex = None def check_types(self, *a, **kw): if self._check_types is None: out = check_types(*a, **kw) self._check_types = pickle.dumps(...
class CallOnceOnly(object):
def __init__(self): self._check_types = None self._check_ieee_macros = None self._check_complex = None def check_types(self, *a, **kw): if self._check_types is None: out = check_types(*a, **kw) self._check_types = pickle.dumps(out) else: ...
led-based memoize does not work because config_cmd is an instance # method, which cPickle does not like. # # Use pickle in all cases, as cPickle is gone in python3 and the difference # in time is only in build. -- Charles Harris, 2013-03-30 class CallOnceOnly(object):
72
72
241
6
65
PacktPublishing/Supercharge-Your-Applications-with-GraalVM
Chapter08/python/ab-env/lib/python3.8/site-packages/numpy-1.16.4-py3.8-macosx-10.16-x86_64.egg/numpy/core/setup.py
Python
CallOnceOnly
CallOnceOnly
39
67
39
39
8aa663ff2b9f67b4010bb70270d4d3d04689cf7d
bigcode/the-stack
train
120182b0ba178484d64f00fa
train
function
def is_npy_no_smp(): """Return True if the NPY_NO_SMP symbol must be defined in public header (when SMP support cannot be reliably enabled).""" # Perhaps a fancier check is in order here. # so that threads are only enabled if there # are actually multiple CPUS? -- but # threaded code can be n...
def is_npy_no_smp():
"""Return True if the NPY_NO_SMP symbol must be defined in public header (when SMP support cannot be reliably enabled).""" # Perhaps a fancier check is in order here. # so that threads are only enabled if there # are actually multiple CPUS? -- but # threaded code can be nice even on a single ...
.path.join(sys.prefix, "libs") else: return get_config_var('LIBDIR') def is_npy_no_signal(): """Return True if the NPY_NO_SIGNAL symbol must be defined in configuration header.""" return sys.platform == 'win32' def is_npy_no_smp():
64
64
118
8
56
PacktPublishing/Supercharge-Your-Applications-with-GraalVM
Chapter08/python/ab-env/lib/python3.8/site-packages/numpy-1.16.4-py3.8-macosx-10.16-x86_64.egg/numpy/core/setup.py
Python
is_npy_no_smp
is_npy_no_smp
81
90
81
81
75b605f29fe240cea3fb44cc87c1bb7e6e284a4b
bigcode/the-stack
train
436112f7e216d0f1eef66cf5
train
function
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration, dot_join from numpy.distutils.system_info import get_info config = Configuration('core', parent_package, top_path) local_dir = config.local_path codegen_dir = join(local_dir, 'code_generators') ...
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration, dot_join from numpy.distutils.system_info import get_info config = Configuration('core', parent_package, top_path) local_dir = config.local_path codegen_dir = join(local_dir, 'code_generators') if is_released(config): warnings.simple...
config_cmd.check_decl('CHAR_BIT', headers=['Python.h']): raise RuntimeError( "Config wo CHAR_BIT is not supported" ", please contact the maintainers") return private_defines, public_defines def check_mathlib(config_cmd): # Testing the C math library mathlibs = [] mathl...
256
256
5,728
9
247
PacktPublishing/Supercharge-Your-Applications-with-GraalVM
Chapter08/python/ab-env/lib/python3.8/site-packages/numpy-1.16.4-py3.8-macosx-10.16-x86_64.egg/numpy/core/setup.py
Python
configuration
configuration
388
972
388
388
f9bc0f63d97e20b67cf38a308d48f34143623eb5
bigcode/the-stack
train
62acc8480df96f0a9695827e
train
function
def check_math_capabilities(config, moredefs, mathlibs): def check_func(func_name): return config.check_func(func_name, libraries=mathlibs, decl=True, call=True) def check_funcs_once(funcs_name): decl = dict([(f, True) for f in funcs_name]) st = config.c...
def check_math_capabilities(config, moredefs, mathlibs):
def check_func(func_name): return config.check_func(func_name, libraries=mathlibs, decl=True, call=True) def check_funcs_once(funcs_name): decl = dict([(f, True) for f in funcs_name]) st = config.check_funcs_once(funcs_name, libraries=mathlibs, ...
-- but # threaded code can be nice even on a single # CPU so that long-calculating code doesn't # block. return 'NPY_NOSMP' in os.environ def win32_checks(deflist): from numpy.distutils.misc_util import get_build_architecture a = get_build_architecture() # Distutils hack on AMD64 on wi...
221
221
738
13
208
PacktPublishing/Supercharge-Your-Applications-with-GraalVM
Chapter08/python/ab-env/lib/python3.8/site-packages/numpy-1.16.4-py3.8-macosx-10.16-x86_64.egg/numpy/core/setup.py
Python
check_math_capabilities
check_math_capabilities
108
181
108
108
d8ef8a2132bc20b3b032c702a87c78b0ac83e7b0
bigcode/the-stack
train
f8770334dce609f983f37c5f
train
function
def check_types(config_cmd, ext, build_dir): private_defines = [] public_defines = [] # Expected size (in number of bytes) for each type. This is an # optimization: those are only hints, and an exhaustive search for the size # is done if the hints are wrong. expected = {'short': [2], 'int': [4]...
def check_types(config_cmd, ext, build_dir):
private_defines = [] public_defines = [] # Expected size (in number of bytes) for each type. This is an # optimization: those are only hints, and an exhaustive search for the size # is done if the hints are wrong. expected = {'short': [2], 'int': [4], 'long': [8, 4], 'float': [4...
tested by python's # autoconf, hoping their own test are correct _macros = ["isnan", "isinf", "signbit", "isfinite"] for f in _macros: py_symbol = fname2def("decl_%s" % f) already_declared = config.check_decl(py_symbol, headers=["Python.h", "math.h"]) if already_decl...
256
256
1,190
11
244
PacktPublishing/Supercharge-Your-Applications-with-GraalVM
Chapter08/python/ab-env/lib/python3.8/site-packages/numpy-1.16.4-py3.8-macosx-10.16-x86_64.egg/numpy/core/setup.py
Python
check_types
check_types
261
360
261
261
935b014b1ecad47e9976bffcdc06ffca64e5f83c
bigcode/the-stack
train
136ea1de3d114ee3491d1b8c
train
class
class ChiHousingAuthoritySpider(CityScrapersSpider): name = 'chi_housing_authority' agency = 'Chicago Housing Authority' timezone = 'America/Chicago' start_urls = [ 'http://www.thecha.org/about/board-meetings-agendas-and-resolutions/board-information-and-meetings', # noqa ] def parse(s...
class ChiHousingAuthoritySpider(CityScrapersSpider):
name = 'chi_housing_authority' agency = 'Chicago Housing Authority' timezone = 'America/Chicago' start_urls = [ 'http://www.thecha.org/about/board-meetings-agendas-and-resolutions/board-information-and-meetings', # noqa ] def parse(self, response): """ `parse` should al...
import re from datetime import datetime, time import scrapy from city_scrapers_core.constants import BOARD from city_scrapers_core.items import Meeting from city_scrapers_core.spiders import CityScrapersSpider class ChiHousingAuthoritySpider(CityScrapersSpider):
55
256
1,261
11
43
eabedrapo/city-scrapers
city_scrapers/spiders/chi_housing_authority.py
Python
ChiHousingAuthoritySpider
ChiHousingAuthoritySpider
10
144
10
10
0844ad0d4a2d3d55c3a4f3369826eb81015441e3
bigcode/the-stack
train
50c335a41a83450c434da64b
train
class
class A: def __init__(self, a): self.a = a def __gt__(self, other): if (self.a > other.a): return True else: return False
class A:
def __init__(self, a): self.a = a def __gt__(self, other): if (self.a > other.a): return True else: return False
from __future__ import print_function class A:
11
64
47
3
7
Sajaki/intellij-community
python/testData/debug/stepping/test_smart_step_into_comparison_operator.py
Python
A
A
4
12
4
4
1d6473e7cab0e13e7269798e0ef8fab6ce3efa85
bigcode/the-stack
train
c7294460d919acbd63aaf48b
train
class
class Exploit(FTPClient): __info__ = { "name": "Technicolor TG784n-v3 Auth Bypass", "description": "Module exploits Technicolor TG784n-v3 authentication bypass vulnerability.", "authors": ( "Jose Moreira", # vulnerability discovery & analysis "0BuRner", # routersplo...
class Exploit(FTPClient):
__info__ = { "name": "Technicolor TG784n-v3 Auth Bypass", "description": "Module exploits Technicolor TG784n-v3 authentication bypass vulnerability.", "authors": ( "Jose Moreira", # vulnerability discovery & analysis "0BuRner", # routersploit module "Mar...
import re from maza.core.exploit import * from maza.core.ftp.ftp_client import FTPClient class Exploit(FTPClient):
31
192
640
7
23
ArturSpirin/maza
maza/modules/exploits/routers/technicolor/tg784_authbypass.py
Python
Exploit
Exploit
6
72
6
6
f93a8f75a603fd4e2ee0b2616daeb60ad991e463
bigcode/the-stack
train
542defe0e9a7302323cc5973
train
function
def test_tensors_not_collated_exception(workers): """ Ensure that the sy.combine_pointers works as expected """ bob = workers["bob"] alice = workers["alice"] x = th.tensor([1, 2, 3, 4, 5]).send(bob) y = th.tensor([1, 2, 3, 4, 5]).send(alice) with pytest.raises(sy.exceptions.TensorsNot...
def test_tensors_not_collated_exception(workers):
""" Ensure that the sy.combine_pointers works as expected """ bob = workers["bob"] alice = workers["alice"] x = th.tensor([1, 2, 3, 4, 5]).send(bob) y = th.tensor([1, 2, 3, 4, 5]).send(alice) with pytest.raises(sy.exceptions.TensorsNotCollocatedException): b = x + y x = t...
import pytest import torch as th import syft as sy from syft.frameworks.torch.tensors.decorators import LoggingTensor def test_tensors_not_collated_exception(workers):
39
92
309
11
27
amitkarn3/PythnSyft
test/test_exceptions.py
Python
test_tensors_not_collated_exception
test_tensors_not_collated_exception
8
38
8
8
e95bff4005df03ed3f743ccb76e179cc2b709c3c
bigcode/the-stack
train
5f042df251ac62e515fcafab
train
function
def cleanup_keyring(keyring: TempKeyring): keyring.cleanup()
def cleanup_keyring(keyring: TempKeyring):
keyring.cleanup()
from ecostake.util.errors import Err from ecostake.util.ints import uint32 from tests.block_tools import create_block_tools, test_constants from tests.util.keyring import TempKeyring from .ram_db import create_ram_blockchain def cleanup_keyring(keyring: TempKeyring):
64
64
16
11
52
Ecostake-Network/ecostake-blockchain
tests/core/full_node/test_conditions.py
Python
cleanup_keyring
cleanup_keyring
35
36
35
35
0340ebc6a3a373e5010ae24972b0efeb56c473eb
bigcode/the-stack
train
b3c8e22e408c690299564154
train
class
class TestConditions: @pytest.mark.asyncio async def test_invalid_block_age(self): conditions = Program.to(assemble(f"(({ConditionOpcode.ASSERT_HEIGHT_RELATIVE[0]} 2))")) await check_conditions(conditions, expected_err=Err.ASSERT_HEIGHT_RELATIVE_FAILED) @pytest.mark.asyncio async def te...
class TestConditions: @pytest.mark.asyncio
async def test_invalid_block_age(self): conditions = Program.to(assemble(f"(({ConditionOpcode.ASSERT_HEIGHT_RELATIVE[0]} 2))")) await check_conditions(conditions, expected_err=Err.ASSERT_HEIGHT_RELATIVE_FAILED) @pytest.mark.asyncio async def test_valid_block_age(self): conditions = ...
_block_result == ReceiveBlockResult.NEW_PEAK assert fork_height == len(blocks) - 1 else: assert err == expected_err assert received_block_result == ReceiveBlockResult.INVALID_BLOCK assert fork_height is None return coins_added, coins_removed finally:...
256
256
1,084
11
245
Ecostake-Network/ecostake-blockchain
tests/core/full_node/test_conditions.py
Python
TestConditions
TestConditions
132
229
132
133
f2211d974debdc241af77631210039fccd37bbde
bigcode/the-stack
train
5f2f580ba97bf585be458958
train
function
def initial_blocks(block_count: int = 4) -> List[FullBlock]: blocks = bt.get_consecutive_blocks( block_count, guarantee_transaction_block=True, farmer_reward_puzzle_hash=EASY_PUZZLE_HASH, pool_reward_puzzle_hash=EASY_PUZZLE_HASH, ) return blocks
def initial_blocks(block_count: int = 4) -> List[FullBlock]:
blocks = bt.get_consecutive_blocks( block_count, guarantee_transaction_block=True, farmer_reward_puzzle_hash=EASY_PUZZLE_HASH, pool_reward_puzzle_hash=EASY_PUZZLE_HASH, ) return blocks
the `EASY_PUZZLE` because it's pretty easy to solve. EASY_PUZZLE = Program.to(assemble("1")) EASY_PUZZLE_HASH = EASY_PUZZLE.get_tree_hash() def initial_blocks(block_count: int = 4) -> List[FullBlock]:
64
64
72
17
47
Ecostake-Network/ecostake-blockchain
tests/core/full_node/test_conditions.py
Python
initial_blocks
initial_blocks
55
62
55
55
891b9cd891543dc6e844754c040bd9b3f180cf70
bigcode/the-stack
train
045851324cb76bfe12a67320
train
function
async def check_conditions( condition_solution: Program, expected_err: Optional[Err] = None, spend_reward_index: int = -2 ): blocks = initial_blocks() coin = list(blocks[spend_reward_index].get_included_reward_coins())[0] coin_spend = CoinSpend(coin, EASY_PUZZLE, condition_solution) spend_bundle = ...
async def check_conditions( condition_solution: Program, expected_err: Optional[Err] = None, spend_reward_index: int = -2 ):
blocks = initial_blocks() coin = list(blocks[spend_reward_index].get_included_reward_coins())[0] coin_spend = CoinSpend(coin, EASY_PUZZLE, condition_solution) spend_bundle = SpendBundle([coin_spend], G2Element()) # now let's try to create a block with the spend bundle and ensure that it doesn't va...
ly await connection.close() # we must call `shut_down` or the executor in `Blockchain` doesn't stop blockchain.shut_down() async def check_conditions( condition_solution: Program, expected_err: Optional[Err] = None, spend_reward_index: int = -2 ):
64
64
134
31
33
Ecostake-Network/ecostake-blockchain
tests/core/full_node/test_conditions.py
Python
check_conditions
check_conditions
118
129
118
120
6ba0c3c6654e59df6d0c2c27ee52f220e483d3ef
bigcode/the-stack
train
21bec83e68dc086699bdd84b
train
function
async def check_spend_bundle_validity( constants: ConsensusConstants, blocks: List[FullBlock], spend_bundle: SpendBundle, expected_err: Optional[Err] = None, ) -> Tuple[List[CoinRecord], List[CoinRecord]]: """ This test helper create an extra block after the given blocks that contains the given ...
async def check_spend_bundle_validity( constants: ConsensusConstants, blocks: List[FullBlock], spend_bundle: SpendBundle, expected_err: Optional[Err] = None, ) -> Tuple[List[CoinRecord], List[CoinRecord]]:
""" This test helper create an extra block after the given blocks that contains the given `SpendBundle`, and then invokes `receive_block` to ensure that it's accepted (if `expected_err=None`) or fails with the correct error code. """ try: connection, blockchain = await create_ram_blockch...
(block_count: int = 4) -> List[FullBlock]: blocks = bt.get_consecutive_blocks( block_count, guarantee_transaction_block=True, farmer_reward_puzzle_hash=EASY_PUZZLE_HASH, pool_reward_puzzle_hash=EASY_PUZZLE_HASH, ) return blocks async def check_spend_bundle_validity( const...
123
123
412
54
68
Ecostake-Network/ecostake-blockchain
tests/core/full_node/test_conditions.py
Python
check_spend_bundle_validity
check_spend_bundle_validity
65
115
65
70
58d9b9bea282ff945a59facb2cab5db940ff39ee
bigcode/the-stack
train
4fa5a4b2cb70d359e2746739
train
class
class GraphQLException(Exception): """ Base class for GraphQL exceptions. Subclasses should provide `.status_code` and `.default_detail` properties. """ default_detail = "A server error occurred." default_code = "error" def __init__(self, detail=None, code=None): self.detail = deta...
class GraphQLException(Exception):
""" Base class for GraphQL exceptions. Subclasses should provide `.status_code` and `.default_detail` properties. """ default_detail = "A server error occurred." default_code = "error" def __init__(self, detail=None, code=None): self.detail = detail if detail is None: ...
class GraphQLException(Exception):
6
64
117
6
0
mfdeux/ariadne-utils
ariadne_utils/exceptions.py
Python
GraphQLException
GraphQLException
2
20
2
2
f637e686cbe5c553c4d147ff332b451e5e5b4904
bigcode/the-stack
train
7d471de0edf46dc550457534
train
function
def JINJA_CONFIG(): import jinja2 from django.conf import settings from caching.base import cache config = {'extensions': ['tower.template.i18n', 'caching.ext.cache', 'jinja2.ext.autoescape', 'jinja2.ext.with_'], 'finalize': lambda x: x if x is not None else ''...
def JINJA_CONFIG():
import jinja2 from django.conf import settings from caching.base import cache config = {'extensions': ['tower.template.i18n', 'caching.ext.cache', 'jinja2.ext.autoescape', 'jinja2.ext.with_'], 'finalize': lambda x: x if x is not None else ''} if (hasattr(ca...
.contrib.django', # Extra apps for testing. 'django_nose', 'test_utils', # Extra app for python migrations. 'django_extensions', # App for sample data 'eadred', ) TEST_RUNNER = 'test_utils.runner.RadicalTestSuiteRunner' def JINJA_CONFIG():
68
68
227
6
62
taliasman/kitsune
settings.py
Python
JINJA_CONFIG
JINJA_CONFIG
423
440
423
423
93bf0c0b6949f9c9522a17edb72986d9e69bdd83
bigcode/the-stack
train
573c9e9ba4eb36aa77d65ca4
train
function
def read_only_mode(env): env['READ_ONLY'] = True # Replace the default (master) db with a slave connection. if not env.get('SLAVE_DATABASES'): raise Exception("We need at least one slave database.") slave = env['SLAVE_DATABASES'][0] env['DATABASES']['default'] = env['DATABASES'][slave] ...
def read_only_mode(env):
env['READ_ONLY'] = True # Replace the default (master) db with a slave connection. if not env.get('SLAVE_DATABASES'): raise Exception("We need at least one slave database.") slave = env['SLAVE_DATABASES'][0] env['DATABASES']['default'] = env['DATABASES'][slave] # No sessions without th...
/products/' # Email EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Read-only mode setup. READ_ONLY = False # Turn on read-only mode in settings_local.py by putting this line # at the VERY BOTTOM: read_only_mode(globals()) def read_only_mode(env):
64
64
180
6
58
taliasman/kitsune
settings.py
Python
read_only_mode
read_only_mode
877
894
877
877
275b10bcb341f56b1c209151392a6944d3c4633a
bigcode/the-stack
train
c6e7b2ee24902c6c15a2d22c
train
class
class ImageScalarSiamese(BasicImageSiamese): r""" Siamese model that uses both images and scalar values as input. It uses scalar features extracted with PyRadiomics and provided through a Tensorflow ``placeholder``, the model assumes that there are :any:`settings.NUMBER_FEATURES` for each input. :...
class ImageScalarSiamese(BasicImageSiamese):
r""" Siamese model that uses both images and scalar values as input. It uses scalar features extracted with PyRadiomics and provided through a Tensorflow ``placeholder``, the model assumes that there are :any:`settings.NUMBER_FEATURES` for each input. :param learning_rate: :param gpu_level: Am...
method ``BasicSiamese._fc_layers`` :param x: Image, usually previously filtered with the convolutional layers. :return: Tensor with shape ``[batch, 1]`` """ device = '/gpu:0' if self._gpu_level >= 3 else '/cpu:0' self.logger.debug(f"Using device: {device} for FC layers") ...
256
256
1,686
13
242
bhklab/DeepCINET
Sources/models/siameses.py
Python
ImageScalarSiamese
ImageScalarSiamese
393
589
393
393
0c056d5f460c73a83f2f8d0e8d5beed4e7fb7f6a
bigcode/the-stack
train
bc795d72636ea6e792513925
train
class
class ScalarOnlyDropoutSiamese(ScalarOnlySiamese): def __init__(self, **kwargs): super().__init__(**kwargs) def _sister(self): # Out: [batch, 500] x = self.x_scalar x = self._dense( x, 500, "fc1" ) x = tf.layers.dropout( ...
class ScalarOnlyDropoutSiamese(ScalarOnlySiamese):
def __init__(self, **kwargs): super().__init__(**kwargs) def _sister(self): # Out: [batch, 500] x = self.x_scalar x = self._dense( x, 500, "fc1" ) x = tf.layers.dropout( x, rate=self._dropout, ...
"]), } def uses_images(self) -> bool: """ Implementation of :func:`BasicModel.uses_images`. This model does not uses images to work. :return: :any:`False` since this model does not use images to work """ return False class ScalarOnlyDropoutSiamese(ScalarOnlySiamese)...
75
75
253
15
59
bhklab/DeepCINET
Sources/models/siameses.py
Python
ScalarOnlyDropoutSiamese
ScalarOnlyDropoutSiamese
1,030
1,084
1,030
1,031
adddffdd00d4e853edc88e8d9505c59055192a74
bigcode/the-stack
train
55d7da8bdaa2748cc5064a6a
train
class
class VolumeOnlySiamese(BasicSiamese): r""" Model that only uses the volume radiomic feature The features are provided by the package from `PyRadiomics <https://github.com/Radiomics/pyradiomics>`_ It trains a model in the form :math:`y = w \cdot V + b` **Attributes**: Includes the same attri...
class VolumeOnlySiamese(BasicSiamese):
r""" Model that only uses the volume radiomic feature The features are provided by the package from `PyRadiomics <https://github.com/Radiomics/pyradiomics>`_ It trains a model in the form :math:`y = w \cdot V + b` **Attributes**: Includes the same attributes as :class:`BasicSiamese` and adds...
=self._dropout, training=self.training ) # Out: [batch, 50] x = self._dense( x, 50, "fc3" ) x = tf.layers.dropout( x, rate=self._dropout, training=self.training ) # Out: [batch,...
120
120
401
12
107
bhklab/DeepCINET
Sources/models/siameses.py
Python
VolumeOnlySiamese
VolumeOnlySiamese
1,087
1,136
1,087
1,087
f9445a22df390e2636f0148c95cf7082ecf9234f
bigcode/the-stack
train
ce1ef3269c6fe88cffe08d11
train
class
class ResidualImageScalarSiamese(ImageScalarSiamese): def __init__(self, **kwargs): self.residual_count_a = 0 self.residual_count_b = 0 super().__init__(**kwargs) def _conv_layers(self, x: tf.Tensor) -> tf.Tensor: device = '/gpu:0' if self._gpu_level >= 1 else '/cpu:0' ...
class ResidualImageScalarSiamese(ImageScalarSiamese):
def __init__(self, **kwargs): self.residual_count_a = 0 self.residual_count_b = 0 super().__init__(**kwargs) def _conv_layers(self, x: tf.Tensor) -> tf.Tensor: device = '/gpu:0' if self._gpu_level >= 1 else '/cpu:0' with tf.device(device): x = self._stem_blo...
) def _dense(self, x: tf.Tensor, units: int, name: str, activation=tf.nn.relu) -> tf.Tensor: return tf.layers.dense( x, units=units, activation=activation, kernel_initializer=tf.contrib.layers.xavier_initializer(), kernel_regularizer=tf.contrib.l...
256
256
2,379
14
242
bhklab/DeepCINET
Sources/models/siameses.py
Python
ResidualImageScalarSiamese
ResidualImageScalarSiamese
592
939
592
593
49a0e912d1870c6de0e6ff801102f8f490fd1174
bigcode/the-stack
train
5219c6f356469959a9104470
train
class
class ScalarOnlySiamese(BasicSiamese): r""" Model that uses only radiomic features as input to train It has the same parameters as :class:`BasicSiamese` It only uses the radiomic features obtained with `PyRadiomics <https://github.com/Radiomics/pyradiomics>`_ **Attributes**: Includes the sam...
class ScalarOnlySiamese(BasicSiamese):
r""" Model that uses only radiomic features as input to train It has the same parameters as :class:`BasicSiamese` It only uses the radiomic features obtained with `PyRadiomics <https://github.com/Radiomics/pyradiomics>`_ **Attributes**: Includes the same attributes as :class:`BasicSiamese` a...
1", filters=50, kernel_size=1, padding="same" ) x_d = self._conv3d( x=x_d, name="d_1_conv_3x3", filters=50, kernel_size=3, padding="same" ) x_...
170
170
569
12
158
bhklab/DeepCINET
Sources/models/siameses.py
Python
ScalarOnlySiamese
ScalarOnlySiamese
942
1,027
942
942
76a3a64b5b95977d2f4bc24c5f6ff9a3a2753618
bigcode/the-stack
train
e30088d77d214ceb89ea4c83
train
class
class ImageSiamese(BasicImageSiamese): """ Class representing the initial and simple siamese structure used for the first steps of the project. It inherits :any:`BasicSiamese` so it has the same tensors to be fed. **Convolutional Model**: It contains parallel in inception_block and 3 FC layers ...
class ImageSiamese(BasicImageSiamese):
""" Class representing the initial and simple siamese structure used for the first steps of the project. It inherits :any:`BasicSiamese` so it has the same tensors to be fed. **Convolutional Model**: It contains parallel in inception_block and 3 FC layers """ def __init__(self, **kwargs)...
ese` class creates a model that combines the image input with the scalar input of the radiomic features, extracted with PyRadiomics. - The :class:`ResidualImageScalarSiamese` class creates a model that combines the image input with the scalar input but it also uses a residual network to fit the images. It als...
256
256
1,420
12
243
bhklab/DeepCINET
Sources/models/siameses.py
Python
ImageSiamese
ImageSiamese
33
269
33
33
d771979e38318ec70c7ec316757162faa0b8d3d0
bigcode/the-stack
train
7e025133de34fe06907b1912
train
class
class SimpleImageSiamese(BasicImageSiamese): r""" Simple siamese network implementation that uses images as input. Has the same parameters as :class:`BasicImageSiamese` **Convolutional Model**: It contains 4 convolutional layers and 3 FC layers - :math:`3^3` kernel with 30 filters and st...
class SimpleImageSiamese(BasicImageSiamese):
r""" Simple siamese network implementation that uses images as input. Has the same parameters as :class:`BasicImageSiamese` **Convolutional Model**: It contains 4 convolutional layers and 3 FC layers - :math:`3^3` kernel with 30 filters and stride = 2 - :math:`3^3` kernel with 40...
= '/gpu:0' if self._gpu_level >= 3 else '/cpu:0' self.logger.debug(f"Using device: {device} for FC layers") with tf.device(device): # Out: [batch, 64*64*64*1] x = tf.layers.flatten( x, name="flat" ) # Out: [batch, 100] ...
256
256
901
13
242
bhklab/DeepCINET
Sources/models/siameses.py
Python
SimpleImageSiamese
SimpleImageSiamese
272
390
272
272
0f295ee36f0b6e6bf93fb29f6dbd5022f384bbc1
bigcode/the-stack
train
800a57ef8a9f9fca6da5c9ec
train
function
def build_d_sources_with_gdc(source_dir, output_dir, compiler_executable): build_command = [ compiler_executable, '-O3', '-m64', '-fno-bounds-check', '-frelease', '-o' + os.path.join(output_dir, common.EXECUTABLE_NAME), '-I' + os.path.join(common.COMMON_DIR_PA...
def build_d_sources_with_gdc(source_dir, output_dir, compiler_executable):
build_command = [ compiler_executable, '-O3', '-m64', '-fno-bounds-check', '-frelease', '-o' + os.path.join(output_dir, common.EXECUTABLE_NAME), '-I' + os.path.join(common.COMMON_DIR_PATH, 'lang_d'), ] d_source_files = glob.glob(os.path.join(source_dir...
' + os.path.join(output_dir, common.EXECUTABLE_NAME), '-I' + os.path.join(common.COMMON_DIR_PATH, 'lang_d'), os.path.join(source_dir, 'main.d') ]) def build_d_sources_with_gdc(source_dir, output_dir, compiler_executable):
63
64
140
17
46
kennyalive/language-arena
framework/lang_d.py
Python
build_d_sources_with_gdc
build_d_sources_with_gdc
38
51
38
38
e00ee92dc4f75e711042df0f8c32c30cf2488971
bigcode/the-stack
train
1cbaa4e9c76dceccdbb7e1a2
train
function
def get_dmd_version(rdmd_path): dmd_executable_name = 'dmd.exe' if os.name == 'nt' else 'dmd' dmd_path = os.path.join(os.path.dirname(rdmd_path), dmd_executable_name) return common.get_first_line_from_command_output([dmd_path, '--version'])
def get_dmd_version(rdmd_path):
dmd_executable_name = 'dmd.exe' if os.name == 'nt' else 'dmd' dmd_path = os.path.join(os.path.dirname(rdmd_path), dmd_executable_name) return common.get_first_line_from_command_output([dmd_path, '--version'])
import common import glob import os import subprocess def get_dmd_version(rdmd_path):
21
64
71
9
11
kennyalive/language-arena
framework/lang_d.py
Python
get_dmd_version
get_dmd_version
7
10
7
7
7f1661db323f176eed434bf3f65c8268fe775d7d
bigcode/the-stack
train
ba93900cf2cf8b0f3579a1b8
train
function
def build_d_sources_with_ldc(source_dir, output_dir, compiler_executable): build_command = [ compiler_executable, '-O3', '-m64', '-release', '-boundscheck=off', '-singleobj', '-od' + output_dir, '-of' + os.path.join(output_dir, common.EXECUTABLE_NAME),...
def build_d_sources_with_ldc(source_dir, output_dir, compiler_executable):
build_command = [ compiler_executable, '-O3', '-m64', '-release', '-boundscheck=off', '-singleobj', '-od' + output_dir, '-of' + os.path.join(output_dir, common.EXECUTABLE_NAME), '-I' + os.path.join(common.COMMON_DIR_PATH, 'lang_d') ] d_...
glob.glob(os.path.join(source_dir, '*.d')) d_source_files.append(os.path.join(common.COMMON_DIR_PATH, 'lang_d', 'common.d')) build_command.extend(d_source_files) subprocess.call(build_command) def build_d_sources_with_ldc(source_dir, output_dir, compiler_executable):
64
64
151
17
47
kennyalive/language-arena
framework/lang_d.py
Python
build_d_sources_with_ldc
build_d_sources_with_ldc
54
69
54
54
217cd17baa483108af1a5d8e2709cf948c791c4e
bigcode/the-stack
train
55a64db1eac654d9174451d9
train
function
def get_gdc_version(compiler_executable): return common.get_first_line_from_command_output([compiler_executable, '--version'])
def get_gdc_version(compiler_executable):
return common.get_first_line_from_command_output([compiler_executable, '--version'])
md.exe' if os.name == 'nt' else 'dmd' dmd_path = os.path.join(os.path.dirname(rdmd_path), dmd_executable_name) return common.get_first_line_from_command_output([dmd_path, '--version']) def get_gdc_version(compiler_executable):
63
64
27
10
53
kennyalive/language-arena
framework/lang_d.py
Python
get_gdc_version
get_gdc_version
13
14
13
13
e515496f3fc4cb647ee352e2c370fc6583fb731e
bigcode/the-stack
train
b05b56b066593add2024b71b
train
function
def get_ldc_version(compiler_executable): lines = common.get_command_output([compiler_executable, '--version']) return ' '.join(map(str.strip, lines[:2]))
def get_ldc_version(compiler_executable):
lines = common.get_command_output([compiler_executable, '--version']) return ' '.join(map(str.strip, lines[:2]))
_path), dmd_executable_name) return common.get_first_line_from_command_output([dmd_path, '--version']) def get_gdc_version(compiler_executable): return common.get_first_line_from_command_output([compiler_executable, '--version']) def get_ldc_version(compiler_executable):
63
64
38
10
53
kennyalive/language-arena
framework/lang_d.py
Python
get_ldc_version
get_ldc_version
17
19
17
17
577006a323f1e4af19e3744b73272b2243508d0a
bigcode/the-stack
train
34bea6f6241bb58a57ffc9ce
train
function
def build_d_sources_with_dmd(source_dir, output_dir, compiler_executable): subprocess.call([ compiler_executable, '--build-only', '-O', '-inline', '-release', '-m64', '-boundscheck=off', '-od' + output_dir, '-of' + os.path.join(output_dir, comm...
def build_d_sources_with_dmd(source_dir, output_dir, compiler_executable):
subprocess.call([ compiler_executable, '--build-only', '-O', '-inline', '-release', '-m64', '-boundscheck=off', '-od' + output_dir, '-of' + os.path.join(output_dir, common.EXECUTABLE_NAME), '-I' + os.path.join(common.COMMON_DIR_PATH, 'l...
compiler_executable, '--version']) def get_ldc_version(compiler_executable): lines = common.get_command_output([compiler_executable, '--version']) return ' '.join(map(str.strip, lines[:2])) def build_d_sources_with_dmd(source_dir, output_dir, compiler_executable):
63
64
112
17
46
kennyalive/language-arena
framework/lang_d.py
Python
build_d_sources_with_dmd
build_d_sources_with_dmd
22
35
22
22
7f466cd61212c743ac2b9cf0df5f08724e1b3556
bigcode/the-stack
train
f122a5762c063963bff372bb
train
class
class S4Conic(S4OpticalSurface): def __init__(self, ccc=numpy.zeros(10)): if ccc is not None: self.ccc = ccc.copy() else: self.ccc = numpy.zeros(10) @classmethod def initialize_from_coefficients(cls, ccc): if numpy.array(ccc).size != 10: raise E...
class S4Conic(S4OpticalSurface):
def __init__(self, ccc=numpy.zeros(10)): if ccc is not None: self.ccc = ccc.copy() else: self.ccc = numpy.zeros(10) @classmethod def initialize_from_coefficients(cls, ccc): if numpy.array(ccc).size != 10: raise Exception("Invalid coefficients (di...
import numpy from shadow4.optical_surfaces.s4_optical_surface import S4OpticalSurface from shadow4.tools.arrayofvectors import vector_refraction from numpy.testing import assert_equal, assert_almost_equal # OE surface in form of conic equation: # ccc[0]*X^2 + ccc[1]*Y^2 + ccc[2]*Z^2 + # ccc[3]*X*Y + ccc[...
161
256
13,200
11
149
srio/minishadow
shadow4/optical_surfaces/s4_conic.py
Python
S4Conic
S4Conic
16
1,096
16
17
2fb02bc313d36aa7e80a4034f0dd8f3b9cebf02d
bigcode/the-stack
train
897577b7ac59963b10b1a220
train
class
class Migration(migrations.Migration): dependencies = [ ('dictdata', '0007_jaword_fcreater'), ] operations = [ migrations.AlterField( model_name='cnword', name='fwordclass', field=models.CharField(max_length=12, null=True, blank=True), ), ...
class Migration(migrations.Migration):
dependencies = [ ('dictdata', '0007_jaword_fcreater'), ] operations = [ migrations.AlterField( model_name='cnword', name='fwordclass', field=models.CharField(max_length=12, null=True, blank=True), ), migrations.AlterField( mode...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
31
64
180
7
23
szatjp/rabbitplan
dictdata/migrations/0008_auto_20161209_2341.py
Python
Migration
Migration
7
33
7
8
a3ef5e88968c172a44d0d1c800cada0ee01210fa
bigcode/the-stack
train
4ff87a5a36b0826bcf5241ae
train
function
def encode_multipart_formdata(fields, boundary=None): """ Encode a dictionary of ``fields`` using the multipart/form-data mime format. :param fields: Dictionary of fields. The key is treated as the field name, and the value as the body of the form-data. If the value is a tuple of two ...
def encode_multipart_formdata(fields, boundary=None):
""" Encode a dictionary of ``fields`` using the multipart/form-data mime format. :param fields: Dictionary of fields. The key is treated as the field name, and the value as the body of the form-data. If the value is a tuple of two elements, then the first element is treated as the f...
urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import codecs import mimetools import mimetypes try: from io import StringIO except ImportError: from io import StringIO # pylint: disable-msg=W0404 writer = codecs.lookup('utf-8')[3] def get_content_type(...
110
110
369
11
99
archiephan78/py3TOP
pyTOP/packages/requests/packages/urllib3/filepost.py
Python
encode_multipart_formdata
encode_multipart_formdata
24
71
24
24
99d9e5de1b6b2b93e8f0708c218f752eb71d46b8
bigcode/the-stack
train
00449010191e506d0cc9db9a
train
function
def get_content_type(filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
def get_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
/licenses/mit-license.php import codecs import mimetools import mimetypes try: from io import StringIO except ImportError: from io import StringIO # pylint: disable-msg=W0404 writer = codecs.lookup('utf-8')[3] def get_content_type(filename):
64
64
24
6
58
archiephan78/py3TOP
pyTOP/packages/requests/packages/urllib3/filepost.py
Python
get_content_type
get_content_type
20
21
20
20
8036dd998c8c8849ab4d1562e42f659edfd9cb00
bigcode/the-stack
train
a43f878b1a61ef9bdeca4076
train
function
def create_logger() -> logging.Logger: logger = logging.getLogger("helo") console_handler = logging.StreamHandler(sys.stderr) console_handler.setFormatter(ColoredFormatter()) if logger.level == logging.NOTSET: logger.setLevel(logging.INFO) logger.addHandler(console_handler) return log...
def create_logger() -> logging.Logger:
logger = logging.getLogger("helo") console_handler = logging.StreamHandler(sys.stderr) console_handler.setFormatter(ColoredFormatter()) if logger.level == logging.NOTSET: logger.setLevel(logging.INFO) logger.addHandler(console_handler) return logger
import logging import sys from typing import Optional BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) def create_logger() -> logging.Logger:
42
64
63
8
34
at7h/trod
helo/_logging.py
Python
create_logger
create_logger
8
18
8
8
9fdade95b73fbfb04382422ff15ceac598be1878
bigcode/the-stack
train
c48ed74e225fa5a0c571261f
train
class
class ColoredFormatter(logging.Formatter): LOG_FORMAT = "[$TCS%(asctime)s$TCN] [%(levelname)s] %(message)s" DATE_FORMAT = "%Y-%m-%d %H:%M:%S" COLOR_SEQ = "\033[1;{}m" RESET_SEQ = "\033[0m" COLORS = { "WARNING": YELLOW, "DEBUG": BLUE, "INFO": GREEN, "ERROR": RED, ...
class ColoredFormatter(logging.Formatter):
LOG_FORMAT = "[$TCS%(asctime)s$TCN] [%(levelname)s] %(message)s" DATE_FORMAT = "%Y-%m-%d %H:%M:%S" COLOR_SEQ = "\033[1;{}m" RESET_SEQ = "\033[0m" COLORS = { "WARNING": YELLOW, "DEBUG": BLUE, "INFO": GREEN, "ERROR": RED, "CRITICAL": MAGENTA, } def __in...
import Optional BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) def create_logger() -> logging.Logger: logger = logging.getLogger("helo") console_handler = logging.StreamHandler(sys.stderr) console_handler.setFormatter(ColoredFormatter()) if logger.level == logging.NOTSET: ...
96
96
321
7
88
at7h/trod
helo/_logging.py
Python
ColoredFormatter
ColoredFormatter
21
60
21
21
d3b24bb142c4ab66a2dd5cdbfd23f3de332477e1
bigcode/the-stack
train
a73c4a89d8815dbba6fa54ff
train
class
class ChatbotConfig(AppConfig): name = 'ChatBot'
class ChatbotConfig(AppConfig):
name = 'ChatBot'
from django.apps import AppConfig class ChatbotConfig(AppConfig):
14
64
14
7
6
pk8742/ChatRoom
ChatBot/apps.py
Python
ChatbotConfig
ChatbotConfig
4
5
4
4
2049d8706878db800ddd6a5dc1ee0cc3aa67aa1b
bigcode/the-stack
train
4d3ba8935b5b8c9a0ac338dd
train
class
class Migration(migrations.Migration): dependencies = [ ('origins', '0021_auto_20210327_1707'), ] operations = [ migrations.RenameField( model_name='fossil', old_name='mptt_taxon', new_name='ttaxon', ), ]
class Migration(migrations.Migration):
dependencies = [ ('origins', '0021_auto_20210327_1707'), ] operations = [ migrations.RenameField( model_name='fossil', old_name='mptt_taxon', new_name='ttaxon', ), ]
# Generated by Django 2.2.19 on 2021-03-27 17:25 from django.db import migrations class Migration(migrations.Migration):
36
64
69
7
28
dennereed/paleocore
origins/migrations/0022_auto_20210327_1725.py
Python
Migration
Migration
6
18
6
7
7f9860d53246953b17d0863ca8d2838300d3a6ea
bigcode/the-stack
train
02331499f1ed5ff8e4fce317
train
function
def deploy_pystol(): """ Install Pystol from Python. This is a main component of the input for the controller """ load_kubernetes_config() v1 = kubernetes.client.CoreV1Api() deployment = kubernetes.client.AppsV1Api() rbac = kubernetes.client.RbacAuthorizationV1Api() apicli = kuberne...
def deploy_pystol():
""" Install Pystol from Python. This is a main component of the input for the controller """ load_kubernetes_config() v1 = kubernetes.client.CoreV1Api() deployment = kubernetes.client.AppsV1Api() rbac = kubernetes.client.RbacAuthorizationV1Api() apicli = kubernetes.client.ApiClient(...
#!/usr/bin/env python """ Copyright 2019 Pystol (pystol.org). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agre...
207
256
1,239
6
201
ccamacho/pystol
pystol-operator/pystol/deployer.py
Python
deploy_pystol
deploy_pystol
35
161
35
35
3568ad05ea2ac16626f92d5e57d68e526ec03f6f
bigcode/the-stack
train
92e031b6e29dece6db0c6615
train
class
class Answer(object): def __init__(self, answer): self.answer = answer
class Answer(object):
def __init__(self, answer): self.answer = answer
Question(object): def __init__(self, question): self.question = question def addQuestion(self, packet, question): pass class Answers(object): def __init__(self): self.answers = {} def addAnswer(self, packet, answer): pass class Answer(object):
64
64
19
4
59
akmenon1996/intl-iot
destination/trafficAnalyser/DNSTracker.py
Python
Answer
Answer
34
37
34
35
e857c09273fec9903bd3180b0b55b44922043c17
bigcode/the-stack
train
6dca93cc9c974bebbfddb39f
train
class
class Record(object): def __init__(self): pass
class Record(object):
def __init__(self): pass
class Tracker(object): def __init__(self): pass class Record(object):
19
64
14
4
14
akmenon1996/intl-iot
destination/trafficAnalyser/DNSTracker.py
Python
Record
Record
8
11
8
9
dce357df45db697b8c6c0e1d64e6134e2414d637
bigcode/the-stack
train
dafe3ad5b9ffd3923ef869ec
train
class
class Tracker(object): def __init__(self): pass
class Tracker(object):
def __init__(self): pass
class Tracker(object):
4
64
14
4
0
akmenon1996/intl-iot
destination/trafficAnalyser/DNSTracker.py
Python
Tracker
Tracker
2
5
2
3
6bb2ad47310c466a97c42fa3c865bb7563de0a7e
bigcode/the-stack
train
92d078c987865356e1a10b4b
train
class
class Answers(object): def __init__(self): self.answers = {} def addAnswer(self, packet, answer): pass
class Answers(object):
def __init__(self): self.answers = {} def addAnswer(self, packet, answer): pass
(object): def __init__(self): pass class Questions(object): def __init__(self): self.questions = {} class Question(object): def __init__(self, question): self.question = question def addQuestion(self, packet, question): pass class Answers(object):
64
64
29
4
59
akmenon1996/intl-iot
destination/trafficAnalyser/DNSTracker.py
Python
Answers
Answers
26
32
26
27
7da3f65dd2850f9d3d1d047c254757ae890c512a
bigcode/the-stack
train
9853aef1dd939ab6243719e1
train
class
class Question(object): def __init__(self, question): self.question = question def addQuestion(self, packet, question): pass
class Question(object):
def __init__(self, question): self.question = question def addQuestion(self, packet, question): pass
class Tracker(object): def __init__(self): pass class Record(object): def __init__(self): pass class Questions(object): def __init__(self): self.questions = {} class Question(object):
49
64
32
4
45
akmenon1996/intl-iot
destination/trafficAnalyser/DNSTracker.py
Python
Question
Question
18
24
18
19
d87927bbca24a46d7fc4535a55a2995a6e05d675
bigcode/the-stack
train
cddd4b6e96c28b959d7251a4
train
class
class Questions(object): def __init__(self): self.questions = {}
class Questions(object):
def __init__(self): self.questions = {}
class Tracker(object): def __init__(self): pass class Record(object): def __init__(self): pass class Questions(object):
33
64
16
4
28
akmenon1996/intl-iot
destination/trafficAnalyser/DNSTracker.py
Python
Questions
Questions
13
16
13
14
87bf37594dfbbe6dc2c3b062608ce2e03bf39a6e
bigcode/the-stack
train
0e6ca6849af3fd45263c5922
train
class
class UserInfo(Service): msg_type = Message response_cls = oidc.OpenIDSchema error_msg = oidc.ResponseMessage endpoint_name = "userinfo_endpoint" synchronous = True service_name = "userinfo" default_authn_method = "bearer_header" http_method = "GET" metadata_attributes = { "...
class UserInfo(Service):
msg_type = Message response_cls = oidc.OpenIDSchema error_msg = oidc.ResponseMessage endpoint_name = "userinfo_endpoint" synchronous = True service_name = "userinfo" default_authn_method = "bearer_header" http_method = "GET" metadata_attributes = { "userinfo_signed_response_...
import logging from typing import Optional from typing import Union from idpyoidc.client.oauth2.utils import get_state_parameter from idpyoidc.client.service import Service from idpyoidc.exception import MissingSigningKey from idpyoidc.message import Message from idpyoidc.message import oidc logger = logging.getLogge...
189
256
868
5
184
IdentityPython/idpy-oidc
src/idpyoidc/client/oidc/userinfo.py
Python
UserInfo
UserInfo
31
161
31
31
ea743d68504a1aaa70566cb0298b8a7c30c5bd87
bigcode/the-stack
train
38a1533f972b0c2a0ce4152b
train
function
def carry_state(request_args=None, **kwargs): """ Make sure post_construct_methods have access to state :param request_args: :param kwargs: :return: The value of the state parameter """ return request_args, {"state": get_state_parameter(request_args, kwargs)}
def carry_state(request_args=None, **kwargs):
""" Make sure post_construct_methods have access to state :param request_args: :param kwargs: :return: The value of the state parameter """ return request_args, {"state": get_state_parameter(request_args, kwargs)}
.message import oidc logger = logging.getLogger(__name__) UI2REG = { "sigalg": "userinfo_signed_response_alg", "encalg": "userinfo_encrypted_response_alg", "encenc": "userinfo_encrypted_response_enc", } def carry_state(request_args=None, **kwargs):
64
64
63
10
54
IdentityPython/idpy-oidc
src/idpyoidc/client/oidc/userinfo.py
Python
carry_state
carry_state
20
28
20
20
9d0ec21c720c111aff835561240f9e0e2eb35cc3
bigcode/the-stack
train
e2be1a9381c1c48cb336f78e
train
function
def ProjectChannelInfo(project_channel_vo: ProjectChannel, minimal=False): info = { 'project_channel_id': project_channel_vo.project_channel_id, 'name': project_channel_vo.name, 'state': project_channel_vo.state } if not minimal: info.update({ 'data': change_stru...
def ProjectChannelInfo(project_channel_vo: ProjectChannel, minimal=False):
info = { 'project_channel_id': project_channel_vo.project_channel_id, 'name': project_channel_vo.name, 'state': project_channel_vo.state } if not minimal: info.update({ 'data': change_struct_type(project_channel_vo.data), 'secret_id': project_channel_...
ScheduleInfo(schedule_info): info = { 'day_of_week': schedule_info.day_of_week, 'start_hour': schedule_info.start_hour, 'end_hour': schedule_info.end_hour } return project_channel_pb2.ProjectChannelSchedule(**info) def ProjectChannelInfo(project_channel_vo: ProjectChannel, minimal=F...
69
69
232
14
55
whdalsrnt/notification
src/spaceone/notification/info/project_channel_info.py
Python
ProjectChannelInfo
ProjectChannelInfo
20
43
20
20
009e1292b8b65d5e7e57ec977b0186cd232f9745
bigcode/the-stack
train
c957965c9f6707091c6d4c23
train
function
def ProjectChannelsInfo(project_channel_vos, total_count, **kwargs): results = list(map(functools.partial(ProjectChannelInfo, **kwargs), project_channel_vos)) return project_channel_pb2.ProjectChannelsInfo(results=results, total_count=total_count)
def ProjectChannelsInfo(project_channel_vos, total_count, **kwargs):
results = list(map(functools.partial(ProjectChannelInfo, **kwargs), project_channel_vos)) return project_channel_pb2.ProjectChannelsInfo(results=results, total_count=total_count)
utils.datetime_to_iso8601(project_channel_vo.created_at), 'tags': change_struct_type(project_channel_vo.tags), 'domain_id': project_channel_vo.domain_id }) return project_channel_pb2.ProjectChannelInfo(**info) def ProjectChannelsInfo(project_channel_vos, total_count, **kwargs):
64
64
55
15
49
whdalsrnt/notification
src/spaceone/notification/info/project_channel_info.py
Python
ProjectChannelsInfo
ProjectChannelsInfo
46
48
46
46
ca82b05a1f2f5500ed6522b6138a6a6d0e711962
bigcode/the-stack
train
18ad379ae7c0f511b7afe26e
train
function
def ScheduleInfo(schedule_info): info = { 'day_of_week': schedule_info.day_of_week, 'start_hour': schedule_info.start_hour, 'end_hour': schedule_info.end_hour } return project_channel_pb2.ProjectChannelSchedule(**info)
def ScheduleInfo(schedule_info):
info = { 'day_of_week': schedule_info.day_of_week, 'start_hour': schedule_info.start_hour, 'end_hour': schedule_info.end_hour } return project_channel_pb2.ProjectChannelSchedule(**info)
functools from spaceone.api.notification.v1 import project_channel_pb2 from spaceone.core.pygrpc.message_type import * from spaceone.core import utils from spaceone.notification.model.project_channel_model import ProjectChannel __all__ = ['ProjectChannelInfo', 'ProjectChannelsInfo'] def ScheduleInfo(schedule_info):
64
64
56
6
58
whdalsrnt/notification
src/spaceone/notification/info/project_channel_info.py
Python
ScheduleInfo
ScheduleInfo
11
17
11
11
f8362bb0446a3ad2b014d3db339a7dee57f7fb59
bigcode/the-stack
train
0cc541be3c27706181072fcb
train
class
class TestSettingsMappingExtended(unittest.TestCase): """SettingsMappingExtended unit test stubs""" def setUp(self): pass def tearDown(self): pass def testSettingsMappingExtended(self): """Test SettingsMappingExtended""" # FIXME: construct object with mandatory attribu...
class TestSettingsMappingExtended(unittest.TestCase):
"""SettingsMappingExtended unit test stubs""" def setUp(self): pass def tearDown(self): pass def testSettingsMappingExtended(self): """Test SettingsMappingExtended""" # FIXME: construct object with mandatory attributes with example values # model = isi_sdk_8_1_...
import absolute_import import unittest import isi_sdk_8_1_1 from isi_sdk_8_1_1.models.settings_mapping_extended import SettingsMappingExtended # noqa: E501 from isi_sdk_8_1_1.rest import ApiException class TestSettingsMappingExtended(unittest.TestCase):
64
64
95
9
54
mohitjain97/isilon_sdk_python
isi_sdk_8_1_1/test/test_settings_mapping_extended.py
Python
TestSettingsMappingExtended
TestSettingsMappingExtended
23
36
23
23
2f732d5bb18065486b9291c912f953256877f5c1
bigcode/the-stack
train
870d8a125d9dbe5ee3286631
train
function
def model_configure(*args, **kwargs): kwargs['module'] = 'trax.models' return gin.external_configurable(*args, **kwargs)
def model_configure(*args, **kwargs):
kwargs['module'] = 'trax.models' return gin.external_configurable(*args, **kwargs)
.models.research import funnel_transformer from trax.models.research import layerdrop_transformer from trax.models.research import rezero from trax.models.research import rse from trax.models.research import transformer2 # Ginify def model_configure(*args, **kwargs):
64
64
33
10
53
pkozakowski/trax
trax/models/__init__.py
Python
model_configure
model_configure
37
39
37
37
4e1e95a612b55cbfa9d1734ebdaafdd4314f3751
bigcode/the-stack
train