id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
1664473
<reponame>rmarx/quic_iot import argparse import os import shutil import re import sys from multiprocessing import Process import gc import time from random import random import json import multiprocessing from util.Util import Util from lib.analyzers.DeviceAnalyzer import DeviceAnalyzer def main(): global device_...
StarcoderdataPython
6586637
""" I/O operations to save and load embeddings. """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved import json import csv from typing import List, Tuple, Dict import numpy as np INVALID_FILENAME_CHARACTERS = [','] def _is_valid_filename(filename: str) -> bool: """Returns False if t...
StarcoderdataPython
12817206
<gh_stars>1-10 #!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import argparse from util import io # plot a single variable from an output file # # Usage: ./plotvar.py filename variable def makeplot(plotfile, variable, outfile): sim = io.read(plotfile) myd = sim.cc_data myg = m...
StarcoderdataPython
5020787
<reponame>xudonmao/VMT<filename>codebase/models/nns/large.py<gh_stars>10-100 import tensorflow as tf from codebase.args import args from codebase.models.extra_layers import leaky_relu, noise from tensorbayes.layers import dense, conv2d, avg_pool, max_pool, batch_norm, instance_norm from tensorflow.contrib.framework imp...
StarcoderdataPython
6688782
<reponame>Flickswitch/phx_events from hypothesis import given from phx_events import json_handler from phx_events.client import PHXChannelsClient from phx_events.phx_messages import PHXEvent, PHXEventMessage, PHXMessage from tests.strategy_utils import event_strategy, phx_event_strategy class TestPHXChannelsClientPa...
StarcoderdataPython
6464933
<reponame>frank-qcd-qk/cepton_sdk_redist #!/usr/bin/env python3 import argparse import datetime import os import shutil import subprocess import sys from cepton_util.capture import * from cepton_util.common import * def main(): description = """ Clips camera, network, and ROS. Dependencies: ffmpeg, wireshark. ...
StarcoderdataPython
6662038
<reponame>haominhe/Graduate # CS 545 Machine Learning # Homework 3 SVMs and Feature Selection # <NAME> """ References: Lecture Slides https://archive.ics.uci.edu/ml/datasets/Spambase http://scikit-learn.org/stable/modules/preprocessing.html https://github.com/paolo215/CS445-ML https://github.com/asayles https://githu...
StarcoderdataPython
3535776
<gh_stars>1-10 import numpy as np import pandas as pd import utm # https://github.com/Turbo87/utm from pytransform3d import visualizer import open3d as o3d from slither.service import Service from slither.core.unit_conversions import convert_m_to_km def all_trackpoints(lat_range, lon_range): s = Service() df...
StarcoderdataPython
364375
<filename>1.py #!/usr/bin/env python3 -tt print(2+3) print("hello") print("after commit")
StarcoderdataPython
1976294
<reponame>tahigash/unicon.plugins<filename>src/unicon/plugins/iosxe/sdwan/__init__.py from unicon.plugins.iosxe import IosXESingleRpConnection, IosXEServiceList from unicon.plugins.iosxe.sdwan.statemachine import SDWANSingleRpStateMachine from unicon.plugins.iosxe.sdwan import service_implementation as svc from unico...
StarcoderdataPython
9790146
import json """ STEP1 Just loading JSON """ with open("sample_sig.json") as data_file: lst_sigdata = json.loads(data_file.read()) for dic_Asigdata in lst_sigdata: print(dic_Asigdata) print(dic_Asigdata["signature"]) lst_2bytetoken = dic_Asigdata["signature"].split()...
StarcoderdataPython
8140379
""" Working example of how to use a "robot" account. A robot account is a hidden super user, which communicates over OAuth1 - as if that super user had already authorized the application for access. The code below demonstrates how to do a GET, POST and DELETE request using the `requests` and `requests_oauthlib` libra...
StarcoderdataPython
9723245
<filename>conftest.py<gh_stars>0 import pytest from selenium import webdriver @pytest.fixture(scope='session') def browser(): driver = webdriver.Chrome(executable_path='./chromedriver.exe') yield driver driver.quit()
StarcoderdataPython
5170856
""" Test Case 6 Note that user input is always after the prompt 'Enter your move (for help enter "H"): ' """ """ Description: Just showing cells, eventual loss SIZE = 10, MINES = 10, random.seed(1) """ """ Test Case 1: Results Mines: 10 0123456789 0 XXXXXXXXXX 0 1 XXXXXXXXXX 1 2 XXXXXXXXXX 2 3 XXXXXXXXXX 3 4 XXXXXX...
StarcoderdataPython
9713958
from django.test import TestCase from django.core import signing from django.core.exceptions import SuspiciousOperation from django.http import HttpResponse from django.contrib.formtools.wizard.storage.cookie import CookieStorage from django.contrib.formtools.wizard.tests.storagetests import get_request, TestStorage ...
StarcoderdataPython
52488
# coding=utf-8 ''' accuracy:98% ''' import tensorflow as tf def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): return tf.nn.con...
StarcoderdataPython
6411595
# import midi_testing_stuff # A 4.7Kohm pullup between DATA and POWER is REQUIRED! import time import board from adafruit_onewire.bus import OneWireBus from adafruit_ds18x20 import DS18X20 # Initialize one-wire bus on board D5. ow_bus = OneWireBus(board.GP2) # Scan for sensors and grab them all devices = ow_bus.scan(...
StarcoderdataPython
8106873
import DataHandling as DH data = DH.LoadCSV('G:/Projects/Repos/data-vis-study/IncomeInequality.csv') # output javascript to an html file file = open("generatedMap.html", "w") file.write("<html>\n") file.write(" <head>\n") file.write(" <script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.j...
StarcoderdataPython
3241321
import two_lane_traffic as traffic import curses import time stdscr = curses.initscr() curses.noecho() curses.curs_set(0) curses.start_color() for i in range(1, 7): curses.init_pair(i, 7 - i, curses.COLOR_BLACK) t = traffic.Traffic(n = 100, density = .1, prob = .3) for i in range(1000): stdscr.clear() t.iterate(...
StarcoderdataPython
1768953
<reponame>konstantinKim/vd-backend from marshmallow_jsonapi import Schema, fields from marshmallow import validate from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy.exc import SQLAlchemyError db = SQLAlchemy(session_options={"autoflush": False}) class CRUD(): def add(self, resource): db.sess...
StarcoderdataPython
9708478
''' import modules ''' from PIL import Image import matplotlib.pyplot as plt from requests.api import head from wordcloud import WordCloud, wordcloud import numpy as np import requests import string from nltk import corpus stopwords=corpus.stopwords.words('english') bioText=[] '''url = "https://api.platform.iplt20.co...
StarcoderdataPython
3261683
from librespot.audio.storage.AudioFile import AudioFile from librespot.audio.storage.AudioFileStreaming import AudioFileStreaming from librespot.audio.storage.ChannelManager import ChannelManager
StarcoderdataPython
11312711
import abc from custodian.custodian import ErrorHandler, Validator #TODO: do we stick to custodian's ErrorHandler/Validator inheritance ?? class SRCErrorHandler(ErrorHandler): HANDLER_PRIORITIES = {'PRIORITY_FIRST': 0, 'PRIORITY_VERY_HIGH': 1, 'PRIORITY_HIGH':...
StarcoderdataPython
9728424
<gh_stars>0 # Generated by Django 3.1.2 on 2020-10-29 09:38 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
StarcoderdataPython
12843386
with open('matrix.txt', 'r') as m: n = m.read().split('\n') matrix = [i.split(',') for i in n] del matrix[-1] for index1, value1 in enumerate(matrix): for index2, value2 in enumerate(value1): matrix[index1][index2] = int(value2) row_pos = len(matrix)-1 ind_pos = len(matrix[row_pos])-1 while r...
StarcoderdataPython
1824652
print('Dê o valor de 7 pesos e descubra o maior e o menor entre eles') peso = float(input('Digite o valor do 1° peso: ')) while peso <= 0: peso = float(input('Valor inválido, por favor digite outro: ')) maior = peso menor = peso for c in range(0, 6): peso = float(input('Digite o {}° peso: '.format(c+2))) wh...
StarcoderdataPython
26995
# Generated from jsgParser.g4 by ANTLR 4.9 # encoding: utf-8 from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u77...
StarcoderdataPython
9656702
# (C) Datadog, Inc. 2019-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import pytest from mock import MagicMock from datadog_checks.ambari import AmbariCheck from datadog_checks.base import AgentCheck from datadog_checks.base.errors import CheckException from . import respo...
StarcoderdataPython
6545803
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 17 22:21:54 2018 @author: haithem.afli """ from gensim.models import Word2Vec from sklearn.decomposition import PCA from matplotlib import pyplot # define training data sentences = [['this', 'is', 'the', 'second', 'lecture', 'about', 'word2vec'], ...
StarcoderdataPython
40824
<gh_stars>0 # Generated by Django 3.2.5 on 2021-07-18 10:06 import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('arbeitsstunden', '0014_auto_20210705_1948'), ] operations = [ migrations.AlterF...
StarcoderdataPython
3459885
<gh_stars>1-10 """The alert module of the usecases package consists of all the interfaces and classes the describe the alert sending methods. It has an AlertSender interface which other concrete AlertSenders like InProcessAlertSender, MessageBrokerAlertSender, ExternalServiceAlertSEnder, etc implement. This package a...
StarcoderdataPython
8174621
<gh_stars>10-100 from torch import nn from criterions.common.perceptual_loss import PerceptualLoss import torch class Wrapper: @staticmethod def get_args(parser): parser.add('--dice_weight', type=float, default=1e-2) @staticmethod def get_net(args): criterion = Criterion(args.dice_wei...
StarcoderdataPython
11283017
<filename>parameters.py import argparse BOOL_MAP = { "true" : True, "false" : False } parser = argparse.ArgumentParser( description='Runs a learning example on a registered gym environment.' ) parser.add_argument( '--variant', default=None, type=str ) parser.add_argument(...
StarcoderdataPython
157784
from pathlib import Path import json folder = Path(__file__).parent.parent / 'others' / 'numpy_journey' out_folder = Path(__file__).parent.parent.parent / 'Desktop' / 'python_folder' def load_data(file): with file.open('r') as fr: data = json.load(fr) file_name = file.name.split('.')[0] wr...
StarcoderdataPython
9756936
<gh_stars>1000+ # -*- coding: utf-8 -*- from __future__ import unicode_literals import sys import subprocess from .exceptions import ProgramError def _subprocess_copy(text, args_list): p = subprocess.Popen(args_list, stdin=subprocess.PIPE, close_fds=True) p.communicate(input=text.encode('utf-8')) def copy...
StarcoderdataPython
8088519
<reponame>Tollanador/alias-free-gan import subprocess import os import gc import torch import pytest def clean_up(): gc.collect() torch.cuda.empty_cache() def test_trainer_from_scratch(): trainer_script_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../..', 'scripts/trainer.py') ...
StarcoderdataPython
9668113
<reponame>jreyes1108/antelope_contrib # -*- coding: utf-8 -*- # # """ Object Relational Mapper tools for Antelope Datascope """ from aug.contrib.orm.core import (Dbtuple, Relation, Connection) from aug.contrib.orm.dbobjects import (Dbrecord, DbrecordList) # Below this line for compatibility with previous versions from ...
StarcoderdataPython
1900806
import google.oauth2.credentials import json from RuleInteraction import RuleInteraction, RuleSet from googleapiclient.discovery import build from googleapiclient.errors import HttpError from google_auth_oauthlib.flow import InstalledAppFlow # TODO: You will need to change this to the location of your secrets file CL...
StarcoderdataPython
3352269
import pandas as pd import numpy as np from typing import Union from sklearn.utils import check_array from .transformer import TransformableList DTypeString = Union[type, str] class FeaturePipeline(object): """An pipeline for transforming observation data frames into features for learning.""" def __init...
StarcoderdataPython
3566349
from __future__ import annotations from pathlib import Path from ._ffi import ffi, lib from .metadata import Metadata from .task import Task __all__ = ["Server"] class Server: def __init__(self, db_filepath: Path): self._dcp_server = ffi.NULL self._dcp_server = lib.dcp_server_create(bytes(db_f...
StarcoderdataPython
4895034
<reponame>stanionascu/python-embyapi # coding: utf-8 """ Emby Server API Explore the Emby Server API # noqa: E501 OpenAPI spec version: 4.1.1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class DlnaDirectPlayProfile(ob...
StarcoderdataPython
9761721
<filename>OJ_Assignment/Ch02-Linear_List/1011.2.22.py class ListNode: def __init__(self, data, next = None): self.val = data self.nxt = next class LinkList: def __init__(self, headval): self.head = ListNode(headval) def reverse(self): p = self.head.nxt self.head.nxt =...
StarcoderdataPython
1963348
<gh_stars>10-100 # Copyright (C) 2021 <NAME>.V. All rights reserved. # Import ibapi deps from ibapi.client import EClient from ibapi.wrapper import EWrapper from ibapi.contract import * import threading import time class App(EWrapper, EClient): def __init__(self, ipaddress, portid, clientid): EClient.__...
StarcoderdataPython
5139263
<reponame>tobiashaefele1/datavis_clone """this module reads in a data object into the the Kreise table of the DB declare local temporary table `missing_value` ( missing_value KREISE not null ); """ import warnings import pymysql def index_column(column, cursor, table_name): """ Change specific column to ...
StarcoderdataPython
9618084
<filename>src/project/loader.py import os.path as osp from typing import List, Tuple, Union import pandas as pd import torch from rdkit import Chem from torch_geometric.data import Data, InMemoryDataset class GenFeatures(object): def __init__(self): self.symbols = [ 'B', 'C', 'N', 'O', 'F', '...
StarcoderdataPython
6444475
<reponame>skabrits/- from Analysys.pnn import Stalin3000_anal_probe from tqdm import notebook import torch import torch.utils.data as utils_data import numpy as np import matplotlib.pyplot as plt import csv import pprint from math import * BS = 4 class NumDs(utils_data.Dataset): def __init__(self, inp, outp): ...
StarcoderdataPython
4866950
<reponame>gagocarrilloedgar/python-starter grid = [ [3, 4, 5], [56, 7, 7], ] print(grid[0][0]) # Nested loop for row in grid: for col in row: print(col)
StarcoderdataPython
3528908
#custom_posts.py import os from libs.config import app from libs.classes import createFiles as createClass def init(name): #define config vars CUSTOM_POSTS_FOLDER = os.environ.get('CUSTOM_POSTS') custom_post_name = name plural = input('Plural Label: ').lower() singular = input('Singular Label: ').lower() slug =...
StarcoderdataPython
39961
<gh_stars>100-1000 from django import template from django.utils.encoding import force_str from django.utils.functional import keep_lazy from django.utils.safestring import SafeText, mark_safe from django.template.defaultfilters import stringfilter register = template.Library() _slack_escapes = { ord('&'): u'&amp...
StarcoderdataPython
9742617
data = [] class replier: global data def __init__(self, packName, room, isDebugChat): self.isDebugChat = isDebugChat self.packName = packName self.room = room self.data = data def clear(self): del data[:] def reply(self, msg): data.append(msg) print(data) class KakaoLink: glo...
StarcoderdataPython
6541566
from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path from .utils import just_redirect_by_name # common addresses urlpatterns = [ path("accounts/github/", include("github_auth.urls")), path("follow/", include("django_...
StarcoderdataPython
394320
from haystack.forms import SearchForm from haystack.query import EmptySearchQuerySet, SearchQuerySet from maintainer.models import Maintainer class MaintainerAutocompleteForm(SearchForm): def no_query_found(self): return EmptySearchQuerySet() def search(self): if not self.is_valid(): ...
StarcoderdataPython
6660554
from ctypes import * def test_a_string(dll): """ A testcase which accesses *values* in a dll. """ a_string = (c_char * 16).in_dll(dll, "a_string") assert a_string.raw == b"0123456789abcdef" a_string[15:16] = b'$' assert dll.get_a_string_char(15) == ord('$')
StarcoderdataPython
4956130
<filename>convert_model/convert_tf_model_temporal_to_tflite.py import tensorflow as tf import argparse parser = argparse.ArgumentParser() parser.add_argument("--model_name", type=str, default='covid19_model_temporal_mobilenetV1_for_N0_N1', nargs="?", ...
StarcoderdataPython
64487
<reponame>jbwexler/reproman # ex: set sts=4 ts=4 sw=4 noet: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the reproman package for the # copyright and license terms. # # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #...
StarcoderdataPython
365679
import datetime import json import os.path import pytest from freshdesk.v1.models import Ticket @pytest.fixture def ticket(api): return api.tickets.get_ticket(1) @pytest.fixture def ticket_json(): return json.loads(open(os.path.join(os.path.dirname(__file__), "sample_json_data", "ticket_1.json")).read()) ...
StarcoderdataPython
1738655
from django.contrib import admin from corehq.apps.reports.models import ReportsSidebarOrdering class ReportsSidebarOrderingAdmin(admin.ModelAdmin): list_display = ('domain', 'id') admin.site.register(ReportsSidebarOrdering, ReportsSidebarOrderingAdmin)
StarcoderdataPython
11388099
<gh_stars>0 import numpy as np from time import time import random # def standard_np_sample(num_classes, classes_per_episode): # start_time = time() # res = random.sample(range(num_classes), classes_per_episode) # end_time = time() # seconds_elapsed = end_time - start_time # assert len(res) == class...
StarcoderdataPython
3433061
import os import sys sys.path.insert(0, os.path.abspath('..')) # Expect unused import warnings as these imports just create linkage import bridge.Card as Card import bridge.Bid as Bid
StarcoderdataPython
8125738
"""Common methods utylized by the app."""
StarcoderdataPython
3437125
import argparse import datetime import gettext import json def print_list(old_file, new_file, style): with open(old_file, "r") as oldf: old_lists = json.load(oldf) oldf.close() with open(new_file, "r") as newf: new_lists = json.load(newf) newf.close() ...
StarcoderdataPython
3766
<gh_stars>0 # MIT License # # Copyright (c) 2019 Red Hat, Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mo...
StarcoderdataPython
5072113
# Copyright 2022 Google LLC. # # 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 writing, ...
StarcoderdataPython
151
"""Test for .prep.read module """ from hidrokit.prep import read import numpy as np import pandas as pd A = pd.DataFrame( data=[ [1, 3, 4, np.nan, 2, np.nan], [np.nan, 2, 3, np.nan, 1, 4], [2, np.nan, 1, 3, 4, np.nan] ], columns=['A', 'B', 'C', 'D', 'E', 'F'] ) A_date = A.set_inde...
StarcoderdataPython
11374457
<reponame>ststuck/usaspending-api from typing import List from decimal import Decimal from django.db.models import F from usaspending_api.accounts.models import TreasuryAppropriationAccount from usaspending_api.common.cache_decorator import cache_response from usaspending_api.disaster.v2.views.disaster_base import ( ...
StarcoderdataPython
3268185
<gh_stars>10-100 from .common import experimental from .repeat_testfile import *
StarcoderdataPython
1752355
import numpy as np import tensorflow as tf from copy import deepcopy from tf_rl.common.utils import create_checkpoint class DDPG: def __init__(self, ggnn, critic, node_info, num_action, params): self.params = params self.num_action = num_action self.eval_flg = False self.index_time...
StarcoderdataPython
8058950
""" CUB-200-2011 (Bird) Dataset""" import os import pdb from PIL import Image from torch.utils.data import Dataset from utils import get_transform from typing import List DATAPATH = './the-nature-conservancy-fisheries-monitoring' image_path = {} image_label = {} class FishDataset(Dataset): """ # Description:...
StarcoderdataPython
9731802
import os import pytest import janitor.biology @pytest.mark.biology def test_join_fasta(biodf): df = biodf.join_fasta( filename=os.path.join(pytest.TEST_DATA_DIR, "sequences.fasta"), id_col="sequence_accession", col_name="sequence", ) assert "sequence" in df.columns
StarcoderdataPython
8183610
import itertools import sys sys.path.append('/Users/rodrigobresan/Documents/dev/github/anti_spoofing/spoopy/spoopy') import json import os import pickle import numpy as np from sklearn.ensemble import BaggingClassifier from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import SVC #from classifier i...
StarcoderdataPython
9720896
<filename>kutana/backends/vkontakte/backend.py from random import random import asyncio import json import re import aiohttp from ...logger import logger from ...backend import Backend from ...update import ( ReceiverType, UpdateType, Update, Message, Attachment, ) from ...exceptions import RequestException NAIVE...
StarcoderdataPython
4925181
import numpy as np from astropy.table import Table import requests from PIL import Image from io import BytesIO import pylab import os import pandas as pd import matplotlib.pyplot as plt from astropy.io import fits from astropy import units as u from astropy.coordinates import SkyCoord import re from astro_ghost.PS1Que...
StarcoderdataPython
11239093
<reponame>CoderDream/python-best-practice sites = ["Baidu", "Google", "Runoob", "Taobao"] for site in sites: if site == "Runoob": print("菜鸟教程!") break print("循环数据 " + site) else: print("没有循环数据!") print("完成循环!")
StarcoderdataPython
1823293
import csv def write_to_csv(csv_data, csv_file, csv_columns): with open(csv_file, 'w', newline='\n') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) writer.writeheader() for data in csv_data: writer.writerow(data) def read_csv(cvs_file): file = open(c...
StarcoderdataPython
3438581
<filename>binding.gyp { 'targets': [ { 'target_name': 'uvcI2cDeviceBinding', 'defines': [ 'V8_DEPRECATION_WARNINGS=1' ], 'sources': [ 'UVCLinuxControl.cpp', 'UVCLinux.cpp', 'uvcI2cDevice.cpp', 'UVCLinuxControl.h', 'UVCLinux.h' ], 'libraries': [ '-ldl' ] } ] }
StarcoderdataPython
9763265
<filename>v1/tip_bot.py<gh_stars>0 import json import requests import subprocess from telegram.ext.dispatcher import run_async from telegram.ext import Updater with open('services.json') as conf_file: conf = json.load(conf_file) bot_token = conf['telegram_bot']['bot_token'] constant_url = conf['constant...
StarcoderdataPython
8023502
from django.shortcuts import render from .documents import PatentDocument from django.core.paginator import Paginator from django.contrib import messages from patent_search.models import Patentsview from django.db.models import Q import json with open('patent_word.txt') as word_file: word_data = json.load(word_fil...
StarcoderdataPython
1608258
<filename>metaworld/benchmarks/ml1.py<gh_stars>1-10 from metaworld.benchmarks.base import Benchmark from metaworld.envs.mujoco.multitask_env import MultiClassMultiTaskEnv from metaworld.envs.mujoco.env_dict import HARD_MODE_ARGS_KWARGS, HARD_MODE_CLS_DICT class ML1(MultiClassMultiTaskEnv, Benchmark): def __init_...
StarcoderdataPython
1716566
<gh_stars>0 import keras from keras import backend as K from keras.models import Sequential from keras.layers import Conv2D, BatchNormalization, ZeroPadding2D, Lambda, Layer import pickle import numpy as np import cv2 class LRN(Layer): def __init__(self, alpha=256,k=0,beta=0.5,n=256, **kwargs): super(LRN,...
StarcoderdataPython
4801347
<filename>src/grafimo/motif.py """Motif object definition. The motif PWM in JASPAR or MEME format is represented by the motif class in GRAFIMO. In a single motif object can be accessed the corresponding probability matrices, scaled score matrices, P-value matrices, etc. """ from grafimo.GRAFIMOException import NotVa...
StarcoderdataPython
151034
from glob import glob import os png_paths = glob('../data/bitmoji/*/*.png') npy_paths = glob('../data/bitmoji/*/*.npy') png_set = set([os.path.splitext(p)[0] for p in png_paths]) npy_set = set([os.path.splitext(p)[0] for p in npy_paths]) sym_diff = png_set ^ npy_set print len(sym_diff) print sym_diff
StarcoderdataPython
9658472
<reponame>gmwils/skritter # -*- coding: utf-8 -*- """Download user stats from Skritter as a CSV file $ python examples/progress_stats.py filename Note: requires environment variables set for OAuth client details, and for user authentication details. eg. export SKRITTER_OAUTH_CLIENT_NAME='<client name>' export...
StarcoderdataPython
119452
<reponame>ksvr444/daily-coding-problem class OrderLog: def __init__(self, size): self.log = list() self.size = size def __repr__(self): return str(self.log) def record(self, order_id): self.log.append(order_id) if len(self.log) > self.size: self.log = se...
StarcoderdataPython
3592266
<filename>site/views/api_views.py import flask import os import pandas from data.source import Endpoint, RequestMethod, DataView from services.select_services import get_objects, search_object from services.save_services import save_object import data.db_session as db_session import datetime import json from flask_logi...
StarcoderdataPython
5171373
<filename>examples/default/pybind11/run.py #! /usr/bin/env python import binder runner = binder.Runner() runner.msg = "I am running, am I?" runner.Run()
StarcoderdataPython
3461138
from .korail import SeatOption from .train import TrainType from .passenger import ( AdultPsg, TeenPsg, SeniorPsg, ChildPsg, BabyPsg, DisabilityAPsg, DisabilityBPsg, ) from .discount import ( YouthDisc, TeenDisc, MomDisc, BasicLive, FamilyDisc, StoGDisc, )
StarcoderdataPython
11257576
<gh_stars>1-10 #!/usr/bin/python # -*- coding: utf-8 -*- from thumbor.utils import logger from thumbor.result_storages import BaseStorage, ResultStorageResult from tornado.concurrent import return_future import boto3 from botocore.client import Config from io import BytesIO import re import magic import mimetypes cl...
StarcoderdataPython
9754300
# https://www.hackerrank.com/challenges/strange-advertising n = int(input().strip()) total_shown = 5 total_liked = 0 for i in range(n): liked = int(total_shown / 2) #print(liked, "out of", total_shown, "liked it on", i) total_liked += liked total_shown = liked * 3 print(total_liked)
StarcoderdataPython
9792035
<reponame>rajshrivastava/LeetCode # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def verticalOrder(self, root: TreeNode) -> List[List[int]]: ...
StarcoderdataPython
4984194
<filename>correctiv_nursinghomes/migrations/0004_auto_20160525_1639.py<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-25 14:39 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): de...
StarcoderdataPython
1896229
<reponame>ioanabirsan/python # Write a function that receives as a parameter the path to an xml document and an attrs dictionary and # returns those elements that have as attributes all the keys in the dictionary and values ​​the corresponding values. # For example, for the dictionary: # {"class": "url", "name": ...
StarcoderdataPython
3467771
<gh_stars>1-10 import unittest from harmony_tools.core import note_operations from harmony_tools import notes as n class TestCore(unittest.TestCase): def test_note_operations(self): self.assertEqual(note_operations.half_tone(n.A), n.A_sharp) self.assertEqual(note_operations.tone(n.A), n.B) ...
StarcoderdataPython
1811981
import random from matplotlib import pyplot from matplotlib import animation import agent_framework import csv import time n = 100 # number of agents k = 200 # number of iterations neighbourhood = 20 agents = [] environment = [] with open('in_example.txt', newline='\n') as f: reader = csv.reader(f, quoting=csv...
StarcoderdataPython
3311266
# coding=utf-8 import sys if 'sphinx' in sys.modules: WITH_MODELIO = False else: try: # noinspection PyUnresolvedReferences from org.modelio.api.modelio import Modelio WITH_MODELIO = True except: WITH_MODELIO = False if WITH_MODELIO: __all__ = [ # ... ...
StarcoderdataPython
240011
<gh_stars>10-100 import unittest from libpysal.examples import load_example import geopandas as gpd import numpy as np from segregation.singlegroup import MinMax class SpatialMinMax_Tester(unittest.TestCase): def test_SpatialMinMax(self): s_map = gpd.read_file(load_example("Sacramento1").get_path("sacrame...
StarcoderdataPython
367893
<reponame>shenshaoyong/recommender-system-dev-workshop-code<gh_stars>1-10 import redis import logging import pickle class RedisCache: news_type_news_ids = 'news_type_news_ids_dict' def __init__(self, host='localhost', port=6379, db=0): logging.info('Initial RedisCache ...') # Initial connec...
StarcoderdataPython
5108512
<reponame>diffgram/python-sdk<gh_stars>1-10 from ..regular.regular import refresh_from_dict class File(): """ file literal object See File Constructor for creating new files in Diffgram Service Feb 3, 2020. Perhaps should be all in the same File class. """ def __init__( self, ...
StarcoderdataPython
9760655
<reponame>levilelis/h-levin import tensorflow as tf import numpy as np from models.loss_functions import LevinLoss, CrossEntropyLoss,\ CrossEntropyMSELoss, LevinMSELoss, MSELoss, ImprovedLevinLoss,\ ImprovedLevinMSELoss, RegLevinLoss, RegLevinMSELoss class InvalidLossFunction(Exception): pass class Heuris...
StarcoderdataPython
1730165
# calculation tools from __future__ import division as __division__ import numpy as np # spot diagram rms calculator def rms(xy_list): x = xy_list[0] - np.mean(xy_list[0]) y = xy_list[1] - np.mean(xy_list[1]) # rms = np.sqrt(sum(x**2+y**2)/len(xy_list)) rms = np.hypot(x, y).mean() return rms
StarcoderdataPython
103017
<reponame>jupyterhub/builderhub<filename>conftest.py<gh_stars>0 """top-level pytest config options can only be defined here, not in binderhub/tests/conftest.py """ def pytest_addoption(parser): parser.addoption( "--helm", action="store_true", default=False, help="Run tests marked ...
StarcoderdataPython