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
d50967adaf150dfa2e1bfa2e
train
function
def create_dynamic_topic_model(corpus_filepath: str, dict_filepath: str, time_slices: list): """ Creates topic models based on preprocessed data. :param corpus_filepath: :param dict_filepath: :param time_slices: :return: """ corpus = gensim.corpora.MmCorpus(gensim_test_utils.datapath(co...
def create_dynamic_topic_model(corpus_filepath: str, dict_filepath: str, time_slices: list):
""" Creates topic models based on preprocessed data. :param corpus_filepath: :param dict_filepath: :param time_slices: :return: """ corpus = gensim.corpora.MmCorpus(gensim_test_utils.datapath(corpus_filepath)) id2word = gensim.corpora.Dictionary.load(fname=dict_filepath) # Crea...
_" + str(i) for i in range(0, 6)]] = pd.DataFrame(df.topic_probs.values.tolist(), index=df.index) df = pd.read_pickle("tmp.pkl") def test(rec): print(rec) print(type(rec)) exit() df[["topic_" + str(i) for i in range(0, 6)]] = df[["topic_" + str(i) for i in range(0, 6)]].apply( ...
256
256
858
22
234
catb0y/TheQuickWar
compute_topic_model.py
Python
create_dynamic_topic_model
create_dynamic_topic_model
48
116
48
48
dba36296f64a1fc55150af6649b8307a0051d190
bigcode/the-stack
train
ea23158000cc933961da584a
train
function
def postprocess_topic_model(corpus_filepath: str, model_filepath: str, articles_filepath: str, dict_filepath: str): """ Postprocesses results of finished topic model in preparation of visualization of topic relevance over time. :param corpus_filepath: :param model_filepath: :param articles_filepath:...
def postprocess_topic_model(corpus_filepath: str, model_filepath: str, articles_filepath: str, dict_filepath: str):
""" Postprocesses results of finished topic model in preparation of visualization of topic relevance over time. :param corpus_filepath: :param model_filepath: :param articles_filepath: :param dict_filepath: :return: """ corpus = gensim.corpora.MmCorpus(gensim_test_utils.datapath(corp...
import logging import os from pprint import pprint import pandas as pd import gensim from gensim.test import utils as gensim_test_utils def postprocess_topic_model(corpus_filepath: str, model_filepath: str, articles_filepath: str, dict_filepath: str):
58
136
454
26
31
catb0y/TheQuickWar
compute_topic_model.py
Python
postprocess_topic_model
postprocess_topic_model
9
45
9
9
5b5e8cfb739028e5b57a527c6ecb5d0ceaf4952c
bigcode/the-stack
train
7cee64e7b1875e8d2252cef3
train
class
class Threads: list = [] thread = [] def __init__(self): pass def put(self, **kwargs): self.list.append(kwargs) pass def run(self): self.thread = [] for item in self.list: self.thread.append(threading.Thread( name=item['team']['n...
class Threads:
list = [] thread = [] def __init__(self): pass def put(self, **kwargs): self.list.append(kwargs) pass def run(self): self.thread = [] for item in self.list: self.thread.append(threading.Thread( name=item['team']['name'] + ' ' + i...
# from classes.` import threading class Threads:
11
64
155
3
7
NskCTF/jury-attack-defense
classes/checker/threads.py
Python
Threads
Threads
4
31
4
4
ba27463519cdc69929a25ba0b0e02f5ff1fa48a5
bigcode/the-stack
train
adc2da82b3d8cb535b3c4791
train
class
class KubectlHelper(object): """Contains methods for kubectl commands""" def __init__(self, args, context=None): self.nuvoloso_helper = NuvolosoHelper(args) self.context = context if context else self.get_current_context() def get_current_context(self): return self.nuvoloso_helper...
class KubectlHelper(object):
"""Contains methods for kubectl commands""" def __init__(self, args, context=None): self.nuvoloso_helper = NuvolosoHelper(args) self.context = context if context else self.get_current_context() def get_current_context(self): return self.nuvoloso_helper.run_check_output(KUBECTL_CUR...
ectl delete pvc %s --context %s" KUBECTL_LABEL = "kubectl label nodes --context %s" KUBECTL_LOGS = "kubectl logs %s --context %s" KUBECTL_GET_CONTEXTS = "kubectl config get-contexts" KUBECTL_CURRENT_CONTEXT = "kubectl config current-context" KUBECTL_GET_NODES = "kubectl get nodes --context %s" KUBECTL_USE_CONTEXT = "ku...
256
256
5,490
6
250
Nuvoloso/testing_open_source
lib/nuvoloso/dependencies/kubectl_helper.py
Python
KubectlHelper
KubectlHelper
71
618
71
71
5e4026cbf011187933c28c715784baf8f84bc398
bigcode/the-stack
train
9643e41c27d54dbc9d181718
train
class
class Migration(migrations.Migration): dependencies = [ ("zerver", "0091_realm_allow_edit_history"), ] operations = [ migrations.CreateModel( name="ScheduledEmail", fields=[ ( "id", models.AutoField( ...
class Migration(migrations.Migration):
dependencies = [ ("zerver", "0091_realm_allow_edit_history"), ] operations = [ migrations.CreateModel( name="ScheduledEmail", fields=[ ( "id", models.AutoField( auto_created=True, primary...
# Generated by Django 1.11.2 on 2017-07-11 23:41 import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration):
51
64
194
7
43
TylerPham2000/zulip
zerver/migrations/0092_create_scheduledemail.py
Python
Migration
Migration
7
43
7
8
f88b1b336699f7da5ca4f8cdbefda667d9074186
bigcode/the-stack
train
b14d15f8bbfae8eba048ab33
train
class
@ddt.ddt class ShareSnapshotInstancesApiTest(test.TestCase): """Share snapshot instance Api Test.""" def setUp(self): super(ShareSnapshotInstancesApiTest, self).setUp() self.controller = (share_snapshot_instances. ShareSnapshotInstancesController()) self.resour...
@ddt.ddt class ShareSnapshotInstancesApiTest(test.TestCase):
"""Share snapshot instance Api Test.""" def setUp(self): super(ShareSnapshotInstancesApiTest, self).setUp() self.controller = (share_snapshot_instances. ShareSnapshotInstancesController()) self.resource_name = self.controller.resource_name self.api_vers...
. # All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
256
256
1,696
16
239
snpd25/manila
manila/tests/api/v2/test_share_snapshot_instances.py
Python
ShareSnapshotInstancesApiTest
ShareSnapshotInstancesApiTest
35
248
35
36
87766e87d74ba302a379e03bc5574aec6ad40be4
bigcode/the-stack
train
763a5f6e91df767d0ddf0d31
train
function
def _PrefixWith(prefix, lst): return [posixpath.join(prefix, item) for item in lst]
def _PrefixWith(prefix, lst):
return [posixpath.join(prefix, item) for item in lst]
_TEMPLATES, EXTENSIONS, DOCS, JSON_TEMPLATES, PUBLIC_TEMPLATES) from fake_fetchers import ConfigureFakeFetchers from file_system import FileNotFoundError from rietveld_patcher import RietveldPatcher import url_constants def _PrefixWith(prefix, lst):
64
64
24
8
55
SlimKatLegacy/android_external_chromium_org
chrome/common/extensions/docs/server2/rietveld_patcher_test.py
Python
_PrefixWith
_PrefixWith
19
20
19
19
5adc5f82afa3b0310557d6789f682121688e06f9
bigcode/the-stack
train
62947a5abcc92da7a52bf3bf
train
class
class RietveldPatcherTest(unittest.TestCase): def setUp(self): ConfigureFakeFetchers() self._patcher = RietveldPatcher( '14096030', AppEngineUrlFetcher(url_constants.CODEREVIEW_SERVER)) def _ReadLocalFile(self, filename): with open(os.path.join(sys.path[0], 't...
class RietveldPatcherTest(unittest.TestCase):
def setUp(self): ConfigureFakeFetchers() self._patcher = RietveldPatcher( '14096030', AppEngineUrlFetcher(url_constants.CODEREVIEW_SERVER)) def _ReadLocalFile(self, filename): with open(os.path.join(sys.path[0], 'test_data', 'rietvel...
BSD-style license that can be # found in the LICENSE file. import os import posixpath import sys import unittest from appengine_url_fetcher import AppEngineUrlFetcher from extensions_paths import ( ARTICLES_TEMPLATES, EXTENSIONS, DOCS, JSON_TEMPLATES, PUBLIC_TEMPLATES) from fake_fetchers import ConfigureFakeFetch...
138
138
460
11
127
SlimKatLegacy/android_external_chromium_org
chrome/common/extensions/docs/server2/rietveld_patcher_test.py
Python
RietveldPatcherTest
RietveldPatcherTest
23
78
23
23
53238b93bde1d3f4a1fc2e7fb72c4c5bead814f6
bigcode/the-stack
train
6f412a0d5c38cd2673131fa9
train
class
class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('places', '0002_auto_20210626_1346'), ('news', '0004_auto_20210627_0118'), ('comments', '0010_review_check'), ] operations = [ migrations.AlterModelOp...
class Migration(migrations.Migration):
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('places', '0002_auto_20210626_1346'), ('news', '0004_auto_20210627_0118'), ('comments', '0010_review_check'), ] operations = [ migrations.AlterModelOptions( name='comment', ...
# Generated by Django 3.1.7 on 2021-06-26 22:18 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
51
153
510
7
43
Gregory124124/ignatovich-main
config/comments/migrations/0011_auto_20210627_0118.py
Python
Migration
Migration
8
76
8
9
5f7c3aeaa1f915f1036d3eff7ae8971f900f874c
bigcode/the-stack
train
3e6ca46e5c35fb03bf57c786
train
class
class ImporterAppConfig(AppConfig): name = "importer"
class ImporterAppConfig(AppConfig):
name = "importer"
from django.apps import AppConfig class ImporterAppConfig(AppConfig):
15
64
15
8
6
juliecentofanti172/juliecentofanti.github.io
importer/apps.py
Python
ImporterAppConfig
ImporterAppConfig
4
5
4
4
30bb8215486ce87c452cf68f2d70423f7b83c5fc
bigcode/the-stack
train
6193510156b8846d952560d2
train
class
class LessonAdmin(admin.ModelAdmin): list_display = ('title', 'course', 'group', 'date_starttime', 'date_endtime') list_filter = ('group', 'course', 'course__year__start_year') search_fields = ('title', 'course__name', 'description')
class LessonAdmin(admin.ModelAdmin):
list_display = ('title', 'course', 'group', 'date_starttime', 'date_endtime') list_filter = ('group', 'course', 'course__year__start_year') search_fields = ('title', 'course__name', 'description')
# coding: utf-8 from lessons.models import Lesson from django.contrib import admin class LessonAdmin(admin.ModelAdmin):
26
64
63
7
18
AnnaSvalova/anytask
anytask/lessons/admin.py
Python
LessonAdmin
LessonAdmin
7
10
7
7
be6349f26c50324d4b28a102786b370828e7384f
bigcode/the-stack
train
9020c1ea600ba68e43aaa8c1
train
class
class VectorDiffeomixtureTest( test_util.VectorDistributionTestHelpers, test.TestCase): """Tests the VectorDiffeomixture distribution.""" def testSampleProbConsistentBroadcastMixNoBatch(self): with self.test_session() as sess: dims = 4 vdm = vector_diffeomixture_lib.VectorDiffeomixture( ...
class VectorDiffeomixtureTest( test_util.VectorDistributionTestHelpers, test.TestCase):
"""Tests the VectorDiffeomixture distribution.""" def testSampleProbConsistentBroadcastMixNoBatch(self): with self.test_session() as sess: dims = 4 vdm = vector_diffeomixture_lib.VectorDiffeomixture( mix_loc=[[0.], [1.]], mix_scale=[1.], distribution=normal_lib.Normal(...
not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDI...
256
256
1,826
20
235
ryorda/tensorflow-viennacl
tensorflow/contrib/distributions/python/kernel_tests/vector_diffeomixture_test.py
Python
VectorDiffeomixtureTest
VectorDiffeomixtureTest
33
230
33
34
243883d6434ccd4afee5845e4adfd69622c017b1
bigcode/the-stack
train
c49f57bbe0693360813f7e8c
train
function
def save_tables( db: SQLAlchemy, backup_name: str = "", structure: bool = True, data: bool = False, backup_path: str = BACKUP_PATH, ): # Make a new folder for the backup backup_folder = Path("%s/%s" % (backup_path, backup_name)) try: backup_folder.mkdir(parents=True, exist_ok=Fal...
def save_tables( db: SQLAlchemy, backup_name: str = "", structure: bool = True, data: bool = False, backup_path: str = BACKUP_PATH, ): # Make a new folder for the backup
backup_folder = Path("%s/%s" % (backup_path, backup_name)) try: backup_folder.mkdir(parents=True, exist_ok=False) except FileExistsError: click.echo( "Can't save backup, because directory %s/%s already exists." % (backup_path, backup_name) ) return ...
-using db.drop_all() click.echo("Recreating everything ...") db.create_all() click.echo("Committing ...") db.session.commit() def save_tables( db: SQLAlchemy, backup_name: str = "", structure: bool = True, data: bool = False, backup_path: str = BACKUP_PATH, ): # Make a new fo...
87
87
293
52
35
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
save_tables
save_tables
603
636
603
610
2d139d343cd5d7988cd3e7b6fd45f0577565c463
bigcode/the-stack
train
807c2e8b93fc971509e38f22
train
function
def get_affected_classes(structure: bool = True, data: bool = False) -> List: affected_classes = [] if structure: affected_classes += [ Role, User, RolesUsers, Sensor, MarketType, Market, AssetType, Asset, ...
def get_affected_classes(structure: bool = True, data: bool = False) -> List:
affected_classes = [] if structure: affected_classes += [ Role, User, RolesUsers, Sensor, MarketType, Market, AssetType, Asset, WeatherSensorType, WeatherSensor, DataSource...
." % c.__tablename__ ) else: click.echo( "Can't load backup, because directory %s/%s does not exist." % (backup_path, backup_name) ) def get_affected_classes(structure: bool = True, data: bool = False) -> List:
64
64
101
21
43
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
get_affected_classes
get_affected_classes
688
706
688
688
b52475efc8dc476a27e6e389afdd9f68df280f36
bigcode/the-stack
train
a6eb2ee0296cd32c8b19a2c8
train
function
def add_data_sources(db: SQLAlchemy): db.session.add(DataSource(name="Seita", type="demo script"))
def add_data_sources(db: SQLAlchemy):
db.session.add(DataSource(name="Seita", type="demo script"))
_local_timezone from flexmeasures.data.transactional import as_transaction BACKUP_PATH = app.config.get("FLEXMEASURES_DB_BACKUP_PATH") LOCAL_TIME_ZONE = app.config.get("FLEXMEASURES_TIMEZONE") infl_eng = inflect.engine() def add_data_sources(db: SQLAlchemy):
64
64
25
9
55
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
add_data_sources
add_data_sources
40
41
40
40
1dc1e22872571633b1a6f0f50ceeeb39708528a5
bigcode/the-stack
train
05d7fa1bc86c2a7146e55a4b
train
function
@as_transaction def populate_structure(db: SQLAlchemy): """ Add initial structural data for assets, markets, data sources TODO: add user roles (they can get created on-the-fly, but we should be more pro-active) """ click.echo("Populating the database %s with structural data ..." % db.engi...
@as_transaction def populate_structure(db: SQLAlchemy):
""" Add initial structural data for assets, markets, data sources TODO: add user roles (they can get created on-the-fly, but we should be more pro-active) """ click.echo("Populating the database %s with structural data ..." % db.engine) add_data_sources(db) add_asset_types(db) ...
, tzinfo=pytz.utc), horizon=timedelta(0), data_source_id=source.id, market=market, ) ) # ------------ Main functions -------------------------------- # These can registered at the app object as cli functions @as_transaction def populate_structure(db:...
64
64
203
12
51
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
populate_structure
populate_structure
177
197
177
178
ad8492f306404e95765a006efcbfc11a30c1a117
bigcode/the-stack
train
65f6404a280127cc365483b9
train
function
@as_transaction def depopulate_measurements( db: SQLAlchemy, generic_asset_type: Optional[str] = None, generic_asset_id: Optional[id] = None, ): click.echo("Depopulating (time series) data from the database %s ..." % db.engine) num_prices_deleted = 0 num_power_measurements_deleted = 0 num_we...
@as_transaction def depopulate_measurements( db: SQLAlchemy, generic_asset_type: Optional[str] = None, generic_asset_id: Optional[id] = None, ):
click.echo("Depopulating (time series) data from the database %s ..." % db.engine) num_prices_deleted = 0 num_power_measurements_deleted = 0 num_weather_measurements_deleted = 0 # TODO: simplify this when sensors moved to one unified table if generic_asset_id is None: if generic_asset_...
user in users: db.session.delete(user) num_users_deleted += 1 click.echo("Deleted %d MarketTypes" % num_market_types_deleted) click.echo("Deleted %d Markets" % num_markets_deleted) click.echo("Deleted %d WeatherSensorTypes" % num_sensor_types_deleted) click.echo("Deleted %d WeatherSenso...
196
196
654
40
156
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
depopulate_measurements
depopulate_measurements
403
491
403
408
e6357f3e9929be9e76a420cd5fb82b2928d4a0f8
bigcode/the-stack
train
5ff169d0ae8a01a883eff025
train
function
def add_weather_sensor_types(db: SQLAlchemy): db.session.add(WeatherSensorType(name="temperature")) db.session.add(WeatherSensorType(name="wind_speed")) db.session.add(WeatherSensorType(name="radiation"))
def add_weather_sensor_types(db: SQLAlchemy):
db.session.add(WeatherSensorType(name="temperature")) db.session.add(WeatherSensorType(name="wind_speed")) db.session.add(WeatherSensorType(name="radiation"))
( name="building", display_name="building", is_consumer=True, is_producer=True, can_shift=True, daily_seasonality=True, weekly_seasonality=True, yearly_seasonality=True, ) ) def add_weather_sensor_types(db: SQLAl...
64
64
48
10
54
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
add_weather_sensor_types
add_weather_sensor_types
116
119
116
116
b8ac4a0369c650f464f6fbbb8e9b7c31d1c2cae6
bigcode/the-stack
train
4ac0c3f0a8bf7ac8011a738d
train
function
def add_market_types(db: SQLAlchemy): db.session.add( MarketType( name="day_ahead", display_name="day-ahead market", daily_seasonality=True, weekly_seasonality=True, yearly_seasonality=True, ) ) db.session.add( MarketType( ...
def add_market_types(db: SQLAlchemy):
db.session.add( MarketType( name="day_ahead", display_name="day-ahead market", daily_seasonality=True, weekly_seasonality=True, yearly_seasonality=True, ) ) db.session.add( MarketType( name="tou_tariff", ...
=True, ) ) def add_weather_sensor_types(db: SQLAlchemy): db.session.add(WeatherSensorType(name="temperature")) db.session.add(WeatherSensorType(name="wind_speed")) db.session.add(WeatherSensorType(name="radiation")) def add_market_types(db: SQLAlchemy):
63
64
109
9
54
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
add_market_types
add_market_types
122
140
122
122
ba42a777e5fd023252b274c41a5be5a00a7123af
bigcode/the-stack
train
3cae873d1e4f0926d85ded69
train
function
def add_asset_types(db: SQLAlchemy): db.session.add( AssetType( name="solar", display_name="solar panel", is_producer=True, daily_seasonality=True, yearly_seasonality=True, ) ) db.session.add( AssetType( name="wi...
def add_asset_types(db: SQLAlchemy):
db.session.add( AssetType( name="solar", display_name="solar panel", is_producer=True, daily_seasonality=True, yearly_seasonality=True, ) ) db.session.add( AssetType( name="wind", display_name="wind t...
_configurator from flexmeasures.data.models.forecasting.exceptions import NotEnoughDataException from flexmeasures.utils.time_utils import ensure_local_timezone from flexmeasures.data.transactional import as_transaction BACKUP_PATH = app.config.get("FLEXMEASURES_DB_BACKUP_PATH") LOCAL_TIME_ZONE = app.config.get("FLEX...
116
117
393
9
107
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
add_asset_types
add_asset_types
44
113
44
44
cf003a44b280a6e8210e817dbe2e38ecaf210472
bigcode/the-stack
train
8431cfd8fe3bc0fcf4f0c736
train
function
@as_transaction def load_tables( db: SQLAlchemy, backup_name: str = "", structure: bool = True, data: bool = False, backup_path: str = BACKUP_PATH, ): if ( Path("%s/%s" % (backup_path, backup_name)).exists() and Path("%s/%s" % (backup_path, backup_name)).is_dir() ): a...
@as_transaction def load_tables( db: SQLAlchemy, backup_name: str = "", structure: bool = True, data: bool = False, backup_path: str = BACKUP_PATH, ):
if ( Path("%s/%s" % (backup_path, backup_name)).exists() and Path("%s/%s" % (backup_path, backup_name)).is_dir() ): affected_classes = get_affected_classes(structure, data) statement = "SELECT sequence_name from information_schema.sequences;" data = db.session.execute(sta...
except SQLAlchemyError as e: click.echo( "Can't save table %s because of the following error:\n\n\t%s\n\nCleaning up..." % (c.__tablename__, e) ) rmtree(backup_folder) click.echo("Removed directory %s/%s." % (backup_path, backup_name)) @as_transaction def load_ta...
116
116
388
46
70
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
load_tables
load_tables
639
685
639
646
a91ebc4280b9752d1e5743b3450c1750235df7a8
bigcode/the-stack
train
946416a38e3c7cf80a704622
train
function
@as_transaction def depopulate_structure(db: SQLAlchemy): click.echo("Depopulating structural data from the database %s ..." % db.engine) num_assets_deleted = db.session.query(Asset).delete() num_asset_types_deleted = db.session.query(AssetType).delete() num_markets_deleted = db.session.query(Market).de...
@as_transaction def depopulate_structure(db: SQLAlchemy):
click.echo("Depopulating structural data from the database %s ..." % db.engine) num_assets_deleted = db.session.query(Asset).delete() num_asset_types_deleted = db.session.query(AssetType).delete() num_markets_deleted = db.session.query(Market).delete() num_market_types_deleted = db.session.query(Mar...
(Power.horizon > timedelta(hours=0)).count() ) click.echo( "DB now has %d Price Forecasts" % db.session.query(Price).filter(Price.horizon > timedelta(hours=0)).count() ) click.echo( "DB now has %d Weather Forecasts" % db.session.query(Weather).filter(Weather.horizon > tim...
104
104
349
14
90
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
depopulate_structure
depopulate_structure
372
400
372
373
d99a177c09920d1ce8051748a01e32af01e6896d
bigcode/the-stack
train
28b837d9db1c02add95f95cc
train
function
@as_transaction def depopulate_prognoses( db: SQLAlchemy, generic_asset_type: Optional[str] = None, generic_asset_id: Optional[id] = None, ): click.echo( "Depopulating (time series) forecasts and schedules data from the database %s ..." % db.engine ) num_prices_deleted = 0 nu...
@as_transaction def depopulate_prognoses( db: SQLAlchemy, generic_asset_type: Optional[str] = None, generic_asset_id: Optional[id] = None, ):
click.echo( "Depopulating (time series) forecasts and schedules data from the database %s ..." % db.engine ) num_prices_deleted = 0 num_power_measurements_deleted = 0 num_weather_measurements_deleted = 0 # Clear all jobs num_forecasting_jobs_deleted = app.queues["forecasting...
(Power.asset == asset) .delete() ) else: num_power_measurements_deleted = 0 elif generic_asset_type == "WeatherSensor": sensor = ( db.session.query(WeatherSensor) .filter(WeatherSensor.id == generic_asse...
219
219
733
41
178
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
depopulate_prognoses
depopulate_prognoses
494
589
494
499
cd9ee85c5a858ee767d4f98f0a1729d6b132efc4
bigcode/the-stack
train
31ac98f0061955ede26d2b82
train
function
def add_dummy_tou_market(db: SQLAlchemy): """ Add a dummy time-of-use market with a 1-year resolution. Also add a few price points, each covering a whole year. Note that for this market, the leap years will not have a price on December 31st. To fix that, we should use 366 days as resolution, bu...
def add_dummy_tou_market(db: SQLAlchemy):
""" Add a dummy time-of-use market with a 1-year resolution. Also add a few price points, each covering a whole year. Note that for this market, the leap years will not have a price on December 31st. To fix that, we should use 366 days as resolution, but test what that involves on that day, or ...
, yearly_seasonality=True, ) ) db.session.add( MarketType( name="tou_tariff", display_name="time-of use tariff", daily_seasonality=True, weekly_seasonality=False, yearly_seasonality=True, ) ) def add_dummy_tou_ma...
73
73
246
11
62
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
add_dummy_tou_market
add_dummy_tou_market
143
170
143
143
3df3d7b2d93110bb1e347e5338c07653da785067
bigcode/the-stack
train
95c8285c92f8420d62df2913
train
function
@as_transaction # noqa: C901 def populate_time_series_forecasts( # noqa: C901 db: SQLAlchemy, horizons: List[timedelta], forecast_start: datetime, forecast_end: datetime, event_resolution: Optional[timedelta] = None, generic_asset_type: Optional[str] = None, generic_asset_id: Optional[int]...
@as_transaction # noqa: C901 def populate_time_series_forecasts( # noqa: C901 db: SQLAlchemy, horizons: List[timedelta], forecast_start: datetime, forecast_end: datetime, event_resolution: Optional[timedelta] = None, generic_asset_type: Optional[str] = None, generic_asset_id: Optional[int]...
training_and_testing_period = timedelta(days=30) click.echo( "Populating the database %s with time series forecasts of %s ahead ..." % (db.engine, infl_eng.join([naturaldelta(horizon) for horizon in horizons])) ) # Set a data source for the forecasts data_source = DataSource.query....
add user roles (they can get created on-the-fly, but we should be more pro-active) """ click.echo("Populating the database %s with structural data ..." % db.engine) add_data_sources(db) add_asset_types(db) add_weather_sensor_types(db) add_market_types(db) add_dummy_tou_market(db) ...
256
256
1,324
83
173
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
populate_time_series_forecasts
populate_time_series_forecasts
200
369
200
209
e62a4ba0af0b5295ea61f4426ce10d08e580a6b5
bigcode/the-stack
train
6cc1f5b845ab3d07965d48ea
train
function
def reset_db(db: SQLAlchemy): db.session.commit() # close any existing sessions click.echo("Dropping everything in %s ..." % db.engine) db.reflect() # see http://jrheard.tumblr.com/post/12759432733/dropping-all-tables-on-postgres-using db.drop_all() click.echo("Recreating everything ...") db.c...
def reset_db(db: SQLAlchemy):
db.session.commit() # close any existing sessions click.echo("Dropping everything in %s ..." % db.engine) db.reflect() # see http://jrheard.tumblr.com/post/12759432733/dropping-all-tables-on-postgres-using db.drop_all() click.echo("Recreating everything ...") db.create_all() click.echo("Co...
cheduling_jobs_deleted) click.echo("Deleted %d Price Forecasts" % num_prices_deleted) click.echo("Deleted %d Power Forecasts" % num_power_measurements_deleted) click.echo("Deleted %d Weather Forecasts" % num_weather_measurements_deleted) def reset_db(db: SQLAlchemy):
64
64
99
8
56
SeitaBV/flexmeasures
flexmeasures/data/scripts/data_gen.py
Python
reset_db
reset_db
592
600
592
592
e3f5f50bb373fae77571ba628f4f29b86a8fa2b6
bigcode/the-stack
train
48e71fd9bd57d3aa68043952
train
class
class Solution: def numberToWords(self, num): below20 = ( "One Two Three Four Five Six Seven Eight Nine Ten " "Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen " "Eighteen Nineteen" ).split() tens = ("x x Twenty Thirty Forty Fifty Sixty Seventy Ei...
class Solution:
def numberToWords(self, num): below20 = ( "One Two Three Four Five Six Seven Eight Nine Ten " "Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen " "Eighteen Nineteen" ).split() tens = ("x x Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety").sp...
class Solution:
3
72
240
3
0
ferhatelmas/algo
leetCode/algorithms/medium/integer_to_english_words.py
Python
Solution
Solution
1
23
1
1
092c0278508d3e8f2ca9019a943746e0cc8d671a
bigcode/the-stack
train
0a7004686d98958a88d6f588
train
class
class DisplayNode(): def __init__(self): rospy.init_node("display_node") rospy.loginfo("Setting up display node") lcd_init() rospy.loginfo("Display initialised and ready for use") self.sub = rospy.Subscriber("/message", String, self.display_text) def wait_for_finish(se...
class DisplayNode():
def __init__(self): rospy.init_node("display_node") rospy.loginfo("Setting up display node") lcd_init() rospy.loginfo("Display initialised and ready for use") self.sub = rospy.Subscriber("/message", String, self.display_text) def wait_for_finish(self): rospy.sp...
from .lcd_i2c import lcd_init from .lcd_i2c import lcd_string from .lcd_i2c import LCD_LINE_1 from .lcd_i2c import LCD_LINE_2 from std_msgs.msg import String import rospy class DisplayNode():
58
64
161
4
53
madman32/spotMicro
spot_micro_display/src/display_node.py
Python
DisplayNode
DisplayNode
10
30
10
10
1329abdd0deca057e1423a9b5bebea4fc5daf0ce
bigcode/the-stack
train
0c535c8cfa3623e2943ee951
train
class
class Table: """Represents a table, handling cells that can span on multiple lines or rows, like:: +-----------+-----+ | AAA | BBB | +-----+-----+ | | | XXX | | | +-----+-----+ | DDD | CCC | +-----+-----------+ This class can be ...
class Table:
"""Represents a table, handling cells that can span on multiple lines or rows, like:: +-----------+-----+ | AAA | BBB | +-----+-----+ | | | XXX | | | +-----+-----+ | DDD | CCC | +-----+-----------+ This class can be used in two w...
, Tuple, Union from typing import cast from docutils import nodes, writers from docutils.nodes import Element, Node, Text from docutils.utils import column_width from sphinx import addnodes from sphinx.locale import admonitionlabels, _ from sphinx.util.docutils import SphinxTranslator if False: # For type annota...
256
256
1,646
3
253
3v1lW1th1n/sphinx
sphinx/writers/text.py
Python
Table
Table
55
253
55
55
23a01f6b629714eb5aa8962624949e30c2ff3552
bigcode/the-stack
train
e505cec91b5b5ba3386584f7
train
class
class TextWrapper(textwrap.TextWrapper): """Custom subclass that uses a different word separator regex.""" wordsep_re = re.compile( r'(\s+|' # any whitespace r'(?<=\s)(?::[a-z-]+:)?`\S+|' # interpreted text start r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[...
class TextWrapper(textwrap.TextWrapper):
"""Custom subclass that uses a different word separator regex.""" wordsep_re = re.compile( r'(\s+|' # any whitespace r'(?<=\s)(?::[a-z-]+:)?`\S+|' # interpreted text start r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|' # hyphenated words r...
out[1:]) ] glue.append(tail) return head + "".join(chain(*zip(out, glue))) for lineno, line in enumerate(self.lines): if self.separator and lineno == self.separator: out.append(writesep("=", lineno)) else: out.append(w...
245
245
817
8
237
3v1lW1th1n/sphinx
sphinx/writers/text.py
Python
TextWrapper
TextWrapper
256
356
256
256
6709ae72c98dfd8cd875c795b95565306f1dd436
bigcode/the-stack
train
de3955b655ef2f0bd99d53a7
train
class
class TextWriter(writers.Writer): supported = ('text',) settings_spec = ('No options here.', '', ()) settings_defaults = {} # type: Dict output = None # type: str def __init__(self, builder: "TextBuilder") -> None: super().__init__() self.builder = builder def translate(self...
class TextWriter(writers.Writer):
supported = ('text',) settings_spec = ('No options here.', '', ()) settings_defaults = {} # type: Dict output = None # type: str def __init__(self, builder: "TextBuilder") -> None: super().__init__() self.builder = builder def translate(self) -> None: visitor = self....
(reversed_chunks.pop()) MAXWIDTH = 70 STDINDENT = 3 def my_wrap(text: str, width: int = MAXWIDTH, **kwargs) -> List[str]: w = TextWrapper(width=width, **kwargs) return w.wrap(text) class TextWriter(writers.Writer):
64
64
114
7
57
3v1lW1th1n/sphinx
sphinx/writers/text.py
Python
TextWriter
TextWriter
368
382
368
368
7c9d3b724968d5b8228e5b6786dcb3de44d06ddb
bigcode/the-stack
train
e6e259ed094f7b481e022b6c
train
class
class Cell: """Represents a cell in a table. It can span on multiple columns or on multiple lines. """ def __init__(self, text="", rowspan=1, colspan=1): self.text = text self.wrapped = [] # type: List[str] self.rowspan = rowspan self.colspan = colspan self.col =...
class Cell:
"""Represents a cell in a table. It can span on multiple columns or on multiple lines. """ def __init__(self, text="", rowspan=1, colspan=1): self.text = text self.wrapped = [] # type: List[str] self.rowspan = rowspan self.colspan = colspan self.col = None ...
Element, Node, Text from docutils.utils import column_width from sphinx import addnodes from sphinx.locale import admonitionlabels, _ from sphinx.util.docutils import SphinxTranslator if False: # For type annotation from sphinx.builders.text import TextBuilder class Cell:
64
64
169
3
60
3v1lW1th1n/sphinx
sphinx/writers/text.py
Python
Cell
Cell
31
52
31
31
8e61c7ccc7b1102d413d9248e42f12b229ee1b09
bigcode/the-stack
train
4688b249754e94ece75194ff
train
function
def my_wrap(text: str, width: int = MAXWIDTH, **kwargs) -> List[str]: w = TextWrapper(width=width, **kwargs) return w.wrap(text)
def my_wrap(text: str, width: int = MAXWIDTH, **kwargs) -> List[str]:
w = TextWrapper(width=width, **kwargs) return w.wrap(text)
cur_line.append(l) reversed_chunks[-1] = r elif not cur_line: cur_line.append(reversed_chunks.pop()) MAXWIDTH = 70 STDINDENT = 3 def my_wrap(text: str, width: int = MAXWIDTH, **kwargs) -> List[str]:
64
64
39
21
42
3v1lW1th1n/sphinx
sphinx/writers/text.py
Python
my_wrap
my_wrap
363
365
363
363
c7826bf83d64128f5d1abf468e587afbd718ac1d
bigcode/the-stack
train
cfdb88cc6ec39a14eeee82be
train
class
class TextTranslator(SphinxTranslator): builder = None # type: TextBuilder def __init__(self, document: nodes.document, builder: "TextBuilder") -> None: super().__init__(document, builder) newlines = self.config.text_newlines if newlines == 'windows': self.nl = '\r\n' ...
class TextTranslator(SphinxTranslator):
builder = None # type: TextBuilder def __init__(self, document: nodes.document, builder: "TextBuilder") -> None: super().__init__(document, builder) newlines = self.config.text_newlines if newlines == 'windows': self.nl = '\r\n' elif newlines == 'native': ...
original method for using self._break_word() instead of slice. """ space_left = max(width - cur_len, 1) if self.break_long_words: l, r = self._break_word(reversed_chunks[-1], space_left) cur_line.append(l) reversed_chunks[-1] = r elif not cur_line: ...
256
256
5,830
7
248
3v1lW1th1n/sphinx
sphinx/writers/text.py
Python
TextTranslator
TextTranslator
385
1,170
385
385
23dffc0ba7fca1e99a58c79b73a3010db137790c
bigcode/the-stack
train
91f9c62b700c0e4ca64ac783
train
function
def main() -> None: # account to send the transfer and sign transactions sender: LocalAccount = Account.from_key(env("SENDER_PRIVATE_KEY")) # account to receive the transfer receiver: LocalAccount = Account.from_key(env("RECEIVER_PRIVATE_KEY")) # account to establish flashbots reputation # NOTE:...
def main() -> None: # account to send the transfer and sign transactions
sender: LocalAccount = Account.from_key(env("SENDER_PRIVATE_KEY")) # account to receive the transfer receiver: LocalAccount = Account.from_key(env("RECEIVER_PRIVATE_KEY")) # account to establish flashbots reputation # NOTE: it should not store funds signature: LocalAccount = Account.from_key(env...
""" Minimal viable example of flashbots usage with dynamic fee transactions. """ import os from eth_account.account import Account from eth_account.signers.local import LocalAccount from flashbots import flashbot from web3 import Web3, HTTPProvider from web3.exceptions import TransactionNotFound from web3.types impor...
101
203
677
17
84
lecoos/web3-flashbots
examples/eip1559.py
Python
main
main
19
91
19
20
cc4f9b14bc1363cb1de206b491dda8b267b1d558
bigcode/the-stack
train
0493c79d1200435107abde99
train
function
def env(key: str) -> str: return os.environ.get(key)
def env(key: str) -> str:
return os.environ.get(key)
""" import os from eth_account.account import Account from eth_account.signers.local import LocalAccount from flashbots import flashbot from web3 import Web3, HTTPProvider from web3.exceptions import TransactionNotFound from web3.types import TxParams def env(key: str) -> str:
64
64
16
9
54
lecoos/web3-flashbots
examples/eip1559.py
Python
env
env
15
16
15
15
d06e9a3b82deb3e6176bfc2fe85b57849ce5c7e7
bigcode/the-stack
train
535c00970e8a1f80a093f955
train
class
class TestClient(unittest.TestCase): def test_is_asyncio_based(self): c = client.Client() self.assertEqual(c.is_asyncio_based(), False) def test_create(self): c = client.Client() self.assertEqual(c.handlers, {}) for attr in ['base_url', 'transports', 'sid', 'upgrades', ...
class TestClient(unittest.TestCase):
def test_is_asyncio_based(self): c = client.Client() self.assertEqual(c.is_asyncio_based(), False) def test_create(self): c = client.Client() self.assertEqual(c.handlers, {}) for attr in ['base_url', 'transports', 'sid', 'upgrades', 'ping_interval', ...
import json import logging import ssl import time import unittest import six if six.PY3: from unittest import mock else: import mock import websocket from engineio import client from engineio import exceptions from engineio import packet from engineio import payload if six.PY2: ConnectionError = OSError ...
83
256
10,998
7
75
harmon/python-engineio
tests/common/test_client.py
Python
TestClient
TestClient
23
1,248
23
23
8ab3d9100c8a705bbf14faa6a77136fcd0d95b36
bigcode/the-stack
train
20ae9ee6f3291439f7712a08
train
function
def make_clustered_plot(t_vec,y_vec,gap_length,c='red'): t_diff = np.diff(t_vec)*fs t_diff = np.min(np.array([t_diff,gap_length*np.ones_like(t_diff)]),axis=0) t_diff = t_diff - np.min(t_diff) t_diff = t_diff/np.max(t_diff) indices = np.where(t_diff>0.5)[0] ranges = [] for i in range(1,l...
def make_clustered_plot(t_vec,y_vec,gap_length,c='red'):
t_diff = np.diff(t_vec)*fs t_diff = np.min(np.array([t_diff,gap_length*np.ones_like(t_diff)]),axis=0) t_diff = t_diff - np.min(t_diff) t_diff = t_diff/np.max(t_diff) indices = np.where(t_diff>0.5)[0] ranges = [] for i in range(1,len(indices)): id1,id2 = (indices[i-1]+1,indices[i...
_silence = t_vec[silence_mask] pseudovoice_signal_speech = pseudovoice_signal[speech_mask] pseudovoice_signal_silence = pseudovoice_signal[silence_mask] def make_clustered_plot(t_vec,y_vec,gap_length,c='red'):
64
64
142
16
48
akkurowski/Pseudoseech-VAD-Test-Signal-Generator
view_result.py
Python
make_clustered_plot
make_clustered_plot
29
39
29
29
1ef6bd6142c2602898286c77c3dff1b210254b2f
bigcode/the-stack
train
4f81da51a2177c59cc3e44ca
train
class
class TestRecursive(EmbeddingTests): def test_recursive(self): add_recursive_cffi = self.prepare_module('add_recursive') self.compile('add_recursive-test', [add_recursive_cffi]) output = self.execute('add_recursive-test') assert output == ("preparing REC\n" ...
class TestRecursive(EmbeddingTests):
def test_recursive(self): add_recursive_cffi = self.prepare_module('add_recursive') self.compile('add_recursive-test', [add_recursive_cffi]) output = self.execute('add_recursive-test') assert output == ("preparing REC\n" "some_callback(400)\n" ...
# Generated by pypy/tool/import_cffi.py from pypy.module.test_lib_pypy.cffi_tests.embedding.test_basic import EmbeddingTests class TestRecursive(EmbeddingTests):
37
64
118
7
29
m4sterchain/mesapy
pypy/module/test_lib_pypy/cffi_tests/embedding/test_recursive.py
Python
TestRecursive
TestRecursive
5
16
5
5
b84cf5d8f4e0e7c97c8d3ec31160fb36b44d9e3d
bigcode/the-stack
train
7a797b5a3dd442ef15a8df03
train
function
def shell_sort(array, n): gap = n // 2 while gap > 0: for i in range(gap, n): temp = array[i] j = i while j >= gap and array[j - gap] > temp: array[j] = array[j - gap] j -= gap array[j] = temp gap //= 2
def shell_sort(array, n):
gap = n // 2 while gap > 0: for i in range(gap, n): temp = array[i] j = i while j >= gap and array[j - gap] > temp: array[j] = array[j - gap] j -= gap array[j] = temp gap //= 2
# Python3 program for implementation of Shell Sort def shell_sort(array, n):
17
64
86
7
9
MarcosFloresta/Data_Structures_and_Algorithms
sorting/shell_sort.py
Python
shell_sort
shell_sort
2
12
2
2
d9e70394d543cf8b1e76b5e0aae5a3ce1a35158b
bigcode/the-stack
train
d0c942ed483e8dd791921931
train
class
class MaterialObjectDataHandler(ItemDataHandler): material_type = MaterialTypeWrapper(validator_func=get_material)
class MaterialObjectDataHandler(ItemDataHandler):
material_type = MaterialTypeWrapper(validator_func=get_material)
: self.obj.occupying_characters.create(character=character) del self.occupants def remove_occupant(self, character): if any(self.obj.occupying_characters.filter(character=character).delete()): del self.occupants class MaterialObjectDataHandler(ItemDataHandler):
64
64
22
9
54
dvoraen/arxcode
world/crafting/craft_data_handlers.py
Python
MaterialObjectDataHandler
MaterialObjectDataHandler
185
186
185
185
df1b129cd2eb4784b88d39e5adfd16cc7399d9c8
bigcode/the-stack
train
67f6e20ae61e2fd6404a033b
train
class
class WearableDataHandler(CraftDataHandler): worn_time = EquippedStatusWrapper() currently_worn = EquippedStatusWrapper() armor_penalty = ArmorOverrideWrapper() armor_resilience = ArmorOverrideWrapper() slot_limit = ArmorOverrideWrapper() slot = ArmorOverrideWrapper()
class WearableDataHandler(CraftDataHandler):
worn_time = EquippedStatusWrapper() currently_worn = EquippedStatusWrapper() armor_penalty = ArmorOverrideWrapper() armor_resilience = ArmorOverrideWrapper() slot_limit = ArmorOverrideWrapper() slot = ArmorOverrideWrapper()
arges: return False self.charges -= 1 return True @property def charges(self): return self.quality_level @charges.setter def charges(self, val): self.quality_level = val class WearableDataHandler(CraftDataHandler):
64
64
60
10
53
dvoraen/arxcode
world/crafting/craft_data_handlers.py
Python
WearableDataHandler
WearableDataHandler
137
143
137
137
85cc8e2b32143df4222a4f80a31a88d318a8f73f
bigcode/the-stack
train
8c38b72bf1d5385e7d85dcf9
train
class
class ConsumableDataHandler(CraftDataHandler): def get_quality_appearance(self): if self.charges >= 0: msg = "\nIt has %s uses remaining." % self.charges else: msg = "\nIt has infinite uses." msg += " It can be used with the {wuse{n command." return msg d...
class ConsumableDataHandler(CraftDataHandler):
def get_quality_appearance(self): if self.charges >= 0: msg = "\nIt has %s uses remaining." % self.charges else: msg = "\nIt has infinite uses." msg += " It can be used with the {wuse{n command." return msg def consume(self): """ Use a cha...
rafter ).num_attempts except ObjectDoesNotExist: return 0 def set_refine_attempts_for_character(self, crafter, attempts): self.obj.crafting_record.set_refine_attempts(crafter, attempts) class ConsumableDataHandler(CraftDataHandler):
64
64
165
10
54
dvoraen/arxcode
world/crafting/craft_data_handlers.py
Python
ConsumableDataHandler
ConsumableDataHandler
109
134
109
109
da18631cdc750c3a9e7cd36b54bb1b7a1e7e637b
bigcode/the-stack
train
f4b3d6cd8d3c0b674a1036e4
train
class
class PlaceDataHandler(CraftDataHandler): max_spots = PlaceSpotsOverrideWrapper() @CachedProperty def occupants(self): return [ob.character for ob in self.obj.occupying_characters.all()] def add_occupant(self, character): if character not in self.occupants: self.obj.occupyi...
class PlaceDataHandler(CraftDataHandler):
max_spots = PlaceSpotsOverrideWrapper() @CachedProperty def occupants(self): return [ob.character for ob in self.obj.occupying_characters.all()] def add_occupant(self, character): if character not in self.occupants: self.obj.occupying_characters.create(character=character) ...
_be_dodged = WeaponOverrideWrapper() can_be_countered = WeaponOverrideWrapper() can_parry = WeaponOverrideWrapper() can_riposte = WeaponOverrideWrapper() difficulty_mod = WeaponOverrideWrapper() flat_damage_bonus = WeaponOverrideWrapper() class PlaceDataHandler(CraftDataHandler):
64
64
122
9
55
dvoraen/arxcode
world/crafting/craft_data_handlers.py
Python
PlaceDataHandler
PlaceDataHandler
168
182
168
168
a733602332cce6061d37b1c1706881175720ed4e
bigcode/the-stack
train
cf1c539aaddadc8b31d42b30
train
class
class MaskDataHandler(WearableDataHandler): mask_desc = MaskedDescriptionWrapper("description")
class MaskDataHandler(WearableDataHandler):
mask_desc = MaskedDescriptionWrapper("description")
raftDataHandler): worn_time = EquippedStatusWrapper() currently_worn = EquippedStatusWrapper() armor_penalty = ArmorOverrideWrapper() armor_resilience = ArmorOverrideWrapper() slot_limit = ArmorOverrideWrapper() slot = ArmorOverrideWrapper() class MaskDataHandler(WearableDataHandler):
64
64
21
10
54
dvoraen/arxcode
world/crafting/craft_data_handlers.py
Python
MaskDataHandler
MaskDataHandler
146
147
146
146
d86ae479614adc8106ac4ffdbaeff51898c5c848
bigcode/the-stack
train
ab9d7e12cc1a279198e8c907
train
class
class CraftDataHandler(ItemDataHandler): """Encapsulates data/methods for any crafted object in game""" def get_crafting_desc(self): """ :type self: ObjectDB """ string = "" adorns = self.adorn_objects # adorns are a dict of the ID of the crafting material type t...
class CraftDataHandler(ItemDataHandler):
"""Encapsulates data/methods for any crafted object in game""" def get_crafting_desc(self): """ :type self: ObjectDB """ string = "" adorns = self.adorn_objects # adorns are a dict of the ID of the crafting material type to amount if adorns: a...
""" Handler for hiding implementation details of data storage for a crafted object behind an abstraction layer """ from django.core.exceptions import ObjectDoesNotExist from evennia_extensions.object_extensions.item_data_handler import ItemDataHandler from server.utils.arx_utils import CachedProperty from world.craftin...
134
204
682
8
125
dvoraen/arxcode
world/crafting/craft_data_handlers.py
Python
CraftDataHandler
CraftDataHandler
21
106
21
21
aec9926c183f4c7b71f9172827b9352e33a75772
bigcode/the-stack
train
17c79961941b5d66a4f990d4
train
class
class WieldableDataHandler(WearableDataHandler): currently_wielded = EquippedStatusWrapper() ready_phrase = EquippedStatusWrapper() attack_skill = WeaponOverrideWrapper() attack_stat = WeaponOverrideWrapper() damage_stat = WeaponOverrideWrapper() damage_bonus = WeaponOverrideWrapper() attack...
class WieldableDataHandler(WearableDataHandler):
currently_wielded = EquippedStatusWrapper() ready_phrase = EquippedStatusWrapper() attack_skill = WeaponOverrideWrapper() attack_stat = WeaponOverrideWrapper() damage_stat = WeaponOverrideWrapper() damage_bonus = WeaponOverrideWrapper() attack_type = WeaponOverrideWrapper() can_be_parrie...
_penalty = ArmorOverrideWrapper() armor_resilience = ArmorOverrideWrapper() slot_limit = ArmorOverrideWrapper() slot = ArmorOverrideWrapper() class MaskDataHandler(WearableDataHandler): mask_desc = MaskedDescriptionWrapper("description") class WieldableDataHandler(WearableDataHandler):
64
64
147
12
52
dvoraen/arxcode
world/crafting/craft_data_handlers.py
Python
WieldableDataHandler
WieldableDataHandler
150
165
150
150
05b92d6386a29f22c738c52c574a5d4c5ab77deb
bigcode/the-stack
train
a76191d529db33789456b322
train
class
class PredictionKey(AnnotationKeyMixin, Meta.Base): """A Prediction's annotation key.""" pass
class PredictionKey(AnnotationKeyMixin, Meta.Base):
"""A Prediction's annotation key.""" pass
"""Fonduer learning prediction model.""" from sqlalchemy import Column, Float from fonduer.meta import Meta from fonduer.utils.models.annotation import AnnotationKeyMixin, AnnotationMixin class PredictionKey(AnnotationKeyMixin, Meta.Base):
49
64
22
11
37
annelhote/fonduer
src/fonduer/learning/models/prediction.py
Python
PredictionKey
PredictionKey
8
11
8
8
25ccd88f65a219c98920d27f5e59696f303da1e6
bigcode/the-stack
train
3f5aa866ef06c2bc78fb1b4a
train
class
class Prediction(AnnotationMixin, Meta.Base): """A Prediction table. A probability associated with a Candidate, indicating the degree of belief that the Candidate is true. A Prediction's annotation key indicates which process or method produced the Prediction, e.g., which model with which Paramete...
class Prediction(AnnotationMixin, Meta.Base):
"""A Prediction table. A probability associated with a Candidate, indicating the degree of belief that the Candidate is true. A Prediction's annotation key indicates which process or method produced the Prediction, e.g., which model with which ParameterSet. """ value = Column(Float, nulla...
prediction model.""" from sqlalchemy import Column, Float from fonduer.meta import Meta from fonduer.utils.models.annotation import AnnotationKeyMixin, AnnotationMixin class PredictionKey(AnnotationKeyMixin, Meta.Base): """A Prediction's annotation key.""" pass class Prediction(AnnotationMixin, Meta.Base):...
64
64
74
9
54
annelhote/fonduer
src/fonduer/learning/models/prediction.py
Python
Prediction
Prediction
14
24
14
14
16e9af336fb8f5441cd0809d78ba147d9bc2b47a
bigcode/the-stack
train
26a850f89b96e2cca0fc41ca
train
function
@jax.jit def rotation_matrix(theta): """Return the 2D rotation matrix for angle theta""" return jnp.array( [[jnp.cos(theta), -jnp.sin(theta)], [jnp.sin(theta), jnp.cos(theta)]] )
@jax.jit def rotation_matrix(theta):
"""Return the 2D rotation matrix for angle theta""" return jnp.array( [[jnp.cos(theta), -jnp.sin(theta)], [jnp.sin(theta), jnp.cos(theta)]] )
jnp.maximum(x_dist, z_dist)) phi = phi + jnp.linalg.norm( jnp.maximum(jnp.array([1e-3, 1e-3]), jnp.array([x_dist, z_dist])) ) return phi @jax.jit def rotation_matrix(theta):
64
64
56
10
53
dawsonc/a_tale_of_two_gradients
autograd_manipulation/sim.py
Python
rotation_matrix
rotation_matrix
47
52
47
48
75f1f25f7c064ec335b6e6ce6abe4339f6addcc3
bigcode/the-stack
train
2782382b81d9d6639b389864
train
function
@jax.jit def calc_box_ground_wrench(box_state, box_size, mu_d, c, psi_s, contact_k, contact_d): """Compute the contact wrench between the box and the ground. args: box_state: current (x, z, theta, vx, vz, omega) state of the box box_size: float indicating the side length of the box mu_d...
@jax.jit def calc_box_ground_wrench(box_state, box_size, mu_d, c, psi_s, contact_k, contact_d):
"""Compute the contact wrench between the box and the ground. args: box_state: current (x, z, theta, vx, vz, omega) state of the box box_size: float indicating the side length of the box mu_d: coefficient of friction between box and ground while slipping c: coefficient of tangen...
_finger_ground = jnp.minimum(jnp.zeros(1), p_WF[1]) # Get the contact forces. Approximate ground force as a damped spring, as in # the simplified friction model from eq 21 and 22 in # https://arxiv.org/pdf/2109.05143.pdf, but with damping. normal_velocity = v_WF[1] normal_force = -contact_k * phi_f...
250
250
835
31
218
dawsonc/a_tale_of_two_gradients
autograd_manipulation/sim.py
Python
calc_box_ground_wrench
calc_box_ground_wrench
93
170
93
94
1da4ec18e986246842e74c537b23ec998e03b6d0
bigcode/the-stack
train
b2f3846c1cb97ed1eabf4dcd
train
function
def box_single_finger_simulate( box_state_initial, finger_state_initial, finger_state_desired_trace, finger_control_stiffness, N_steps, ): """Simulate the evolution of the box-finger system with one finger, starting at the given initial states and applying the specified control inputs a...
def box_single_finger_simulate( box_state_initial, finger_state_initial, finger_state_desired_trace, finger_control_stiffness, N_steps, ):
"""Simulate the evolution of the box-finger system with one finger, starting at the given initial states and applying the specified control inputs args: box_state_initial: initial (x, z, theta, vx, vz, omega) state of the box finger_state_initial: initial (x, z, vx, vz) state of the finger ...
finger_state_dot = finger_state_dot.at[2:].add(finger_forces / finger_mass_kg) # Torques box_state_dot = box_state_dot.at[5].add(box_forces[2] / box_inertia) # Itegrate new_box_state = box_state + dt * box_state_dot new_finger_state = finger_state + dt * finger_state_dot return new_box_st...
135
135
452
37
97
dawsonc/a_tale_of_two_gradients
autograd_manipulation/sim.py
Python
box_single_finger_simulate
box_single_finger_simulate
361
409
361
367
7a8e797621764d86a8446c22b8bcea80382b1d4a
bigcode/the-stack
train
1a10857a8443be9e7121a50d
train
function
@jax.jit def box_single_finger_step( box_state, finger_state, finger_state_desired, finger_control_stiffness, ): """Compute a single discrete-time update for box manipulation with one finger, using the penalty method for contact modelling with a simplified Coulomb friction model args: ...
@jax.jit def box_single_finger_step( box_state, finger_state, finger_state_desired, finger_control_stiffness, ):
"""Compute a single discrete-time update for box manipulation with one finger, using the penalty method for contact modelling with a simplified Coulomb friction model args: box_state: current (x, z, theta, vx, vz, omega) state of the box finger_state: current (x, z, vx, vz) state of the fin...
normal_force = normal_force - contact_d * normal_velocity * (phi_finger_box < 0) sticking_mask = jnp.linalg.norm(tangential_velocity + 1e-3) <= psi_s slipping_mask = jnp.logical_not(sticking_mask) mu = sticking_mask * c * tangential_velocity + slipping_mask * mu_d * tangent tangent_force = -mu * nor...
256
256
865
34
221
dawsonc/a_tale_of_two_gradients
autograd_manipulation/sim.py
Python
box_single_finger_step
box_single_finger_step
264
358
264
270
2410861535a3cb3a35630e55bcfd98eeaba0ad6e
bigcode/the-stack
train
7f442e8a5edb442d8a09e7db
train
function
@jax.jit def box_two_finger_step( box_state, finger1_state, finger1_state_desired, finger2_state, finger2_state_desired, finger_control_stiffness, ): """Compute a single discrete-time update for box manipulation with one finger, using the penalty method for contact modelling with a simpl...
@jax.jit def box_two_finger_step( box_state, finger1_state, finger1_state_desired, finger2_state, finger2_state_desired, finger_control_stiffness, ):
"""Compute a single discrete-time update for box manipulation with one finger, using the penalty method for contact modelling with a simplified Coulomb friction model args: box_state: current (x, z, theta, vx, vz, omega) state of the box finger1_state: current (x, z, vx, vz) state of the fi...
.at[0, :].set(box_state_initial) finger_state_trace = finger_state_trace.at[0, :].set(finger_state_initial) # Simulate for i in range(1, N_steps): # get currents state current_box_state = box_state_trace[i - 1, :] current_finger_state = finger_state_trace[i - 1, :] current_f...
256
256
1,258
48
207
dawsonc/a_tale_of_two_gradients
autograd_manipulation/sim.py
Python
box_two_finger_step
box_two_finger_step
412
530
412
420
430ba52e0a7aa529431c0885497bca8cdd8beb82
bigcode/the-stack
train
646cee65968c433f728d22ca
train
function
@jax.jit def calc_box_finger_wrench( box_state, finger_state, box_size, mu_d, c, psi_s, contact_k, contact_d ): """Compute the contact wrench between the box and the ground. args: box_state: current (x, z, theta, vx, vz, omega) state of the box finger_state: current (x, z, vx, vz) state of ...
@jax.jit def calc_box_finger_wrench( box_state, finger_state, box_size, mu_d, c, psi_s, contact_k, contact_d ):
"""Compute the contact wrench between the box and the ground. args: box_state: current (x, z, theta, vx, vz, omega) state of the box finger_state: current (x, z, vx, vz) state of the finger box_size: float indicating the side length of the box mu_d: coefficient of friction betwe...
1] normal_force = -contact_k * phi_corner_ground[i] normal_force = normal_force - contact_d * normal_velocity * ( phi_corner_ground[i] < 0 ) tangential_velocity = v_WC[i, 0] sticking_mask = jnp.abs(tangential_velocity) <= psi_s slipping_mask = jnp.logical_not...
256
256
1,044
38
217
dawsonc/a_tale_of_two_gradients
autograd_manipulation/sim.py
Python
calc_box_finger_wrench
calc_box_finger_wrench
173
261
173
176
7b42b71c65311ff49c230492e70aff8e3b0492ff
bigcode/the-stack
train
0f40e630deadcf92f32ba4ff
train
function
@jax.jit def calc_finger_ground_force(finger_state, mu_d, c, psi_s, contact_k, contact_d): """Compute the contact force between a finger and the ground. args: finger_state: current (x, z, theta, vx, vz, omega) state of the box mu_d: coefficient of friction between box and ground while slipping ...
@jax.jit def calc_finger_ground_force(finger_state, mu_d, c, psi_s, contact_k, contact_d):
"""Compute the contact force between a finger and the ground. args: finger_state: current (x, z, theta, vx, vz, omega) state of the box mu_d: coefficient of friction between box and ground while slipping c: coefficient of tangential velocity in determining sticking friction psi_...
jnp.maximum(jnp.array([1e-3, 1e-3]), jnp.array([x_dist, z_dist])) ) return phi @jax.jit def rotation_matrix(theta): """Return the 2D rotation matrix for angle theta""" return jnp.array( [[jnp.cos(theta), -jnp.sin(theta)], [jnp.sin(theta), jnp.cos(theta)]] ) @jax.jit def calc_finge...
120
120
400
29
91
dawsonc/a_tale_of_two_gradients
autograd_manipulation/sim.py
Python
calc_finger_ground_force
calc_finger_ground_force
55
90
55
56
041cf94431fc26cdfa88e557a73b34d13c54c2cd
bigcode/the-stack
train
1eec065eb5b1f21748ef65da
train
function
def box_two_finger_simulate( box_state_initial, finger1_state_initial, finger1_state_desired_trace, finger2_state_initial, finger2_state_desired_trace, finger_control_stiffness, N_steps, ): """Simulate the evolution of the box-finger system with one finger, starting at the given init...
def box_two_finger_simulate( box_state_initial, finger1_state_initial, finger1_state_desired_trace, finger2_state_initial, finger2_state_desired_trace, finger_control_stiffness, N_steps, ):
"""Simulate the evolution of the box-finger system with one finger, starting at the given initial states and applying the specified control inputs args: box_state_initial: initial (x, z, theta, vx, vz, omega) state of the box finger1_state_initial: initial (x, z, vx, vz) state of the finger...
.at[2:].add(finger1_forces / finger_mass_kg) finger2_state_dot = finger2_state_dot.at[2:].add(finger2_forces / finger_mass_kg) # Torques box_state_dot = box_state_dot.at[5].add(box_forces[2] / box_inertia) # Itegrate new_box_state = box_state + dt * box_state_dot new_finger1_state = finger1_st...
198
198
663
53
144
dawsonc/a_tale_of_two_gradients
autograd_manipulation/sim.py
Python
box_two_finger_simulate
box_two_finger_simulate
533
593
533
541
af20989324631c7ac920adfc4b621efa6a126a63
bigcode/the-stack
train
4f3bb842aed8ba7b0d5a42a9
train
function
@jax.jit def box_finger_signed_distance(box_pose, finger_pose, box_size): """Compute the signed distance from the box to the finger args: box_pose: current (x, z, theta) state of the box finger_pose: current (x, z) state of the finger box_size: side length of box returns: fl...
@jax.jit def box_finger_signed_distance(box_pose, finger_pose, box_size):
"""Compute the signed distance from the box to the finger args: box_pose: current (x, z, theta) state of the box finger_pose: current (x, z) state of the finger box_size: side length of box returns: float signed distance """ # Credit to this stackoverflow answer for ...
"""Automatically-differentiable manipulation simulation engine using JAX""" import jax.numpy as jnp import jax @jax.jit def box_finger_signed_distance(box_pose, finger_pose, box_size):
45
126
423
20
24
dawsonc/a_tale_of_two_gradients
autograd_manipulation/sim.py
Python
box_finger_signed_distance
box_finger_signed_distance
6
44
6
7
a51bb7dc37f596a47030a272c86f2e7931f1f1ff
bigcode/the-stack
train
c3f8e052b14de0afd5c239a0
train
function
def write_header(trees, file_name): # Track the number of plots and which objects have been plotted thus far num_plots = 0 parsed_objs = set() # Open the writing tool writer = FileOutput(file_name) writer.writeline(header) for tree in trees: # We only want to write stuff in 'event...
def write_header(trees, file_name): # Track the number of plots and which objects have been plotted thus far
num_plots = 0 parsed_objs = set() # Open the writing tool writer = FileOutput(file_name) writer.writeline(header) for tree in trees: # We only want to write stuff in 'events' TTree with this tool if tree.name in ['Event', 'EventBase']: # Plot first branches of sing...
', 'Short_t', 'UInt_t', 'Int_t', 'Long64_t', 'ULong64_t', 'Float_t', 'Double_t'] # Regular branches to plot to_plot += [b.name for b in objdef.branches \ if 'packed' not in b.name and \ not b.name.endswith('_') and \ not b.is_array()...
213
213
712
25
188
dr-stringfellow/SUEPTree
lib/suep/relval.py
Python
write_header
write_header
82
153
82
84
37110bc30ba6a1911dda9a9176da33c297cba793
bigcode/the-stack
train
50c31ecd37718dd53cd47d92
train
function
def parents(objdef): """ Get all parents and self recursively """ output = [objdef] if objdef.parent not in ['Element', 'Singlet', 'TreeEntry', 'EventBase']: output.extend(parents(PhysicsObject.get(objdef.parent))) return output
def parents(objdef):
""" Get all parents and self recursively """ output = [objdef] if objdef.parent not in ['Element', 'Singlet', 'TreeEntry', 'EventBase']: output.extend(parents(PhysicsObject.get(objdef.parent))) return output
{ constexpr static const char* name = "%s/%s"; std::vector<float> operator () (suep::Event& event) { %s return output; } };""" # Ending of EnumerateBranches.h footer = """ }; #endif""" def parents(objdef):
64
64
63
5
59
dr-stringfellow/SUEPTree
lib/suep/relval.py
Python
parents
parents
40
48
40
40
d4ad692ab7dd6196f301df4d9c1a1fddd401a4af
bigcode/the-stack
train
7d4a1607c0663fd89f78c375
train
function
def plot_set(objdef): """ Get the set of members of an object to plot """ to_plot = [] acceptable = ['bool', 'char', 'int', 'float', 'double', 'Bool_t', 'Char_t', 'UChar_t', 'UShort_t', 'Short_t', 'UInt_t', 'Int_t', 'Long64_t', 'ULong64_t', 'Fl...
def plot_set(objdef):
""" Get the set of members of an object to plot """ to_plot = [] acceptable = ['bool', 'char', 'int', 'float', 'double', 'Bool_t', 'Char_t', 'UChar_t', 'UShort_t', 'Short_t', 'UInt_t', 'Int_t', 'Long64_t', 'ULong64_t', 'Float_t', 'Double_t'] ...
footer = """ }; #endif""" def parents(objdef): """ Get all parents and self recursively """ output = [objdef] if objdef.parent not in ['Element', 'Singlet', 'TreeEntry', 'EventBase']: output.extend(parents(PhysicsObject.get(objdef.parent))) return output def plot_set(objdef):
75
75
252
6
68
dr-stringfellow/SUEPTree
lib/suep/relval.py
Python
plot_set
plot_set
51
79
51
51
c0b546cdeb5f5ea19dbc13606350f2d8bbfc83c2
bigcode/the-stack
train
924b2701046398abd29dfd80
train
function
def build_discriminator_with_teacher(filters=16): inputs = Input(shape=input_shape, name='dis_input') x = inputs z_teacher_input = Input(shape=(latent_dim,), name='z_teacher') z_teacher = Dropout(rate=0.75)(z_teacher_input) # z_teacher具有0.75的概率死掉 z_embedding = Dense(1024, activation='linear', ...
def build_discriminator_with_teacher(filters=16):
inputs = Input(shape=input_shape, name='dis_input') x = inputs z_teacher_input = Input(shape=(latent_dim,), name='z_teacher') z_teacher = Dropout(rate=0.75)(z_teacher_input) # z_teacher具有0.75的概率死掉 z_embedding = Dense(1024, activation='linear', name='z_embbding_dis')(z_teache...
经过debug ,确认为64*64*1 outputs = Conv2DTranspose(filters=1, kernel_size=kernel_size, activation='sigmoid', padding='same', name='decoder_output')(x) # instantiate decoder model return Model(...
79
79
266
10
69
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
build_discriminator_with_teacher
build_discriminator_with_teacher
312
338
312
312
e77360c8cedde0a7e6731b9fc87b28e501bfc544
bigcode/the-stack
train
e93da3945a3284b38756c8bb
train
function
def plot_resultsz2(models, epoch): """Plots labels and MNIST digits as function of 2-dim latent vector # Arguments: models (tuple): encoder and decoder models data (tuple): test data and label batch_size (int): prediction batch size model_name (string): which model is u...
def plot_resultsz2(models, epoch):
"""Plots labels and MNIST digits as function of 2-dim latent vector # Arguments: models (tuple): encoder and decoder models data (tuple): test data and label batch_size (int): prediction batch size model_name (string): which model is using this function """ dec...
reshape(digit_size, digit_size) figure[i * digit_size: (i + 1) * digit_size, j * digit_size: (j + 1) * digit_size] = digit plt.figure(figsize=(15, 15)) plt.xlabel("z[0]") plt.ylabel("z[1]") plt.imshow(figure, cmap='Greys_r') plt.savefig(fil...
118
118
396
9
108
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
plot_resultsz2
plot_resultsz2
164
204
164
164
3853678a45152a438e454ed1446457479b314fae
bigcode/the-stack
train
6fbbf3c0cd94794134d0abf3
train
function
def parse_imagestr2numpy(image_features): image1 = tf.io.decode_raw(image_features['image_raw'], tf.uint8) image1 = tf.cast(image1, tf.float32) image2 = -tf.reshape(image1, [128, 128, 3])/255.0 + 1 # 黑1 image2 = image2[:, :, 0] # 把这一行去掉就可以实现三通道图片的输入 return image2
def parse_imagestr2numpy(image_features):
image1 = tf.io.decode_raw(image_features['image_raw'], tf.uint8) image1 = tf.cast(image1, tf.float32) image2 = -tf.reshape(image1, [128, 128, 3])/255.0 + 1 # 黑1 image2 = image2[:, :, 0] # 把这一行去掉就可以实现三通道图片的输入 return image2
tf.int64), 'image_raw': tf.io.FixedLenFeature([], tf.string), } def _parse_image_function(example_proto): # Parse the input tf.Example proto using the dictionary above. return tf.io.parse_single_example(example_proto, image_feature_description) def parse_imagestr2numpy(image_features):
64
64
104
9
55
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
parse_imagestr2numpy
parse_imagestr2numpy
220
225
220
220
27ff4beffa616235bb2f11a432e53c69723ea07e
bigcode/the-stack
train
a59f8854ad01ca0570ad3e85
train
function
def compare_z(z1, z2, transitional_num=10): # distance = np.linalg.norm(z1,z2) plt.imshow(np.squeeze(VAER_GAN_instance.generator.predict(z1)), cmap='Greys_r') for i in range(transitional_num): z = z1 + (z2 - z1)*(i + 1)/transitional_num plt.imshow(np.squeeze( VAE...
def compare_z(z1, z2, transitional_num=10): # distance = np.linalg.norm(z1,z2)
plt.imshow(np.squeeze(VAER_GAN_instance.generator.predict(z1)), cmap='Greys_r') for i in range(transitional_num): z = z1 + (z2 - z1)*(i + 1)/transitional_num plt.imshow(np.squeeze( VAER_GAN_instance.generator.predict(z)), cmap='Greys_r') plt.show()
= z[0] + 1e-1 plt.imshow(np.squeeze( VAER_GAN_instance.generator.predict(z)), cmap='Greys_r') plt.show() def compare_z(z1, z2, transitional_num=10): # distance = np.linalg.norm(z1,z2)
64
64
106
26
38
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
compare_z
compare_z
599
610
599
600
4768de646c5ceae31a89c5c63fa68c39babe5436
bigcode/the-stack
train
6e72de28d300b5864f91e9d1
train
function
def fine_tuning_z(z): plt.imshow(np.squeeze(VAER_GAN_instance.generator.predict(z)), cmap='Greys_r') plt.show() for i in range(1, 100): z[0] = z[0] + 1e-1 plt.imshow(np.squeeze( VAER_GAN_instance.generator.predict(z)), cmap='Greys_r') plt.show()
def fine_tuning_z(z):
plt.imshow(np.squeeze(VAER_GAN_instance.generator.predict(z)), cmap='Greys_r') plt.show() for i in range(1, 100): z[0] = z[0] + 1e-1 plt.imshow(np.squeeze( VAER_GAN_instance.generator.predict(z)), cmap='Greys_r') plt.show()
lepoch_13z2vaerGAN_Tue_Oct_26_21_51_38_2021.h5') a128batch = parsed_image_dataset.take(1) print(type(a128batch)) a128batch_list = list(a128batch.as_numpy_iterator()) def fine_tuning_z(z):
64
64
86
7
57
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
fine_tuning_z
fine_tuning_z
588
596
588
589
a2ee4c8b9d761a47671dfe620d13ff1f1aae7562
bigcode/the-stack
train
dc080e5f2b2410e2e1978bbc
train
function
def gen_about_discriminator_loss(reconstructed_output, generated_output, refined_reconstructed_output, refined_generated_output): loss2 = keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)( tf.ones_like(reconstructed_output), reconstructed_output) loss3 = keras.l...
def gen_about_discriminator_loss(reconstructed_output, generated_output, refined_reconstructed_output, refined_generated_output):
loss2 = keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)( tf.ones_like(reconstructed_output), reconstructed_output) loss3 = keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)( tf.ones_like(generated_output), gene...
_logits=True, reduction=tf.keras.losses.Reduction.NONE)( tf.zeros_like(refined_generated_output), refined_generated_output) return loss1 + loss2 + loss3 + loss4 + loss5 def gen_about_discriminator_loss(reconstructed_output, generated_output, refined_reconstructed_output, refined_generated_output):
64
64
178
22
41
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
gen_about_discriminator_loss
gen_about_discriminator_loss
541
550
541
541
53e59cacfdaa124d0cd2cd218514ee6dd9cac424
bigcode/the-stack
train
1fbdc2ff2dcd75fc727ef910
train
function
def test_plot(model, a128batch): testresult = model.predict(a128batch) testresult = np.squeeze(testresult) # testresult = np.where(testresult>0.78,testresult,0) digit_size = 128 row = 2 col = 25 figure = np.zeros((digit_size * 2 * row, digit_size * col)) # 4行10列 for i in range(col): ...
def test_plot(model, a128batch):
testresult = model.predict(a128batch) testresult = np.squeeze(testresult) # testresult = np.where(testresult>0.78,testresult,0) digit_size = 128 row = 2 col = 25 figure = np.zeros((digit_size * 2 * row, digit_size * col)) # 4行10列 for i in range(col): # import pdb # pdb.s...
最近的code下标 result = [] for i in range(check_num): result.append(codelist[result_index[i]]) print('{}--{}'.format(result_index[i], distance_list[i])) for i in range(check_num): plt.imshow(np.squeeze( VAER_GAN_instance.generator.predict(result[i])), cmap='Greys_r') ...
100
100
334
9
91
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
test_plot
test_plot
670
693
670
670
bea4ce35e03de655782fed05aa821f5efeac5cb4
bigcode/the-stack
train
308e0498d3f3f0d229ca547c
train
function
def collect_z(check_index=50, check_num=6): _, _, code = VAER_GAN_instance.encoder.predict(parsed_image_dataset) check_img = Image.open('gene/{}.jpg'.format(check_index)) check_img = np.array(check_img) print(-(check_img/255.0)) check_img = -(check_img/255.0) + 1 print(check_img) plt.imsh...
def collect_z(check_index=50, check_num=6):
_, _, code = VAER_GAN_instance.encoder.predict(parsed_image_dataset) check_img = Image.open('gene/{}.jpg'.format(check_index)) check_img = np.array(check_img) print(-(check_img/255.0)) check_img = -(check_img/255.0) + 1 print(check_img) plt.imshow(check_img, cmap='Greys_r') plt.savefig...
transitional_num=10): # distance = np.linalg.norm(z1,z2) plt.imshow(np.squeeze(VAER_GAN_instance.generator.predict(z1)), cmap='Greys_r') for i in range(transitional_num): z = z1 + (z2 - z1)*(i + 1)/transitional_num plt.imshow(np.squeeze( VAER_GAN_instance.genera...
125
125
418
13
111
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
collect_z
collect_z
615
667
615
616
fee728cfba18563ecd5f639ca8a9be03013c4443
bigcode/the-stack
train
7bcc470bb35fc4cd7e98d70c
train
function
def _parse_image_function(example_proto): # Parse the input tf.Example proto using the dictionary above. return tf.io.parse_single_example(example_proto, image_feature_description)
def _parse_image_function(example_proto): # Parse the input tf.Example proto using the dictionary above.
return tf.io.parse_single_example(example_proto, image_feature_description)
'height': tf.io.FixedLenFeature([], tf.int64), 'width': tf.io.FixedLenFeature([], tf.int64), 'image_raw': tf.io.FixedLenFeature([], tf.string), } def _parse_image_function(example_proto): # Parse the input tf.Example proto using the dictionary above.
64
64
36
22
42
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
_parse_image_function
_parse_image_function
215
217
215
216
b1c3c583d304b8ca7a4d2a418895d7676bc4d27a
bigcode/the-stack
train
94824f2f3f519fd2a396ae23
train
class
class VAER_GAN(keras.Model): def __init__( self, generator, discriminator, encoder, refiner ): super(VAER_GAN, self).__init__() self.generator = generator self.discriminator = discriminator self.encoder = encoder self.refiner = refi...
class VAER_GAN(keras.Model):
def __init__( self, generator, discriminator, encoder, refiner ): super(VAER_GAN, self).__init__() self.generator = generator self.discriminator = discriminator self.encoder = encoder self.refiner = refiner def compile( ...
activation='linear')(x) return Model(inputs=[inputs, z_teacher_input], outputs=x, name='discriminator') def build_refiner(): z = Input(shape=(latent_dim,), name='z_input') reconstructed_picture = Input( shape=(image_size, image_size, 1), name='reconstructed_picture') reconstructed_picture_de...
256
256
968
9
246
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
VAER_GAN
VAER_GAN
363
492
363
363
96357a676d70adc4999ff987486037b251a3919d
bigcode/the-stack
train
9f97e25b44d984da7fa9e8f9
train
function
def plot_results(models, batch): """Plots labels and MNIST digits as function of 3-dim latent vector # Arguments: models (tuple): encoder and decoder models data (tuple): test data and label batch_size (int): prediction batch size model_name (string): which model is usi...
def plot_results(models, batch):
"""Plots labels and MNIST digits as function of 3-dim latent vector # Arguments: models (tuple): encoder and decoder models data (tuple): test data and label batch_size (int): prediction batch size model_name (string): which model is using this function """ enc...
Gaussian. # Arguments: args (tensor): mean and log of variance of Q(z|X) # Returns: z (tensor): sampled latent map """ z_mean, z_log_var = args batch = K.shape(z_mean)[0] dim = K.int_shape(z_mean)[1] # by default, random_normal has mean=0 and std=1.0 epsilon = K.rando...
129
129
433
7
121
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
plot_results
plot_results
122
160
122
122
a9e7f8812ee645d48299d36e6ec2531e86c95a65
bigcode/the-stack
train
c78342e17bd352d003402fd5
train
function
def plot_results1d(models, experiment_dim=0, latent_dim=14): """1d # Arguments: models (tuple): encoder and decoder models data (tuple): test data and label batch_size (int): prediction batch size model_name (string): which model is using this function """ decoder = mod...
def plot_results1d(models, experiment_dim=0, latent_dim=14):
"""1d # Arguments: models (tuple): encoder and decoder models data (tuple): test data and label batch_size (int): prediction batch size model_name (string): which model is using this function """ decoder = models experiment_code = np.ones((1, latent_dim))*2 n =...
from tensorflow.python.ops.variables import trainable_variables from tensorflow.keras.callbacks import TensorBoard # matplotlib.use('Agg') # 这样可以不显示图窗 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import argparse import os import glob import time import datetime import heapq from PIL impor...
102
102
341
17
84
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
plot_results1d
plot_results1d
42
76
42
42
a8aa80a244d80101b11d531618aabd70e829e671
bigcode/the-stack
train
3c7176a6fa3b16af02b87938
train
function
def ref_about_discriminator_loss(refined_reconstructed_output, refined_generated_output): loss4 = keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)( tf.ones_like(refined_reconstructed_output), refined_reconstructed_output) loss5 = keras.losses.BinaryCrossentropy...
def ref_about_discriminator_loss(refined_reconstructed_output, refined_generated_output):
loss4 = keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)( tf.ones_like(refined_reconstructed_output), refined_reconstructed_output) loss5 = keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)( tf.ones_like(refined...
5 = keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)( tf.ones_like(refined_generated_output), refined_generated_output) return loss2 + loss3 + loss4 + loss5 def ref_about_discriminator_loss(refined_reconstructed_output, refined_generated_output):
64
64
98
16
47
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
ref_about_discriminator_loss
ref_about_discriminator_loss
553
558
553
553
3afb23571f8648663dea0563233a0291a97726b1
bigcode/the-stack
train
1815b92263c884bb79cdce02
train
function
def reconstructed_loss(real_img, reconstructed_img): reconstructed_img = K.flatten(reconstructed_img) real_img = K.flatten(real_img) # 显示shape为(None,) difference = reconstructed_img-real_img # weighted_img_difference = tf.multiply(K.square(difference),0.625+0.625*real_img) weighted_img_difference =...
def reconstructed_loss(real_img, reconstructed_img):
reconstructed_img = K.flatten(reconstructed_img) real_img = K.flatten(real_img) # 显示shape为(None,) difference = reconstructed_img-real_img # weighted_img_difference = tf.multiply(K.square(difference),0.625+0.625*real_img) weighted_img_difference = K.square(difference) return image_size*image_siz...
,reconstructed_img]) return reconstructed_img encoder_optimizer = tf.keras.optimizers.RMSprop() generator_optimizer = tf.keras.optimizers.RMSprop() discriminator_optimizer = tf.keras.optimizers.RMSprop() refiner_optimizer = tf.keras.optimizers.RMSprop() def reconstructed_loss(real_img, reconstructed_img):
64
64
99
9
55
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
reconstructed_loss
reconstructed_loss
501
507
501
501
f80c3412f4f9d55dedac834ec1fddbbd927cfe04
bigcode/the-stack
train
34f86cb6dc64f828fc5da612
train
function
def build_encoder(filters=32): inputs = Input(shape=input_shape, name='encoder_input') x = inputs # 3层卷积 for i in range(3): x = Conv2D(filters=filters, kernel_size=kernel_size, activation='relu', strides=2, padding='same...
def build_encoder(filters=32):
inputs = Input(shape=input_shape, name='encoder_input') x = inputs # 3层卷积 for i in range(3): x = Conv2D(filters=filters, kernel_size=kernel_size, activation='relu', strides=2, padding='same')(x) filters *= 2 ...
_image_dataset = parsed_image_dataset.batch(batch_size) input_shape = (image_size, image_size, 1) kernel_size = 3 filters = 16 latent_dim = 12 epochs = 100 # VAE model = encoder + decoder # build encoder model def build_encoder(filters=32):
66
66
222
7
58
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
build_encoder
build_encoder
256
282
256
256
e4be4d1af9a176c151a8e1232e219a59f11cc742
bigcode/the-stack
train
a13c7de41f24fc0a44f18f91
train
function
def sampling(args): """Reparameterization trick by sampling fr an isotropic unit Gaussian. # Arguments: args (tensor): mean and log of variance of Q(z|X) # Returns: z (tensor): sampled latent map """ z_mean, z_log_var = args batch = K.shape(z_mean)[0] dim = K.int_...
def sampling(args):
"""Reparameterization trick by sampling fr an isotropic unit Gaussian. # Arguments: args (tensor): mean and log of variance of Q(z|X) # Returns: z (tensor): sampled latent map """ z_mean, z_log_var = args batch = K.shape(z_mean)[0] dim = K.int_shape(z_mean)[1] ...
# def on_epoch_end(self, epoch, logs=None): # super(My_tensorboardcallback, self).on_epoch_end(epoch,logs) # writer = self._get_writer(self._validation_run_name) # with writer.as_default(): # 计算数据集特征 def sampling(args):
64
64
136
4
59
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
sampling
sampling
101
117
101
101
30928501122d6fd9516e95fdc76f3a6f48828063
bigcode/the-stack
train
12b8161e2de3fce12a3dba64
train
function
def build_decoder(filters=128): # build decoder model shape = (None, 16, 16, 128) latent_inputs = Input(shape=(latent_dim,), name='z_sampling') x = Dense(shape[1] * shape[2] * shape[3], activation='relu')(latent_inputs) x = Reshape((shape[1], shape[2], shape[3]))(x) for i in rang...
def build_decoder(filters=128): # build decoder model
shape = (None, 16, 16, 128) latent_inputs = Input(shape=(latent_dim,), name='z_sampling') x = Dense(shape[1] * shape[2] * shape[3], activation='relu')(latent_inputs) x = Reshape((shape[1], shape[2], shape[3]))(x) for i in range(3): x = Conv2DTranspose(filters=filters, ...
z = Lambda(sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var]) # instantiate encoder model return Model(inputs, [z_mean, z_log_var, z], name='encoder') def build_decoder(filters=128): # build decoder model
64
64
212
13
51
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
build_decoder
build_decoder
285
309
285
286
084c5098588eadd4308870cfc91cbcacb60de414
bigcode/the-stack
train
8e108d0e3fdf6521dafd7b69
train
function
def kl_loss(z_mean, z_log_var): kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var) kl_loss = K.sum(kl_loss, axis=-1) kl_loss *= -0.5 return kl_loss
def kl_loss(z_mean, z_log_var):
kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var) kl_loss = K.sum(kl_loss, axis=-1) kl_loss *= -0.5 return kl_loss
),0.625+0.625*real_img) weighted_img_difference = K.square(difference) return image_size*image_size*tf.reduce_mean(weighted_img_difference, axis=-1) # 我在维度方面仍然存在疑惑 def kl_loss(z_mean, z_log_var):
64
64
61
10
53
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
kl_loss
kl_loss
511
515
511
511
0c592be3c3e8281a34225ecd1030c902e5f18937
bigcode/the-stack
train
43a7a7d728889bc4b161a115
train
function
def build_refiner(): z = Input(shape=(latent_dim,), name='z_input') reconstructed_picture = Input( shape=(image_size, image_size, 1), name='reconstructed_picture') reconstructed_picture_denoised = tf.where( reconstructed_picture > 0.78, reconstructed_picture, 0) # z_embedding = Dense(64*...
def build_refiner():
z = Input(shape=(latent_dim,), name='z_input') reconstructed_picture = Input( shape=(image_size, image_size, 1), name='reconstructed_picture') reconstructed_picture_denoised = tf.where( reconstructed_picture > 0.78, reconstructed_picture, 0) # z_embedding = Dense(64*64,activation='selu')...
='relu')(x) # 对z_embedding和x进行加和操作 x = add([x, z_embedding]) x = Dense(1, activation='linear')(x) return Model(inputs=[inputs, z_teacher_input], outputs=x, name='discriminator') def build_refiner():
64
64
214
5
59
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
build_refiner
build_refiner
341
358
341
341
201fef0b5b15bf750266bc6ddb3c742eb6a92124
bigcode/the-stack
train
e945644e2b67b2c9fb2e8425
train
function
def discriminator_loss(real_output, reconstructed_output, generated_output, refined_reconstructed_output, refined_generated_output): loss1 = keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)( tf.ones_like(real_output), real_output) loss2 = keras.losses.BinaryCro...
def discriminator_loss(real_output, reconstructed_output, generated_output, refined_reconstructed_output, refined_generated_output):
loss1 = keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)( tf.ones_like(real_output), real_output) loss2 = keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)( tf.zeros_like(reconstructed_output), reconstructed_out...
.losses.Reduction.NONE)(tf.zeros_like(generated_output),generated_output) # return loss1 + loss2 + loss3 # discriminator_loss使用的不是图片,而是关于图片的那些输出 def discriminator_loss(real_output, reconstructed_output, generated_output, refined_reconstructed_output, refined_generated_output):
64
64
213
21
42
tf2gan/vae-gan-code-for-reinforced-panel
plot_results_gui_latent12vaegan.py
Python
discriminator_loss
discriminator_loss
526
538
526
526
2322f8cf9e27282f8066761b87ae0d8725d51524
bigcode/the-stack
train
bcee95e69d3edbf7cfb6ec0a
train
class
class GPCEncoder(BaseEncoder): UNK_IDX = 0 def __init__(self, encoder_path=ENCODER_PATH, vocab_path=None): super().__init__(encoder_path=encoder_path, vocab_path=vocab_path) self.encoder = spm.SentencePieceProcessor() self.encoder.Load(ENCODER_PATH + ".model") self.start_token...
class GPCEncoder(BaseEncoder):
UNK_IDX = 0 def __init__(self, encoder_path=ENCODER_PATH, vocab_path=None): super().__init__(encoder_path=encoder_path, vocab_path=vocab_path) self.encoder = spm.SentencePieceProcessor() self.encoder.Load(ENCODER_PATH + ".model") self.start_token = self.encoder.piece_to_id("<_...
from finetune.util.tokenization import normalize_nfkc, WEIRD_SPM_CHAR import sentencepiece as spm import unicodedata FINETUNE_FOLDER = os.path.dirname(finetune.__file__) ENCODER_PATH = os.path.join(FINETUNE_FOLDER, "model", "oscar", "encoder") LOGGER = logging.getLogger("finetune") def train_tokenizer(filename, vo...
194
194
647
7
187
IndicoDataSolutions/finetune-transformer-lm
finetune/base_models/oscar/encoder.py
Python
GPCEncoder
GPCEncoder
31
116
31
31
4293f281df6df2992517c41e851b2d564f8c5a1b
bigcode/the-stack
train
1ab22d8af3ceff1d4b9a6181
train
function
def train_tokenizer(filename, vocab_size=128000): spm.SentencePieceTrainer.train( ( "--input={} --model_prefix={} --user_defined_symbols=<_start_>,<_delimiter_>,<_classify_> --unk_id=0 " "--vocab_size={} --input_sentence_size=10000000 --shuffle_input_sentence=true" " --ma...
def train_tokenizer(filename, vocab_size=128000):
spm.SentencePieceTrainer.train( ( "--input={} --model_prefix={} --user_defined_symbols=<_start_>,<_delimiter_>,<_classify_> --unk_id=0 " "--vocab_size={} --input_sentence_size=10000000 --shuffle_input_sentence=true" " --max_sentence_length=10000000 --character_coverage=0....
import unicodedata FINETUNE_FOLDER = os.path.dirname(finetune.__file__) ENCODER_PATH = os.path.join(FINETUNE_FOLDER, "model", "oscar", "encoder") LOGGER = logging.getLogger("finetune") def train_tokenizer(filename, vocab_size=128000):
64
64
110
12
52
IndicoDataSolutions/finetune-transformer-lm
finetune/base_models/oscar/encoder.py
Python
train_tokenizer
train_tokenizer
21
28
21
21
2eb5312142fb5cfb7354929f64288cf8a0d9d44c
bigcode/the-stack
train
4dd1fcdc75da26df5943c023
train
function
def load_model_data(m, d, data_portal, scenario_directory, subproblem, stage): """ :param m: :param d: :param data_portal: :param scenario_directory: :param subproblem: :param stage: :return: """ generic_load_model_data( m=m, d=d, data_portal=data_portal,...
def load_model_data(m, d, data_portal, scenario_directory, subproblem, stage):
""" :param m: :param d: :param data_portal: :param scenario_directory: :param subproblem: :param stage: :return: """ generic_load_model_data( m=m, d=d, data_portal=data_portal, scenario_directory=scenario_directory, subproblem=subproblem, ...
reserve_provision_ramp_rate_limit_param=RESERVE_PROVISION_RAMP_RATE_LIMIT_PARAM_NAME, reserve_provision_ramp_rate_limit_constraint=RESERVE_PROVISION_RAMP_RATE_LIMIT_CONSTRAINT_NAME, ) def load_model_data(m, d, data_portal, scenario_directory, subproblem, stage):
64
64
146
20
44
souissim/gridpath
gridpath/project/operations/reserves/op_type_dependent/regulation_up.py
Python
load_model_data
load_model_data
69
89
69
69
410c4c78c158fc1bbb2c4a2c27ab94ae10014aa9
bigcode/the-stack
train
7b2984a97c699743ce970594
train
function
def write_model_inputs( scenario_directory, scenario_id, subscenarios, subproblem, stage, conn ): """ Get inputs from database and write out the model input projects.tab file (to be precise, amend it). :param scenario_directory: string, the scenario directory :param subscenarios: SubScenarios ob...
def write_model_inputs( scenario_directory, scenario_id, subscenarios, subproblem, stage, conn ):
""" Get inputs from database and write out the model input projects.tab file (to be precise, amend it). :param scenario_directory: string, the scenario directory :param subscenarios: SubScenarios object with all subscenario info :param subproblem: :param stage: :param conn: database conn...
get_inputs_from_database( scenario_id, subscenarios, subproblem, stage, conn ) df = cursor_to_df(prj_ramp_rates) write_validation_to_database( conn=conn, scenario_id=scenario_id, subproblem_id=subproblem, stage_id=stage, gridpath_module=__name__, db_...
137
137
459
24
113
souissim/gridpath
gridpath/project/operations/reserves/op_type_dependent/regulation_up.py
Python
write_model_inputs
write_model_inputs
143
201
143
145
4b547896dd66214b14a74d01878060180a60a2cb
bigcode/the-stack
train
aa91e7c01322e499f52823ff
train
function
def get_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn): """ :param subscenarios: SubScenarios object with all subscenario info :param subproblem: :param stage: :param conn: database connection :return: """ # TODO: generalize this for all reserves and inner join ...
def get_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn):
""" :param subscenarios: SubScenarios object with all subscenario info :param subproblem: :param stage: :param conn: database connection :return: """ # TODO: generalize this for all reserves and inner join to portfolio subproblem = 1 if subproblem == "" else subproblem stage = 1 ...
ramp_rate_limit_column_name=RESERVE_PROVISION_RAMP_RATE_LIMIT_COLUMN_NAME_IN_INPUT_FILE, reserve_provision_ramp_rate_limit_param=RESERVE_PROVISION_RAMP_RATE_LIMIT_PARAM_NAME, ) def get_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn):
64
64
193
20
44
souissim/gridpath
gridpath/project/operations/reserves/op_type_dependent/regulation_up.py
Python
get_inputs_from_database
get_inputs_from_database
92
113
92
92
b4d1d8f3042fceed8c6118157d556c6d492edd51
bigcode/the-stack
train
453bb775b09e5f785922da0f
train
function
def add_model_components(m, d, scenario_directory, subproblem, stage): """ :param m: :param d: :return: """ generic_add_model_components( m=m, d=d, scenario_directory=scenario_directory, subproblem=subproblem, stage=stage, reserve_projects_set=RE...
def add_model_components(m, d, scenario_directory, subproblem, stage):
""" :param m: :param d: :return: """ generic_add_model_components( m=m, d=d, scenario_directory=scenario_directory, subproblem=subproblem, stage=stage, reserve_projects_set=RESERVE_PROJECTS_SET_NAME, reserve_project_operational_timepoints...
_PARAM_NAME = "regulation_up_ramp_rate_limit" RESERVE_PROJECTS_SET_NAME = "REGULATION_UP_PROJECTS" RESERVE_PRJ_OPR_TMPS_SET_NAME = "REGULATION_UP_PRJ_OPR_TMPS" def add_model_components(m, d, scenario_directory, subproblem, stage):
64
64
157
16
48
souissim/gridpath
gridpath/project/operations/reserves/op_type_dependent/regulation_up.py
Python
add_model_components
add_model_components
47
66
47
47
f4ffb7fb3e8001593a1a090049246ea30469461c
bigcode/the-stack
train
90753c7256324bf5eb67816d
train
function
def validate_inputs(scenario_id, subscenarios, subproblem, stage, conn): """ Get inputs from database and validate the inputs :param subscenarios: SubScenarios object with all subscenario info :param subproblem: :param stage: :param conn: database connection :return: """ prj_ramp_ra...
def validate_inputs(scenario_id, subscenarios, subproblem, stage, conn):
""" Get inputs from database and validate the inputs :param subscenarios: SubScenarios object with all subscenario info :param subproblem: :param stage: :param conn: database connection :return: """ prj_ramp_rates = get_inputs_from_database( scenario_id, subscenarios, subpro...
_operational_chars WHERE project_operational_chars_scenario_id = {};""".format( subscenarios.PROJECT_OPERATIONAL_CHARS_SCENARIO_ID ) ) return prj_ramp_rates def validate_inputs(scenario_id, subscenarios, subproblem, stage, conn):
64
64
192
18
45
souissim/gridpath
gridpath/project/operations/reserves/op_type_dependent/regulation_up.py
Python
validate_inputs
validate_inputs
116
140
116
116
933ec83d2e26dde7ae3cf25e58b53ae23f53caa2
bigcode/the-stack
train
3256012614c6e8524337a013
train
function
def test_DictLike(): d = mfu.DictLike() d['x'] = 2 d['y'] = 3 d['z'] = 77 assert str(d) == "{'x': 2, 'y': 3, 'z': 77}" assert repr(d) == "DictLike({'x': 2, 'y': 3, 'z': 77})" assert len(d) == 3 assert d['x'] == 2 assert d.pop('x') with pytest.raises(KeyError): print(d[...
def test_DictLike():
d = mfu.DictLike() d['x'] = 2 d['y'] = 3 d['z'] = 77 assert str(d) == "{'x': 2, 'y': 3, 'z': 77}" assert repr(d) == "DictLike({'x': 2, 'y': 3, 'z': 77})" assert len(d) == 3 assert d['x'] == 2 assert d.pop('x') with pytest.raises(KeyError): print(d['x'])
is None assert mf.check_type('y', 11.2, float) is None assert mf.check_type('z', 'abc', str) is None with pytest.raises(TypeError): mf.check_type('x', 55.5, int) def test_DictLike():
64
64
133
6
58
airinnova/model-framework
tests/test_misc.py
Python
test_DictLike
test_DictLike
45
59
45
45
f664a2811697abc291a0e705a3f2466023d210b3
bigcode/the-stack
train
82356015db722cc7c1afc273
train
function
def test_is_primitive_type(): assert mf.is_primitve_type(bool) assert mf.is_primitve_type(int) class MyType: pass assert not mf.is_primitve_type(MyType)
def test_is_primitive_type():
assert mf.is_primitve_type(bool) assert mf.is_primitve_type(int) class MyType: pass assert not mf.is_primitve_type(MyType)
mframework as mf import mframework._utils as mfu from mframework import log as log log.on def test_log(): log.off log.on def test_version(): from mframework.__version__ import __version__ print(__version__) def test_is_primitive_type():
64
64
47
7
57
airinnova/model-framework
tests/test_misc.py
Python
test_is_primitive_type
test_is_primitive_type
26
33
26
26
17adf7c9ecfeb0f4bc484e5cb3b006ea0b5cfef2
bigcode/the-stack
train
17533d60eeafd925617316e2
train
function
def test_check_type(): assert mf.check_type('x', 11, int) is None assert mf.check_type('y', 11.2, float) is None assert mf.check_type('z', 'abc', str) is None with pytest.raises(TypeError): mf.check_type('x', 55.5, int)
def test_check_type():
assert mf.check_type('x', 11, int) is None assert mf.check_type('y', 11.2, float) is None assert mf.check_type('z', 'abc', str) is None with pytest.raises(TypeError): mf.check_type('x', 55.5, int)
.__version__ import __version__ print(__version__) def test_is_primitive_type(): assert mf.is_primitve_type(bool) assert mf.is_primitve_type(int) class MyType: pass assert not mf.is_primitve_type(MyType) def test_check_type():
64
64
76
5
59
airinnova/model-framework
tests/test_misc.py
Python
test_check_type
test_check_type
36
42
36
36
358bcfdb6c9adeeff593ae84e96d8f4ef937b348
bigcode/the-stack
train
c5027902e7418acff7c82389
train
function
def test_SpecEntry(): s = mf.SpecEntry(schema=int, required=0, max_items=1, doc='abc') assert s.schema is int assert s.max_items == 1 assert s.singleton is True assert s.required == 0 assert s.doc == 'abc' with pytest.raises(TypeError): s.max_items = 'FALSE' with pytest.raises(...
def test_SpecEntry():
s = mf.SpecEntry(schema=int, required=0, max_items=1, doc='abc') assert s.schema is int assert s.max_items == 1 assert s.singleton is True assert s.required == 0 assert s.doc == 'abc' with pytest.raises(TypeError): s.max_items = 'FALSE' with pytest.raises(TypeError): s....
ids = ('myUID', 'myUID2') exp_values = ('two', 'three') for i, (uid, value) in enumerate(d.iter_uids('a')): assert exp_uids[i] == uid assert exp_values[i] == value def test_SpecEntry():
64
64
96
6
57
airinnova/model-framework
tests/test_misc.py
Python
test_SpecEntry
test_SpecEntry
118
130
118
118
94e55ab4c7955aeed9e390acae3ade709fec7407
bigcode/the-stack
train
f9687fd70e9297532751ee51
train
function
def test_SpecDict(): d = mf.SpecDict() d['spec1'] = mf.SpecEntry(int) d['spec2'] = mf.SpecEntry(bool) # Cannot redefine a specification with pytest.raises(KeyError): d['spec2'] = mf.SpecEntry(str) # Value must be SpecEntry with pytest.raises(ValueError): d['spec3'] = 3 ...
def test_SpecDict():
d = mf.SpecDict() d['spec1'] = mf.SpecEntry(int) d['spec2'] = mf.SpecEntry(bool) # Cannot redefine a specification with pytest.raises(KeyError): d['spec2'] = mf.SpecEntry(str) # Value must be SpecEntry with pytest.raises(ValueError): d['spec3'] = 3 assert d['spec1'].sc...
x': 2, 'y': 3, 'z': 77})" assert len(d) == 3 assert d['x'] == 2 assert d.pop('x') with pytest.raises(KeyError): print(d['x']) def test_SpecDict():
63
64
110
6
57
airinnova/model-framework
tests/test_misc.py
Python
test_SpecDict
test_SpecDict
62
76
62
62
a90c346b68714ba7905e98ace40625619f2258c2
bigcode/the-stack
train
98a7bc5cb03f5539c4585fe5
train
function
def test_log(): log.off log.on
def test_log():
log.off log.on
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Test various building blocks """ import pytest import mframework._mframework as mf import mframework._utils as mfu from mframework import log as log log.on def test_log():
58
64
12
4
53
airinnova/model-framework
tests/test_misc.py
Python
test_log
test_log
16
18
16
16
1ec14ff5065878275a3f46baf6e2c3c27d409662
bigcode/the-stack
train
472e8eb84a437759b9f8f028
train
function
def test_version(): from mframework.__version__ import __version__ print(__version__)
def test_version():
from mframework.__version__ import __version__ print(__version__)
# -*- coding: utf-8 -*- """ Test various building blocks """ import pytest import mframework._mframework as mf import mframework._utils as mfu from mframework import log as log log.on def test_log(): log.off log.on def test_version():
64
64
20
4
59
airinnova/model-framework
tests/test_misc.py
Python
test_version
test_version
21
23
21
21
ac09d467c11d8ad7f7324181917e9840f0eda97e
bigcode/the-stack
train
f8f98eaf4ebf081f830b8d3d
train
function
def test_ItemDict(): d = mf.ItemDict() assert d['x'] == {} d['y'] = 1 d['y'] = 2 d['y'] = 3 assert len(d['y']) == 3 assert list(d['y'].values()) == [1, 2, 3] # Test assigning UIDs d.assign_uid('y', 'special_entry') assert 3 == d.get_by_uid('y', 'special_entry') d.assign_ui...
def test_ItemDict():
d = mf.ItemDict() assert d['x'] == {} d['y'] = 1 d['y'] = 2 d['y'] = 3 assert len(d['y']) == 3 assert list(d['y'].values()) == [1, 2, 3] # Test assigning UIDs d.assign_uid('y', 'special_entry') assert 3 == d.get_by_uid('y', 'special_entry') d.assign_uid('y', 'another_speci...
d['spec1'] = mf.SpecEntry(int) d['spec2'] = mf.SpecEntry(bool) # Cannot redefine a specification with pytest.raises(KeyError): d['spec2'] = mf.SpecEntry(str) # Value must be SpecEntry with pytest.raises(ValueError): d['spec3'] = 3 assert d['spec1'].schema == int assert...
102
102
341
5
96
airinnova/model-framework
tests/test_misc.py
Python
test_ItemDict
test_ItemDict
79
115
79
79
511a5b8be66b9afa99ebe8aba51adeb33fb43191
bigcode/the-stack
train
2723491705bc7d3676565449
train
function
def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_overwrite=False): """ Moves a file from one location to another in the safest way possible. First, tries ``os.rename``, which is simple but will break across filesystems. If that fails, streams manually from one file to anothe...
def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_overwrite=False):
""" Moves a file from one location to another in the safest way possible. First, tries ``os.rename``, which is simple but will break across filesystems. If that fails, streams manually from one file to another in pure Python. If the destination file exists and ``allow_overwrite`` is ``False``, thi...
st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) __all__ = ['file_move_safe'] def _samefile(src, dst): # Macintosh, Unix. if hasattr(os.path,'samefile'): try: return os.path.samefile(src, dst) except OSError: return False # All other ...
135
135
451
26
109
vladushakov987/appengine_python3
google/appengine/_internal/django/core/files/move.py
Python
file_move_safe
file_move_safe
39
89
39
39
99f0385c921d9ce0a0906da093f2f90886deb789
bigcode/the-stack
train
faa258cf05b3fdf2e47b1f76
train
function
def _samefile(src, dst): # Macintosh, Unix. if hasattr(os.path,'samefile'): try: return os.path.samefile(src, dst) except OSError: return False # All other platforms: check for same pathname. return (os.path.normcase(os.path.abspath(src)) == os.path.n...
def _samefile(src, dst): # Macintosh, Unix.
if hasattr(os.path,'samefile'): try: return os.path.samefile(src, dst) except OSError: return False # All other platforms: check for same pathname. return (os.path.normcase(os.path.abspath(src)) == os.path.normcase(os.path.abspath(dst)))
if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) __all__ = ['file_move_safe'] def _samefile(src, dst): # Macintosh, Unix.
64
64
79
14
50
vladushakov987/appengine_python3
google/appengine/_internal/django/core/files/move.py
Python
_samefile
_samefile
27
37
27
28
c64e00ac791a8cb70671b6a4de180d8ee7b5d468
bigcode/the-stack
train
ca2c5d8c65833f97f6e36391
train
class
class Ui_dck_procedures(object): def setupUi(self, dck_procedures): dck_procedures.setObjectName("dck_procedures") dck_procedures.resize(316, 480) self.dwc_procedures = QtWidgets.QWidget() self.dwc_procedures.setObjectName("dwc_procedures") self.verticalLayout = QtWidgets.QVB...
class Ui_dck_procedures(object):
def setupUi(self, dck_procedures): dck_procedures.setObjectName("dck_procedures") dck_procedures.resize(316, 480) self.dwc_procedures = QtWidgets.QWidget() self.dwc_procedures.setObjectName("dwc_procedures") self.verticalLayout = QtWidgets.QVBoxLayout(self.dwc_procedures) ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file './dock_procedures.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_dck_procedures(object):
78
256
1,351
9
68
mlabru/visil
view/common/dock_procedures_ui.py
Python
Ui_dck_procedures
Ui_dck_procedures
11
96
11
11
d36e50a29a80513faa8f5226489339ad66c92cbd
bigcode/the-stack
train
1690b48d1f0e0ca1218d8a9d
train
class
class EmpiricalCovariance(BaseEstimator): """Maximum likelihood covariance estimator Read more in the :ref:`User Guide <covariance>`. Parameters ---------- store_precision : bool, default=True Specifies if the estimated precision is stored. assume_centered : bool, default=False ...
class EmpiricalCovariance(BaseEstimator):
"""Maximum likelihood covariance estimator Read more in the :ref:`User Guide <covariance>`. Parameters ---------- store_precision : bool, default=True Specifies if the estimated precision is stored. assume_centered : bool, default=False If True, data are not centered before co...
Likelihood Estimator). Examples -------- >>> from sklearn.covariance import empirical_covariance >>> X = [[1,1,1],[1,1,1],[1,1,1], ... [0,0,0],[0,0,0],[0,0,0]] >>> empirical_covariance(X) array([[0.25, 0.25, 0.25], [0.25, 0.25, 0.25], [0.25, 0.25, 0.25]]) """...
256
256
1,688
8
247
talahajeer/scikit-learn
sklearn/covariance/_empirical_covariance.py
Python
EmpiricalCovariance
EmpiricalCovariance
101
325
101
101
4b860801e9f774e64a7f755235208a9370749d61
bigcode/the-stack
train