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
5222c24daf4daa4f479f740d
train
class
class LGP(Model): def __init__(self, n_nearest=None, norm_X=NoNormalization(), # norm_y=NoNormalization(), kernel="gaussian", n_max_iter=0, # norm_X=Standardization(), norm_y=ZeroToOneNormalizatio...
class LGP(Model):
def __init__(self, n_nearest=None, norm_X=NoNormalization(), # norm_y=NoNormalization(), kernel="gaussian", n_max_iter=0, # norm_X=Standardization(), norm_y=ZeroToOneNormalization(), ...
(x[None, :]) y_hat = out["y"][0] return y_hat, kernel def mse(params, fac, n_closest, X, Y, x, y): y_hat, kernel = predict(params, fac, n_closest, X, Y, x) mse = (y_hat - y) ** 2 return mse[0] def kernel_from_params(fac, params): theta = anp.exp(params[0]) kernel = fac.create(theta=thet...
210
210
701
5
205
anyoptimization/ezmodel
ezmodel/experimental/custom2/lgp.py
Python
LGP
LGP
50
140
50
51
e5574c9adb47253d2fcbed80a3e67ceea4c18e67
bigcode/the-stack
train
00e726b7d2b4fb3f1cce8211
train
function
@pytest.fixture def sms(): return factories.SmsFactory()
@pytest.fixture def sms():
return factories.SmsFactory()
import pytest from apps.sms.tests import factories @pytest.fixture def sms():
16
64
13
6
9
ukwahlula/django-server-boilerplate
{{cookiecutter.project_slug}}/apps/sms/tests/fixtures.py
Python
sms
sms
6
8
6
7
94fa12cd2c98b7b6099e0779fe29a28471c67334
bigcode/the-stack
train
ff6942b9665dffedcdfcf611
train
class
class ProfileStatsFile(object): """Store per-platform/fn profiling results in a file. There was no json module available when this was written, but now the file format which is very deterministically line oriented is kind of handy in any case for diffs and merges. """ def __init__(self, filen...
class ProfileStatsFile(object):
"""Store per-platform/fn profiling results in a file. There was no json module available when this was written, but now the file format which is very deterministically line oriented is kind of handy in any case for diffs and merges. """ def __init__(self, filename, sort="cumulative", dump=Non...
# testing/profiling.py # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php """Profiling support for unit and performance tests. These are special purpos...
250
256
1,285
6
244
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/sqlalchemy/testing/profiling.py
Python
ProfileStatsFile
ProfileStatsFile
58
226
58
58
7477114e0c183dc658eca356028f5087396e9b3b
bigcode/the-stack
train
25160658373333a320163ab1
train
function
def function_call_count(variance=0.05, times=1, warmup=0): """Assert a target for a test case's function call count. The main purpose of this assertion is to detect changes in callcounts for various functions - the actual number is not as important. Callcounts are stored in a file keyed to Python versi...
def function_call_count(variance=0.05, times=1, warmup=0):
"""Assert a target for a test case's function call count. The main purpose of this assertion is to detect changes in callcounts for various functions - the actual number is not as important. Callcounts are stored in a file keyed to Python version and OS platform information. This file is generated...
s\n\n" % test_key) for platform_key in sorted(per_fn): per_platform = per_fn[platform_key] c = ",".join(str(count) for count in per_platform["counts"]) profile_f.write("%s %s %s\n" % (test_key, platform_key, c)) profile_f.close() def function_call_coun...
91
91
306
20
71
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/sqlalchemy/testing/profiling.py
Python
function_call_count
function_call_count
229
266
229
229
9bff56711a900ce9ad5ee7e709d0be8cfad94f45
bigcode/the-stack
train
50e5895a385846ac98f3332f
train
function
def _start_current_test(id_): global _current_test _current_test = id_ if _profile_stats.force_write: _profile_stats.reset_count()
def _start_current_test(id_):
global _current_test _current_test = id_ if _profile_stats.force_write: _profile_stats.reset_count()
= None _profile_stats = None """global ProfileStatsFileInstance. plugin_base assigns this at the start of all tests. """ _current_test = None """String id of current test. plugin_base assigns this at the start of each test using _start_current_test. """ def _start_current_test(id_):
64
64
36
8
56
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/sqlalchemy/testing/profiling.py
Python
_start_current_test
_start_current_test
50
55
50
50
8a07b79957a2d207ea2625a8522ed69d9842e104
bigcode/the-stack
train
88531114dee0c30f708acc78
train
function
@contextlib.contextmanager def count_functions(variance=0.05): if cProfile is None: raise config._skip_test_exception("cProfile is not installed") if not _profile_stats.has_stats() and not _profile_stats.write: config.skip_test( "No profiling stats available on this " "p...
@contextlib.contextmanager def count_functions(variance=0.05):
if cProfile is None: raise config._skip_test_exception("cProfile is not installed") if not _profile_stats.has_stats() and not _profile_stats.write: config.skip_test( "No profiling stats available on this " "platform for this function. Run tests with " "--wri...
from sqlalchemy.testing import mock @decorator def wrap(fn, *args, **kw): with mock.patch.object( deprecations, "SQLALCHEMY_WARN_20", False ), mock.patch.object( row.LegacyRow, "_default_key_style", row.KEY_OBJECTS_NO_WARN ): for warm in range(w...
146
146
488
16
129
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/sqlalchemy/testing/profiling.py
Python
count_functions
count_functions
269
335
269
270
516bb39fbd51005dca1db7fad1733ec7981857eb
bigcode/the-stack
train
63d8730d5ec68ec7daf049f1
train
class
class Struct: def __init__(self, **args): self._urls = {} self._urls.update(args) def get_url(self, key): return self._urls[key] def __getattr__(self, key): return self._urls[key] def __str__(self): return str(self._urls) def __repr__(self): retur...
class Struct:
def __init__(self, **args): self._urls = {} self._urls.update(args) def get_url(self, key): return self._urls[key] def __getattr__(self, key): return self._urls[key] def __str__(self): return str(self._urls) def __repr__(self): return str(self._url...
import os import json class Struct:
9
64
86
3
5
jmchandonia/narrative
src/biokbase/narrative/common/url_config.py
Python
Struct
Struct
5
21
5
6
54f948ae071431b7dde3f4f4f713d6bd4324ce45
bigcode/the-stack
train
57e3e1e8f0b24074a5d6aecf
train
function
def example(variant): import torch logger.log(torch.__version__) date_format = "%m/%d/%Y %H:%M:%S %Z" date = datetime.now(tz=pytz.utc) logger.log("start") logger.log("Current date & time is: {}".format(date.strftime(date_format))) if torch.cuda.is_available(): x = torch.randn(3) ...
def example(variant):
import torch logger.log(torch.__version__) date_format = "%m/%d/%Y %H:%M:%S %Z" date = datetime.now(tz=pytz.utc) logger.log("start") logger.log("Current date & time is: {}".format(date.strftime(date_format))) if torch.cuda.is_available(): x = torch.randn(3) logger.log(str(x....
""" Example of running stuff on EC2 """ import time from datetime import datetime import pytz from pytz import timezone from rlkit.core import logger from rlkit.launchers.launcher_util import run_experiment def example(variant):
53
71
237
5
47
mihdalal/raps
rlkit/examples/doodad/ec2_example.py
Python
example
example
14
40
14
14
58dfd5c730fe75e5fe1f593a70719cf787cf7a8e
bigcode/the-stack
train
8ca33d7309dc5dcebb2b6f5d
train
function
@pytest.fixture def volume(): return read_mrc(MRC_FILE)
@pytest.fixture def volume():
return read_mrc(MRC_FILE)
import pytest from have_your_cake.mrc import read_mrc MRC_FILE = '../../emd_10160.map' @pytest.fixture def mrc_file(): return MRC_FILE @pytest.fixture def volume():
47
64
15
6
40
bbarad/have_your_cake
have_your_cake/tests/conftest.py
Python
volume
volume
12
14
12
13
a53d85a9745cfb840761d983ffed11181c382b71
bigcode/the-stack
train
9ceb2285a24cf54bed9e9313
train
function
@pytest.fixture def mrc_file(): return MRC_FILE
@pytest.fixture def mrc_file():
return MRC_FILE
import pytest from have_your_cake.mrc import read_mrc MRC_FILE = '../../emd_10160.map' @pytest.fixture def mrc_file():
35
64
14
8
27
bbarad/have_your_cake
have_your_cake/tests/conftest.py
Python
mrc_file
mrc_file
7
9
7
8
3d9a039cb1bb015757f0eb178c5a08a70c56f09c
bigcode/the-stack
train
e15ffad0b93f5c721bbcea97
train
class
class LinearFeedbackShiftRegister(Module): """ A linear feedback shift register. Useful for generating long pseudorandom sequences with a minimal amount of logic. Use ``CEInserter`` and ``ResetInserter`` transformers to control the LFSR. :param degree: Width of register, in bits. :type...
class LinearFeedbackShiftRegister(Module):
""" A linear feedback shift register. Useful for generating long pseudorandom sequences with a minimal amount of logic. Use ``CEInserter`` and ``ResetInserter`` transformers to control the LFSR. :param degree: Width of register, in bits. :type degree: int :param taps: Feedb...
from migen import * __all__ = ["LinearFeedbackShiftRegister"] class LinearFeedbackShiftRegister(Module):
22
105
351
7
15
yorickvP/Glasgow
software/glasgow/gateware/lfsr.py
Python
LinearFeedbackShiftRegister
LinearFeedbackShiftRegister
7
52
7
7
ac6776db55d96b446e0d09c7901f29d0832b5043
bigcode/the-stack
train
5fb10226cc96ee602a8b6ea8
train
class
class LFSRTestCase(unittest.TestCase): def setUp(self): self.tb = LFSRTestbench(degree=16, taps=(16, 14, 13, 11)) @simulation_test def test_generate(self, tb): soft_values = list(self.tb.dut.generate()) hard_values = [] for _ in range(len(soft_values)): hard_valu...
class LFSRTestCase(unittest.TestCase):
def setUp(self): self.tb = LFSRTestbench(degree=16, taps=(16, 14, 13, 11)) @simulation_test def test_generate(self, tb): soft_values = list(self.tb.dut.generate()) hard_values = [] for _ in range(len(soft_values)): hard_values.append((yield self.tb.dut.value)) ...
# ------------------------------------------------------------------------------------------------- import unittest from migen.fhdl import verilog from . import simulation_test class LFSRTestbench(Module): def __init__(self, **kwargs): self.submodules.dut = LinearFeedbackShiftRegister(**kwargs) class ...
64
64
121
10
54
yorickvP/Glasgow
software/glasgow/gateware/lfsr.py
Python
LFSRTestCase
LFSRTestCase
67
80
67
67
df08e73f251e191779a0145652dbe0ab2cc56937
bigcode/the-stack
train
115f19d0321dd298c2743940
train
class
class LFSRTestbench(Module): def __init__(self, **kwargs): self.submodules.dut = LinearFeedbackShiftRegister(**kwargs)
class LFSRTestbench(Module):
def __init__(self, **kwargs): self.submodules.dut = LinearFeedbackShiftRegister(**kwargs)
(tap - 1)) & 1 value = ((value << 1) & mask) | feedback if value == self.reset: break # ------------------------------------------------------------------------------------------------- import unittest from migen.fhdl import verilog from . import simulation_test class LFSRTes...
64
64
32
8
55
yorickvP/Glasgow
software/glasgow/gateware/lfsr.py
Python
LFSRTestbench
LFSRTestbench
62
64
62
62
7ffcaa66a6955b8fe1df91ccbf14d2b5337a1654
bigcode/the-stack
train
062cc1d36c55844ddcbba040
train
function
@try_json def create_blocksat_order(message: str, bid: str, network: str, uuid): logger.debug("Creating blocksat order") if network.strip().lower() == "testnet": satellite_url = CONFIG["blocksat"]["TESTNET_URL"] elif network.strip().lower() == "mainnet": satellite_url = CONFIG["blocksat"]["M...
@try_json def create_blocksat_order(message: str, bid: str, network: str, uuid):
logger.debug("Creating blocksat order") if network.strip().lower() == "testnet": satellite_url = CONFIG["blocksat"]["TESTNET_URL"] elif network.strip().lower() == "mainnet": satellite_url = CONFIG["blocksat"]["MAINNET_URL"] else: return {"response": "Invalid network"} db.orde...
na.database as db from lntenna.server.config import CONFIG from lntenna.swap.utilities import try_json logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG, format=CONFIG["logging"]["FORMAT"]) @try_json def create_blocksat_order(message: str, bid: str, network: str, uuid):
70
71
239
23
47
willcl-ark/lntenna-python
lntenna/swap/create_blocksat_order.py
Python
create_blocksat_order
create_blocksat_order
14
36
14
15
15349da9fa476187f7d468936278289fe7c4d032
bigcode/the-stack
train
75d78171a18b50d051008b79
train
class
class TestChordFromNoteIndex(unittest.TestCase): def test_note_1(self): chord = Chord.from_note_index(note=1, quality="", scale="Cmaj") self.assertEqual(chord, Chord("C")) def test_note_2(self): chord = Chord.from_note_index(note=2, quality="m7", scale="F#min") self.assertEqual...
class TestChordFromNoteIndex(unittest.TestCase):
def test_note_1(self): chord = Chord.from_note_index(note=1, quality="", scale="Cmaj") self.assertEqual(chord, Chord("C")) def test_note_2(self): chord = Chord.from_note_index(note=2, quality="m7", scale="F#min") self.assertEqual(chord, Chord("G#m7")) def test_note_3(self):...
Equal(c.root, "D") self.assertEqual(c.quality.quality, "m7b5") def test_invalid_slash_chord(self): self.assertRaises(ValueError, Chord, "C/H") def test_eq(self): c1 = Chord("C") c2 = Chord("C") self.assertEqual(c1, c2) def test_eq_alias(self): c1 = Chord("C...
159
159
532
10
149
adamnemecek/pychord
test/test_chord.py
Python
TestChordFromNoteIndex
TestChordFromNoteIndex
75
123
75
76
397f184e5feab7f70bca5c70d5277eebbe5e8023
bigcode/the-stack
train
266c5dae7fd58fddc79ab677
train
class
class TestChordCreations(unittest.TestCase): def test_normal_chord(self): c = Chord("C") self.assertEqual(c.root, "C") self.assertEqual(c.quality.quality, "") def test_invalid_chord(self): self.assertRaises(ValueError, Chord, "H") def test_minor_chord(self): c = Ch...
class TestChordCreations(unittest.TestCase):
def test_normal_chord(self): c = Chord("C") self.assertEqual(c.root, "C") self.assertEqual(c.quality.quality, "") def test_invalid_chord(self): self.assertRaises(ValueError, Chord, "H") def test_minor_chord(self): c = Chord("Am") self.assertEqual(c.root, "A"...
import unittest from pychord import Chord class TestChordCreations(unittest.TestCase):
20
160
535
9
10
adamnemecek/pychord
test/test_chord.py
Python
TestChordCreations
TestChordCreations
6
72
6
7
0f9cee1a8e3e317182cc269231ca60e6bcb973ac
bigcode/the-stack
train
79774f0a4786732b69c9b69d
train
class
class ClientDirectory: def __init__(self, parent, handle): self.parent = parent self.handle = NS(handle) self.filesCache = [] def read(self): d = self.parent._sendRequest(FXP_READDIR, self.handle) return d def close(self): return self.parent._sendRequest(FX...
class ClientDirectory:
def __init__(self, parent, handle): self.parent = parent self.handle = NS(handle) self.filesCache = [] def read(self): d = self.parent._sendRequest(FXP_READDIR, self.handle) return d def close(self): return self.parent._sendRequest(FXP_CLOSE, self.handle) ...
_WRITE, data) def getAttrs(self): return self.parent._sendRequest(FXP_FSTAT, self.handle) def setAttrs(self, attrs): data = self.handle + self.parent._packAttributes(attrs) return self.parent._sendRequest(FXP_FSTAT, data) class ClientDirectory:
64
64
201
4
60
hawkowl/twisted
twisted/conch/ssh/filetransfer.py
Python
ClientDirectory
ClientDirectory
817
851
817
818
e0d0ceb6d9556dafe624871d7c28177fd9ce8e08
bigcode/the-stack
train
cc76c8fe587ca22d3d2679c3
train
class
class FileTransferBase(protocol.Protocol): versions = (3, ) packetTypes = {} def __init__(self): self.buf = b'' self.otherVersion = None # this gets set def sendPacket(self, kind, data): self.transport.write(struct.pack('!LB', len(data)+1, kind) + data) def dataReceived(...
class FileTransferBase(protocol.Protocol):
versions = (3, ) packetTypes = {} def __init__(self): self.buf = b'' self.otherVersion = None # this gets set def sendPacket(self, kind, data): self.transport.write(struct.pack('!LB', len(data)+1, kind) + data) def dataReceived(self, data): self.buf += data ...
# -*- test-case-name: twisted.conch.test.test_filetransfer -*- # # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from __future__ import division, absolute_import import errno import struct from zope.interface import implementer from twisted.conch.interfaces import ISFTPServer, ISFTPFile from...
124
256
898
7
117
hawkowl/twisted
twisted/conch/ssh/filetransfer.py
Python
FileTransferBase
FileTransferBase
22
118
22
23
48bffb3e7ab45dd036f047e39e122cf0dee57f7e
bigcode/the-stack
train
55b7036d784fb56e825a6f94
train
class
class FileTransferClient(FileTransferBase): def __init__(self, extData = {}): """ @param extData: a dict of extended_name : extended_data items to be sent to the server. """ FileTransferBase.__init__(self) self.extData = {} self.counter = 0 self.openR...
class FileTransferClient(FileTransferBase):
def __init__(self, extData = {}): """ @param extData: a dict of extended_name : extended_data items to be sent to the server. """ FileTransferBase.__init__(self) self.extData = {} self.counter = 0 self.openRequests = {} # id -> Deferred self.wa...
Error): # EOF code = FX_EOF if reason.value.args: message = networkString(reason.value.args[0]) elif isinstance(reason.value, NotImplementedError): code = FX_OP_UNSUPPORTED if reason.value.args: message = networkString(reason.value....
255
256
2,578
8
247
hawkowl/twisted
twisted/conch/ssh/filetransfer.py
Python
FileTransferClient
FileTransferClient
470
789
470
471
58bb80f0bd846dbafd7709adf4517972c517dd5d
bigcode/the-stack
train
bdfdb703f067a260033efe3e
train
class
class SFTPError(Exception): def __init__(self, errorCode, errorMessage, lang = ''): Exception.__init__(self) self.code = errorCode self._message = errorMessage self.lang = lang def message(self): """ A string received over the network that explains the error to...
class SFTPError(Exception):
def __init__(self, errorCode, errorMessage, lang = ''): Exception.__init__(self) self.code = errorCode self._message = errorMessage self.lang = lang def message(self): """ A string received over the network that explains the error to a human. """ ...
cbReadDir(self, names): self.filesCache = names[1:] return names[0] def _ebReadDir(self, reason): reason.trap(EOFError) def _(): raise StopIteration self.next = _ return reason class SFTPError(Exception):
64
64
187
6
57
hawkowl/twisted
twisted/conch/ssh/filetransfer.py
Python
SFTPError
SFTPError
854
877
854
855
cc33f75b8587fffc04a3127ae749822177da6e92
bigcode/the-stack
train
c33c190946d5958cc4c831c7
train
class
@implementer(ISFTPFile) class ClientFile: def __init__(self, parent, handle): self.parent = parent self.handle = NS(handle) def close(self): return self.parent._sendRequest(FXP_CLOSE, self.handle) def readChunk(self, offset, length): data = self.handle + struct.pack("!QL", ...
@implementer(ISFTPFile) class ClientFile:
def __init__(self, parent, handle): self.parent = parent self.handle = NS(handle) def close(self): return self.parent._sendRequest(FXP_CLOSE, self.handle) def readChunk(self, offset, length): data = self.handle + struct.pack("!QL", offset, length) return self.parent...
@param otherVersion: an integer representing the version of the SFTP protocol they are claiming. @param extData: a dictionary of extended_name : extended_data items. These items are sent by the client to indicate additional features. """ @implementer(ISFTPFile) class ClientFile:
63
64
190
11
52
hawkowl/twisted
twisted/conch/ssh/filetransfer.py
Python
ClientFile
ClientFile
793
815
793
794
ca3d47ef5e9824f6b14e96eee49a4daf8a55c3c4
bigcode/the-stack
train
830365e37b884b50ecdcf93d
train
class
class FileTransferServer(FileTransferBase): def __init__(self, data=None, avatar=None): FileTransferBase.__init__(self) self.client = ISFTPServer(avatar) # yay interfaces self.openFiles = {} self.openDirs = {} def packet_INIT(self, data): version ,= struct.unpack('!L', ...
class FileTransferServer(FileTransferBase):
def __init__(self, data=None, avatar=None): FileTransferBase.__init__(self) self.client = ISFTPServer(avatar) # yay interfaces self.openFiles = {} self.openDirs = {} def packet_INIT(self, data): version ,= struct.unpack('!L', data[:4]) self.version = min(list(sel...
data = b'' if 'size' in attrs: data += struct.pack('!Q', attrs['size']) flags |= FILEXFER_ATTR_SIZE if 'uid' in attrs and 'gid' in attrs: data += struct.pack('!2L', attrs['uid'], attrs['gid']) flags |= FILEXFER_ATTR_OWNERGROUP if 'permissions' in ...
256
256
3,462
8
247
hawkowl/twisted
twisted/conch/ssh/filetransfer.py
Python
FileTransferServer
FileTransferServer
120
466
120
121
beacf89d0fa14e874c0e288af860a716b62813f2
bigcode/the-stack
train
dc09277af8bd8956d6a1afac
train
function
@listener(is_plugin=True, outgoing=True, incoming=True, command="portball", description="回复你要临时禁言的人的消息来实现XX秒的禁言", parameters="<理由>(空格)<时间/秒>") async def portball(context): if context.is_group: admins = await context.client.get_participants(context.chat, filter=ChannelParticipantsAdmins) ...
@listener(is_plugin=True, outgoing=True, incoming=True, command="portball", description="回复你要临时禁言的人的消息来实现XX秒的禁言", parameters="<理由>(空格)<时间/秒>") async def portball(context):
if context.is_group: admins = await context.client.get_participants(context.chat, filter=ChannelParticipantsAdmins) reply = await context.get_reply_message() # if message sender is one of admins or group anonymous bot if (context.sender in admins) or (context.sender_id == 1087968824)...
from pagermaid import bot, log from pagermaid.listener import listener from telethon.errors import rpcerrorlist from asyncio import sleep from datetime import timedelta from telethon.tl.types import ChannelParticipantsAdmins @listener(is_plugin=True, outgoing=True, incoming=True, command="portball", ...
101
231
771
56
44
onoc1yn/PagerMaid_Plugins
portball.py
Python
portball
portball
9
82
9
12
a001a5f1e1bfc17ab3e5815ae19c83f257349d02
bigcode/the-stack
train
1c4c48de80729e31122aac68
train
class
class VagaSerializer(serializers.ModelSerializer): class Meta: model = Vaga fields = '__all__'
class VagaSerializer(serializers.ModelSerializer):
class Meta: model = Vaga fields = '__all__'
from rest_framework import serializers from .models import Vaga class VagaSerializer(serializers.ModelSerializer):
21
64
25
8
12
flaviogf/Cursos
geral/curso_devmedia_api_django_rest/api_vagas/api/serializer.py
Python
VagaSerializer
VagaSerializer
6
9
6
6
9f7673eefdf3ee78e1abb97427dbf63c01f94f3b
bigcode/the-stack
train
2967091d0ee26975448ef2f0
train
class
class BlackBody(Fittable1DModel): """ Blackbody model using the Planck function. Parameters ---------- temperature : `~astropy.units.Quantity` ['temperature'] Blackbody temperature. scale : float or `~astropy.units.Quantity` ['dimensionless'] Scale factor output_units: `~a...
class BlackBody(Fittable1DModel):
""" Blackbody model using the Planck function. Parameters ---------- temperature : `~astropy.units.Quantity` ['temperature'] Blackbody temperature. scale : float or `~astropy.units.Quantity` ['dimensionless'] Scale factor output_units: `~astropy.units.CompositeUnit` or str...
# Licensed under a 3-clause BSD style license - see LICENSE.rst # copied and modified from astropy: https://github.com/astropy/astropy/pull/12304 """ Models that have physical origins. """ # pylint: disable=invalid-name, no-member import warnings import numpy as np from astropy import constants as const from astropy...
136
256
3,015
10
126
check-spelling/jdaviz
jdaviz/models/physical_models.py
Python
BlackBody
BlackBody
21
337
21
21
29b172ce99d6d4a0155f0504b7a73b9e83557402
bigcode/the-stack
train
3fc2138bc81db68817d0b7f9
train
function
def rewrite_all_files(input_dir, output_src, output_trgt, meta_file): """ Recuryively rewrites all files :param input_dir: :param output_src: :param output_trgt: :param meta_file: :return: """ # get a listing of all plain txt files in the dir and all sub dirs achieved_text_list ...
def rewrite_all_files(input_dir, output_src, output_trgt, meta_file):
""" Recuryively rewrites all files :param input_dir: :param output_src: :param output_trgt: :param meta_file: :return: """ # get a listing of all plain txt files in the dir and all sub dirs achieved_text_list = [] target_text_list = [] for root, dirs, files in os.walk(in...
__author__ = 'zweiss' import sys import re import os def rewrite_all_files(input_dir, output_src, output_trgt, meta_file):
34
84
280
17
16
zweiss/KCTErrorExtractor
KCT_Long_Reader.py
Python
rewrite_all_files
rewrite_all_files
9
43
9
9
e71c0e4539d9a9f0e80567c572aa794c80a6d1d5
bigcode/the-stack
train
44a428194e37699456aec474
train
function
def get_text_from_file(txt_file, is_achieved_text): """ Reads text from the Karlsruhe Children Texts Corpus as either achieved or corrected text :param txt_file: :param is_achieved_text: :return: """ rval = '' in_stream = open(txt_file, 'r') for l in in_stream.readlines(): li...
def get_text_from_file(txt_file, is_achieved_text):
""" Reads text from the Karlsruhe Children Texts Corpus as either achieved or corrected text :param txt_file: :param is_achieved_text: :return: """ rval = '' in_stream = open(txt_file, 'r') for l in in_stream.readlines(): line = l.strip() if len(line) == 0: ...
_achieved_text) # write it to output file name = get_file_name(txt_file[txt_file.rfind('/')+1:], meta_dict) src_file = out_dir + ('original-' if is_achieved_text else 'corrected-') + name + '.txt' src_writer = open(src_file, 'w') src_writer.write(text) src_writer.close() def get_text_from_file...
97
97
325
14
83
zweiss/KCTErrorExtractor
KCT_Long_Reader.py
Python
get_text_from_file
get_text_from_file
115
145
115
115
48873c84a084cc21f84861015300148ebb82e97d
bigcode/the-stack
train
dccbc42291b88f47b11036d7
train
function
def get_file_name(old_file, meta_dict): prefix = old_file[0:old_file.rindex('.')] student_id = prefix[2:prefix.rindex('.')] if student_id not in meta_dict.keys(): print('Warning: Unknown student id: ' + student_id) return prefix + '-none'*17 week = prefix.split('.')[4] week = week...
def get_file_name(old_file, meta_dict):
prefix = old_file[0:old_file.rindex('.')] student_id = prefix[2:prefix.rindex('.')] if student_id not in meta_dict.keys(): print('Warning: Unknown student id: ' + student_id) return prefix + '-none'*17 week = prefix.split('.')[4] week = week.replace('week', '') prefix += '-' +...
tmp = tmp.replace('&#34;', '\"') tmp = re.sub('[a-z]+([A-Z])', ' ', tmp) tmp = tmp.replace(' ', ' ') rval += tmp.strip() + '\n' in_stream.close() return rval def get_file_name(old_file, meta_dict):
69
69
231
10
58
zweiss/KCTErrorExtractor
KCT_Long_Reader.py
Python
get_file_name
get_file_name
148
174
148
148
e40c118f46d6505fa486d3769e25389b50b518ca
bigcode/the-stack
train
64c1ef8cca4b670e76b1d0a1
train
function
def rewrite_file(txt_file, out_dir, meta_dict, is_achieved_text): """ Rewrites a file :param txt_file: :param out_dir: :param meta_dict: :param is_achieved_text: :return: """ # get data text = get_text_from_file(txt_file, is_achieved_text) # write it to output file name...
def rewrite_file(txt_file, out_dir, meta_dict, is_achieved_text):
""" Rewrites a file :param txt_file: :param out_dir: :param meta_dict: :param is_achieved_text: :return: """ # get data text = get_text_from_file(txt_file, is_achieved_text) # write it to output file name = get_file_name(txt_file[txt_file.rfind('/')+1:], meta_dict) ...
, year, age, school_type, l1, l2, l3, is_multiling, years_in_germany, book1, book2, book3] in_stream.close() return meta_dict def rewrite_file(txt_file, out_dir, meta_dict, is_achieved_text):
64
64
158
18
45
zweiss/KCTErrorExtractor
KCT_Long_Reader.py
Python
rewrite_file
rewrite_file
93
112
93
93
7ccf48e2aa91a5d2e88d55c8f9d9c4ee39362d90
bigcode/the-stack
train
cdd6b669c640381e69d1db8a
train
function
def get_meta_data(meta_file): """ Reads meta data from csv :param meta_file: :return: """ meta_dict = {} in_stream = open(meta_file, 'r') is_header = True for line in in_stream.readlines(): if is_header: is_header = False continue col = line.sp...
def get_meta_data(meta_file):
""" Reads meta data from csv :param meta_file: :return: """ meta_dict = {} in_stream = open(meta_file, 'r') is_header = True for line in in_stream.readlines(): if is_header: is_header = False continue col = line.split(';') if len(col) <...
_H1'): achieved_text_list.append(os.path.join(root, name)) meta_dict = get_meta_data(meta_file) # process all files and save them to the output file counter = 0 for txt_file in achieved_text_list: print('Started rewriting of ' + txt_file) rewrite_file(txt_file, outp...
144
145
486
7
137
zweiss/KCTErrorExtractor
KCT_Long_Reader.py
Python
get_meta_data
get_meta_data
46
90
46
46
7673f43a904cd49e737a9722beca8ab2e56169bb
bigcode/the-stack
train
257c50094c51ab915f937720
train
class
class AppsList(AppsFormatMany): """List the Apps catalog """ VERBOSITY = Verbosity.BRIEF EXTRA_VERBOSITY = Verbosity.LISTING def take_action(self, parsed_args): parsed_args = self.preprocess_args(parsed_args) self.requests_client.setup(API_NAME, SERVICE_VERSION) self.update_...
class AppsList(AppsFormatMany):
"""List the Apps catalog """ VERBOSITY = Verbosity.BRIEF EXTRA_VERBOSITY = Verbosity.LISTING def take_action(self, parsed_args): parsed_args = self.preprocess_args(parsed_args) self.requests_client.setup(API_NAME, SERVICE_VERSION) self.update_payload(parsed_args) he...
from tapis_cli.display import Verbosity from . import API_NAME, SERVICE_VERSION from .models import App from .formatters import AppsFormatMany __all__ = ['AppsList'] class AppsList(AppsFormatMany):
48
64
155
8
40
shwetagopaul92/tapis-cli-ng
tapis_cli/commands/taccapis/v2/apps/list.py
Python
AppsList
AppsList
10
31
10
10
da501dae3ce635c064af30067a929bd37fd09a1e
bigcode/the-stack
train
086f205b76f872b83b2f5885
train
class
class DataParallel(nn.Module): def __init__(self, model, device_ids, dim): super().__init__() self.model = model.model self.network = nn.DataParallel(model, device_ids, dim) def forward(self, x): return self.network(x)
class DataParallel(nn.Module):
def __init__(self, model, device_ids, dim): super().__init__() self.model = model.model self.network = nn.DataParallel(model, device_ids, dim) def forward(self, x): return self.network(x)
in varx[key].items(): base_str += '\n\t' + str(sub_key) + ': ' + str(sub_item) else: base_str += '\n\t' + str(varx[key]) base_str += '\n\n' return base_str class DataParallel(nn.Module):
64
64
59
6
57
lizhaoliu-Lec/Revisiting_Deep_Metric_Learning_PyTorch
utilities/misc.py
Python
DataParallel
DataParallel
31
38
31
31
639c41e5742a4f987bd3e5a15ecf93f131ee1a25
bigcode/the-stack
train
15b2e8ff57cef8c4ba5ea140
train
function
def gimme_params(model): """ ACQUIRE NUMBER OF WEIGHTS """ model_parameters = filter(lambda p: p.requires_grad, model.parameters()) params = sum([np.prod(p.size()) for p in model_parameters]) return params
def gimme_params(model):
""" ACQUIRE NUMBER OF WEIGHTS """ model_parameters = filter(lambda p: p.requires_grad, model.parameters()) params = sum([np.prod(p.size()) for p in model_parameters]) return params
import numpy as np import torch.nn as nn def gimme_params(model):
17
64
53
6
10
lizhaoliu-Lec/Revisiting_Deep_Metric_Learning_PyTorch
utilities/misc.py
Python
gimme_params
gimme_params
5
11
5
5
4dfc104212ca52ec5b9097f07fecbe7f075220b8
bigcode/the-stack
train
46e29d40b419fb1bdbf0359a
train
function
def gimme_save_string(opt): """ SAVE TRAINING PARAMETERS IN NICE STRING """ varx = vars(opt) base_str = '' for key in varx: base_str += str(key) if isinstance(varx[key], dict): for sub_key, sub_item in varx[key].items(): base_str += '\n\t' + str(sub_ke...
def gimme_save_string(opt):
""" SAVE TRAINING PARAMETERS IN NICE STRING """ varx = vars(opt) base_str = '' for key in varx: base_str += str(key) if isinstance(varx[key], dict): for sub_key, sub_item in varx[key].items(): base_str += '\n\t' + str(sub_key) + ': ' + str(sub_item) ...
.nn as nn def gimme_params(model): """ ACQUIRE NUMBER OF WEIGHTS """ model_parameters = filter(lambda p: p.requires_grad, model.parameters()) params = sum([np.prod(p.size()) for p in model_parameters]) return params def gimme_save_string(opt):
64
64
120
7
56
lizhaoliu-Lec/Revisiting_Deep_Metric_Learning_PyTorch
utilities/misc.py
Python
gimme_save_string
gimme_save_string
14
28
14
14
533d3bad8fd683ff814b0a97e7e672439a8806f1
bigcode/the-stack
train
6fbb705b24fc1b55caa9f911
train
class
class RpcServer: """ Implementation of RPC server. """ def __init__(self, rpc_api: Any, service_name: str, stop_cb: Callable, root_path, net_config): self.rpc_api = rpc_api self.stop_cb: Callable = stop_cb self.log = log self.shut_down = False self.websocket: Opt...
class RpcServer:
""" Implementation of RPC server. """ def __init__(self, rpc_api: Any, service_name: str, stop_cb: Callable, root_path, net_config): self.rpc_api = rpc_api self.stop_cb: Callable = stop_cb self.log = log self.shut_down = False self.websocket: Optional[aiohttp.Cli...
import asyncio import json import logging import traceback from pathlib import Path from typing import Any, Callable, Dict, List, Optional import aiohttp from beer.server.outbound_message import NodeType from beer.server.server import ssl_context_for_server from beer.types.peer_info import PeerInfo from beer.util.byt...
128
256
2,159
4
124
beer-network/beer-blockchain
beer/rpc/rpc_server.py
Python
RpcServer
RpcServer
21
286
21
21
f81746bd8d1c4a26c3027df9f9c888c4dbab4382
bigcode/the-stack
train
2e5410fa509d99e555c8fde6
train
function
async def start_rpc_server( rpc_api: Any, self_hostname: str, daemon_port: uint16, rpc_port: uint16, stop_cb: Callable, root_path: Path, net_config, connect_to_daemon=True, ): """ Starts an HTTP server with the following RPC methods, to be used by local clients to query the n...
async def start_rpc_server( rpc_api: Any, self_hostname: str, daemon_port: uint16, rpc_port: uint16, stop_cb: Callable, root_path: Path, net_config, connect_to_daemon=True, ):
""" Starts an HTTP server with the following RPC methods, to be used by local clients to query the node. """ app = aiohttp.web.Application() rpc_server = RpcServer(rpc_api, rpc_api.service_name, stop_cb, root_path, net_config) rpc_server.rpc_api.service._set_state_changed_callback(rpc_server...
except aiohttp.ClientConnectorError: self.log.warning(f"Cannot connect to daemon at ws://{self_hostname}:{daemon_port}") except Exception as e: tb = traceback.format_exc() self.log.warning(f"Exception: {tb} {type(e)}") await asyncio.sle...
120
120
400
56
64
beer-network/beer-blockchain
beer/rpc/rpc_server.py
Python
start_rpc_server
start_rpc_server
289
339
289
298
56c3592934777753151d0422be31a55c56a2039d
bigcode/the-stack
train
52b4f8e285837eb35150d417
train
class
class TestAdaptersAllSoap(object): """Test all Adapters of type: soap.""" @pytest.fixture def adapter(self, adapter_soap, http_client, auth): """Get an adapter object of type: soap.""" api_module = adapter_soap["api_module"] api_client_cls = adapter_soap["api_client"] adapte...
class TestAdaptersAllSoap(object):
"""Test all Adapters of type: soap.""" @pytest.fixture def adapter(self, adapter_soap, http_client, auth): """Get an adapter object of type: soap.""" api_module = adapter_soap["api_module"] api_client_cls = adapter_soap["api_client"] adapter_cls = adapter_soap["adapter"] ...
# -*- coding: utf-8 -*- """Test suite for pytan3.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import pytan3 import pytest class TestAdaptersAllSoap(object):
62
256
953
7
54
lifehackjim/pytan3
pytan3/tests/test_adapters/test_adapters_all_soap.py
Python
TestAdaptersAllSoap
TestAdaptersAllSoap
12
104
12
12
c85da0d2f8095b04c56812b05a13e239f7a99c3b
bigcode/the-stack
train
f4b2ddf882a2c60aec23ed19
train
class
class APIUnitTestSystemCertificate(unit_test_framework.APIUnitTest): crt = "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUR5VENDQXJHZ0F3SUJBZ0lVZUZacVZwcXlDNXRqa0I2TWNwdnIybGlHRDc0d0RRWUpLb1pJaHZjTkFRRUwKQlFBd2N6RUxNQWtHQTFVRUJoTUNWVk14RFRBTEJnTlZCQWdNQkZWMFlXZ3hEakFNQmdOVkJBY01CVkJ5YjNadgpNUnN3R1FZRFZRUUtEQkpxWVhKbFpH...
class APIUnitTestSystemCertificate(unit_test_framework.APIUnitTest):
crt = "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUR5VENDQXJHZ0F3SUJBZ0lVZUZacVZwcXlDNXRqa0I2TWNwdnIybGlHRDc0d0RRWUpLb1pJaHZjTkFRRUwKQlFBd2N6RUxNQWtHQTFVRUJoTUNWVk14RFRBTEJnTlZCQWdNQkZWMFlXZ3hEakFNQmdOVkJBY01CVkJ5YjNadgpNUnN3R1FZRFZRUUtEQkpxWVhKbFpHaGxibVJ5YVdOcmMyOXVNVE14RWpBUUJnTlZCQXNNQ1VSbGRtVnNiM0JsCmNqRVVNQklHQ...
import unit_test_framework class APIUnitTestSystemCertificate(unit_test_framework.APIUnitTest):
18
256
5,858
13
4
heichalot/pfsense-api
tests/test_api_v1_system_certificate.py
Python
APIUnitTestSystemCertificate
APIUnitTestSystemCertificate
4
283
4
4
77ed6e89d8988f4750a375d679df567c9f693cf2
bigcode/the-stack
train
0e6b62a281b6c9bc6b1cdbd5
train
class
class simple_producer: def __init__(self, data, buffer_size=512): self.data = data self.buffer_size = buffer_size def more(self): if len(self.data) > self.buffer_size: result = self.data[:self.buffer_size] self.data = self.data[self.buffer_size:] ret...
class simple_producer:
def __init__(self, data, buffer_size=512): self.data = data self.buffer_size = buffer_size def more(self): if len(self.data) > self.buffer_size: result = self.data[:self.buffer_size] self.data = self.data[self.buffer_size:] return result else:...
else: del self.producer_fifo[0] # we tried to send some actual data return def discard_buffers(self): # Emergencies only! self.ac_in_buffer = b'' del self.incoming[:] self.producer_fifo.clear() class simple_producer:
64
64
92
5
59
oleksandr-pavlyk/cpython
Lib/asynchat.py
Python
simple_producer
simple_producer
279
293
279
280
48abffd7a536d4a6d26bd588ab647ad7b8aaecae
bigcode/the-stack
train
d794a0a9a5c9612c4f441036
train
function
def find_prefix_at_end(haystack, needle): l = len(needle) - 1 while l and not haystack.endswith(needle[:l]): l -= 1 return l
def find_prefix_at_end(haystack, needle):
l = len(needle) - 1 while l and not haystack.endswith(needle[:l]): l -= 1 return l
: no; circa Python-2.0, Jan 2001] # new python: 28961/s # old python: 18307/s # re: 12820/s # regex: 14035/s def find_prefix_at_end(haystack, needle):
64
64
45
11
52
oleksandr-pavlyk/cpython
Lib/asynchat.py
Python
find_prefix_at_end
find_prefix_at_end
311
315
311
311
b1818572b80af595ab257dca60e88c38d7cff9e7
bigcode/the-stack
train
43d07cd67ec48e38f975ac8b
train
class
class async_chat(asyncore.dispatcher): """This is an abstract class. You must derive from this class, and add the two methods collect_incoming_data() and found_terminator()""" # these are overridable defaults ac_in_buffer_size = 65536 ac_out_buffer_size = 65536 # we don't want to enable the ...
class async_chat(asyncore.dispatcher):
"""This is an abstract class. You must derive from this class, and add the two methods collect_incoming_data() and found_terminator()""" # these are overridable defaults ac_in_buffer_size = 65536 ac_out_buffer_size = 65536 # we don't want to enable the use of encoding by default, because tha...
and the other sends a response (examples would be the common internet protocols - smtp, nntp, ftp, etc..). The handle_read() method looks at the input stream for the current 'terminator' (usually '\r\n' for single-line responses, '\r\n.\r\n' for multi-line output), calling self.found_terminator() on its receipt. for...
256
256
1,628
8
248
oleksandr-pavlyk/cpython
Lib/asynchat.py
Python
async_chat
async_chat
60
276
60
60
07ac6ae30f8cffa5e5baec8ad3838f2432ba6a76
bigcode/the-stack
train
928a210120ba998c3b5cda6d
train
function
def pyx_to_dll(filename, ext=None, force_rebuild=0, build_in_temp=False, pyxbuild_dir=None, setup_args=None, reload_support=False, inplace=False): """Compile a PYX file to a DLL and return the name of the generated .so or .dll .""" assert os.path.exists(filename), "Could not find %s" % os....
def pyx_to_dll(filename, ext=None, force_rebuild=0, build_in_temp=False, pyxbuild_dir=None, setup_args=None, reload_support=False, inplace=False):
"""Compile a PYX file to a DLL and return the name of the generated .so or .dll .""" assert os.path.exists(filename), "Could not find %s" % os.path.abspath(filename) path, name = os.path.split(os.path.abspath(filename)) if not ext: modname, extension = os.path.splitext(name) ass...
"""Build a Pyrex file from .pyx source to .so loadable module using the installed distutils infrastructure. Call: out_fname = pyx_to_dll("foo.pyx") """ import os import sys from distutils.errors import DistutilsArgError, DistutilsError, CCompilerError from distutils.extension import Extension from distutils.util impo...
170
256
1,075
40
130
VPetras/mobile-test-app
.buildozer/android/platform/build-armeabi-v7a/build/venv/lib/python3.7/site-packages/pyximport/pyxbuild.py
Python
pyx_to_dll
pyx_to_dll
23
154
23
24
40806ac48c79ad21282c8d6895faaea9523c603d
bigcode/the-stack
train
5fb46866f668173659cc7df1
train
class
class KinectDataSource: def __init__(self, input, output): self.input = input self.output = output self.crop_corner = (160, 0) # (x, y) self.crop_size = (960, 720) # (width, height) self.output_size = (640, 480) # (width, height) self.zoom_x = float(self.output_siz...
class KinectDataSource:
def __init__(self, input, output): self.input = input self.output = output self.crop_corner = (160, 0) # (x, y) self.crop_size = (960, 720) # (width, height) self.output_size = (640, 480) # (width, height) self.zoom_x = float(self.output_size[0] / self.crop_size[0])...
#Copyright 2020 Nod Labs import argparse import open3d as o3d import os import json import glob import sys from PIL import Image import numpy as np class KinectDataSource:
47
256
1,094
5
41
JiatianWu/tf-monodepth2
kinect_tools/kinect_data_process.py
Python
KinectDataSource
KinectDataSource
11
137
11
12
8bae1454be24601d49e1ec13abf1d1a08e27258f
bigcode/the-stack
train
1033bd6a12d80d47784fa110
train
class
class SimpleTuner(Tuner): """ simple tuner, test for weight sharing """ def __init__(self): super(SimpleTuner, self).__init__() self.trial_meta = {} self.f_id = None # father self.sig_event = Event() self.thread_lock = Lock() def generate_parameters(self, p...
class SimpleTuner(Tuner):
""" simple tuner, test for weight sharing """ def __init__(self): super(SimpleTuner, self).__init__() self.trial_meta = {} self.f_id = None # father self.sig_event = Event() self.thread_lock = Lock() def generate_parameters(self, parameter_id): if s...
""" SimpleTuner for Weight Sharing """ import logging from threading import Event, Lock from nni.tuner import Tuner _logger = logging.getLogger('WeightSharingTuner') class SimpleTuner(Tuner):
46
118
395
7
39
xumeng723/nni
test/async_sharing_test/simple_tuner.py
Python
SimpleTuner
SimpleTuner
13
66
13
13
e3b4f75bb1144b67b202905786c03916f300b0ab
bigcode/the-stack
train
f002f26bfcea65d3ba283857
train
class
class StringRepresentationTests(TestCase): def setUp(self): isd17 = ISD.objects.create(isd_id=17, label='Switzerland') ISD.objects.create(isd_id=18, label='North America') ISD.objects.create(isd_id=19, label='EU') ISD.objects.create(isd_id=60) AS.objects.create(isd=isd17, a...
class StringRepresentationTests(TestCase):
def setUp(self): isd17 = ISD.objects.create(isd_id=17, label='Switzerland') ISD.objects.create(isd_id=18, label='North America') ISD.objects.create(isd_id=19, label='EU') ISD.objects.create(isd_id=60) AS.objects.create(isd=isd17, as_id='ff00:0:1101', label='SCMN') AS...
required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unitte...
109
109
365
7
101
juagargi/scionlab
scionlab/tests/test_models.py
Python
StringRepresentationTests
StringRepresentationTests
21
52
21
22
ace16d6506feb3aaafc86614b6634ffef809260f
bigcode/the-stack
train
dd66b336f2393372267a4f85
train
class
class DeleteASTests(TestCase): fixtures = ['testtopo-ases-links'] def setUp(self): patcher = patch('scionlab.models.AS._pre_delete', side_effect=AS._pre_delete, autospec=True) self.mock_as_pre_delete = patcher.start() self.addCleanup(patcher.stop) def test_delete_single_as(self): ...
class DeleteASTests(TestCase):
fixtures = ['testtopo-ases-links'] def setUp(self): patcher = patch('scionlab.models.AS._pre_delete', side_effect=AS._pre_delete, autospec=True) self.mock_as_pre_delete = patcher.start() self.addCleanup(patcher.stop) def test_delete_single_as(self): as_ = AS.objects.last() ...
.remote_interface(), link.interfaceB) self.assertEquals(link.interfaceB.remote_interface(), link.interfaceA) self.assertEquals(link.interfaceA.remote_as(), link.interfaceB.AS) self.assertEquals(link.interfaceB.remote_as(), link.interfaceA.AS) def _sanity_check_interface(self, interface): ...
125
125
419
7
118
juagargi/scionlab
scionlab/tests/test_models.py
Python
DeleteASTests
DeleteASTests
203
248
203
203
607ac3aee7768cb66527d263ec042b0dc30f1c27
bigcode/the-stack
train
4d8e9e3d3a305ae0bd421bb8
train
class
class LinkModificationTests(TestCase): fixtures = ['testtopo-ases'] AS_SCMN = 'ffaa:0:1101' AS_ETHZ = 'ffaa:0:1102' AS_SWTH = 'ffaa:0:1103' def _as_a(self): return AS.objects.get(as_id=self.AS_SCMN) def _as_b(self): return AS.objects.get(as_id=self.AS_ETHZ) def _as_c(self...
class LinkModificationTests(TestCase):
fixtures = ['testtopo-ases'] AS_SCMN = 'ffaa:0:1101' AS_ETHZ = 'ffaa:0:1102' AS_SWTH = 'ffaa:0:1103' def _as_a(self): return AS.objects.get(as_id=self.AS_SCMN) def _as_b(self): return AS.objects.get(as_id=self.AS_ETHZ) def _as_c(self): return AS.objects.get(as_id=...
isd=isd, as_id='ff00:1:1', public_ip='192.0.2.11' ) self.assertTrue(hasattr(as_, 'hosts')) self.assertEqual(as_.hosts.count(), 1) host = as_.hosts.first() self.assertEqual(host.internal_ip, "127.0.0.1") self.assertTrue(host.needs_config_deploymen...
250
250
834
7
243
juagargi/scionlab
scionlab/tests/test_models.py
Python
LinkModificationTests
LinkModificationTests
108
200
108
108
323585f65382cd59781e735916cf0cb1a486a2cd
bigcode/the-stack
train
0ac3bbece66ed1293909c176
train
class
class InitASTests(TestCase): def test_create_as_with_keys(self): isd = ISD.objects.create(isd_id=17, label='Switzerland') as_ = AS.objects.create(isd=isd, as_id='ff00:1:1') utils.check_as_keys(self, as_) def test_create_coreas_with_keys(self): isd = ISD.objects.create(isd_id=17,...
class InitASTests(TestCase):
def test_create_as_with_keys(self): isd = ISD.objects.create(isd_id=17, label='Switzerland') as_ = AS.objects.create(isd=isd, as_id='ff00:1:1') utils.check_as_keys(self, as_) def test_create_coreas_with_keys(self): isd = ISD.objects.create(isd_id=17, label='Switzerland') ...
) for a in AS.objects.all())) expected_as_strs = [ '17-ff00:0:1101 (SCMN)', '17-ff00:0:1102 (ETHZ)', '17-ff00:0:1103 (SWTH)', '17-ff00:1:1', ] self.assertEqual(as_strs, expected_as_strs) class InitASTests(TestCase):
93
93
311
7
86
juagargi/scionlab
scionlab/tests/test_models.py
Python
InitASTests
InitASTests
55
83
55
55
5554ce4e0bf7702c683efeac5b86f165a88c140b
bigcode/the-stack
train
695f74836647817fe228c535
train
class
class UpdateASKeysTests(TestCase): fixtures = ['testtopo-ases'] def test_update_keys(self): Host.objects.reset_needs_config_deployment() as_ = AS.objects.first() prev_certificate_chain = as_.certificate_chain as_.update_keys() self.assertEqual( list(Host....
class UpdateASKeysTests(TestCase):
fixtures = ['testtopo-ases'] def test_update_keys(self): Host.objects.reset_needs_config_deployment() as_ = AS.objects.first() prev_certificate_chain = as_.certificate_chain as_.update_keys() self.assertEqual( list(Host.objects.needs_config_deployment()),...
.0.1") self.assertTrue(host.needs_config_deployment()) self.assertTrue(hasattr(host, 'services')) self.assertEqual(sorted(s.type for s in host.services.iterator()), ['BS', 'CS', 'PS', 'ZK']) class UpdateASKeysTests(TestCase):
63
64
114
8
55
juagargi/scionlab
scionlab/tests/test_models.py
Python
UpdateASKeysTests
UpdateASKeysTests
86
105
86
86
23b93760040bc34f5871de5e1761d804863fcd60
bigcode/the-stack
train
216bdeb9573ced59ea427e3f
train
class
class TestPortgroupObject(base.TestCase): def test_portgroup_init(self): portgroup_dict = apiutils.portgroup_post_data(node_id=None) del portgroup_dict['extra'] portgroup = api_portgroup.Portgroup(**portgroup_dict) self.assertEqual(wtypes.Unset, portgroup.extra)
class TestPortgroupObject(base.TestCase):
def test_portgroup_init(self): portgroup_dict = apiutils.portgroup_post_data(node_id=None) del portgroup_dict['extra'] portgroup = api_portgroup.Portgroup(**portgroup_dict) self.assertEqual(wtypes.Unset, portgroup.extra)
portgroup, topic): """Fake used to mock out the conductor RPCAPI's update_portgroup method. Saves the updated portgroup object and returns the updated portgroup as-per the real method. """ portgroup.save() return portgroup class TestPortgroupObject(base.TestCase):
64
64
67
9
54
DhuldevValekar3/ironic
ironic/tests/unit/api/controllers/v1/test_portgroup.py
Python
TestPortgroupObject
TestPortgroupObject
55
61
55
56
fadddf0633f47c17fed338db05a66c2ec71c5952
bigcode/the-stack
train
3aa23d7b24fee5bd49bbbd8a
train
class
@mock.patch.object(rpcapi.ConductorAPI, 'update_portgroup', autospec=True, side_effect=_rpcapi_update_portgroup) class TestPatchExtraVifPortId(test_api_base.BaseApiTest): headers = {api_base.Version.string: str(api_v1.max_version())} def setUp(self): super(TestPatchExtraVifPortId, se...
@mock.patch.object(rpcapi.ConductorAPI, 'update_portgroup', autospec=True, side_effect=_rpcapi_update_portgroup) class TestPatchExtraVifPortId(test_api_base.BaseApiTest):
headers = {api_base.Version.string: str(api_v1.max_version())} def setUp(self): super(TestPatchExtraVifPortId, self).setUp() self.node = obj_utils.create_test_node(self.context) self.portgroup = obj_utils.create_test_portgroup(self.context, ...
1.39"}) self.assertEqual(http_client.CONFLICT, response.status_code) self.assertFalse(mock_upd.called) def test_update_in_inspecting_allowed(self, mock_upd): self.node.provision_state = states.INSPECTING self.node.save() address = 'AA:BB:CC:DD:EE:FF' mock_upd.return_...
256
256
1,456
45
211
DhuldevValekar3/ironic
ironic/tests/unit/api/controllers/v1/test_portgroup.py
Python
TestPatchExtraVifPortId
TestPatchExtraVifPortId
1,098
1,225
1,098
1,100
da29938dd89d6c5e8bfe5a83ccd1655621583bd4
bigcode/the-stack
train
c841a8426c4c74e8ae6b8044
train
class
class TestPost(test_api_base.BaseApiTest): headers = {api_base.Version.string: str(api_v1.max_version())} def setUp(self): super(TestPost, self).setUp() self.node = obj_utils.create_test_node(self.context) @mock.patch.object(notification_utils, '_emit_api_notification') @mock.patch.obj...
class TestPost(test_api_base.BaseApiTest):
headers = {api_base.Version.string: str(api_v1.max_version())} def setUp(self): super(TestPost, self).setUp() self.node = obj_utils.create_test_node(self.context) @mock.patch.object(notification_utils, '_emit_api_notification') @mock.patch.object(common_utils, 'warn_about_deprecated_ex...
'} intern_info = self.portgroup.internal_info intern_info.update({'tenant_vif_port_id': 'bar'}) self.portgroup.internal_info = intern_info self.portgroup.save() headers = {api_base.Version.string: '1.28'} response = self._test_remove_extra_vif_port_id(headers, mock_warn, ...
256
256
3,220
10
246
DhuldevValekar3/ironic
ironic/tests/unit/api/controllers/v1/test_portgroup.py
Python
TestPost
TestPost
1,228
1,515
1,228
1,228
f4e64ae5b2669e002af53a3d3fbfd1789943d8e5
bigcode/the-stack
train
0f353284cf97b8ab5a9e27f2
train
class
class TestListPortgroups(test_api_base.BaseApiTest): headers = {api_base.Version.string: str(api_v1.max_version())} def setUp(self): super(TestListPortgroups, self).setUp() self.node = obj_utils.create_test_node(self.context) def test_empty(self): data = self.get_json('/portgroups'...
class TestListPortgroups(test_api_base.BaseApiTest):
headers = {api_base.Version.string: str(api_v1.max_version())} def setUp(self): super(TestListPortgroups, self).setUp() self.node = obj_utils.create_test_node(self.context) def test_empty(self): data = self.get_json('/portgroups', headers=self.headers) self.assertEqual([], ...
_utils from ironic.api.controllers.v1 import portgroup as api_portgroup from ironic.api.controllers.v1 import utils as api_utils from ironic.common import exception from ironic.common import states from ironic.common import utils as common_utils from ironic.conductor import rpcapi from ironic import objects from ironic...
256
256
5,178
12
244
DhuldevValekar3/ironic
ironic/tests/unit/api/controllers/v1/test_portgroup.py
Python
TestListPortgroups
TestListPortgroups
64
591
64
64
af78f1fef41fc4a7d5ca224608662e9f8dcd267b
bigcode/the-stack
train
cd4f9f1ef78ac40923fafcee
train
class
@mock.patch.object(rpcapi.ConductorAPI, 'destroy_portgroup') class TestDelete(test_api_base.BaseApiTest): headers = {api_base.Version.string: str(api_v1.max_version())} def setUp(self): super(TestDelete, self).setUp() self.node = obj_utils.create_test_node(self.context) self.portgroup =...
@mock.patch.object(rpcapi.ConductorAPI, 'destroy_portgroup') class TestDelete(test_api_base.BaseApiTest):
headers = {api_base.Version.string: str(api_v1.max_version())} def setUp(self): super(TestDelete, self).setUp() self.node = obj_utils.create_test_node(self.context) self.portgroup = obj_utils.create_test_portgroup(self.context, na...
self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) def test_create_portgroup_mode_properties(self): mode = '802.3ad' props = {'bond_prop': 123} pdict = apiutils.post_get_test_portgroup(mode=mode, properties=props) ...
230
230
768
26
204
DhuldevValekar3/ironic
ironic/tests/unit/api/controllers/v1/test_portgroup.py
Python
TestDelete
TestDelete
1,518
1,593
1,518
1,519
a507ae8c544c8fff551b81efc663255b68bb3f11
bigcode/the-stack
train
ad7cbfca20a56401c9f380ce
train
function
def _rpcapi_update_portgroup(self, context, portgroup, topic): """Fake used to mock out the conductor RPCAPI's update_portgroup method. Saves the updated portgroup object and returns the updated portgroup as-per the real method. """ portgroup.save() return portgroup
def _rpcapi_update_portgroup(self, context, portgroup, topic):
"""Fake used to mock out the conductor RPCAPI's update_portgroup method. Saves the updated portgroup object and returns the updated portgroup as-per the real method. """ portgroup.save() return portgroup
ironic.objects import fields as obj_fields from ironic.tests import base from ironic.tests.unit.api import base as test_api_base from ironic.tests.unit.api import utils as apiutils from ironic.tests.unit.objects import utils as obj_utils def _rpcapi_update_portgroup(self, context, portgroup, topic):
64
64
66
16
47
DhuldevValekar3/ironic
ironic/tests/unit/api/controllers/v1/test_portgroup.py
Python
_rpcapi_update_portgroup
_rpcapi_update_portgroup
45
52
45
45
76a87cb64caeec782a23ca54f0f978c9070cfbd8
bigcode/the-stack
train
d788a7e1aaaae90921190989
train
class
@mock.patch.object(rpcapi.ConductorAPI, 'update_portgroup') class TestPatch(test_api_base.BaseApiTest): headers = {api_base.Version.string: str(api_v1.max_version())} def setUp(self): super(TestPatch, self).setUp() self.node = obj_utils.create_test_node(self.context) self.portgroup = ob...
@mock.patch.object(rpcapi.ConductorAPI, 'update_portgroup') class TestPatch(test_api_base.BaseApiTest):
headers = {api_base.Version.string: str(api_v1.max_version())} def setUp(self): super(TestPatch, self).setUp() self.node = obj_utils.create_test_node(self.context) self.portgroup = obj_utils.create_test_portgroup(self.context, nam...
test_get_all_by_node_uuid_ok(self, mock_get_rpc_node): mock_get_rpc_node.return_value = self.node obj_utils.create_test_portgroup(self.context, node_id=self.node.id) data = self.get_json('/portgroups/detail?node=%s' % (self.node.uuid), headers=self.headers) ...
255
256
4,882
26
229
DhuldevValekar3/ironic
ironic/tests/unit/api/controllers/v1/test_portgroup.py
Python
TestPatch
TestPatch
594
1,095
594
595
2f35aa220ac17c2952a9368f6d92c8651005a3c3
bigcode/the-stack
train
461f8922960e4a25da54e7f0
train
class
class RecurrentPayment(object): def __init__(self, authorize_now=True): self.authorize_now = authorize_now self.start_date = None self.end_date = None self.interval = None self.recurrent_payment_id = None
class RecurrentPayment(object):
def __init__(self, authorize_now=True): self.authorize_now = authorize_now self.start_date = None self.end_date = None self.interval = None self.recurrent_payment_id = None
INTERVAL_MONTHLY = "Monthly" INTERVAL_BIMONTHLY = "Bimonthly" INTERVAL_QUARTERLY = "Quarterly" INTERVAL_SEMIANNUAL = "SemiAnnual" INTERVAL_ANNUAL = "Annual" class RecurrentPayment(object):
60
64
55
6
54
CharlesTenorio/API-3.0-Python
cieloApi3/recurrentPayment.py
Python
RecurrentPayment
RecurrentPayment
8
16
8
9
107e7029360ffe9c6199b92478106067fd87f958
bigcode/the-stack
train
586641ce3c62597fde800c2a
train
class
@method_decorator(login_required, name='dispatch') class Success(TemplateView): template_name = "aristotle_json_editor/success.html" def get_context_data(self, **kwargs): """ Insert the form into the context dict. """ kwargs['data'] = self.request.GET.get('data') uuids...
@method_decorator(login_required, name='dispatch') class Success(TemplateView):
template_name = "aristotle_json_editor/success.html" def get_context_data(self, **kwargs): """ Insert the form into the context dict. """ kwargs['data'] = self.request.GET.get('data') uuids = self.request.GET.get('uuids').split(',') kwargs['items'] = aristotle....
, **kwargs): """ Insert the form into the context dict. """ kwargs['quick_starters'] = get_quick_starters() return super(QuickStart, self).get_context_data(**kwargs) @method_decorator(login_required, name='dispatch') class Success(TemplateView):
64
64
120
17
47
aristotle-mdr/json-metadata-editor
aristotle_json_editor/views.py
Python
Success
Success
66
78
66
67
0178d21af018c9608af0ddd8bcdfe81b9e722541
bigcode/the-stack
train
047df7806e5f2430690b7cd2
train
class
class SchemaFileMixin(object): def get_schema_file(self, name): # file_name = name.split("/")[-1].split("\\")[-1] name = name.replace("//", "/") if name.startswith('/'): name = name[1:] return os.path.join( os.path.dirname(os.path.abspath(__file__)), ...
class SchemaFileMixin(object):
def get_schema_file(self, name): # file_name = name.split("/")[-1].split("\\")[-1] name = name.replace("//", "/") if name.startswith('/'): name = name[1:] return os.path.join( os.path.dirname(os.path.abspath(__file__)), 'schemas', "%s.s...
ISTOTLE_SETTINGS.get('QUICK_STARTERS', []) out = collections.OrderedDict() for q in qs: out[q] = { 'name': q, 'model': ContentType.objects.get(model=q).model_class() } return out class SchemaFileMixin(object):
64
64
84
6
57
aristotle-mdr/json-metadata-editor
aristotle_json_editor/views.py
Python
SchemaFileMixin
SchemaFileMixin
40
50
40
40
6a29641c74fd2c3c24a727905cb09a07ca6e17bf
bigcode/the-stack
train
60612e85389e44f78e860ac8
train
function
def get_quick_starters(): from django.conf import settings qs = settings.ARISTOTLE_SETTINGS.get('QUICK_STARTERS', []) out = collections.OrderedDict() for q in qs: out[q] = { 'name': q, 'model': ContentType.objects.get(model=q).model_class() } return out
def get_quick_starters():
from django.conf import settings qs = settings.ARISTOTLE_SETTINGS.get('QUICK_STARTERS', []) out = collections.OrderedDict() for q in qs: out[q] = { 'name': q, 'model': ContentType.objects.get(model=q).model_class() } return out
ModelFormSet from aristotle_mdr.perms import ( user_can_view, user_can_edit, user_in_workgroup, user_is_workgroup_manager, user_can_change_status ) from .forms import JSONSchemaForm import os import json import collections def get_quick_starters():
64
64
77
7
56
aristotle-mdr/json-metadata-editor
aristotle_json_editor/views.py
Python
get_quick_starters
get_quick_starters
28
37
28
28
dfe0b815ce3003a3527d377f7aa7ddbbee42ab98
bigcode/the-stack
train
74bba4bedc5f566cc9e775ff
train
class
@method_decorator(login_required, name='dispatch') class QuickStart(TemplateView): template_name = "quick_start_editor/dashboard/quick_editor_main.html" def get_context_data(self, **kwargs): """ Insert the form into the context dict. """ kwargs['quick_starters'] = get_...
@method_decorator(login_required, name='dispatch') class QuickStart(TemplateView):
template_name = "quick_start_editor/dashboard/quick_editor_main.html" def get_context_data(self, **kwargs): """ Insert the form into the context dict. """ kwargs['quick_starters'] = get_quick_starters() return super(QuickStart, self).get_context_data(**kwargs)
", "/") if name.startswith('/'): name = name[1:] return os.path.join( os.path.dirname(os.path.abspath(__file__)), 'schemas', "%s.schema"%name ) @method_decorator(login_required, name='dispatch') class QuickStart(TemplateView):
64
64
87
18
46
aristotle-mdr/json-metadata-editor
aristotle_json_editor/views.py
Python
QuickStart
QuickStart
53
63
53
54
1f1127da20a033b11c78ddc24d10a919b6c19a64
bigcode/the-stack
train
f02f259fd7cdbf8477aaafe1
train
class
class Serialiser(object): def __init__(self, root, extra={}): self.root = root self.serialised_extras = {} self.items = [] self.uuids = [] @transaction.atomic() def serialise(self, data, obj_type, defaults={}): import copy values = copy.deepcopy(defaults)...
class Serialiser(object):
def __init__(self, root, extra={}): self.root = root self.serialised_extras = {} self.items = [] self.uuids = [] @transaction.atomic() def serialise(self, data, obj_type, defaults={}): import copy values = copy.deepcopy(defaults) field_na...
.cleaned_data['extra_data'] print(obj) s = Serialiser(obj) s.serialise(obj, content_type) url = self.get_success_url() + '?' + urlencode( { "data": form.data, "uuids": ",".join(map(str,s.uuids)) } ) ...
219
219
730
5
213
aristotle-mdr/json-metadata-editor
aristotle_json_editor/views.py
Python
Serialiser
Serialiser
151
246
151
151
08e1aa75032d2e87a8d16a906e69ef440bc88aea
bigcode/the-stack
train
740754e931f1036da454229c
train
class
@method_decorator(login_required, name='dispatch') class ServeSchema(View, SchemaFileMixin): content_type = "application/json" def get_template_names(self): return ['aristotle_json_editor/schemas/%s.schema' % self.kwargs['schema_name']] def get(self, *args, **kwargs): print(self.kwargs['sch...
@method_decorator(login_required, name='dispatch') class ServeSchema(View, SchemaFileMixin):
content_type = "application/json" def get_template_names(self): return ['aristotle_json_editor/schemas/%s.schema' % self.kwargs['schema_name']] def get(self, *args, **kwargs): print(self.kwargs['schema_name']) with open(self.get_schema_file(self.kwargs['schema_name']), 'rb') as f: ...
_success_url() + '?' + urlencode( { "data": form.data, "uuids": ",".join(map(str,s.uuids)) } ) return HttpResponseRedirect(url) @method_decorator(login_required, name='dispatch') class ServeSchema(View, SchemaFileMixin):
64
64
121
20
44
aristotle-mdr/json-metadata-editor
aristotle_json_editor/views.py
Python
ServeSchema
ServeSchema
136
147
136
137
e64dcc4eb92a48ba1d3dac546b7214a9c9950ebd
bigcode/the-stack
train
05dfedd2c9b25ab7527dc744
train
class
@method_decorator(login_required, name='dispatch') class LoadEditor(SchemaFileMixin, FormView): template_name = "aristotle_json_editor/editor.html" form_class = JSONSchemaForm success_url = "/json_edit/success" def dispatch(self, request, *args, **kwargs): if self.kwargs['schema_name'] not in ...
@method_decorator(login_required, name='dispatch') class LoadEditor(SchemaFileMixin, FormView):
template_name = "aristotle_json_editor/editor.html" form_class = JSONSchemaForm success_url = "/json_edit/success" def dispatch(self, request, *args, **kwargs): if self.kwargs['schema_name'] not in get_quick_starters(): raise Http404 return super().dispatch(request, *args, ...
uccess.html" def get_context_data(self, **kwargs): """ Insert the form into the context dict. """ kwargs['data'] = self.request.GET.get('data') uuids = self.request.GET.get('uuids').split(',') kwargs['items'] = aristotle.models._concept.objects.filter(uuid__in=uuids...
113
113
378
22
91
aristotle-mdr/json-metadata-editor
aristotle_json_editor/views.py
Python
LoadEditor
LoadEditor
81
133
81
82
1b75eb050f682bc8df5d10d6e53326bb3dc3ce31
bigcode/the-stack
train
46af4e83c2e36e7598b51731
train
function
@command() @option("--input", required=True, help="the Feather file to read input from") @option("--output", required=True, help="the text file to write output to") def main(input, output): basicConfig(level=DEBUG) # Load data. info("Loading data") X = pd.read_feather(input) debug(f"Result: {X....
@command() @option("--input", required=True, help="the Feather file to read input from") @option("--output", required=True, help="the text file to write output to") def main(input, output):
basicConfig(level=DEBUG) # Load data. info("Loading data") X = pd.read_feather(input) debug(f"Result: {X.shape}") columns = sorted(X.columns) # Write output. info("Writing output") with open(output, "w") as handle: handle.write("\n".join(columns))
Obtains column names. """ from click import * from logging import * import pandas as pd @command() @option("--input", required=True, help="the Feather file to read input from") @option("--output", required=True, help="the text file to write output to") def main(input, output):
64
64
120
45
18
morrislab/plos-medicine-joint-patterns
scripts/data/demographics/get_columns.py
Python
main
main
11
34
11
15
cdc74834c25fc52a72e53e36d6db8e2a7176b03a
bigcode/the-stack
train
94a07d687c3b2eb21c51b9d0
train
class
class Command(BaseCommand): help = 'Наполняет базу Procurements данными из csv' def customer_update(self, num=500): with open(r'C:\Users\Eduard\Desktop\Projects\true_actum_hack\data\х Заказчики.csv', 'r', encoding='cp1251') as f: reader = csv.DictReader(f, delimiter=';') ...
class Command(BaseCommand):
help = 'Наполняет базу Procurements данными из csv' def customer_update(self, num=500): with open(r'C:\Users\Eduard\Desktop\Projects\true_actum_hack\data\х Заказчики.csv', 'r', encoding='cp1251') as f: reader = csv.DictReader(f, delimiter=';') for i, row in enu...
import csv import re from django.core.management import BaseCommand # import os from procurements.models import Customer, Region, ContactPerson, ProductionType, Contractor, Product, Producer, Country, \ ProductType, Characteristic, Material, Purchase, PurchaseMethod, CustomerItem, ProductItem, ContractorItem clas...
70
256
2,142
5
64
ldsad7/actum_hack
procurements/management/commands/inflate_db.py
Python
Command
Command
11
233
11
11
84e05473698d420197b5d436b5170e1437f646cd
bigcode/the-stack
train
abaa2bbcdb777ff74b007318
train
class
class SimpleGA: '''Simple Genetic Algorithm.''' def __init__(self, num_params, # number of model parameters sigma_init=0.1, # initial standard deviation sigma_decay=0.999, # anneal standard deviation sigma_limit=0.01, # stop annealing if less than th...
class SimpleGA:
'''Simple Genetic Algorithm.''' def __init__(self, num_params, # number of model parameters sigma_init=0.1, # initial standard deviation sigma_decay=0.999, # anneal standard deviation sigma_limit=0.01, # stop annealing if less than this ...
.popsize, }) def rms_stdev(self): sigma = self.es.result[6] return np.mean(np.sqrt(sigma*sigma)) def ask(self): '''returns a list of parameters''' self.solutions = np.array(self.es.ask()) return self.solutions def tell(self, reward_table_result): ...
246
246
823
4
242
adafok/brain-tokyo-workshop
learntopredict/cartpole/es.py
Python
SimpleGA
SimpleGA
134
232
134
134
15ad278c82464e26dd10c5d92e72f7a6aa2f95b0
bigcode/the-stack
train
9fd35dcb7e272d27df254c85
train
class
class OpenES: ''' Basic Version of OpenAI Evolution Strategies.''' def __init__(self, num_params, # number of model parameters sigma_init=0.1, # initial standard deviation sigma_decay=0.999, # anneal standard deviation sigma_limit=0.0...
class OpenES:
''' Basic Version of OpenAI Evolution Strategies.''' def __init__(self, num_params, # number of model parameters sigma_init=0.1, # initial standard deviation sigma_decay=0.999, # anneal standard deviation sigma_limit=0.01, ...
self.first_iteration: reward = reward_table solution = self.solutions else: reward = np.concatenate([reward_table, self.elite_rewards]) solution = np.concatenate([self.solutions, self.elite_params]) idx = np.argsort(reward)[::-1][0:self.elite_popsize] self.elite_rewards = reward[i...
256
256
1,038
4
252
adafok/brain-tokyo-workshop
learntopredict/cartpole/es.py
Python
OpenES
OpenES
234
350
234
234
eaac7a9b32486e9f4f5d616446739be1be4f66f7
bigcode/the-stack
train
5f0593e2584cc86a1ecf80ca
train
function
def compute_ranks(x): """ Returns ranks in [0, len(x)) Note: This is different from scipy.stats.rankdata, which returns ranks in [1, len(x)]. (https://github.com/openai/evolution-strategies-starter/blob/master/es_distributed/es.py) """ assert x.ndim == 1 ranks = np.empty(len(x), dtype=int) ranks[x.argso...
def compute_ranks(x):
""" Returns ranks in [0, len(x)) Note: This is different from scipy.stats.rankdata, which returns ranks in [1, len(x)]. (https://github.com/openai/evolution-strategies-starter/blob/master/es_distributed/es.py) """ assert x.ndim == 1 ranks = np.empty(len(x), dtype=int) ranks[x.argsort()] = np.arange(len(...
import numpy as np def compute_ranks(x):
11
64
102
6
4
adafok/brain-tokyo-workshop
learntopredict/cartpole/es.py
Python
compute_ranks
compute_ranks
3
12
3
3
af7f21b4e564598a165de16e212798c2af438c7e
bigcode/the-stack
train
532a6b4b050a825f6f2a62cf
train
class
class Adam(Optimizer): def __init__(self, pi, stepsize, beta1=0.99, beta2=0.999): Optimizer.__init__(self, pi) self.stepsize = stepsize self.beta1 = beta1 self.beta2 = beta2 self.m = np.zeros(self.dim, dtype=np.float32) self.v = np.zeros(self.dim, dtype=np.float32) def _compute_step(self, g...
class Adam(Optimizer):
def __init__(self, pi, stepsize, beta1=0.99, beta2=0.999): Optimizer.__init__(self, pi) self.stepsize = stepsize self.beta1 = beta1 self.beta2 = beta2 self.m = np.zeros(self.dim, dtype=np.float32) self.v = np.zeros(self.dim, dtype=np.float32) def _compute_step(self, globalg): a = self.s...
ize, self.momentum = stepsize, momentum def _compute_step(self, globalg): self.v = self.momentum * self.v + (1. - self.momentum) * globalg step = -self.stepsize * self.v return step class Adam(Optimizer):
64
64
205
5
58
adafok/brain-tokyo-workshop
learntopredict/cartpole/es.py
Python
Adam
Adam
70
84
70
70
3bc9343f4fcc657164d3b53d940ce6fa1a4b5728
bigcode/the-stack
train
c5f54ce28f6f61496ab2d101
train
class
class CMAES: '''CMA-ES wrapper.''' def __init__(self, num_params, # number of model parameters sigma_init=0.10, # initial standard deviation popsize=255, # population size weight_decay=0.01): # weight decay coefficient self.num_params = num_p...
class CMAES:
'''CMA-ES wrapper.''' def __init__(self, num_params, # number of model parameters sigma_init=0.10, # initial standard deviation popsize=255, # population size weight_decay=0.01): # weight decay coefficient self.num_params = num_params sel...
def _compute_step(self, globalg): a = self.stepsize * np.sqrt(1 - self.beta2 ** self.t) / (1 - self.beta1 ** self.t) self.m = self.beta1 * self.m + (1 - self.beta1) * globalg self.v = self.beta2 * self.v + (1 - self.beta2) * (globalg * globalg) step = -a * self.m / (np.sqrt(self.v) + self.epsilon) ...
115
115
386
4
110
adafok/brain-tokyo-workshop
learntopredict/cartpole/es.py
Python
CMAES
CMAES
86
132
86
86
ea4210139553591cc62a38fdd71af82899f97892
bigcode/the-stack
train
3ac8f9d0edb69ac5472c5b2f
train
class
class Optimizer(object): def __init__(self, pi, epsilon=1e-08): self.pi = pi self.dim = pi.num_params self.epsilon = epsilon self.t = 0 def update(self, globalg): self.t += 1 step = self._compute_step(globalg) theta = self.pi.mu ratio = np.linalg.norm(step) / (np.linalg.norm(theta) ...
class Optimizer(object):
def __init__(self, pi, epsilon=1e-08): self.pi = pi self.dim = pi.num_params self.epsilon = epsilon self.t = 0 def update(self, globalg): self.t += 1 step = self._compute_step(globalg) theta = self.pi.mu ratio = np.linalg.norm(step) / (np.linalg.norm(theta) + self.epsilon) self....
model_param_grid = np.array(model_param_list) return - weight_decay * np.mean(model_param_grid * model_param_grid, axis=1) # adopted from: # https://github.com/openai/evolution-strategies-starter/blob/master/es_distributed/optimizers.py class Optimizer(object):
64
64
130
5
58
adafok/brain-tokyo-workshop
learntopredict/cartpole/es.py
Python
Optimizer
Optimizer
30
46
30
30
fec59f1b05457aa5873d7d0824418d82467954be
bigcode/the-stack
train
36b11cf78e52c7fe97cee8a6
train
class
class PEPG: '''Extension of PEPG with bells and whistles.''' def __init__(self, num_params, # number of model parameters sigma_init=0.10, # initial standard deviation sigma_alpha=0.20, # learning rate for standard deviation sigma_deca...
class PEPG:
'''Extension of PEPG with bells and whistles.''' def __init__(self, num_params, # number of model parameters sigma_init=0.10, # initial standard deviation sigma_alpha=0.20, # learning rate for standard deviation sigma_decay=0.999, ...
self.best_mu = best_mu self.best_reward = self.curr_best_reward # main bit: # standardize the rewards to have a gaussian distribution normalized_reward = (reward - np.mean(reward)) / np.std(reward) change_mu = 1./(self.popsize*self.sigma)*np.dot(self.epsilon.T, normalized_reward) ...
256
256
1,699
5
251
adafok/brain-tokyo-workshop
learntopredict/cartpole/es.py
Python
PEPG
PEPG
352
525
352
352
2a667fd830f6da49cf0ec08712b71fbb8b45f8ca
bigcode/the-stack
train
64bb2eb9f4abfba623e8d1da
train
class
class BasicSGD(Optimizer): def __init__(self, pi, stepsize): Optimizer.__init__(self, pi) self.stepsize = stepsize def _compute_step(self, globalg): step = -self.stepsize * globalg return step
class BasicSGD(Optimizer):
def __init__(self, pi, stepsize): Optimizer.__init__(self, pi) self.stepsize = stepsize def _compute_step(self, globalg): step = -self.stepsize * globalg return step
) theta = self.pi.mu ratio = np.linalg.norm(step) / (np.linalg.norm(theta) + self.epsilon) self.pi.mu = theta + step return ratio def _compute_step(self, globalg): raise NotImplementedError class BasicSGD(Optimizer):
64
64
62
7
56
adafok/brain-tokyo-workshop
learntopredict/cartpole/es.py
Python
BasicSGD
BasicSGD
49
56
49
49
84679af4d231ff386a046f32e91441f22ee7cc0b
bigcode/the-stack
train
668c24098a9306bbb9c14bff
train
function
def compute_centered_ranks(x): """ https://github.com/openai/evolution-strategies-starter/blob/master/es_distributed/es.py """ y = compute_ranks(x.ravel()).reshape(x.shape).astype(np.float32) y /= (x.size - 1) y -= .5 return y
def compute_centered_ranks(x):
""" https://github.com/openai/evolution-strategies-starter/blob/master/es_distributed/es.py """ y = compute_ranks(x.ravel()).reshape(x.shape).astype(np.float32) y /= (x.size - 1) y -= .5 return y
.com/openai/evolution-strategies-starter/blob/master/es_distributed/es.py) """ assert x.ndim == 1 ranks = np.empty(len(x), dtype=int) ranks[x.argsort()] = np.arange(len(x)) return ranks def compute_centered_ranks(x):
64
64
73
8
55
adafok/brain-tokyo-workshop
learntopredict/cartpole/es.py
Python
compute_centered_ranks
compute_centered_ranks
14
21
14
14
46aa901a6d7f37878939eafe970679dd401b1fac
bigcode/the-stack
train
a1d69c282f6ea0f611b91439
train
function
def compute_weight_decay(weight_decay, model_param_list): model_param_grid = np.array(model_param_list) return - weight_decay * np.mean(model_param_grid * model_param_grid, axis=1)
def compute_weight_decay(weight_decay, model_param_list):
model_param_grid = np.array(model_param_list) return - weight_decay * np.mean(model_param_grid * model_param_grid, axis=1)
ategies-starter/blob/master/es_distributed/es.py """ y = compute_ranks(x.ravel()).reshape(x.shape).astype(np.float32) y /= (x.size - 1) y -= .5 return y def compute_weight_decay(weight_decay, model_param_list):
64
64
42
11
52
adafok/brain-tokyo-workshop
learntopredict/cartpole/es.py
Python
compute_weight_decay
compute_weight_decay
23
25
23
23
15dc0d8eca5af621fa6c31530494d71db8b3c47d
bigcode/the-stack
train
55ddce05e70a920ff85dfd52
train
class
class SGD(Optimizer): def __init__(self, pi, stepsize, momentum=0.9): Optimizer.__init__(self, pi) self.v = np.zeros(self.dim, dtype=np.float32) self.stepsize, self.momentum = stepsize, momentum def _compute_step(self, globalg): self.v = self.momentum * self.v + (1. - self.momentum) * globalg s...
class SGD(Optimizer):
def __init__(self, pi, stepsize, momentum=0.9): Optimizer.__init__(self, pi) self.v = np.zeros(self.dim, dtype=np.float32) self.stepsize, self.momentum = stepsize, momentum def _compute_step(self, globalg): self.v = self.momentum * self.v + (1. - self.momentum) * globalg step = -self.stepsize *...
D(Optimizer): def __init__(self, pi, stepsize): Optimizer.__init__(self, pi) self.stepsize = stepsize def _compute_step(self, globalg): step = -self.stepsize * globalg return step class SGD(Optimizer):
64
64
109
5
58
adafok/brain-tokyo-workshop
learntopredict/cartpole/es.py
Python
SGD
SGD
58
67
58
58
6aeffaa86d4a78a56e6e9118dbab96c0f2459470
bigcode/the-stack
train
756bb8aab49a8fb7a03284d9
train
class
class SecretServerMockResponse: def __init__(self, response_code, object): self.code = response_code self.object = object def read(self): return self.object
class SecretServerMockResponse:
def __init__(self, response_code, object): self.code = response_code self.object = object def read(self): return self.object
from stix_shifter.stix_transmission import stix_transmission from stix_shifter_modules.secretserver.entry_point import EntryPoint from stix_shifter_utils.modules.base.stix_transmission.base_status_connector import Status import unittest from unittest.mock import patch class SecretServerMockResponse:
63
64
41
6
56
grimmjow8/stix-shifter
stix_shifter_modules/secretserver/tests/stix_transmission/test_secretserver.py
Python
SecretServerMockResponse
SecretServerMockResponse
9
15
9
9
ef1e7ede6747aa48973adf56ae0be5627891bfd0
bigcode/the-stack
train
514946bd417112428996ce6a
train
class
@patch('stix_shifter_modules.secretserver.stix_transmission.api_client.APIClient.__init__', autospec=True) class TestSecretServerConnection(unittest.TestCase, object): def test_is_async(self, mock_api_client): mock_api_client.return_value = None entry_point = EntryPoint() config = { ...
@patch('stix_shifter_modules.secretserver.stix_transmission.api_client.APIClient.__init__', autospec=True) class TestSecretServerConnection(unittest.TestCase, object):
def test_is_async(self, mock_api_client): mock_api_client.return_value = None entry_point = EntryPoint() config = { "auth": { "username": "admin", "password": "password123" } } connection = { "host": "secret...
from stix_shifter.stix_transmission import stix_transmission from stix_shifter_modules.secretserver.entry_point import EntryPoint from stix_shifter_utils.modules.base.stix_transmission.base_status_connector import Status import unittest from unittest.mock import patch class SecretServerMockResponse: def __init__...
135
256
1,181
37
97
grimmjow8/stix-shifter
stix_shifter_modules/secretserver/tests/stix_transmission/test_secretserver.py
Python
TestSecretServerConnection
TestSecretServerConnection
17
99
17
18
209ee7ee0f14c7034c0c9d4533dfab0e64deb1ee
bigcode/the-stack
train
ac5f2a444672240737afc1d2
train
class
class AEPGroup(Group): """ Group containing all necessary components for wind plant AEP calculations using the FLORIS model """ def __init__(self, nTurbines, nDirections=1, use_rotor_components=False, datasize=0, differentiable=True, optimizingLayout=False, nSamples=0, wake_model=flori...
class AEPGroup(Group):
""" Group containing all necessary components for wind plant AEP calculations using the FLORIS model """ def __init__(self, nTurbines, nDirections=1, use_rotor_components=False, datasize=0, differentiable=True, optimizingLayout=False, nSamples=0, wake_model=floris_wrapper, ...
', 'turbineXw', 'turbineYw', 'rotorDiameter', 'yaw%i' % direction_id, 'hubHeight', 'wtVelocity%i' % direction_id, 'wsPositionXw', 'wsPositionYw', 'wsPositionZ', 'wsArray%i' % direction_id])) self.add('powerComp', Wi...
256
256
1,948
6
250
kilojoules/PlantEnergy
src/wakeexchange/GeneralWindFarmGroups.py
Python
AEPGroup
AEPGroup
126
247
126
126
c5b64f284c6c99774eb1eeb2069677e96d8addce
bigcode/the-stack
train
ff9e3950f2379c315a52b0ab
train
class
class RotorSolveGroup(Group): def __init__(self, nTurbines, direction_id=0, datasize=0, differentiable=True, use_rotor_components=False, nSamples=0, wake_model=floris_wrapper, wake_model_options=None): super(RotorSolveGroup, self).__init__() if wake_model_options...
class RotorSolveGroup(Group):
def __init__(self, nTurbines, direction_id=0, datasize=0, differentiable=True, use_rotor_components=False, nSamples=0, wake_model=floris_wrapper, wake_model_options=None): super(RotorSolveGroup, self).__init__() if wake_model_options is None: wake_mode...
aussSeidel from openmdao.core.mpi_wrap import MPI if MPI: from openmdao.api import PetscKSP from wakeexchange.floris import floris_wrapper, add_floris_params_IndepVarComps #from wakeexchange.gauss import add_gauss_params_IndepVarComps from GeneralWindFarmComponents import WindFrame, AdjustCtCpYaw, MUX, WindFar...
138
138
462
6
131
kilojoules/PlantEnergy
src/wakeexchange/GeneralWindFarmGroups.py
Python
RotorSolveGroup
RotorSolveGroup
19
56
19
20
1cec68aa3a879d308d61c07d913d8831a93d5643
bigcode/the-stack
train
6cf6f0291af662b2697cabb9
train
class
class DirectionGroup(Group): """ Group containing all necessary components for wind plant calculations in a single direction """ def __init__(self, nTurbines, direction_id=0, use_rotor_components=False, datasize=0, differentiable=True, add_IdepVarComps=True, params_IdepVar_func=add...
class DirectionGroup(Group):
""" Group containing all necessary components for wind plant calculations in a single direction """ def __init__(self, nTurbines, direction_id=0, use_rotor_components=False, datasize=0, differentiable=True, add_IdepVarComps=True, params_IdepVar_func=add_floris_params_IndepVarComps,...
ines, direction_id=direction_id, datasize=datasize), promotes=['gen_params:*', 'yaw%i' % direction_id, 'wtVelocity%i' % direction_id, 'Cp_out']) # TODO refactor the model component instance self.add('floris', wake_model(nTurbines, direction_id=direction_id, w...
256
256
923
5
251
kilojoules/PlantEnergy
src/wakeexchange/GeneralWindFarmGroups.py
Python
DirectionGroup
DirectionGroup
59
123
59
59
bdd4633239d5fdc3254a03fc2d623875ff681573
bigcode/the-stack
train
5cf45f33573459c064336aaa
train
function
def initialize_db(app): connect(host=app.config["HOST"])
def initialize_db(app):
connect(host=app.config["HOST"])
from mongoengine import connect def initialize_db(app):
11
64
14
5
5
justsom3guy/flask-blog
app/database/db.py
Python
initialize_db
initialize_db
4
5
4
4
711a477c1c0626c8278d2a4c81b9fe2b8b6d3988
bigcode/the-stack
train
3cb224768e66e4591785f9d8
train
function
def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('pitches', 'posted')
def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.drop_column('pitches', 'posted')
(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('pitches', sa.Column('posted', sa.DateTime(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
63
64
29
18
45
p-koskey/pitch
migrations/versions/b9dce9ff18af_added_datetime.py
Python
downgrade
downgrade
25
27
25
26
8de2918cf5a6136954347d97e19ecafd0057b629
bigcode/the-stack
train
5dc70b99fff563532d825787
train
function
def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('pitches', sa.Column('posted', sa.DateTime(), nullable=True))
def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.add_column('pitches', sa.Column('posted', sa.DateTime(), nullable=True))
sa # revision identifiers, used by Alembic. revision = 'b9dce9ff18af' down_revision = '85b4e8025308' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
64
64
38
18
45
p-koskey/pitch
migrations/versions/b9dce9ff18af_added_datetime.py
Python
upgrade
upgrade
19
21
19
20
2b5a4b3ed907a58510917c6206ff53aa97758ec9
bigcode/the-stack
train
7a80d96caf694622244789bc
train
function
def stft(x, binsize=1024, overlap_factor=.5, hopsize=None, window='hamming', **kwargs): """ STFT, Short-Term Fourier Transform. Parameters: ----------- x: 2d-ndarray, (n_ch, n_samp) Multi-channel signal. binsize: int Window size for processing FFT on. overlap_factor: float ...
def stft(x, binsize=1024, overlap_factor=.5, hopsize=None, window='hamming', **kwargs):
""" STFT, Short-Term Fourier Transform. Parameters: ----------- x: 2d-ndarray, (n_ch, n_samp) Multi-channel signal. binsize: int Window size for processing FFT on. overlap_factor: float The percentage of overlapping between consecutive windows. hopsize: int ...
ValueError("At least one of 'overlap_factor' or 'hopsize' has to have a value.") overlap_factor = hopsize / binsize if overlap_factor is None else overlap_factor hopsize = int(binsize * (1 - overlap_factor)) if hopsize is None else hopsize if overlap_factor in [0, 1]: hopsize = 0 if overlap_facto...
177
177
592
28
148
davidlu89/pytf
pytf/time_frequency/stft.py
Python
stft
stft
48
120
48
48
ea1ae4ab0ac674c65fe75a5e69a890eca1ad3f76
bigcode/the-stack
train
63698660b14601a2abc44500
train
function
def _check_winsize(binsize, overlap_factor=None, hopsize=None): """ Ensure all parameters for defining the windowing size of the signal aligns. Parameters: ----------- binsize: int The length of chunk size. overlap_factor: float The ratio of overlapping between chuncks. hopsiz...
def _check_winsize(binsize, overlap_factor=None, hopsize=None):
""" Ensure all parameters for defining the windowing size of the signal aligns. Parameters: ----------- binsize: int The length of chunk size. overlap_factor: float The ratio of overlapping between chuncks. hopsize: int The number of sample it takes to hop between rows...
try: import pyfftw.interfaces.numpy_fft as fft except ImportError: import scipy.fftpack as fft from ..reconstruction.overlap import overlap_add # Authors : David C.C. Lu <davidlu89@gmail.com> # # License : BSD (3-clause) def _check_winsize(binsize, overlap_factor=None, hopsize=None):
81
81
272
18
63
davidlu89/pytf
pytf/time_frequency/stft.py
Python
_check_winsize
_check_winsize
16
46
16
16
f773500600b620246f18c4c4c2cff6f7fc8c2c52
bigcode/the-stack
train
2e767d927ce371069ccca9b2
train
function
def istft(X, nsamp=None, binsize=1024, overlap_factor=.5, hopsize=None): """ Inverse STFT. Parameters: ----------- X: ndarray, (n_ch, n_win, binsize // 2) or (n_ch, n_win, n_fr, binsize // 2) binsize: int Window size for processing FFT on. overlap_factor: float The percentage ...
def istft(X, nsamp=None, binsize=1024, overlap_factor=.5, hopsize=None):
""" Inverse STFT. Parameters: ----------- X: ndarray, (n_ch, n_win, binsize // 2) or (n_ch, n_win, n_fr, binsize // 2) binsize: int Window size for processing FFT on. overlap_factor: float The percentage of overlapping between consecutive windows. hopsize: int The...
# Process win_ = get_window(window, binsize) frames = stride_tricks.as_strided( _x, shape=(n_ch, n_win, binsize), strides=(_x.strides[0], _x.strides[1]*hopsize, _x.strides[1]) ) X = fft.rfft(frames *...
111
111
371
24
86
davidlu89/pytf
pytf/time_frequency/stft.py
Python
istft
istft
122
164
122
122
05fb4d6306d93d9fe05d0fe43f39b3773506a3b8
bigcode/the-stack
train
f3274c48518f40a193878a78
train
function
def change_file_time(filename: str, timestamp: float): winfile = win32file.CreateFile( filename, ntsecuritycon.FILE_WRITE_ATTRIBUTES, 0, None, win32con.OPEN_EXISTING, 0, None) wintime = pywintypes.Time(timestamp) create_time = wintime last_access_...
def change_file_time(filename: str, timestamp: float):
winfile = win32file.CreateFile( filename, ntsecuritycon.FILE_WRITE_ATTRIBUTES, 0, None, win32con.OPEN_EXISTING, 0, None) wintime = pywintypes.Time(timestamp) create_time = wintime last_access_time = None modified_time = wintime win32file.S...
if = img._getexif() date = exif[0x9003] print('date', date) return datetime.strptime(date, '%Y:%m:%d %H:%M:%S') except: return None def change_file_time(filename: str, timestamp: float):
64
64
112
12
51
hdmun/py-win-file-attr-change
util.py
Python
change_file_time
change_file_time
43
58
43
43
d46b2bcb0edd9b9e220cc59481748d7b2e704137
bigcode/the-stack
train
92a5bab2f5280bdc3a388f0c
train
function
def get_photo_take_time(path: str): try: img = Image.open(path) exif = img._getexif() date = exif[0x9003] print('date', date) return datetime.strptime(date, '%Y:%m:%d %H:%M:%S') except: return None
def get_photo_take_time(path: str):
try: img = Image.open(path) exif = img._getexif() date = exif[0x9003] print('date', date) return datetime.strptime(date, '%Y:%m:%d %H:%M:%S') except: return None
_IPropertyStore) prop_var_date = propsys.PROPVARIANTType(pywintypes.Time(timestamp), pythoncom.VT_DATE) properties.SetValue(pscon.PKEY_Media_DateEncoded, prop_var_date) properties.Commit() properties = None def get_photo_take_time(path: str):
64
64
73
9
54
hdmun/py-win-file-attr-change
util.py
Python
get_photo_take_time
get_photo_take_time
31
39
31
31
17c76f4a1799e43b1910ff0c09d90f699505e86d
bigcode/the-stack
train
96572b0a5d6a7b3e72e92437
train
function
def set_media_date_encoded(path: str, timestamp: float): properties = propsys.SHGetPropertyStoreFromParsingName(path, None, shellcon.GPS_READWRITE, propsys.IID_IPropertyStore) prop_var_date = propsys.PROPVARIANTType(pywintypes.Time(timestamp), pythoncom.VT_DATE) properties.SetValue(pscon.PKEY_Media_DateEnco...
def set_media_date_encoded(path: str, timestamp: float):
properties = propsys.SHGetPropertyStoreFromParsingName(path, None, shellcon.GPS_READWRITE, propsys.IID_IPropertyStore) prop_var_date = propsys.PROPVARIANTType(pywintypes.Time(timestamp), pythoncom.VT_DATE) properties.SetValue(pscon.PKEY_Media_DateEncoded, prop_var_date) properties.Commit() propertie...
.GetValue(pscon.PKEY_Media_DateEncoded).GetValue() properties = None # release format_dt = '%Y-%m-%d %H:%M:S' return datetime.strptime(prop_dt.strftime(format_dt), format_dt) def set_media_date_encoded(path: str, timestamp: float):
64
64
95
13
51
hdmun/py-win-file-attr-change
util.py
Python
set_media_date_encoded
set_media_date_encoded
23
28
23
23
8c37289a0e3da83370b75889b0b7b5c620493d07
bigcode/the-stack
train
a8ce35ba37688f9f6152e357
train
function
def get_media_date_encoded(path: str): properties = propsys.SHGetPropertyStoreFromParsingName(path, None, shellcon.GPS_READWRITE, propsys.IID_IPropertyStore) prop_dt = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue() properties = None # release format_dt = '%Y-%m-%d %H:%M:S' return date...
def get_media_date_encoded(path: str):
properties = propsys.SHGetPropertyStoreFromParsingName(path, None, shellcon.GPS_READWRITE, propsys.IID_IPropertyStore) prop_dt = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue() properties = None # release format_dt = '%Y-%m-%d %H:%M:S' return datetime.strptime(prop_dt.strftime(format_d...
import pythoncom import pywintypes import win32con import win32file from exif import Image from PIL import Image from win32com.propsys import propsys, pscon from win32comext.shell import shellcon def get_media_date_encoded(path: str):
64
64
96
9
54
hdmun/py-win-file-attr-change
util.py
Python
get_media_date_encoded
get_media_date_encoded
15
20
15
15
2ce5ed0d036c986da6f799a2db5290a8fa63cc9d
bigcode/the-stack
train
c91473eebf2f916c2495ab01
train
function
def set_photo_take_time(path: str, datetime: datetime): with open(path, 'rb') as imfp: img = Image(imfp) img.datetime_original = datetime.strftime('%Y:%m:%d %H:%M:%S') with open(path, 'wb') as imfp: imfp.write(img.get_file())
def set_photo_take_time(path: str, datetime: datetime):
with open(path, 'rb') as imfp: img = Image(imfp) img.datetime_original = datetime.strftime('%Y:%m:%d %H:%M:%S') with open(path, 'wb') as imfp: imfp.write(img.get_file())
intypes.Time(timestamp) create_time = wintime last_access_time = None modified_time = wintime win32file.SetFileTime(winfile, create_time, last_access_time, modified_time) winfile.close() def set_photo_take_time(path: str, datetime: datetime):
64
64
72
13
51
hdmun/py-win-file-attr-change
util.py
Python
set_photo_take_time
set_photo_take_time
61
66
61
61
a4eede974636ca7fc08619f45e48af7ba6b31832
bigcode/the-stack
train
de2185b2f5a2bfe6dab387be
train
function
def dislocate(def_loc, delta, pos): dislocation = np.zeros((def_loc.shape)) dislocation[pos[0], pos[1]] = (np.random.random()-0.5) * 2.0*delta return def_loc + dislocation
def dislocate(def_loc, delta, pos):
dislocation = np.zeros((def_loc.shape)) dislocation[pos[0], pos[1]] = (np.random.random()-0.5) * 2.0*delta return def_loc + dislocation
np.random.random((N,2)) * L def_sigma = np.zeros(N) def_sigma[::2] = 0.5 def_sigma[1::2]= -0.5 return def_loc, def_sigma def dislocate(def_loc, delta, pos):
64
64
59
11
52
ialireza13/Defect-Dynamics
functions.py
Python
dislocate
dislocate
79
82
79
79
1d1f42262329802ceab079c4334a6398a21f179e
bigcode/the-stack
train
738e13975f6fc88fd5423551
train
function
def random_defects(N, L): def_loc = np.random.random((N,2)) * L def_sigma = np.zeros(N) def_sigma[::2] = 0.5 def_sigma[1::2]= -0.5 return def_loc, def_sigma
def random_defects(N, L):
def_loc = np.random.random((N,2)) * L def_sigma = np.zeros(N) def_sigma[::2] = 0.5 def_sigma[1::2]= -0.5 return def_loc, def_sigma
) # B = np.outer(sigma,sigma)*np.log(L/np.abs(np.outer(z,np.ones(z.shape)) - np.outer(np.ones(z.shape),z))) # np.fill_diagonal(B,sigma*sigma*np.log(L/a)) return B def random_defects(N, L):
64
64
65
8
55
ialireza13/Defect-Dynamics
functions.py
Python
random_defects
random_defects
72
77
72
72
8df3afe7c0fb9e9bd2cb843b50a0e24f7727b670
bigcode/the-stack
train
67e599a76cba8402dd148d35
train
function
def funcB(sigma, z, L, a): B = np.zeros((len(z), len(z)), dtype='complex128') for i in range(len(z)): for j in range(len(z)): if i!=j: B[i,j] = sigma[i]*sigma[j] * np.log(L/np.abs(z[i]-z[j])) continue B[i,j] = sigma[i]*sigma[j] * np.log(L/a) # ...
def funcB(sigma, z, L, a):
B = np.zeros((len(z), len(z)), dtype='complex128') for i in range(len(z)): for j in range(len(z)): if i!=j: B[i,j] = sigma[i]*sigma[j] * np.log(L/np.abs(z[i]-z[j])) continue B[i,j] = sigma[i]*sigma[j] * np.log(L/a) # B = np.outer(sigma,sigma)*n...
1.0-sigma[j]) * (np.conj(q[i,j])-np.power(-1, (sigma[i]+sigma[j]==1))*q[i,j])/(np.conj(z[i]) - np.conj(z[j])) return AF def funcB(sigma, z, L, a):
64
64
152
12
51
ialireza13/Defect-Dynamics
functions.py
Python
funcB
funcB
60
70
60
60
66397d32645a357d551ae690a99d0e14a2a9f739
bigcode/the-stack
train
5a3a520c502a60cba225c47c
train
function
def funcAF(sigma, z, q): AF = np.zeros(len(z), dtype='complex128') for i in range(len(z)): for j in range(len(z)): if i!=j: AF[i] += sigma[i]*sigma[j]/(1.0-sigma[j]) * (np.conj(q[i,j])-np.power(-1, (sigma[i]+sigma[j]==1))*q[i,j])/(np.conj(z[i]) - np.conj(z[j])) return AF
def funcAF(sigma, z, q):
AF = np.zeros(len(z), dtype='complex128') for i in range(len(z)): for j in range(len(z)): if i!=j: AF[i] += sigma[i]*sigma[j]/(1.0-sigma[j]) * (np.conj(q[i,j])-np.power(-1, (sigma[i]+sigma[j]==1))*q[i,j])/(np.conj(z[i]) - np.conj(z[j])) return AF
.ones(z.shape),z))/(np.outer(z_,np.ones(z_.shape)) - np.outer(np.ones(z_.shape),z_)), np.outer(sigma,np.ones(sigma.shape))-1) # np.fill_diagonal(q,0) return q def funcAF(sigma, z, q):
64
64
109
10
53
ialireza13/Defect-Dynamics
functions.py
Python
funcAF
funcAF
52
58
52
52
ad6e3db91c08782a5eff84f92a3027ac87fbad46
bigcode/the-stack
train
adcb56dda679713a1f3de399
train
function
def funcSR(eiphi, sigma, a): # SR = np.zeros(len(sigma), dtype='complex128') # for i in range(len(sigma)): # SR[i] = eiphi[i]*int(sigma[i]==0.5)/(4.0*a) SR = eiphi*(sigma==0.5)/(4.0*a) return SR
def funcSR(eiphi, sigma, a): # SR = np.zeros(len(sigma), dtype='complex128') # for i in range(len(sigma)): # SR[i] = eiphi[i]*int(sigma[i]==0.5)/(4.0*a)
SR = eiphi*(sigma==0.5)/(4.0*a) return SR
return C def funcSR(eiphi, sigma, a): # SR = np.zeros(len(sigma), dtype='complex128') # for i in range(len(sigma)): # SR[i] = eiphi[i]*int(sigma[i]==0.5)/(4.0*a)
64
64
81
60
3
ialireza13/Defect-Dynamics
functions.py
Python
funcSR
funcSR
17
22
17
20
fdc5ca5c75b692496dd446227b88ed3683d8f088
bigcode/the-stack
train
76b5e04fe0f9f9d98882c963
train
function
def funcq(sigma, z, eiphi): q = np.zeros((len(z), len(z)), dtype='complex128') for i in range(len(z)): for j in range(len(z)): if i!=j: q[i,j] = eiphi[i] * np.power((z[i]-z[j])/(np.conj(z[i])-np.conj(z[j])), sigma[i]-1) # z_ = np.conj(z) # q = np.outer(eiphi,np.ones(e...
def funcq(sigma, z, eiphi):
q = np.zeros((len(z), len(z)), dtype='complex128') for i in range(len(z)): for j in range(len(z)): if i!=j: q[i,j] = eiphi[i] * np.power((z[i]-z[j])/(np.conj(z[i])-np.conj(z[j])), sigma[i]-1) # z_ = np.conj(z) # q = np.outer(eiphi,np.ones(eiphi.shape)) * np.power((np....
(eiphi, 1) # eiphi = np.prod(eiphi, axis=1) # eiphi = np.multiply(eiphi, np.power(np.exp(2*1j*psi), len(psi)-1)) return eiphi def funcq(sigma, z, eiphi):
64
64
182
11
52
ialireza13/Defect-Dynamics
functions.py
Python
funcq
funcq
41
50
41
41
76949a791dc378582dad8c07bfd3a6045f364f3d
bigcode/the-stack
train
a02347770e5ecf6f79768807
train
function
def funcpsi(sigma,z): psi = np.power(z/np.conj(z), sigma) return psi
def funcpsi(sigma,z):
psi = np.power(z/np.conj(z), sigma) return psi
') # for i in range(len(sigma)): # SR[i] = eiphi[i]*int(sigma[i]==0.5)/(4.0*a) SR = eiphi*(sigma==0.5)/(4.0*a) return SR def funcpsi(sigma,z):
64
64
25
7
56
ialireza13/Defect-Dynamics
functions.py
Python
funcpsi
funcpsi
24
26
24
24
fcd7c432a87f985a42789b296d38bcea0db6dae8
bigcode/the-stack
train