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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6c0f4961a7fc8bc5c0a7f3d9 | train | function | def nwr_slug(name):
""" National Wildlife Refuge related slug generation. """
deletes = [
'NWRC', 'NWR', 'Complex', 'District', 'National Wildlife Refuge',
'(also sold at fee booth)', 'National Wildlife & Fish Refuge',
'Fish and Wildlife Service']
name = delete_from(name, deletes)
... | def nwr_slug(name):
| """ National Wildlife Refuge related slug generation. """
deletes = [
'NWRC', 'NWR', 'Complex', 'District', 'National Wildlife Refuge',
'(also sold at fee booth)', 'National Wildlife & Fish Refuge',
'Fish and Wildlife Service']
name = delete_from(name, deletes)
return slugify('nw... | .utils.text import slugify
from django.db.utils import IntegrityError
from nationalparks.models import FederalSite
def delete_from(string, deletes):
""" Delete the strings in deletes from string. """
for d in deletes:
string = string.replace(d, '')
return string
def nwr_slug(name):
| 64 | 64 | 84 | 6 | 57 | OpenGlobe/OpenGlobeEKiPAPI | ekip/nationalparks/management/commands/slugify.py | Python | nwr_slug | nwr_slug | 17 | 24 | 17 | 17 | dee26fae5c4f8fddb2ce61ef2c233c1bd8931f67 | bigcode/the-stack | train |
cdd8aaac255d4a762be3d6a1 | train | class | class Command(BaseCommand):
""" Assign a slug to each FederalSite in the database. """
def handle(self, *args, **options):
sites = FederalSite.objects.all()
slug = ''
for site in sites:
print(site.name)
if site.site_type == 'NPS':
slug = nps_slug... | class Command(BaseCommand):
| """ Assign a slug to each FederalSite in the database. """
def handle(self, *args, **options):
sites = FederalSite.objects.all()
slug = ''
for site in sites:
print(site.name)
if site.site_type == 'NPS':
slug = nps_slug(site.website)
e... | _from(name, deletes)
return slugify('nra %s' % name)
def other_slug(name):
""" Not a specific agency. """
deletes = [
'Information Center', 'Visitors Center', 'Area Office',
'Office', 'Central']
name = delete_from(name, deletes)
return slugify('oth %s' % name)
class Command(BaseCom... | 81 | 81 | 273 | 5 | 76 | OpenGlobe/OpenGlobeEKiPAPI | ekip/nationalparks/management/commands/slugify.py | Python | Command | Command | 81 | 121 | 81 | 81 | 3d0ab9de7aeead9f8262becd34a02ad67ca0ef1d | bigcode/the-stack | train |
c2481c01775af5db147a1ffb | train | function | def nra_slug(name):
""" National Recreation Area related slug generation. """
deletes = [
'NRA', 'Field Office', 'National Recreation Area', 'Fee Machines',
'Fee Booth', 'Info Site', 'see also', 'National Monument']
name = delete_from(name, deletes)
return slugify('nra %s' % name)
| def nra_slug(name):
| """ National Recreation Area related slug generation. """
deletes = [
'NRA', 'Field Office', 'National Recreation Area', 'Fee Machines',
'Fee Booth', 'Info Site', 'see also', 'National Monument']
name = delete_from(name, deletes)
return slugify('nra %s' % name)
| BLM related slug generation. """
deletes = [
'BLM', 'Field', 'Office', 'District',
'National', 'Historic', 'Monument']
name = delete_from(name, deletes)
return slugify('blm %s' % name)
def nra_slug(name):
| 64 | 64 | 77 | 6 | 58 | OpenGlobe/OpenGlobeEKiPAPI | ekip/nationalparks/management/commands/slugify.py | Python | nra_slug | nra_slug | 63 | 69 | 63 | 63 | 500d56f799ebab178bbcc9e53a236873d6e9fa70 | bigcode/the-stack | train |
56423680cb36eba1a41cdda8 | train | function | def nps_slug(nps_url):
""" National Park Service related slug generation. """
path = urlparse(nps_url).path
components = [i for i in path.split('/') if i != '']
return slugify('nps %s' % components[0])
| def nps_slug(nps_url):
| """ National Park Service related slug generation. """
path = urlparse(nps_url).path
components = [i for i in path.split('/') if i != '']
return slugify('nps %s' % components[0])
| ', 'Office', 'Ranger Station', 'Information Center', 'NF',
"Visitor's Center", "Management Unit", 'Visitor Center',
'Nature Center']
name = delete_from(name, deletes)
return slugify('nf %s' % name)
def nps_slug(nps_url):
| 64 | 64 | 60 | 8 | 56 | OpenGlobe/OpenGlobeEKiPAPI | ekip/nationalparks/management/commands/slugify.py | Python | nps_slug | nps_slug | 38 | 43 | 38 | 38 | 917d2abf4a9aca0a8c86cc7bc3f4de4ccf4e48e0 | bigcode/the-stack | train |
b0e81bc4b81e3c876cd2b729 | train | function | def delete_from(string, deletes):
""" Delete the strings in deletes from string. """
for d in deletes:
string = string.replace(d, '')
return string
| def delete_from(string, deletes):
| """ Delete the strings in deletes from string. """
for d in deletes:
string = string.replace(d, '')
return string
| from urllib.parse import urlparse
from django.core.management.base import BaseCommand
from django.utils.text import slugify
from django.db.utils import IntegrityError
from nationalparks.models import FederalSite
def delete_from(string, deletes):
| 47 | 64 | 36 | 7 | 39 | OpenGlobe/OpenGlobeEKiPAPI | ekip/nationalparks/management/commands/slugify.py | Python | delete_from | delete_from | 10 | 14 | 10 | 10 | d1653faaec190b2d0ba949ec6b50b9e6a053d790 | bigcode/the-stack | train |
6ddad78491c0b9f34532961f | train | function | def other_slug(name):
""" Not a specific agency. """
deletes = [
'Information Center', 'Visitors Center', 'Area Office',
'Office', 'Central']
name = delete_from(name, deletes)
return slugify('oth %s' % name)
| def other_slug(name):
| """ Not a specific agency. """
deletes = [
'Information Center', 'Visitors Center', 'Area Office',
'Office', 'Central']
name = delete_from(name, deletes)
return slugify('oth %s' % name)
| = [
'NRA', 'Field Office', 'National Recreation Area', 'Fee Machines',
'Fee Booth', 'Info Site', 'see also', 'National Monument']
name = delete_from(name, deletes)
return slugify('nra %s' % name)
def other_slug(name):
| 64 | 64 | 58 | 5 | 59 | OpenGlobe/OpenGlobeEKiPAPI | ekip/nationalparks/management/commands/slugify.py | Python | other_slug | other_slug | 72 | 78 | 72 | 72 | 0310504c1b264bf951b038874c26ee143ab1e034 | bigcode/the-stack | train |
7af0dfa7dc17e6368b0ff8b7 | train | class | class Api(AbstractApi):
# Settings
API_NAME = 'eir019'
ZFILL = True
ROC_FORMAT = True
SEP = ''
# Filters
TRANS_DATE_FILTER = 'TransDate=%s'
SOURCE_FILTER = 'MarketName=%s'
# Column Names
VOLUME_COLUMN = '頭數'
AVG_WEIGHT_COLUMN = '平均重量'
AVG_PRICE_COLUMN = '平均價格'
COLU... | class Api(AbstractApi):
# Settings
| API_NAME = 'eir019'
ZFILL = True
ROC_FORMAT = True
SEP = ''
# Filters
TRANS_DATE_FILTER = 'TransDate=%s'
SOURCE_FILTER = 'MarketName=%s'
# Column Names
VOLUME_COLUMN = '頭數'
AVG_WEIGHT_COLUMN = '平均重量'
AVG_PRICE_COLUMN = '平均價格'
COLUMN_SEP = '-'
def __init__(self, mod... | from django.db.models import Q
import datetime
import json
import math
from .utils import date_transfer
from .abstract import AbstractApi
from apps.dailytrans.models import DailyTran
class Api(AbstractApi):
# Settings
| 48 | 256 | 1,019 | 9 | 38 | travishen/aprp | src/apps/dailytrans/builders/eir019.py | Python | Api | Api | 10 | 127 | 10 | 12 | 46fbe4700e81f78d3c1596162d76066e1a52cb43 | bigcode/the-stack | train |
7b204a30eba4bd36e946ad69 | train | class | class TestPAPI(unittest.TestCase):
def setUp(self):
print("Connecting API")
r = vpp_papi.connect("test_papi")
self.assertEqual(r, 0)
def tearDown(self):
r = vpp_papi.disconnect()
self.assertEqual(r, 0)
#
# The tests themselves
#
#
# Basic request / ... | class TestPAPI(unittest.TestCase):
| def setUp(self):
print("Connecting API")
r = vpp_papi.connect("test_papi")
self.assertEqual(r, 0)
def tearDown(self):
r = vpp_papi.disconnect()
self.assertEqual(r, 0)
#
# The tests themselves
#
#
# Basic request / reply
#
def test_show_versi... | from __future__ import print_function
import unittest, sys, time, threading, struct
import vpp_papi
from ipaddress import *
import glob, subprocess
class TestPAPI(unittest.TestCase):
| 43 | 64 | 145 | 8 | 34 | choonho/vpp | src/vpp-api/python/tests/test_version.py | Python | TestPAPI | TestPAPI | 7 | 32 | 7 | 7 | 642e486f1fc868df24b905a7df1ce132f4b4426a | bigcode/the-stack | train |
98dafdae1a40a932357792ac | train | class | class Set(BaseSet):
""" Mutable set class."""
__slots__ = []
# BaseSet + operations requiring mutability; no hashing
def __init__(self, iterable=None):
"""Construct a set from an optional iterable."""
self._data = {}
if iterable is not None:
self._update(iterable)
... | class Set(BaseSet):
| """ Mutable set class."""
__slots__ = []
# BaseSet + operations requiring mutability; no hashing
def __init__(self, iterable=None):
"""Construct a set from an optional iterable."""
self._data = {}
if iterable is not None:
self._update(iterable)
def __getstate_... | None:
raise # re-raise the TypeError exception we caught
data[transform()] = value
else:
# Safe: only catch TypeError where intended
for element in iterable:
try:
data[element] = value
except... | 256 | 256 | 1,025 | 5 | 250 | microblink/zxing | cpp/scons/scons-local-2.0.0.final.0/SCons/compat/_scons_sets.py | Python | Set | Set | 415 | 562 | 415 | 415 | 6e66f7d6fc1fe570040591be6d32873be3b900b5 | bigcode/the-stack | train |
2252b82122ad3bed714a6b6a | train | class | class _TemporarilyImmutableSet(BaseSet):
# Wrap a mutable set as if it was temporarily immutable.
# This only supplies hashing and equality comparisons.
def __init__(self, set):
self._set = set
self._data = set._data # Needed by ImmutableSet.__eq__()
def __hash__(self):
return... | class _TemporarilyImmutableSet(BaseSet):
# Wrap a mutable set as if it was temporarily immutable.
# This only supplies hashing and equality comparisons.
| def __init__(self, set):
self._set = set
self._data = set._data # Needed by ImmutableSet.__eq__()
def __hash__(self):
return self._set._compute_hash()
| __as_temporarily_immutable__(self):
# Return self wrapped in a temporarily immutable set
return _TemporarilyImmutableSet(self)
class _TemporarilyImmutableSet(BaseSet):
# Wrap a mutable set as if it was temporarily immutable.
# This only supplies hashing and equality comparisons.
| 64 | 64 | 82 | 33 | 31 | microblink/zxing | cpp/scons/scons-local-2.0.0.final.0/SCons/compat/_scons_sets.py | Python | _TemporarilyImmutableSet | _TemporarilyImmutableSet | 565 | 574 | 565 | 568 | 51afda18c449bcd1197df9fde90e59d520330b4b | bigcode/the-stack | train |
d3b56bb4c08aedbdc990edac | train | class | class BaseSet(object):
"""Common base class for mutable and immutable sets."""
__slots__ = ['_data']
# Constructor
def __init__(self):
"""This is an abstract class."""
# Don't call this from a concrete subclass!
if self.__class__ is BaseSet:
raise TypeError("BaseSe... | class BaseSet(object):
| """Common base class for mutable and immutable sets."""
__slots__ = ['_data']
# Constructor
def __init__(self):
"""This is an abstract class."""
# Don't call this from a concrete subclass!
if self.__class__ is BaseSet:
raise TypeError("BaseSet is an abstract class.... | be added to a Set. In particular, you cannot
really add a Set as an element to another Set; if you try, what is
actually added is an ImmutableSet built from it (it compares equal to
the one you tried adding).
When you ask if `x in y' where x is a Set and y is a Set or
ImmutableSet, x is wrapped into a _TemporarilyImm... | 256 | 256 | 2,477 | 5 | 251 | microblink/zxing | cpp/scons/scons-local-2.0.0.final.0/SCons/compat/_scons_sets.py | Python | BaseSet | BaseSet | 79 | 387 | 79 | 79 | 20f023fa92d32bba36c95a2de0e37725198c10b7 | bigcode/the-stack | train |
691f36d8fe1ab7efce5c74cc | train | class | class ImmutableSet(BaseSet):
"""Immutable set class."""
__slots__ = ['_hashcode']
# BaseSet + hashing
def __init__(self, iterable=None):
"""Construct an immutable set from an optional iterable."""
self._hashcode = None
self._data = {}
if iterable is not None:
... | class ImmutableSet(BaseSet):
| """Immutable set class."""
__slots__ = ['_hashcode']
# BaseSet + hashing
def __init__(self, iterable=None):
"""Construct an immutable set from an optional iterable."""
self._hashcode = None
self._data = {}
if iterable is not None:
self._update(iterable)
... | in iterable:
try:
data[element] = value
except TypeError:
transform = getattr(element, "__as_immutable__", None)
if transform is None:
raise # re-raise the TypeError exception we caught
... | 64 | 64 | 153 | 6 | 57 | microblink/zxing | cpp/scons/scons-local-2.0.0.final.0/SCons/compat/_scons_sets.py | Python | ImmutableSet | ImmutableSet | 390 | 413 | 390 | 390 | 59604c4d1f8deace20a9743a7fda91f3d1120801 | bigcode/the-stack | train |
b9c60b3d8894ac7eacecf2ac | train | function | def create_config_dirs(base_dir, platform='ubuntu'):
if platform == 'ubuntu':
platform_config = ubuntu_platform_config
elif platform == 'windows':
platform_config = windows_platform_config
else:
raise RuntimeError('Unknown platform {}. Cannot load config'.format(platform))
gen_c... | def create_config_dirs(base_dir, platform='ubuntu'):
| if platform == 'ubuntu':
platform_config = ubuntu_platform_config
elif platform == 'windows':
platform_config = windows_platform_config
else:
raise RuntimeError('Unknown platform {}. Cannot load config'.format(platform))
gen_conf_dir_default = GENERAL_CONFIG_DIR.lstrip('/') \
... | import os
from indy_node.general_config import general_config
from indy_common.config import GENERAL_CONFIG_DIR, GENERAL_CONFIG_FILE
from indy_node.general_config import ubuntu_platform_config, \
windows_platform_config
def create_config_dirs(base_dir, platform='ubuntu'):
| 52 | 72 | 240 | 11 | 40 | pysingh09/indy-node | indy_node/server/config_helper.py | Python | create_config_dirs | create_config_dirs | 10 | 38 | 10 | 10 | 7de6c62c3e32658fc4926012c95961ed63447365 | bigcode/the-stack | train |
a0a0d55250ac639ed4f4f174 | train | function | def add_silence(snd_data, seconds):
"Add silence to the start and end of 'snd_data' of length 'seconds' (float)"
r = array('h', [0 for i in range(int(seconds*RATE))])
r.extend(snd_data)
r.extend([0 for i in range(int(seconds*RATE))])
return r
| def add_silence(snd_data, seconds):
| "Add silence to the start and end of 'snd_data' of length 'seconds' (float)"
r = array('h', [0 for i in range(int(seconds*RATE))])
r.extend(snd_data)
r.extend([0 for i in range(int(seconds*RATE))])
return r
| return r
# Trim to the left
snd_data = _trim(snd_data)
# Trim to the right
snd_data.reverse()
snd_data = _trim(snd_data)
snd_data.reverse()
return snd_data
def add_silence(snd_data, seconds):
| 64 | 64 | 78 | 11 | 52 | jaroslaw-wieczorek/Project_IP_Telephony_Python_Voip | JaroEliCall/src/record.py | Python | add_silence | add_silence | 63 | 68 | 63 | 63 | 75aa7320da7db3c0d5d1b666224318883b98245c | bigcode/the-stack | train |
59f58c288bd8afc8648cd6a6 | train | function | def normalize(snd_data):
"Average the volume out"
MAXIMUM = 16384
times = float(MAXIMUM)/max(abs(i) for i in snd_data)
r = array('h')
for i in snd_data:
r.append(int(i*times))
return r
| def normalize(snd_data):
| "Average the volume out"
MAXIMUM = 16384
times = float(MAXIMUM)/max(abs(i) for i in snd_data)
r = array('h')
for i in snd_data:
r.append(int(i*times))
return r
|
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100
def is_silent(snd_data):
"Returns 'True' if below the 'silent' threshold"
return max(snd_data) < THRESHOLD
def normalize(snd_data):
| 64 | 64 | 64 | 6 | 57 | jaroslaw-wieczorek/Project_IP_Telephony_Python_Voip | JaroEliCall/src/record.py | Python | normalize | normalize | 27 | 35 | 27 | 27 | 04c17bf9503b449a680e0d838ccf20fc6eda3f17 | bigcode/the-stack | train |
d607ba45f4341d9eeaf466ba | train | function | def record():
"""
Record a word or words from the microphone and
return the data as an array of signed shorts.
Normalizes the audio, trims silence from the
start and end, and pads with 0.5 seconds of
blank sound to make sure VLC et al can play
it without getting chopped off.
"""
... | def record():
| """
Record a word or words from the microphone and
return the data as an array of signed shorts.
Normalizes the audio, trims silence from the
start and end, and pads with 0.5 seconds of
blank sound to make sure VLC et al can play
it without getting chopped off.
"""
p = pyaudio.P... | snd_data.reverse()
return snd_data
def add_silence(snd_data, seconds):
"Add silence to the start and end of 'snd_data' of length 'seconds' (float)"
r = array('h', [0 for i in range(int(seconds*RATE))])
r.extend(snd_data)
r.extend([0 for i in range(int(seconds*RATE))])
return r
def record():
| 90 | 90 | 300 | 3 | 86 | jaroslaw-wieczorek/Project_IP_Telephony_Python_Voip | JaroEliCall/src/record.py | Python | record | record | 71 | 116 | 71 | 71 | e48e9b1d9f34a6705fb1fd892b18ea95edb9aefb | bigcode/the-stack | train |
f25fdef202e9883703cc06c1 | train | function | def is_silent(snd_data):
"Returns 'True' if below the 'silent' threshold"
return max(snd_data) < THRESHOLD
| def is_silent(snd_data):
| "Returns 'True' if below the 'silent' threshold"
return max(snd_data) < THRESHOLD
|
"""
from sys import byteorder
from array import array
from struct import pack
import pyaudio
import wave
THRESHOLD = 500
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100
def is_silent(snd_data):
| 64 | 64 | 34 | 8 | 55 | jaroslaw-wieczorek/Project_IP_Telephony_Python_Voip | JaroEliCall/src/record.py | Python | is_silent | is_silent | 22 | 24 | 22 | 22 | 33b0b148ada73c002872eaddb51255df6ae417e4 | bigcode/the-stack | train |
8844660139e9509a096f3073 | train | function | def trim(snd_data):
"Trim the blank spots at the start and end"
def _trim(snd_data):
snd_started = False
r = array('h')
for i in snd_data:
if not snd_started and abs(i)>THRESHOLD:
snd_started = True
r.append(i)
elif snd_started:
... | def trim(snd_data):
| "Trim the blank spots at the start and end"
def _trim(snd_data):
snd_started = False
r = array('h')
for i in snd_data:
if not snd_started and abs(i)>THRESHOLD:
snd_started = True
r.append(i)
elif snd_started:
r.app... | "Average the volume out"
MAXIMUM = 16384
times = float(MAXIMUM)/max(abs(i) for i in snd_data)
r = array('h')
for i in snd_data:
r.append(int(i*times))
return r
def trim(snd_data):
| 64 | 64 | 133 | 6 | 57 | jaroslaw-wieczorek/Project_IP_Telephony_Python_Voip | JaroEliCall/src/record.py | Python | trim | trim | 38 | 60 | 38 | 38 | 48b4d20cf67cdaf95925a5e0a2c1e7b0413277d6 | bigcode/the-stack | train |
d028b90cf2936c3194495586 | train | function | def record_to_file(path):
"Records from the microphone and outputs the resulting data to 'path'"
sample_width, data = record()
data = pack('<' + ('h'*len(data)), *data)
wf = wave.open(path, 'wb')
wf.setnchannels(1)
wf.setsampwidth(sample_width)
wf.setframerate(RATE)
wf.writeframes(data)... | def record_to_file(path):
| "Records from the microphone and outputs the resulting data to 'path'"
sample_width, data = record()
data = pack('<' + ('h'*len(data)), *data)
wf = wave.open(path, 'wb')
wf.setnchannels(1)
wf.setsampwidth(sample_width)
wf.setframerate(RATE)
wf.writeframes(data)
wf.close()
| sample_width = p.get_sample_size(FORMAT)
stream.stop_stream()
stream.close()
p.terminate()
r = normalize(r)
r = trim(r)
r = add_silence(r, 0.5)
return sample_width, r
def record_to_file(path):
| 64 | 64 | 90 | 6 | 57 | jaroslaw-wieczorek/Project_IP_Telephony_Python_Voip | JaroEliCall/src/record.py | Python | record_to_file | record_to_file | 119 | 129 | 119 | 119 | 1f5a1ee9dc6f0e211379773da8720f14a3a271ba | bigcode/the-stack | train |
7fbd1702ffd9b5c4f0bd3c03 | train | class | class Mailer:
_instance = None
def __init__(self):
self.cfg = None
@classmethod
def init(cls, config: SubmitterConfig):
cls.get().cfg = config
@classmethod
def get(cls):
if cls._instance is None:
cls._instance = Mailer()
return cls._instance
de... | class Mailer:
| _instance = None
def __init__(self):
self.cfg = None
@classmethod
def init(cls, config: SubmitterConfig):
cls.get().cfg = config
@classmethod
def get(cls):
if cls._instance is None:
cls._instance = Mailer()
return cls._instance
def _msg_text(se... | import email
import smtplib
import ssl
from nanopub_submitter.config import SubmitterConfig
from nanopub_submitter.logger import LOG
class Mailer:
| 35 | 203 | 677 | 4 | 30 | ds-wizard/nanopub-submission-service | nanopub_submitter/mailer.py | Python | Mailer | Mailer | 9 | 102 | 9 | 9 | 9cf1b3c9cc3e4473e70699ed0c8a0632602bcb8f | bigcode/the-stack | train |
b284e612738c97b79c0fcbdb | train | class | class EG(Algo):
""" Exponentiated Gradient (EG) algorithm by Helmbold et al.
Reference:
Helmbold, David P., et al.
"On‐Line Portfolio Selection Using Multiplicative Updates."
Mathematical Finance 8.4 (1998): 325-347.
"""
def __init__(self, eta=0.05):
"""
:params... | class EG(Algo):
| """ Exponentiated Gradient (EG) algorithm by Helmbold et al.
Reference:
Helmbold, David P., et al.
"On‐Line Portfolio Selection Using Multiplicative Updates."
Mathematical Finance 8.4 (1998): 325-347.
"""
def __init__(self, eta=0.05):
"""
:params eta: Learning r... | # -*- coding: utf-8 -*-
from ..algo import Algo
from .. import tools
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class EG(Algo):
| 40 | 64 | 168 | 5 | 34 | sandybradley/universal-portfolios | universal/algos/eg.py | Python | EG | EG | 9 | 32 | 9 | 9 | 3c7cc064e7cc6bbcd49bf412ccb03fe716a36f26 | bigcode/the-stack | train |
2fe5b2f27fd3efd632cc6b0e | train | class | class GitAnalyzer:
GIT_REPOSITORIES_DIR = settings.get('git_repositories_dir')
STORAGE_DIR = settings.get('change_graphs_storage_dir')
STORE_INTERVAL = settings.get('change_graphs_store_interval', 300)
TRAVERSE_ASYNC = settings.get('traverse_async', True)
MIN_DATE = None
if settings.get('traver... | class GitAnalyzer:
| GIT_REPOSITORIES_DIR = settings.get('git_repositories_dir')
STORAGE_DIR = settings.get('change_graphs_storage_dir')
STORE_INTERVAL = settings.get('change_graphs_store_interval', 300)
TRAVERSE_ASYNC = settings.get('traverse_async', True)
MIN_DATE = None
if settings.get('traverse_min_date', requi... | import os
import tempfile
import ast
import uuid
import pickle
import multiprocessing
import time
import json
import subprocess
import datetime
from log import logger
from pydriller import RepositoryMining
from pydriller.domain.commit import ModificationType
import settings
import changegraph
class GitAnalyzer:
| 66 | 256 | 2,016 | 4 | 61 | stspbu/code-change-miner | vcs/traverse.py | Python | GitAnalyzer | GitAnalyzer | 20 | 269 | 20 | 20 | 1b4a85a27c4c3aa6616140b5a534dc474de24dc9 | bigcode/the-stack | train |
25dd29a795eb1a78249fed27 | train | class | class RepoInfo:
def __init__(self, repo_name, repo_path, repo_url, commit_hash, commit_dtm,
old_file_path, new_file_path, old_method, new_method,
author_email=None, author_name=None):
self.repo_name = repo_name
self.repo_path = repo_path
self.repo_url = repo... | class RepoInfo:
| def __init__(self, repo_name, repo_path, repo_url, commit_hash, commit_dtm,
old_file_path, new_file_path, old_method, new_method,
author_email=None, author_name=None):
self.repo_name = repo_name
self.repo_path = repo_path
self.repo_url = repo_url
se... | _offset].decode(), IndexError: list index out of range
def get_source(self):
try:
return ast.get_source_segment(self.src, self.ast)
except:
logger.info(f'Unable to extract source segment from {self.ast}', show_pid=True)
return None
class RepoInfo:
| 64 | 64 | 145 | 4 | 59 | stspbu/code-change-miner | vcs/traverse.py | Python | RepoInfo | RepoInfo | 322 | 340 | 322 | 322 | a61e913f6d8859b3e5ca5b1d2db09b0c0b494143 | bigcode/the-stack | train |
2ae1f99e9b0f1830d44a2264 | train | class | class Method:
def __init__(self, path, name, ast, src):
self.file_path = path
self.ast = ast
self.src = src.strip()
self.name = name
self.full_name = name
def extend_path(self, prefix, separator='.'):
self.full_name = f'{prefix}{separator}{self.full_name}'
... | class Method:
| def __init__(self, path, name, ast, src):
self.file_path = path
self.ast = ast
self.src = src.strip()
self.name = name
self.full_name = name
def extend_path(self, prefix, separator='.'):
self.full_name = f'{prefix}{separator}{self.full_name}'
# TODO: last ... | .body:
result = self.visit(st)
if result:
methods += result
for method in methods:
method.extend_path(node.name)
return methods
def visit_FunctionDef(self, node):
return [Method(self.file_path, node.name, node, self.src)]
class Method:
| 63 | 64 | 154 | 3 | 60 | stspbu/code-change-miner | vcs/traverse.py | Python | Method | Method | 301 | 319 | 301 | 301 | 3a24c0988a63cc69ab8adba5c738609c2257da10 | bigcode/the-stack | train |
8520a715646bc985802ae06f | train | class | class ASTMethodExtractor(ast.NodeVisitor):
def __init__(self, path, src):
self.file_path = path
self.src = src
def visit_Module(self, node):
methods = []
for st in node.body:
result = self.visit(st)
if result:
methods += result
ret... | class ASTMethodExtractor(ast.NodeVisitor):
| def __init__(self, path, src):
self.file_path = path
self.src = src
def visit_Module(self, node):
methods = []
for st in node.body:
result = self.visit(st)
if result:
methods += result
return methods
def visit_ClassDef(self, n... | )
old_method_to_new = {}
for old_method in old_methods:
for new_method in new_methods:
if old_method.full_name == new_method.full_name:
old_method_to_new[old_method] = new_method
return old_method_to_new
class ASTMethodExtractor(ast.NodeVisitor):
| 64 | 64 | 149 | 8 | 55 | stspbu/code-change-miner | vcs/traverse.py | Python | ASTMethodExtractor | ASTMethodExtractor | 272 | 298 | 272 | 272 | 3a556481f481a25e4e546682e05df2f29fbdfa75 | bigcode/the-stack | train |
14685b6ff69711b12e0dcb64 | train | function | def test_basic_metadata(standard_graph, session, users, groups, permissions): # noqa
""" Test basic metadata functionality. """
graph = standard_graph # noqa
assert len(users["zorkian"].my_metadata()) == 0, "No metadata yet"
# Test setting "foo" to 1 works, and we get "1" back (metadata is defined ... | def test_basic_metadata(standard_graph, session, users, groups, permissions): # noqa
| """ Test basic metadata functionality. """
graph = standard_graph # noqa
assert len(users["zorkian"].my_metadata()) == 0, "No metadata yet"
# Test setting "foo" to 1 works, and we get "1" back (metadata is defined as strings)
users["zorkian"].set_metadata("foo", 1)
md = users["zorkian"].my_m... | from fixtures import standard_graph, graph, users, groups, session, permissions # noqa
def test_basic_metadata(standard_graph, session, users, groups, permissions): # noqa
| 39 | 120 | 403 | 20 | 18 | zorkian/grouper | tests/test_users.py | Python | test_basic_metadata | test_basic_metadata | 4 | 35 | 4 | 4 | f9251711ffaca1b04ce0364e1ddd7332289696d2 | bigcode/the-stack | train |
cd77d49e7245e3c3ef25cc33 | train | function | def _getselectable(selectable_object):
try:
channel = selectable_object.getchannel()
except:
try:
channel = selectable_object.fileno().getChannel()
except:
raise TypeError("Object '%s' is not watchable" % selectable_object,
errno.ENOTSO... | def _getselectable(selectable_object):
| try:
channel = selectable_object.getchannel()
except:
try:
channel = selectable_object.fileno().getChannel()
except:
raise TypeError("Object '%s' is not watchable" % selectable_object,
errno.ENOTSOCK)
return channel
| does not support them, AFAICT
# They are declared only to support code compatibility with cpython
POLLPRI = 4
POLLERR = 8
POLLHUP = 16
POLLNVAL = 32
def _getselectable(selectable_object):
| 64 | 64 | 69 | 9 | 54 | ennec-e/brython | www/src/Lib/select.py | Python | _getselectable | _getselectable | 36 | 46 | 36 | 36 | 933d8d0cab371a0bce08fe842edfe551eb50788e | bigcode/the-stack | train |
87ceb5c2b323842820fe870c | train | function | def _calcselecttimeoutvalue(value):
if value is None:
return None
try:
floatvalue = float(value)
except Exception as x:
raise TypeError("Select timeout value must be a number or None")
if value < 0:
raise error("Select timeout value cannot be negative", errno.EINVAL)
... | def _calcselecttimeoutvalue(value):
| if value is None:
return None
try:
floatvalue = float(value)
except Exception as x:
raise TypeError("Select timeout value must be a number or None")
if value < 0:
raise error("Select timeout value cannot be negative", errno.EINVAL)
if floatvalue < 0.000001:
re... | operation.
self.selector.selectNow()
except BaseException as exc:
raise _map_exception(exc)
def close(self):
try:
self._deregister_all()
self.selector.close()
except BaseException as exc:
raise _map_exception(exc)
def _calcselectt... | 64 | 64 | 102 | 8 | 56 | ennec-e/brython | www/src/Lib/select.py | Python | _calcselecttimeoutvalue | _calcselecttimeoutvalue | 157 | 168 | 157 | 157 | cb8e272ced1ddcc743f5a431a56762eded1ea9c0 | bigcode/the-stack | train |
d768b5a775a39e3033be6c82 | train | function | def native_select(read_fd_list, write_fd_list, outofband_fd_list, timeout=None):
timeout = _calcselecttimeoutvalue(timeout)
# First create a poll object to do the actual watching.
pobj = _poll_object_cache.get_poll_object()
try:
registered_for_read = {}
# Check the read list
for ... | def native_select(read_fd_list, write_fd_list, outofband_fd_list, timeout=None):
| timeout = _calcselecttimeoutvalue(timeout)
# First create a poll object to do the actual watching.
pobj = _poll_object_cache.get_poll_object()
try:
registered_for_read = {}
# Check the read list
for fd in read_fd_list:
pobj.register(fd, POLLIN)
registered_... | )
else:
pobj.close()
def finalize(self):
if self.is_windows:
while True:
try:
p = self.poll_object_queue.get(False)
p.close()
except Queue.Empty:
return
_poll_object_cache = poll_obj... | 76 | 76 | 254 | 20 | 56 | ennec-e/brython | www/src/Lib/select.py | Python | native_select | native_select | 208 | 235 | 208 | 208 | 3066393d8aa1d1ace0c3f3d6f68e66dd736b88a1 | bigcode/the-stack | train |
275647dd8bdef0b09040c3b1 | train | class | class poll:
def __init__(self):
self.selector = Selector()
self.chanmap = {}
self.unconnected_sockets = []
def _register_channel(self, socket_object, channel, mask):
jmask = 0
if mask & POLLIN:
# Note that OP_READ is NOT a valid event on server socket channe... | class poll:
| def __init__(self):
self.selector = Selector()
self.chanmap = {}
self.unconnected_sockets = []
def _register_channel(self, socket_object, channel, mask):
jmask = 0
if mask & POLLIN:
# Note that OP_READ is NOT a valid event on server socket channels.
... | AFAICT
# They are declared only to support code compatibility with cpython
POLLPRI = 4
POLLERR = 8
POLLHUP = 16
POLLNVAL = 32
def _getselectable(selectable_object):
try:
channel = selectable_object.getchannel()
except:
try:
channel = selectable_object.fileno().getChannel()
... | 192 | 192 | 642 | 3 | 189 | ennec-e/brython | www/src/Lib/select.py | Python | poll | poll | 69 | 155 | 69 | 70 | 3f1e1325b6eaf6ba60583ed91c5a1aa53c522fe1 | bigcode/the-stack | train |
9357f0df1786ab64e4e13bc1 | train | class | class Selector:
def close(self):
pass
def keys(self):
return []
def select(self, timeout=None):
return []
def selectedKeys(self):
class SelectedKeys:
def iterator(self):
return []
return SelectedKeys()
def selectNow(self, timeo... | class Selector:
| def close(self):
pass
def keys(self):
return []
def select(self, timeout=None):
return []
def selectedKeys(self):
class SelectedKeys:
def iterator(self):
return []
return SelectedKeys()
def selectNow(self, timeout=None):
... | channel = selectable_object.getchannel()
except:
try:
channel = selectable_object.fileno().getChannel()
except:
raise TypeError("Object '%s' is not watchable" % selectable_object,
errno.ENOTSOCK)
return channel
# Fake Selector
class S... | 64 | 64 | 66 | 3 | 60 | ennec-e/brython | www/src/Lib/select.py | Python | Selector | Selector | 49 | 67 | 49 | 50 | f5e51411a9dd342ebabd6438d204b550a4207a0b | bigcode/the-stack | train |
1758e00bc10610376c5fb140 | train | function | def _map_exception(exc, circumstance=ALL):
try:
mapped_exception = _exception_map[(exc.__class__, circumstance)]
mapped_exception.java_exception = exc
return mapped_exception
except KeyError:
return error(-1, 'Unmapped java exception: <%s:%s>' % (exc.toString(), circumstance))
| def _map_exception(exc, circumstance=ALL):
| try:
mapped_exception = _exception_map[(exc.__class__, circumstance)]
mapped_exception.java_exception = exc
return mapped_exception
except KeyError:
return error(-1, 'Unmapped java exception: <%s:%s>' % (exc.toString(), circumstance))
| /jython/jython/raw/28a66ba038620292520470a0bb4dc9bb8ac2e403/Lib/select.py
"""
import errno
import os
class error(Exception):
pass
ALL = None
_exception_map = {}
def _map_exception(exc, circumstance=ALL):
| 64 | 64 | 70 | 10 | 54 | ennec-e/brython | www/src/Lib/select.py | Python | _map_exception | _map_exception | 16 | 22 | 16 | 16 | 507376124df16db9ffbaaebe0d6182fe3f5668c1 | bigcode/the-stack | train |
1403a09e7c2269c9bf902c1b | train | class | class poll_object_cache:
def __init__(self):
self.is_windows = os.name == 'nt'
if self.is_windows:
self.poll_object_queue = Queue.Queue()
import atexit
atexit.register(self.finalize)
def get_poll_object(self):
if not self.is_windows:
return poll(... | class poll_object_cache:
| def __init__(self):
self.is_windows = os.name == 'nt'
if self.is_windows:
self.poll_object_queue = Queue.Queue()
import atexit
atexit.register(self.finalize)
def get_poll_object(self):
if not self.is_windows:
return poll()
try:
... | floatvalue < 0.000001:
return 0
return int(floatvalue * 1000) # Convert to milliseconds
# This cache for poll objects is required because of a bug in java on MS Windows
# http://bugs.jython.org/issue1291
class poll_object_cache:
| 64 | 64 | 170 | 5 | 58 | ennec-e/brython | www/src/Lib/select.py | Python | poll_object_cache | poll_object_cache | 173 | 204 | 173 | 174 | c4c0cd8dbccf7c64119436cb45c55c5e3441ddaa | bigcode/the-stack | train |
082c67ae9278afec3ab60206 | train | class | class error(Exception):
pass
| class error(Exception):
| pass
| """
borrowed from jython
https://bitbucket.org/jython/jython/raw/28a66ba038620292520470a0bb4dc9bb8ac2e403/Lib/select.py
"""
import errno
import os
class error(Exception):
| 55 | 64 | 7 | 4 | 50 | ennec-e/brython | www/src/Lib/select.py | Python | error | error | 9 | 10 | 9 | 9 | 1d7ff5edbc7d9e7d9e9055f6cab0637fb51786c0 | bigcode/the-stack | train |
3a629a4d996cee8640adf356 | train | function | def cpython_compatible_select(read_fd_list, write_fd_list, outofband_fd_list, timeout=None):
# First turn all sockets to non-blocking
# keeping track of which ones have changed
modified_channels = []
try:
for socket_list in [read_fd_list, write_fd_list, outofband_fd_list]:
for s in s... | def cpython_compatible_select(read_fd_list, write_fd_list, outofband_fd_list, timeout=None):
# First turn all sockets to non-blocking
# keeping track of which ones have changed
| modified_channels = []
try:
for socket_list in [read_fd_list, write_fd_list, outofband_fd_list]:
for s in socket_list:
channel = _getselectable(s)
if channel.isBlocking():
modified_channels.append(channel)
channel.config... |
finally:
_poll_object_cache.release_poll_object(pobj)
select = native_select
def cpython_compatible_select(read_fd_list, write_fd_list, outofband_fd_list, timeout=None):
# First turn all sockets to non-blocking
# keeping track of which ones have changed
| 64 | 64 | 144 | 44 | 19 | ennec-e/brython | www/src/Lib/select.py | Python | cpython_compatible_select | cpython_compatible_select | 239 | 253 | 239 | 241 | 08e42bb26bcfc7f7075fa417a13c270275d9b113 | bigcode/the-stack | train |
67492cddf6e80fe298de6810 | train | function | @csrf_exempt
def getModels(request, username):
token = parseToken(request)
decoded_username = authorize(token)
if username != None and username == decoded_username:
try:
models = MachineLearningModel.objects.filter(username=username)
serialized_models = serializers.serialize(... | @csrf_exempt
def getModels(request, username):
| token = parseToken(request)
decoded_username = authorize(token)
if username != None and username == decoded_username:
try:
models = MachineLearningModel.objects.filter(username=username)
serialized_models = serializers.serialize("json", models)
except (KeyError, Machi... | quote
import statsmodels.api as sm
import sklearn as sk
import json
from .utils import (
authorize,
parseToken,
parseCsv,
parseVariables,
compute_cm_scores,
regression_metrics
)
@csrf_exempt
def getModels(request, username):
| 64 | 64 | 122 | 12 | 52 | Danial-Hussain/MyModel | server/algo/views.py | Python | getModels | getModels | 21 | 36 | 21 | 22 | 47fe37969866051d4b4f786e0e779fa65898e2c0 | bigcode/the-stack | train |
e6e8c485045a864643e9015e | train | function | @csrf_exempt
def buildModel(request, username):
token = parseToken(request)
decoded_username = authorize(token)
if username != None and username == decoded_username:
decode = lambda data: data.decode("utf-8")
body = json.loads(decode(request.body))
model_type = body["model-type"]
... | @csrf_exempt
def buildModel(request, username):
| token = parseToken(request)
decoded_username = authorize(token)
if username != None and username == decoded_username:
decode = lambda data: data.decode("utf-8")
body = json.loads(decode(request.body))
model_type = body["model-type"]
model_data = parseCsv(unquote(unquote(body[... | JsonResponse, HttpResponseBadRequest
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
from django.core import serializers
from .models import Machine... | 256 | 256 | 1,287 | 12 | 244 | Danial-Hussain/MyModel | server/algo/views.py | Python | buildModel | buildModel | 39 | 213 | 39 | 40 | 76f77f4fdfb9423f91beec892d61a73a04bad776 | bigcode/the-stack | train |
1bbbf53e28b0ba3d14b209a0 | train | function | @csrf_exempt
def saveModel(request, username):
token = parseToken(request)
decoded_username = authorize(token)
if username != None and username == decoded_username:
try:
decode = lambda data: data.decode("utf-8")
body = json.loads(decode(request.body))
model_name ... | @csrf_exempt
def saveModel(request, username):
| token = parseToken(request)
decoded_username = authorize(token)
if username != None and username == decoded_username:
try:
decode = lambda data: data.decode("utf-8")
body = json.loads(decode(request.body))
model_name = body["model-name"]
model_fold = b... | "accuracy": accuracy,
"f_measure": f_measure,
}
except:
return HttpResponseBadRequest("Unable to create model")
else:
return HttpResponseBadRequest("Invalid Model Type")
return JsonResponse({"metrics": metrics})
else:
... | 79 | 79 | 265 | 12 | 67 | Danial-Hussain/MyModel | server/algo/views.py | Python | saveModel | saveModel | 216 | 248 | 216 | 217 | 068be28b8311c8c6c9ac24dc29f798ec9911e7c4 | bigcode/the-stack | train |
b8c1c4b8e2235b0a765052f7 | train | function | def main():
extern_host = "www.google.com"
extern_port = 80
#create socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as proxy_start:
print("Starting proxy server")
#allow reusing address,bind, set to listening mode
proxy_start.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
proxy_start... | def main():
| extern_host = "www.google.com"
extern_port = 80
#create socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as proxy_start:
print("Starting proxy server")
#allow reusing address,bind, set to listening mode
proxy_start.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
proxy_start.bind((HOST,P... | 1024
#get host information
def get_remote_ip(host):
print(f'Getting IP for {host}')
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
print ('Hostname could not be resolved. Exiting')
sys.exit()
print (f'Ip address of {host} is {remote_ip}')
return rem... | 86 | 86 | 289 | 3 | 82 | GevinUA/404_Lab2 | proxy_server.py | Python | main | main | 24 | 66 | 24 | 25 | 18b24d51cc7bc9a428111cbfcffde16f21326531 | bigcode/the-stack | train |
cfd7310f3751af9545b42999 | train | function | def get_remote_ip(host):
print(f'Getting IP for {host}')
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
print ('Hostname could not be resolved. Exiting')
sys.exit()
print (f'Ip address of {host} is {remote_ip}')
return remote_ip
| def get_remote_ip(host):
| print(f'Getting IP for {host}')
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
print ('Hostname could not be resolved. Exiting')
sys.exit()
print (f'Ip address of {host} is {remote_ip}')
return remote_ip
| #!/usr/bin/env python3
import socket,time,sys
HOST = ""
PORT = 8001
BUFFER_SIZE = 1024
#get host information
def get_remote_ip(host):
| 39 | 64 | 75 | 6 | 32 | GevinUA/404_Lab2 | proxy_server.py | Python | get_remote_ip | get_remote_ip | 12 | 21 | 12 | 12 | f83f30f60ac4793d87af6f516967b58d15bcf8cd | bigcode/the-stack | train |
25b6e37175a117e69cb80da9 | train | function | @pytest.fixture(autouse=True)
def add_np(doctest_namespace):
doctest_namespace["np"] = numpy
| @pytest.fixture(autouse=True)
def add_np(doctest_namespace):
| doctest_namespace["np"] = numpy
| : determined"
"automatically."),
)
def pytest_sessionstart(session):
available_mem = session.config.getoption("available_memory")
if available_mem is not None:
os.environ["NPY_AVAILABLE_MEM"] = available_mem
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
| 64 | 64 | 25 | 15 | 48 | HaoZeke/f2py_skel | tests/conftest.py | Python | add_np | add_np | 45 | 47 | 45 | 46 | c5240b577bbeccfb020b839c80cf9a800b0aec67 | bigcode/the-stack | train |
14c351b43d94657e677238de | train | function | @pytest.fixture(autouse=True)
def env_setup(monkeypatch):
monkeypatch.setenv("PYTHONHASHSEED", "0")
| @pytest.fixture(autouse=True)
def env_setup(monkeypatch):
| monkeypatch.setenv("PYTHONHASHSEED", "0")
| ("available_memory")
if available_mem is not None:
os.environ["NPY_AVAILABLE_MEM"] = available_mem
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
doctest_namespace["np"] = numpy
@pytest.fixture(autouse=True)
def env_setup(monkeypatch):
| 64 | 64 | 29 | 14 | 49 | HaoZeke/f2py_skel | tests/conftest.py | Python | env_setup | env_setup | 50 | 52 | 50 | 51 | 2c4add1941a68069d1773529538a5599dfd6b713 | bigcode/the-stack | train |
9b6cbae716c4ae6c6fe54bf2 | train | function | def pytest_addoption(parser):
parser.addoption(
"--available-memory",
action="store",
default=None,
help=("Set amount of memory available for running the "
"test suite. This can result to tests requiring "
"especially large amounts of memory to be skipped.... | def pytest_addoption(parser):
| parser.addoption(
"--available-memory",
action="store",
default=None,
help=("Set amount of memory available for running the "
"test suite. This can result to tests requiring "
"especially large amounts of memory to be skipped. "
"Equivalent t... | leaks_references: Tests that are known to leak references.")
config.addinivalue_line("markers", "slow: Tests that are very slow.")
config.addinivalue_line("markers",
"slow_pypy: Tests that are very slow on pypy.")
def pytest_addoption(parser):
| 63 | 64 | 87 | 6 | 57 | HaoZeke/f2py_skel | tests/conftest.py | Python | pytest_addoption | pytest_addoption | 25 | 36 | 25 | 25 | 7f62f588c06be1a9a6bf9f266162d148448e83f1 | bigcode/the-stack | train |
e003770ab8e344f08a356997 | train | function | def pytest_configure(config):
config.addinivalue_line(
"markers",
"valgrind_error: Tests that are known to error under valgrind.")
config.addinivalue_line(
"markers",
"leaks_references: Tests that are known to leak references.")
config.addinivalue_line("markers", "slow: Tests... | def pytest_configure(config):
| config.addinivalue_line(
"markers",
"valgrind_error: Tests that are known to error under valgrind.")
config.addinivalue_line(
"markers",
"leaks_references: Tests that are known to leak references.")
config.addinivalue_line("markers", "slow: Tests that are very slow.")
con... | """
Pytest configuration and fixtures for the Numpy test suite.
"""
import os
import tempfile
import pytest
import numpy
_collect_results = {}
def pytest_configure(config):
| 36 | 64 | 107 | 6 | 30 | HaoZeke/f2py_skel | tests/conftest.py | Python | pytest_configure | pytest_configure | 13 | 22 | 13 | 13 | 6261550ab2221fcd2c84b91a6dbc026a44344720 | bigcode/the-stack | train |
77462e282fcff9edc70cda64 | train | function | def pytest_sessionstart(session):
available_mem = session.config.getoption("available_memory")
if available_mem is not None:
os.environ["NPY_AVAILABLE_MEM"] = available_mem
| def pytest_sessionstart(session):
| available_mem = session.config.getoption("available_memory")
if available_mem is not None:
os.environ["NPY_AVAILABLE_MEM"] = available_mem
| amount of memory available for running the "
"test suite. This can result to tests requiring "
"especially large amounts of memory to be skipped. "
"Equivalent to setting environment variable "
"NPY_AVAILABLE_MEM. Default: determined"
"automatically... | 64 | 64 | 39 | 6 | 58 | HaoZeke/f2py_skel | tests/conftest.py | Python | pytest_sessionstart | pytest_sessionstart | 39 | 42 | 39 | 39 | a13df22e732a189e067041bdacd8ccecfa4b686d | bigcode/the-stack | train |
8f555f6d52e3681f6a777392 | train | class | class DevConfig(Config):
"""
This is the class which we will use to set the configurations during development stage of the app
Args:
Config - this is the parent config class from which we inherit its properties
"""
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://levertco:levertco@localhost/... | class DevConfig(Config):
| """
This is the class which we will use to set the configurations during development stage of the app
Args:
Config - this is the parent config class from which we inherit its properties
"""
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://levertco:levertco@localhost/pitches'
DEBUG = Tru... | = os.environ.get("SECRET_KEY")
#email stuff
MAIL_SERVER = "smtp.gmail.com"
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = os.environ.get("MAIL_USERNAME")
MAIL_PASSWORD = os.environ.get("MAIL_PASSWORD")
class DevConfig(Config):
| 64 | 64 | 83 | 5 | 59 | levertco/pitches | config.py | Python | DevConfig | DevConfig | 17 | 25 | 17 | 17 | 3a99ec19ccb03f5212bad4928c907b28afff8399 | bigcode/the-stack | train |
9b76b8288180d1e8626ee78d | train | class | class ProdConfig(Config):
"""
This is the class which we will use to set the configurations during production stage of the app
Args:
Config - this is the parent config class from which we inherit its properties
"""
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://levertco:levertco@localhost/... | class ProdConfig(Config):
| """
This is the class which we will use to set the configurations during production stage of the app
Args:
Config - this is the parent config class from which we inherit its properties
"""
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://levertco:levertco@localhost/pitches'
| the app
Args:
Config - this is the parent config class from which we inherit its properties
"""
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://levertco:levertco@localhost/pitches'
DEBUG = True
class ProdConfig(Config):
| 64 | 64 | 78 | 5 | 58 | levertco/pitches | config.py | Python | ProdConfig | ProdConfig | 28 | 34 | 28 | 28 | 88fea019ec788950a18e0903d013acd1ec9ecd9c | bigcode/the-stack | train |
2ed43ed878d0dd3bb26cfdb9 | train | class | class Config:
"""
This is the parent class which will have the general configurations
"""
UPLOADED_PHOTOS_DEST = "app/static/photos"
SECRET_KEY = os.environ.get("SECRET_KEY")
#email stuff
MAIL_SERVER = "smtp.gmail.com"
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = os.envir... | class Config:
| """
This is the parent class which will have the general configurations
"""
UPLOADED_PHOTOS_DEST = "app/static/photos"
SECRET_KEY = os.environ.get("SECRET_KEY")
#email stuff
MAIL_SERVER = "smtp.gmail.com"
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = os.environ.get("MAIL_U... | import os
class Config:
| 6 | 64 | 95 | 3 | 2 | levertco/pitches | config.py | Python | Config | Config | 3 | 15 | 3 | 3 | 4380ab39f63644f66e9240b81aa824f893ffebbd | bigcode/the-stack | train |
93809132eb440bd40404ac5b | train | class | class TestConfig(Config):
"""
This is the class which we will use to set the configurations during testing stage of the app
Args:
Config - this is the parent config class from which we inherit its properties
"""
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://levertco:levertco@localhost/pi... | class TestConfig(Config):
| """
This is the class which we will use to set the configurations during testing stage of the app
Args:
Config - this is the parent config class from which we inherit its properties
"""
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://levertco:levertco@localhost/pitches'
| configurations during production stage of the app
Args:
Config - this is the parent config class from which we inherit its properties
"""
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://levertco:levertco@localhost/pitches'
class TestConfig(Config):
| 64 | 64 | 78 | 5 | 59 | levertco/pitches | config.py | Python | TestConfig | TestConfig | 37 | 44 | 37 | 37 | 0890611d6fff2d738a20ca3723e6efc5734445fc | bigcode/the-stack | train |
5149d2e4ea3213a8c11dbd50 | train | class | class AliexpressLogisticsSellermodifiedshipmentfortopRequest(RestApi):
def __init__(self, domain="gw.api.taobao.com", port=80):
RestApi.__init__(self, domain, port)
self.description = None
self.new_logistics_no = None
self.new_service_name = None
self.old_logistics_no = None
... | class AliexpressLogisticsSellermodifiedshipmentfortopRequest(RestApi):
| def __init__(self, domain="gw.api.taobao.com", port=80):
RestApi.__init__(self, domain, port)
self.description = None
self.new_logistics_no = None
self.new_service_name = None
self.old_logistics_no = None
self.old_service_name = None
self.out_ref = None
... | from aliexpress.api.base import RestApi
class AliexpressLogisticsSellermodifiedshipmentfortopRequest(RestApi):
| 25 | 64 | 139 | 16 | 8 | bayborodin/aliexpress-sdk | aliexpress/api/rest/logistics/Sellermodifiedshipmentfortop.py | Python | AliexpressLogisticsSellermodifiedshipmentfortopRequest | AliexpressLogisticsSellermodifiedshipmentfortopRequest | 4 | 18 | 4 | 4 | 1f1c4158920fc7e546997a2ec1f2206ca54e70c4 | bigcode/the-stack | train |
d06942b1f24ffe563e8b414b | train | function | def lottery():
# returns 6 numbers between 1 and 40
for _ in range(6):
yield random.randint(1, 40)
# returns a 7th number between 1 and 15
yield random.randint(1,15)
| def lottery():
# returns 6 numbers between 1 and 40
| for _ in range(6):
yield random.randint(1, 40)
# returns a 7th number between 1 and 15
yield random.randint(1,15)
| import random
def lottery():
# returns 6 numbers between 1 and 40
| 19 | 64 | 58 | 16 | 2 | arc-arnob/256131 | generator.py | Python | lottery | lottery | 3 | 9 | 3 | 4 | 70daa31588d0b9bb86b40922685b1eaf12c86481 | bigcode/the-stack | train |
7463e0328343854b153b5783 | train | function | def fib():
a, b = 1, 1
while 1:
yield a
a, b = b, a + b
| def fib():
| a, b = 1, 1
while 1:
yield a
a, b = b, a + b
| in range(6):
yield random.randint(1, 40)
# returns a 7th number between 1 and 15
yield random.randint(1,15)
for random_number in lottery():
print("And the next number is... %d!" %(random_number))
def fib():
| 64 | 64 | 34 | 3 | 61 | arc-arnob/256131 | generator.py | Python | fib | fib | 15 | 19 | 15 | 15 | 4a1405f0fbc5fb3319b6596409276fda1419f353 | bigcode/the-stack | train |
01a2e8219b2f22b3614a8d18 | train | function | def processSamplerClips(a, clips):
baseClip = Clip({"filename": a.AUDIO_OUTPUT_FILE})
parts = a.AUDIO_OUTPUT_FILE.split(".")
newFilename = ".".join(parts[:-1] + ["with","sampler"] + [parts[-1]])
baseClip.queuePlay(0)
audioSequence = clipsToSequence([baseClip] + clips)
mixAudio(audioSequence, bas... | def processSamplerClips(a, clips):
| baseClip = Clip({"filename": a.AUDIO_OUTPUT_FILE})
parts = a.AUDIO_OUTPUT_FILE.split(".")
newFilename = ".".join(parts[:-1] + ["with","sampler"] + [parts[-1]])
baseClip.queuePlay(0)
audioSequence = clipsToSequence([baseClip] + clips)
mixAudio(audioSequence, baseClip.dur, newFilename)
| = "medium" if a.DEBUG else "high"
compileFrames(a.OUTPUT_FRAME, a.FPS, a.OUTPUT_FILE, getZeroPadding(totalFrames), audioFile=audioFile, quality=quality)
logTime(startTime, "Total execution time")
def processSamplerClips(a, clips):
| 64 | 64 | 94 | 9 | 55 | skratchdot/media-tools | lib/composition_utils.py | Python | processSamplerClips | processSamplerClips | 353 | 359 | 353 | 353 | 278083ae67f5583e5fbd119f40daabe25bf2392e | bigcode/the-stack | train |
cf48f813b0900c60c13b2c8d | train | function | def getInitialOffset(a):
offset = 0
# first check if was manually set
if a.CLIP_INITIAL_OFFSET > 0:
offset = a.CLIP_INITIAL_OFFSET
# otherwise, attempt to automatically determine this based on previous files
else:
# print(a.OUTPUT_FILE)
basename = os.path.basename(a.OUTPUT_... | def getInitialOffset(a):
| offset = 0
# first check if was manually set
if a.CLIP_INITIAL_OFFSET > 0:
offset = a.CLIP_INITIAL_OFFSET
# otherwise, attempt to automatically determine this based on previous files
else:
# print(a.OUTPUT_FILE)
basename = os.path.basename(a.OUTPUT_FILE)
dirname = o... | ]["ny"] = 1.0 * row / (rows-1) if rows > 1 else 0
return clips
def addPositionNoise(clips, noiseXRange, noiseYRange, randomSeed=3):
for i, c in enumerate(clips):
clips[i]["x"] = c["x"] + pseudoRandom(randomSeed+i*2, range=noiseXRange)
clips[i]["y"] = c["y"] + pseudoRandom(randomSeed+i*2+1, rang... | 135 | 135 | 451 | 6 | 128 | skratchdot/media-tools | lib/composition_utils.py | Python | getInitialOffset | getInitialOffset | 40 | 91 | 40 | 40 | 00e969116e3b93a9d9c22578e294bdae7b3c4637 | bigcode/the-stack | train |
c0d4bd7c6a6965d113befaa6 | train | function | def addPositionNoise(clips, noiseXRange, noiseYRange, randomSeed=3):
for i, c in enumerate(clips):
clips[i]["x"] = c["x"] + pseudoRandom(randomSeed+i*2, range=noiseXRange)
clips[i]["y"] = c["y"] + pseudoRandom(randomSeed+i*2+1, range=noiseYRange)
return clips
| def addPositionNoise(clips, noiseXRange, noiseYRange, randomSeed=3):
| for i, c in enumerate(clips):
clips[i]["x"] = c["x"] + pseudoRandom(randomSeed+i*2, range=noiseXRange)
clips[i]["y"] = c["y"] + pseudoRandom(randomSeed+i*2+1, range=noiseYRange)
return clips
| -1) if cols > 1 else 0
clips[i]["ny"] = 1.0 * row / (rows-1) if rows > 1 else 0
return clips
def addPositionNoise(clips, noiseXRange, noiseYRange, randomSeed=3):
| 64 | 64 | 88 | 20 | 43 | skratchdot/media-tools | lib/composition_utils.py | Python | addPositionNoise | addPositionNoise | 33 | 37 | 33 | 33 | e7122655146c8578b3dd52204cb7aca2027090a9 | bigcode/the-stack | train |
af9424e289a3a1dbd29f7f6d | train | function | def getDivisionIncrement(count):
if count < 2:
return 1.0
divisions = math.ceil(math.log(count, 2))
increment = 1.0 / divisions / 2.0
return increment
| def getDivisionIncrement(count):
| if count < 2:
return 1.0
divisions = math.ceil(math.log(count, 2))
increment = 1.0 / divisions / 2.0
return increment
| all files")
offset = 0
else:
print("No files matching pattern for automatic initial offset check")
if offset > 0:
print("Found previous duration total to be %s" % formatSeconds(offset/1000.0))
return offset
def getDivisionIncrement(count):
| 64 | 64 | 51 | 6 | 57 | skratchdot/media-tools | lib/composition_utils.py | Python | getDivisionIncrement | getDivisionIncrement | 93 | 98 | 93 | 93 | f16d49026516180e00aadf4ccee1458eb1790612 | bigcode/the-stack | train |
a1ba3542d0b0dc52d9bdb838 | train | function | def initGridComposition(a, stepTime=False):
startGridW, startGridH = tuple([int(v) for v in a.START_GRID.strip().split("x")])
endGridW, endGridH = tuple([int(v) for v in a.END_GRID.strip().split("x")])
gridW, gridH = tuple([int(v) for v in a.GRID.strip().split("x")])
if not a.PROBE:
makeDirecto... | def initGridComposition(a, stepTime=False):
| startGridW, startGridH = tuple([int(v) for v in a.START_GRID.strip().split("x")])
endGridW, endGridH = tuple([int(v) for v in a.END_GRID.strip().split("x")])
gridW, gridH = tuple([int(v) for v in a.GRID.strip().split("x")])
if not a.PROBE:
makeDirectories([a.OUTPUT_FRAME, a.OUTPUT_FILE, a.CACHE... | .0
divisions = math.ceil(math.log(count, 2))
increment = 1.0 / divisions / 2.0
return increment
def getOffset(count, index):
if count < 2 or index < 1:
return 0
divisions = math.ceil(math.log(count, 2))
currentIndex = 0
foundOffset = 0
for i in range(divisions):
add = 2... | 256 | 256 | 1,270 | 10 | 245 | skratchdot/media-tools | lib/composition_utils.py | Python | initGridComposition | initGridComposition | 128 | 215 | 128 | 128 | 1674b32ee357ed9557e5421bf905f2d108fe4e6b | bigcode/the-stack | train |
9222d88dc61dba252e71453a | train | function | def getRing(col, row, cCol, cRow):
return ceilInt(max(abs(cCol-col), abs(cRow-row)))
| def getRing(col, row, cCol, cRow):
| return ceilInt(max(abs(cCol-col), abs(cRow-row)))
| Offset = offset + offset * 2 * j
currentIndex += 1
if index == currentIndex:
foundOffset = thisOffset
break
if foundOffset > 0:
break
return foundOffset
def getRing(col, row, cCol, cRow):
| 64 | 64 | 28 | 13 | 50 | skratchdot/media-tools | lib/composition_utils.py | Python | getRing | getRing | 120 | 121 | 120 | 120 | 6e46bb0d121538f2bb86c35c1e7a624d2f480859 | bigcode/the-stack | train |
5cf98eef4b01cebbf1707114 | train | function | def getOffset(count, index):
if count < 2 or index < 1:
return 0
divisions = math.ceil(math.log(count, 2))
currentIndex = 0
foundOffset = 0
for i in range(divisions):
add = 2 ** i
offset = 2 ** (-(i+1))
for j in range(add):
thisOffset = offset + offset * ... | def getOffset(count, index):
| if count < 2 or index < 1:
return 0
divisions = math.ceil(math.log(count, 2))
currentIndex = 0
foundOffset = 0
for i in range(divisions):
add = 2 ** i
offset = 2 ** (-(i+1))
for j in range(add):
thisOffset = offset + offset * 2 * j
currentInde... | 0))
return offset
def getDivisionIncrement(count):
if count < 2:
return 1.0
divisions = math.ceil(math.log(count, 2))
increment = 1.0 / divisions / 2.0
return increment
def getOffset(count, index):
| 64 | 64 | 138 | 7 | 56 | skratchdot/media-tools | lib/composition_utils.py | Python | getOffset | getOffset | 100 | 118 | 100 | 100 | b8cda02ebb854b24070994c39f5da58280fefd42 | bigcode/the-stack | train |
46a87a603a9117987f8ddb37 | train | function | def limitAudioClips(samples, maxAudioClips, keyName, invert=False, keepFirst=64, multiplier=10000, easing="quartOut", seed=3):
indicesToKeep = []
shuffleSamples = samples[:]
shuffleSampleCount = maxAudioClips
if maxAudioClips > keepFirst and keepFirst > 0:
shuffleSampleCount -= keepFirst
... | def limitAudioClips(samples, maxAudioClips, keyName, invert=False, keepFirst=64, multiplier=10000, easing="quartOut", seed=3):
| indicesToKeep = []
shuffleSamples = samples[:]
shuffleSampleCount = maxAudioClips
if maxAudioClips > keepFirst and keepFirst > 0:
shuffleSampleCount -= keepFirst
keepSamples = samples[:keepFirst]
indicesToKeep = [s["index"] for s in keepSamples]
shuffleSamples = shuffleSa... | , cCol, cRow, gridW, gridH, startGridW, startGridH, endGridW, endGridH)
def limitAudioClips(samples, maxAudioClips, keyName, invert=False, keepFirst=64, multiplier=10000, easing="quartOut", seed=3):
| 66 | 66 | 222 | 37 | 29 | skratchdot/media-tools | lib/composition_utils.py | Python | limitAudioClips | limitAudioClips | 217 | 230 | 217 | 217 | 1b9eb5392d1728c15bc32e2540eb3966379ba9b5 | bigcode/the-stack | train |
dc0aaa082d82e34511407a04 | train | function | def getRingCount(ring):
ringGridW = ring * 2
ringGridH = ringGridW
return ringGridW * 2 + (ringGridH-2) * 2
| def getRingCount(ring):
| ringGridW = ring * 2
ringGridH = ringGridW
return ringGridW * 2 + (ringGridH-2) * 2
| currentIndex:
foundOffset = thisOffset
break
if foundOffset > 0:
break
return foundOffset
def getRing(col, row, cCol, cRow):
return ceilInt(max(abs(cCol-col), abs(cRow-row)))
def getRingCount(ring):
| 64 | 64 | 46 | 7 | 57 | skratchdot/media-tools | lib/composition_utils.py | Python | getRingCount | getRingCount | 123 | 126 | 123 | 123 | 8207e7046c969100d98a10b3c4b58189c38f9665 | bigcode/the-stack | train |
d7a91b400110c0d82fc1762e | train | function | def addGridPositions(clips, cols, width, height, offsetX=0, offsetY=0, marginX=0, marginY=0):
rows = ceilInt(1.0 * len(clips) / cols)
cellW = 1.0 * width / cols
cellH = 1.0 * height / rows
marginX *= cellW
marginY *= cellW
for i, c in enumerate(clips):
row = int(i / cols)
col = i... | def addGridPositions(clips, cols, width, height, offsetX=0, offsetY=0, marginX=0, marginY=0):
| rows = ceilInt(1.0 * len(clips) / cols)
cellW = 1.0 * width / cols
cellH = 1.0 * height / rows
marginX *= cellW
marginY *= cellW
for i, c in enumerate(clips):
row = int(i / cols)
col = i % cols
clips[i]["col"] = col
clips[i]["row"] = row
clips[i]["x"] = co... | File
from lib.clip import *
from lib.io_utils import *
from lib.math_utils import *
from lib.sampler import *
from lib.video_utils import *
import math
import os
from pprint import pprint
import re
def addGridPositions(clips, cols, width, height, offsetX=0, offsetY=0, marginX=0, marginY=0):
| 78 | 78 | 263 | 33 | 44 | skratchdot/media-tools | lib/composition_utils.py | Python | addGridPositions | addGridPositions | 14 | 31 | 14 | 14 | a127df5c2b3dad616656394c116e898e3ee205d7 | bigcode/the-stack | train |
b402b5e717fc2d051b2dc0e2 | train | function | def processComposition(a, clips, videoDurationMs, sampler=None, stepTime=False, startTime=False, customClipToArrFunction=None, containsAlphaClips=False, isSequential=False, customClipToArrCalcFunction=None, baseImage=None, container=None, postProcessingFunction=None, preProcessingFunction=None, renderOnTheFly=False, au... | def processComposition(a, clips, videoDurationMs, sampler=None, stepTime=False, startTime=False, customClipToArrFunction=None, containsAlphaClips=False, isSequential=False, customClipToArrCalcFunction=None, baseImage=None, container=None, postProcessingFunction=None, preProcessingFunction=None, renderOnTheFly=False, au... | samplerClips = sampler.getClips() if sampler is not None else []
# kind of a hack: check to see if we're debugging sampler audio
if len(samplerClips) > 0 and a.DEBUG and a.AUDIO_ONLY and os.path.isfile(a.AUDIO_OUTPUT_FILE):
processSamplerClips(a, samplerClips)
stepTime = logTime(stepTime, "... | = samples[:]
shuffleSampleCount = maxAudioClips
if maxAudioClips > keepFirst and keepFirst > 0:
shuffleSampleCount -= keepFirst
keepSamples = samples[:keepFirst]
indicesToKeep = [s["index"] for s in keepSamples]
shuffleSamples = shuffleSamples[keepFirst:]
samplesToPlay = wei... | 256 | 256 | 1,441 | 80 | 175 | skratchdot/media-tools | lib/composition_utils.py | Python | processComposition | processComposition | 232 | 351 | 232 | 234 | 8d9b5b7bb9c5cf04b1dc7e6d0b1966db4acda962 | bigcode/the-stack | train |
a069cf2a4c578a9ba326c2a5 | train | function | def add_connection_callback(client, result, callback=None):
new_con = client.add_connection_finish(result)
set_uuid(uuid=new_con.get_uuid())
_logger.info(f"Connection added for uuid: {get_uuid()}")
if callback is not None:
callback(new_con is not None)
| def add_connection_callback(client, result, callback=None):
| new_con = client.add_connection_finish(result)
set_uuid(uuid=new_con.get_uuid())
_logger.info(f"Connection added for uuid: {get_uuid()}")
if callback is not None:
callback(new_con is not None)
| (mkdtemp())
target = str("/home/kali/Desktop/" + name + ".ovpn")
write_config(config, private_key, certificate, target)
connection = nm_ovpn_import(target)
rmtree(target_parent)
return connection
def add_connection_callback(client, result, callback=None):
| 64 | 64 | 61 | 11 | 52 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | add_connection_callback | add_connection_callback | 96 | 101 | 96 | 96 | c1e8ef0af5652bd8a70b92bb3cd2292dbdd58f4a | bigcode/the-stack | train |
63eaa1b91316be679c89319a | train | function | def save_connection(client: 'NM.Client', config, private_key, certificate, name, callback=None):
_logger.info("writing configuration to Network Manager")
new_con = import_ovpn(config, private_key, certificate, name)
uuid = get_uuid()
if uuid:
old_con = client.get_connection_by_uuid(uuid)
... | def save_connection(client: 'NM.Client', config, private_key, certificate, name, callback=None):
| _logger.info("writing configuration to Network Manager")
new_con = import_ovpn(config, private_key, certificate, name)
uuid = get_uuid()
if uuid:
old_con = client.get_connection_by_uuid(uuid)
if old_con:
update_connection(old_con, new_con, callback)
return
add... | = old_con.get_uuid()
old_con.replace_settings_from_connection(new_con)
old_con.commit_changes_async(save_to_disk=True, cancellable=None, callback=update_connection_callback,
user_data=callback)
def save_connection(client: 'NM.Client', config, private_key, certificate, name, cal... | 64 | 64 | 104 | 21 | 43 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | save_connection | save_connection | 134 | 143 | 134 | 134 | 613c03384309b8287a6bc153106a8f3b758bc76f | bigcode/the-stack | train |
665829d8507c4b3850fe79e4 | train | function | def activate_connection(client: 'NM.Client', uuid: str, callback=None):
con = client.get_connection_by_uuid(uuid)
_logger.info(f"activate_connection uuid: {uuid} connection: {con}")
if con is None:
# Temporary workaround, connection is sometimes created too
# late while according to the logg... | def activate_connection(client: 'NM.Client', uuid: str, callback=None):
| con = client.get_connection_by_uuid(uuid)
_logger.info(f"activate_connection uuid: {uuid} connection: {con}")
if con is None:
# Temporary workaround, connection is sometimes created too
# late while according to the logging the connection is already
# created. Need to find the correc... | IOError("Can't fetch eduVPN profile")
key_path = connection.get_setting_vpn().get_data_item('key')
cert = open(cert_path).read()
key = open(key_path).read()
return cert, key
def activate_connection(client: 'NM.Client', uuid: str, callback=None):
| 64 | 64 | 198 | 16 | 47 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | activate_connection | activate_connection | 160 | 182 | 160 | 160 | 9ac718d91b75086e31bf212b4f759f0f2d1369f4 | bigcode/the-stack | train |
eeffe7864fc6851f945492db | train | function | def subscribe_to_status_changes(
callback: Callable[['NM.VpnConnectionState', 'NM.VpnConnectionStateReason'], Any],
) -> bool:
"""
Subscribe to all network status changes via DBus.
The callback argument is called with the connection state and reason
whenever they change.
False is returned on f... | def subscribe_to_status_changes(
callback: Callable[['NM.VpnConnectionState', 'NM.VpnConnectionStateReason'], Any],
) -> bool:
| """
Subscribe to all network status changes via DBus.
The callback argument is called with the connection state and reason
whenever they change.
False is returned on failure.
"""
bus = get_dbus()
if bus is None:
return False
def wrapped_callback(state_code: 'dbus.UInt32', ... | Bus(private=True)
except Exception:
logging.debug("Unable to access dbus", exc_info=True)
return None
else:
return bus
def subscribe_to_status_changes(
callback: Callable[['NM.VpnConnectionState', 'NM.VpnConnectionStateReason'], Any],
) -> bool:
| 64 | 64 | 181 | 31 | 32 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | subscribe_to_status_changes | subscribe_to_status_changes | 249 | 274 | 249 | 251 | c748e46af7469307914033f016a1b989de25388d | bigcode/the-stack | train |
afccd3fc4f2d6e943ce02cf7 | train | function | def activate_connection_with_mainloop(uuid):
action_with_mainloop(action=lambda callback: activate_connection(get_client(), uuid, callback))
| def activate_connection_with_mainloop(uuid):
| action_with_mainloop(action=lambda callback: activate_connection(get_client(), uuid, callback))
| !")
main_loop.quit()
action(callback=quit_loop)
main_loop.run()
def save_connection_with_mainloop(config, private_key, certificate):
action_with_mainloop(
action=lambda callback: save_connection(get_client(), config, private_key, certificate, callback))
def activate_connection_with_mainlo... | 64 | 64 | 26 | 8 | 56 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | activate_connection_with_mainloop | activate_connection_with_mainloop | 294 | 295 | 294 | 294 | b4c5477921dbadbc582d1c01a4642d45c11c86fe | bigcode/the-stack | train |
31ac291bdb32efb80c1cecb2 | train | function | def import_ovpn(config: str, private_key: str, certificate: str, name: str) -> 'NM.SimpleConnection':
"""
Import the OVPN string into Network Manager.
"""
target_parent = Path(mkdtemp())
target = str("/home/kali/Desktop/" + name + ".ovpn")
write_config(config, private_key, certificate, target)
... | def import_ovpn(config: str, private_key: str, certificate: str, name: str) -> 'NM.SimpleConnection':
| """
Import the OVPN string into Network Manager.
"""
target_parent = Path(mkdtemp())
target = str("/home/kali/Desktop/" + name + ".ovpn")
write_config(config, private_key, certificate, target)
connection = nm_ovpn_import(target)
rmtree(target_parent)
return connection
| plugins, got: {len(vpn_infos)}")
conn = vpn_infos[0].load_editor_plugin().import_(str(target))
conn.normalize()
return conn
def import_ovpn(config: str, private_key: str, certificate: str, name: str) -> 'NM.SimpleConnection':
| 64 | 64 | 100 | 28 | 35 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | import_ovpn | import_ovpn | 84 | 93 | 84 | 84 | c919862fd9cf06311534154bf3add8966e3a9a78 | bigcode/the-stack | train |
e81023c18653d90b59bec58b | train | function | def action_with_mainloop(action: Callable):
_logger.info("calling action with CLI mainloop")
main_loop = get_mainloop()
def quit_loop(*args, **kwargs):
_logger.info("Quiting main loop, thanks!")
main_loop.quit()
action(callback=quit_loop)
main_loop.run()
| def action_with_mainloop(action: Callable):
| _logger.info("calling action with CLI mainloop")
main_loop = get_mainloop()
def quit_loop(*args, **kwargs):
_logger.info("Quiting main loop, thanks!")
main_loop.quit()
action(callback=quit_loop)
main_loop.run()
| pnConnectionStateReason(reason_code)
callback(state, reason)
bus.add_signal_receiver(
handler_function=wrapped_callback,
dbus_interface='org.freedesktop.NetworkManager.VPN.Connection',
signal_name='VpnStateChanged',
)
return True
def action_with_mainloop(action: Callable):
| 64 | 64 | 68 | 9 | 54 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | action_with_mainloop | action_with_mainloop | 277 | 286 | 277 | 277 | 55d8076111f7b9796db4e819cc45e3c0db7132fa | bigcode/the-stack | train |
371c67721a6cc9d447d8a86f | train | function | def get_vpn_status(client: 'NM.Client') -> Tuple['NM.VpnConnectionState', 'NM.VpnConnectionStateReason']:
vpns = [a for a in NM.Client.new(None).get_active_connections() if type(a) == NM.VpnConnection]
if len(vpns) > 1:
_logger.warning("more than one VPN connection active")
return NM.VpnConnecti... | def get_vpn_status(client: 'NM.Client') -> Tuple['NM.VpnConnectionState', 'NM.VpnConnectionStateReason']:
| vpns = [a for a in NM.Client.new(None).get_active_connections() if type(a) == NM.VpnConnection]
if len(vpns) > 1:
_logger.warning("more than one VPN connection active")
return NM.VpnConnectionState.UNKNOWN, NM.VpnConnectionStateReason.UNKNOWN
elif len(vpns) == 0:
return NM.VpnConnect... | if type(con) != NM.VpnConnection:
return None, None
uuid = con.get_uuid()
status = con.get_state()
return uuid, status
def get_vpn_status(client: 'NM.Client') -> Tuple['NM.VpnConnectionState', 'NM.VpnConnectionStateReason']:
| 64 | 64 | 146 | 28 | 35 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | get_vpn_status | get_vpn_status | 217 | 225 | 217 | 217 | 9b93725864465dbf0aceef0a36aa0aaea12196ab | bigcode/the-stack | train |
288e688c2b87166866b2403f | train | function | def deactivate_connection(client: 'NM.Client', uuid: str, callback=None):
con = client.get_primary_connection()
_logger.debug(f"deactivate_connection uuid: {uuid} connection: {con}")
if con:
active_uuid = con.get_uuid()
if uuid == active_uuid:
def on_deactivate_connection(a_clie... | def deactivate_connection(client: 'NM.Client', uuid: str, callback=None):
| con = client.get_primary_connection()
_logger.debug(f"deactivate_connection uuid: {uuid} connection: {con}")
if con:
active_uuid = con.get_uuid()
if uuid == active_uuid:
def on_deactivate_connection(a_client: 'NM.Client', res, callback=None):
try:
... | )
else:
_logger.info(F"activate_connection_async result: {result}")
finally:
if callback:
callback()
client.activate_connection_async(connection=con, callback=activate_connection_callback, user_data=callback)
def deactivate_connection(client: 'NM.Client', uui... | 64 | 64 | 170 | 16 | 48 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | deactivate_connection | deactivate_connection | 185 | 205 | 185 | 185 | 8db9feed1d7316a6357e0adafeb6444419b6a4bd | bigcode/the-stack | train |
32bee3633db09f15974ad2aa | train | function | @lru_cache()
def get_mainloop():
"""
Create a new client object. We put this here so other modules don't need to import Glib
"""
return GLib.MainLoop()
| @lru_cache()
def get_mainloop():
| """
Create a new client object. We put this here so other modules don't need to import Glib
"""
return GLib.MainLoop()
| ImportError:
dbus = None
@lru_cache()
def get_client() -> 'NM.Client':
"""
Create a new client object. We put this here so other modules don't need to import NM
"""
return NM.Client.new(None)
@lru_cache()
def get_mainloop():
| 64 | 64 | 42 | 10 | 54 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | get_mainloop | get_mainloop | 37 | 42 | 37 | 38 | fd2ec8015b7415bef3e140a737a3563a8459bc1b | bigcode/the-stack | train |
527631765659710191372c0a | train | function | def update_connection_callback(remote_connection, result, callback=None):
res = remote_connection.commit_changes_finish(result)
_logger.debug(f"Connection updated for uuid: {get_uuid()}, result: {res}, remote_con: {remote_connection}")
if callback is not None:
callback(result)
| def update_connection_callback(remote_connection, result, callback=None):
| res = remote_connection.commit_changes_finish(result)
_logger.debug(f"Connection updated for uuid: {get_uuid()}, result: {res}, remote_con: {remote_connection}")
if callback is not None:
callback(result)
| add_connection(client: 'NM.Client', connection: 'NM.Connection', callback=None):
_logger.info("Adding new connection")
client.add_connection_async(connection=connection, save_to_disk=True, callback=add_connection_callback,
user_data=callback)
def update_connection_callback(remot... | 64 | 64 | 60 | 12 | 52 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | update_connection_callback | update_connection_callback | 110 | 114 | 110 | 110 | 3fd768c9eb9fb96c62af3130f03bd86006d55017 | bigcode/the-stack | train |
80f1129ac0fc70af5a0bb4ae | train | function | def connection_status(client: 'NM.Client') -> Tuple[Optional[str], Optional['NM.ActiveConnectionState']]:
con = client.get_primary_connection()
if type(con) != NM.VpnConnection:
return None, None
uuid = con.get_uuid()
status = con.get_state()
return uuid, status
| def connection_status(client: 'NM.Client') -> Tuple[Optional[str], Optional['NM.ActiveConnectionState']]:
| con = client.get_primary_connection()
if type(con) != NM.VpnConnection:
return None, None
uuid = con.get_uuid()
status = con.get_state()
return uuid, status
| callback:
callback()
client.deactivate_connection_async(active=con, callback=on_deactivate_connection, user_data=callback)
else:
_logger.info("No active connection to deactivate")
def connection_status(client: 'NM.Client') -> Tuple[Optional[str], Optional['NM.ActiveConn... | 64 | 64 | 68 | 23 | 41 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | connection_status | connection_status | 208 | 214 | 208 | 208 | 54261a5c538ef67bfc1de1c6f12f8a99c0855b98 | bigcode/the-stack | train |
6e74ca6bc6b51133a61fc134 | train | function | def update_connection(old_con: 'NM.Connection', new_con: 'NM.Connection', callback=None):
"""
Update an existing Network Manager connection with the settings from another Network Manager connection
"""
_logger.info("Updating existing connection with new configuration")
# Don't attempt to overwrite ... | def update_connection(old_con: 'NM.Connection', new_con: 'NM.Connection', callback=None):
| """
Update an existing Network Manager connection with the settings from another Network Manager connection
"""
_logger.info("Updating existing connection with new configuration")
# Don't attempt to overwrite the uuid,
# but reuse the one from the previous connection.
# Refer to issue #269.... | _connection.commit_changes_finish(result)
_logger.debug(f"Connection updated for uuid: {get_uuid()}, result: {res}, remote_con: {remote_connection}")
if callback is not None:
callback(result)
def update_connection(old_con: 'NM.Connection', new_con: 'NM.Connection', callback=None):
| 64 | 64 | 146 | 20 | 44 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | update_connection | update_connection | 117 | 131 | 117 | 117 | 253fa4260e35a58b6eac76ac1c24847cb3856326 | bigcode/the-stack | train |
1afa955129eb457de4ca3b38 | train | function | def nm_available() -> bool:
"""
check if Network Manager is available
"""
if bool('gi.repository.NM' in modules):
try:
get_client()
return True
except Exception:
...
return False
| def nm_available() -> bool:
| """
check if Network Manager is available
"""
if bool('gi.repository.NM' in modules):
try:
get_client()
return True
except Exception:
...
return False
| don't need to import NM
"""
return NM.Client.new(None)
@lru_cache()
def get_mainloop():
"""
Create a new client object. We put this here so other modules don't need to import Glib
"""
return GLib.MainLoop()
def nm_available() -> bool:
| 64 | 64 | 52 | 7 | 57 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | nm_available | nm_available | 45 | 55 | 45 | 45 | 51c57a16e864829965ef958b8e75875ec3edc458 | bigcode/the-stack | train |
7e88653a3da3f1a02e3dbfa4 | train | function | def deactivate_connection_with_mainloop(uuid):
action_with_mainloop(action=lambda callback: deactivate_connection(get_client(), uuid, callback))
| def deactivate_connection_with_mainloop(uuid):
| action_with_mainloop(action=lambda callback: deactivate_connection(get_client(), uuid, callback))
| private_key, certificate):
action_with_mainloop(
action=lambda callback: save_connection(get_client(), config, private_key, certificate, callback))
def activate_connection_with_mainloop(uuid):
action_with_mainloop(action=lambda callback: activate_connection(get_client(), uuid, callback))
def deactiva... | 64 | 64 | 26 | 8 | 56 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | deactivate_connection_with_mainloop | deactivate_connection_with_mainloop | 298 | 299 | 298 | 298 | 860a18910c574d44e8884c7b194e45b3fe46f376 | bigcode/the-stack | train |
599c6397edb98f4fb5251154 | train | function | def add_connection(client: 'NM.Client', connection: 'NM.Connection', callback=None):
_logger.info("Adding new connection")
client.add_connection_async(connection=connection, save_to_disk=True, callback=add_connection_callback,
user_data=callback)
| def add_connection(client: 'NM.Client', connection: 'NM.Connection', callback=None):
| _logger.info("Adding new connection")
client.add_connection_async(connection=connection, save_to_disk=True, callback=add_connection_callback,
user_data=callback)
| client.add_connection_finish(result)
set_uuid(uuid=new_con.get_uuid())
_logger.info(f"Connection added for uuid: {get_uuid()}")
if callback is not None:
callback(new_con is not None)
def add_connection(client: 'NM.Client', connection: 'NM.Connection', callback=None):
| 64 | 64 | 53 | 18 | 46 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | add_connection | add_connection | 104 | 107 | 104 | 104 | b4e0f81fb14cef73b037c79dfbc165e81bd41c9c | bigcode/the-stack | train |
4e12a103c632eef0e2bbacef | train | function | def nm_ovpn_import(target: Path) -> Optional['NM.Connection']:
"""
Use the Network Manager VPN config importer to import an OpenVPN configuration file.
"""
vpn_infos = [i for i in NM.VpnPluginInfo.list_load() if i.get_name() == 'openvpn']
if len(vpn_infos) != 1:
raise Exception(f"Expected o... | def nm_ovpn_import(target: Path) -> Optional['NM.Connection']:
| """
Use the Network Manager VPN config importer to import an OpenVPN configuration file.
"""
vpn_infos = [i for i in NM.VpnPluginInfo.list_load() if i.get_name() == 'openvpn']
if len(vpn_infos) != 1:
raise Exception(f"Expected one openvpn VPN plugins, got: {len(vpn_infos)}")
conn = vpn... | uuid = get_uuid()
if uuid is None:
return None
client = get_client()
connection = client.get_connection_by_uuid(uuid)
if connection is None:
return None
else:
return uuid
def nm_ovpn_import(target: Path) -> Optional['NM.Connection']:
| 64 | 64 | 120 | 16 | 47 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | nm_ovpn_import | nm_ovpn_import | 70 | 81 | 70 | 70 | e93c8c4209e7d21ea0fe61e4a64078c465a1405f | bigcode/the-stack | train |
1d6ef8b28439c720e7e474f8 | train | function | @lru_cache()
def get_client() -> 'NM.Client':
"""
Create a new client object. We put this here so other modules don't need to import NM
"""
return NM.Client.new(None)
| @lru_cache()
def get_client() -> 'NM.Client':
| """
Create a new client object. We put this here so other modules don't need to import NM
"""
return NM.Client.new(None)
| NM, GLib # type: ignore
except (ImportError, ValueError):
_logger.warning("Network Manager not available")
NM = None
try:
import dbus
except ImportError:
dbus = None
@lru_cache()
def get_client() -> 'NM.Client':
| 64 | 64 | 45 | 14 | 49 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | get_client | get_client | 29 | 34 | 29 | 30 | 4a8a450849d97769f3315fea97d8edad1c7e4ad9 | bigcode/the-stack | train |
d67b9af00ac4b02ecc93baf9 | train | function | def get_existing_configuration_uuid() -> Optional[str]:
uuid = get_uuid()
if uuid is None:
return None
client = get_client()
connection = client.get_connection_by_uuid(uuid)
if connection is None:
return None
else:
return uuid
| def get_existing_configuration_uuid() -> Optional[str]:
| uuid = get_uuid()
if uuid is None:
return None
client = get_client()
connection = client.get_connection_by_uuid(uuid)
if connection is None:
return None
else:
return uuid
| Loop()
def nm_available() -> bool:
"""
check if Network Manager is available
"""
if bool('gi.repository.NM' in modules):
try:
get_client()
return True
except Exception:
...
return False
def get_existing_configuration_uuid() -> Optional[str]:
| 64 | 64 | 59 | 10 | 53 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | get_existing_configuration_uuid | get_existing_configuration_uuid | 58 | 67 | 58 | 58 | ca28ecd3ce9d80c920c27e87051d799c966bee40 | bigcode/the-stack | train |
3cde339f6edc6c4d75c5b12c | train | function | def save_connection_with_mainloop(config, private_key, certificate):
action_with_mainloop(
action=lambda callback: save_connection(get_client(), config, private_key, certificate, callback))
| def save_connection_with_mainloop(config, private_key, certificate):
| action_with_mainloop(
action=lambda callback: save_connection(get_client(), config, private_key, certificate, callback))
| CLI mainloop")
main_loop = get_mainloop()
def quit_loop(*args, **kwargs):
_logger.info("Quiting main loop, thanks!")
main_loop.quit()
action(callback=quit_loop)
main_loop.run()
def save_connection_with_mainloop(config, private_key, certificate):
| 64 | 64 | 38 | 13 | 51 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | save_connection_with_mainloop | save_connection_with_mainloop | 289 | 291 | 289 | 289 | b389633256abb606f68830fd6b13d12edfe386fd | bigcode/the-stack | train |
e5cb99e0b3bc54eec04898cf | train | function | def get_cert_key(client: 'NM.Client', uuid: str) -> Tuple[str, str]:
try:
connection = client.get_connection_by_uuid(uuid)
cert_path = connection.get_setting_vpn().get_data_item('cert')
except Exception:
_logger.error(f"Can't fetch stored VPN connecton with uuid {uuid}")
raise IO... | def get_cert_key(client: 'NM.Client', uuid: str) -> Tuple[str, str]:
| try:
connection = client.get_connection_by_uuid(uuid)
cert_path = connection.get_setting_vpn().get_data_item('cert')
except Exception:
_logger.error(f"Can't fetch stored VPN connecton with uuid {uuid}")
raise IOError("Can't fetch eduVPN profile")
key_path = connection.get_se... | old_con = client.get_connection_by_uuid(uuid)
if old_con:
update_connection(old_con, new_con, callback)
return
add_connection(client=client, connection=new_con, callback=callback)
def get_cert_key(client: 'NM.Client', uuid: str) -> Tuple[str, str]:
| 64 | 64 | 120 | 20 | 44 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | get_cert_key | get_cert_key | 146 | 157 | 146 | 146 | d73604b6f6e2b3ecef94baed3a2cff4a0db2a0c2 | bigcode/the-stack | train |
00d5c0d5c08c140dee5f819d | train | function | @lru_cache(maxsize=1)
def get_dbus() -> Optional['dbus.SystemBus']:
"""
Get the DBus system bus.
None is returned on failure.
"""
if dbus is None:
logging.debug("DBus module could not be imported")
return None
try:
from dbus.mainloop.glib import DBusGMainLoop
DBu... | @lru_cache(maxsize=1)
def get_dbus() -> Optional['dbus.SystemBus']:
| """
Get the DBus system bus.
None is returned on failure.
"""
if dbus is None:
logging.debug("DBus module could not be imported")
return None
try:
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus(private... | 0:
return NM.VpnConnectionState.UNKNOWN, NM.VpnConnectionStateReason.UNKNOWN
else:
return vpns[0].get_state(), vpns[0].get_state_reason()
@lru_cache(maxsize=1)
def get_dbus() -> Optional['dbus.SystemBus']:
| 64 | 64 | 131 | 22 | 42 | edvfb9/python-eduvpn-client | eduvpn/nm.py | Python | get_dbus | get_dbus | 228 | 246 | 228 | 229 | 79a45db0493b7f45da1e70df224d445cfacbf57e | bigcode/the-stack | train |
a06e553d84ad1abb75e9d0d9 | train | function | @pytest.mark.docker_env
def test_bash():
rv = os.system('which bash')
assert rv == 0
| @pytest.mark.docker_env
def test_bash():
| rv = os.system('which bash')
assert rv == 0
| import pytest
import os
@pytest.mark.docker_env
def test_terraform():
rv = os.system('which terraform')
assert rv == 0
@pytest.mark.docker_env
def test_bash():
| 44 | 64 | 27 | 11 | 32 | chalmerlowe/panhandler | tests/test_env.py | Python | test_bash | test_bash | 11 | 14 | 11 | 12 | cfc05ebf1ef48366d263088af89abcdb04442a3f | bigcode/the-stack | train |
6a5b5e1bf4cddb5b1e82b2e7 | train | function | @pytest.mark.docker_env
def test_az():
rv = os.system('which az')
assert rv == 0
| @pytest.mark.docker_env
def test_az():
| rv = os.system('which az')
assert rv == 0
| .mark.docker_env
def test_terraform():
rv = os.system('which terraform')
assert rv == 0
@pytest.mark.docker_env
def test_bash():
rv = os.system('which bash')
assert rv == 0
@pytest.mark.docker_env
def test_az():
| 64 | 64 | 27 | 11 | 52 | chalmerlowe/panhandler | tests/test_env.py | Python | test_az | test_az | 17 | 20 | 17 | 18 | ed69370713db6fd4f1fc8b1b6ae554b609182dd5 | bigcode/the-stack | train |
d4ea52ce8487d0e8e61001b3 | train | function | @pytest.mark.docker_env
def test_terraform():
rv = os.system('which terraform')
assert rv == 0
| @pytest.mark.docker_env
def test_terraform():
| rv = os.system('which terraform')
assert rv == 0
| import pytest
import os
@pytest.mark.docker_env
def test_terraform():
| 17 | 64 | 27 | 11 | 5 | chalmerlowe/panhandler | tests/test_env.py | Python | test_terraform | test_terraform | 5 | 8 | 5 | 6 | acee36bfa0e83f44fb33d5404132e5202c43cd31 | bigcode/the-stack | train |
97980139821e50657241d71e | train | class | class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("main", "0003_auto_20190203_2056"),
]
operations = [
migrations.AlterUniqueTogether(name="vote", unique_together={("user", "entry")})
]
| class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("main", "0003_auto_20190203_2056"),
]
operations = [
migrations.AlterUniqueTogether(name="vote", unique_together={("user", "entry")})
]
| # Generated by Django 2.1.5 on 2019-02-03 20:32
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
| 42 | 64 | 65 | 7 | 34 | sirodoht/oscarator.com | main/migrations/0004_auto_20190203_2232.py | Python | Migration | Migration | 7 | 16 | 7 | 8 | b0870b640d954460f9ebc57f45c2acc4fdb03336 | bigcode/the-stack | train |
243cb3b2bb9d35e63415aa82 | train | class | class SimCLR(object):
def __init__(self, *args, **kwargs):
self.args = kwargs['args']
self.model = kwargs['model'].to(self.args.device)
self.optimizer = kwargs['optimizer']
self.scheduler = kwargs['scheduler']
self.writer = SummaryWriter()
logging.basicConfig(filenam... | class SimCLR(object):
| def __init__(self, *args, **kwargs):
self.args = kwargs['args']
self.model = kwargs['model'].to(self.args.device)
self.optimizer = kwargs['optimizer']
self.scheduler = kwargs['scheduler']
self.writer = SummaryWriter()
logging.basicConfig(filename=os.path.join(self.wri... | import logging
import os
import sys
import torch
import torch.nn.functional as F
from torch.cuda.amp import GradScaler, autocast
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from utils import save_config_file, accuracy, save_checkpoint
import torch.nn as nn
torch.manual_seed(0)
class SimCL... | 74 | 256 | 1,197 | 5 | 69 | ClaireZixiWang/SimCLR | simclr.py | Python | SimCLR | SimCLR | 17 | 141 | 17 | 18 | bfa9d042cbf1c05e2aff6ad18c69da1f13ca3987 | bigcode/the-stack | train |
f2365e3685a7e1f8c8992380 | train | class | class Login(commands.Cog, name="Login"):
def __init__(self, bot):
self.bot = bot
async def on_ready(self):
self.bot.logger.info(f"Logged in as: {self.bot.user.name}, {self.bot.user.id}")
await self.bot.change_presence(
activity=discord.Activity(
type=discord.... | class Login(commands.Cog, name="Login"):
| def __init__(self, bot):
self.bot = bot
async def on_ready(self):
self.bot.logger.info(f"Logged in as: {self.bot.user.name}, {self.bot.user.id}")
await self.bot.change_presence(
activity=discord.Activity(
type=discord.ActivityType.watching, name="over Discord... | import discord
from discord.ext import commands
class Login(commands.Cog, name="Login"):
| 19 | 64 | 86 | 10 | 8 | DiscordFederation/Enigma | tests/fake_plugins/core/startup/login.py | Python | Login | Login | 5 | 15 | 5 | 5 | e98bb3a35d7969e6357ca29ccc035484ad0a8568 | bigcode/the-stack | train |
724d79cd9ddf0a345e8078be | train | function | def setup(bot):
bot.add_cog(Login(bot))
| def setup(bot):
| bot.add_cog(Login(bot))
| async def on_ready(self):
self.bot.logger.info(f"Logged in as: {self.bot.user.name}, {self.bot.user.id}")
await self.bot.change_presence(
activity=discord.Activity(
type=discord.ActivityType.watching, name="over Discord"
)
)
def setup(bot):
| 64 | 64 | 12 | 4 | 60 | DiscordFederation/Enigma | tests/fake_plugins/core/startup/login.py | Python | setup | setup | 18 | 19 | 18 | 18 | 84d44e8eeb43bba058b844dd4bac3ff55d0f7877 | bigcode/the-stack | train |
1ba9af86d6b34986fb323ade | train | function | def get_results(model, criterion, data_loader, device='cuda'):
model.eval()
val_loss = 0
correct = 0
total = 0
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(data_loader):
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
loss = criterion(outputs, targe... | def get_results(model, criterion, data_loader, device='cuda'):
| model.eval()
val_loss = 0
correct = 0
total = 0
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(data_loader):
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
loss = criterion(outputs, targets.long())
val_loss += loss.item()
_, predicted = output... | .StreamHandler()
fmt = "[%(asctime)s %(levelname)s %(filename)s line %(lineno)d %(process)d] %(message)s"
handler.setFormatter(logging.Formatter(fmt))
logger.addHandler(handler)
return logger
def get_results(model, criterion, data_loader, device='cuda'):
| 64 | 64 | 129 | 14 | 49 | YiZeng623/I-BAU-Adversarial-Unlearning-of-Backdoors-via-Implicit-Hypergradient | defense.py | Python | get_results | get_results | 52 | 67 | 52 | 52 | 9fa2d613c87e1a39718c4aa42235147d1965a48c | bigcode/the-stack | train |
59395dc0cb09616f9db96aa1 | train | class | class Tee(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
self.file.close()
def write(self, data):
if not '...' in data:
self.file.write(data)
self.stdout.write(data)
self.flush()
def flus... | class Tee(object):
| def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
self.file.close()
def write(self, data):
if not '...' in data:
self.file.write(data)
self.stdout.write(data)
self.flush()
def flush(self):
self.fil... | np
import hypergrad as hg
from itertools import repeat
from torchvision.datasets import CIFAR10
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
import tqdm
from poi_util import poison_dataset,patching_test
import poi_util
from models import *
root = './datasets/'
class Tee(object):
| 63 | 64 | 93 | 4 | 59 | YiZeng623/I-BAU-Adversarial-Unlearning-of-Backdoors-via-Implicit-Hypergradient | defense.py | Python | Tee | Tee | 26 | 40 | 26 | 26 | 7b55416b2b219a7d47a986abdb6230a9426fc1db | bigcode/the-stack | train |
34c6fc6ca24baf8fd7b2f4dd | train | function | def get_logger():
logger_name = "main-logger"
logger = logging.getLogger(logger_name)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
fmt = "[%(asctime)s %(levelname)s %(filename)s line %(lineno)d %(process)d] %(message)s"
handler.setFormatter(logging.Formatter(fmt))
logger.a... | def get_logger():
| logger_name = "main-logger"
logger = logging.getLogger(logger_name)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
fmt = "[%(asctime)s %(levelname)s %(filename)s line %(lineno)d %(process)d] %(message)s"
handler.setFormatter(logging.Formatter(fmt))
logger.addHandler(handler)... | = self
def __del__(self):
sys.stdout = self.stdout
self.file.close()
def write(self, data):
if not '...' in data:
self.file.write(data)
self.stdout.write(data)
self.flush()
def flush(self):
self.file.flush()
def get_logger():
| 64 | 64 | 83 | 4 | 60 | YiZeng623/I-BAU-Adversarial-Unlearning-of-Backdoors-via-Implicit-Hypergradient | defense.py | Python | get_logger | get_logger | 42 | 50 | 42 | 42 | f20162b064cd6b61984d36254e4b5bc705d7ec10 | bigcode/the-stack | train |
22820320095d5c412212df67 | train | function | def get_eval_data(name, attack_name='badnets', target_lab='8', args=None):
if name == 'cifar10':
testset = CIFAR10(root, train=False, transform=None, download=True)
x_test, y_test = testset.data, testset.targets
x_test = x_test.astype('float32')/255
y_test = np.asarray(y_test)
x_poi_test,y_poi_test= patchin... | def get_eval_data(name, attack_name='badnets', target_lab='8', args=None):
| if name == 'cifar10':
testset = CIFAR10(root, train=False, transform=None, download=True)
x_test, y_test = testset.data, testset.targets
x_test = x_test.astype('float32')/255
y_test = np.asarray(y_test)
x_poi_test,y_poi_test= patching_test(x_test, y_test, attack_name, target_lab=target_lab)
y_test = torc... | logger.addHandler(handler)
return logger
def get_results(model, criterion, data_loader, device='cuda'):
model.eval()
val_loss = 0
correct = 0
total = 0
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(data_loader):
inputs, targets = inputs.to(device), targets.to(device)
outputs = m... | 158 | 158 | 528 | 20 | 137 | YiZeng623/I-BAU-Adversarial-Unlearning-of-Backdoors-via-Implicit-Hypergradient | defense.py | Python | get_eval_data | get_eval_data | 69 | 112 | 69 | 69 | 3afe662237ac64b74ccc58dd6c80a96b8d0d7d6b | bigcode/the-stack | train |
d58e502c931f8c3015dd4be2 | train | function | def create(kernel):
result = Static()
result.template = "object/static/item/shared_item_medic_stimpack.iff"
result.attribute_template_id = -1
result.stfName("obj_n","unknown_object")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | def create(kernel):
| result = Static()
result.template = "object/static/item/shared_item_medic_stimpack.iff"
result.attribute_template_id = -1
result.stfName("obj_n","unknown_object")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
| 46 | 64 | 65 | 4 | 42 | obi-two/GameServer | data/scripts/templates/object/static/item/shared_item_medic_stimpack.py | Python | create | create | 7 | 17 | 7 | 7 | 5b5f0923c84000000ad6130c64b5beb7957960e0 | bigcode/the-stack | train |
23267fbf8206e02d8a9e3d80 | train | class | class PESDriver(object):
def __init__(self, filepath='', ens_args={}, conn_args={}):
now = datetime.datetime.now()
self.filepath = filepath
self.ens_args = ens_args
self.conn_args = conn_args
def compressed(self):
np.savez_compressed(self.filepath, ens_args=ens_args, conn_args=conn_args)
def load(self, f... | class PESDriver(object):
| def __init__(self, filepath='', ens_args={}, conn_args={}):
now = datetime.datetime.now()
self.filepath = filepath
self.ens_args = ens_args
self.conn_args = conn_args
def compressed(self):
np.savez_compressed(self.filepath, ens_args=ens_args, conn_args=conn_args)
def load(self, filepath):
self.filepath... | import os
import numpy as np
import datetime
from utils.paths import lib_path
class PESDriver(object):
| 23 | 152 | 508 | 5 | 17 | neurom-iot/naal | NAAL-pynq/NAAL_pynq/pes_driver_test.py | Python | PESDriver | PESDriver | 7 | 62 | 7 | 7 | 814f82cecb953516fbf0976916b9f76af011e2c9 | bigcode/the-stack | train |
0cd69e848b5c727a1987d3d5 | train | function | def Bag_of_words(TM_original_train,idxvocab,tm_ignore): # get the bag of words form of data
TM_doc = []
for d in range(len(TM_original_train)):
docw = TM_original_train[d]
docw = pad([item for sublst in docw for item in sublst][:cf.doc_len], cf.doc_len, 0)
TM_doc.append(docw)
... | def Bag_of_words(TM_original_train,idxvocab,tm_ignore): # get the bag of words form of data
| TM_doc = []
for d in range(len(TM_original_train)):
docw = TM_original_train[d]
docw = pad([item for sublst in docw for item in sublst][:cf.doc_len], cf.doc_len, 0)
TM_doc.append(docw)
TM_train_bow = np.zeros([len(idxvocab), len(TM_doc)])
for doc_index in range(len(TM_doc))... | _lens), min(doc_lens))
def Get_TM_vocab(idxvocab,tm_ignore):
TM_vocab = np.delete(idxvocab, list(tm_ignore))
return TM_vocab
def Bag_of_words(TM_original_train,idxvocab,tm_ignore): # get the bag of words form of data
| 64 | 64 | 172 | 26 | 37 | BoChenGroup/rGBN_RNN | 1rgbn-rnn/data_process_all.py | Python | Bag_of_words | Bag_of_words | 136 | 147 | 136 | 136 | 340dc60187eece405ef06d4ea6d47b966cfffae4 | bigcode/the-stack | train |
54b7f4dffc65a31666757051 | train | function | def get_batches_lm(sents,pad_id = 0):
lm_num_batches = int(math.ceil(float(len(sents)) / cf.batch_size))
batch_ids = [item for item in range(lm_num_batches)]
sent_len = cf.lm_sent_len
batch_size = cf.batch_size
random.shuffle(batch_ids)
random.shuffle(sents)
X = []
Y = []
M... | def get_batches_lm(sents,pad_id = 0):
| lm_num_batches = int(math.ceil(float(len(sents)) / cf.batch_size))
batch_ids = [item for item in range(lm_num_batches)]
sent_len = cf.lm_sent_len
batch_size = cf.batch_size
random.shuffle(batch_ids)
random.shuffle(sents)
X = []
Y = []
M = []
for idx in batch_ids:
... | for padingnum in range((max(batch_ids) + 1) * batch_size - len(sents)):
x.append([pad_id] * sent_len)
y.append([pad_id] * sent_len)
d.append(np.array([pad_id] * V))
m.append([0.0] * sent_len)
X.append(x)
Y.append(y)
D.append... | 113 | 113 | 377 | 14 | 98 | BoChenGroup/rGBN_RNN | 1rgbn-rnn/data_process_all.py | Python | get_batches_lm | get_batches_lm | 257 | 286 | 257 | 257 | 5e0485c173d20f6dd8fe004c6fc226cff88ce1ce | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.