id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1633098
<filename>test/test_jsonhash.py import subprocess import json import jsonhash DATA = [ {'a': 1}, {'a': 1, 'b': 2, 'c': 3, 'd': 4}, [1, 3, 2, 5, 43, 3, 1.25], {'a': 'just some dict', '1': [ 'with lists', 1, 'and intergeres', {'a': {'and even more': 'stuff', 'c': -1}} ]} ] code = "...
StarcoderdataPython
3371029
from .bbox_utils import * import numpy as np import torch def get_sum_XQ(grad, box_vertices, dataset_name, box_w, box_l, sign, high_rez=False, scaling_factor=1, grad_copy=None): """ Calculates XQ based on the sum of attributions, using the original attribution values :param high_rez: Whethe...
StarcoderdataPython
3282591
<filename>app.py #!/usr/bin/env python import click def change(amount): # calculate the resultant change and store the result (res) res = [] coins = [1, 5, 10, 25] # value of pennies, nickels, dimes, quarters coin_lookup = {25: "quarters", 10: "dimes", 5: "nickels", 1: "pennies"} # divide the am...
StarcoderdataPython
1773981
""" Algorithm: 1. Find out the minimum value 2. Swap minimum value to 0th position 3. Take sublist(except sorted part) and repeat step 1 and step 2 """ class SortArray: def __init__(self, arr): self.arr = arr def sort_array(self): for i in range(len(arr) - 1): arr_min = min(arr[i:...
StarcoderdataPython
196860
from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import ElectraModel, ElectraPreTrainedModel import torch.nn.functional as F from enum import Enum from bert_insert_model import BertInsertion from bert_delete_model_3 import BertDeletion from bert_replace_model_2 import BertReplace fr...
StarcoderdataPython
4802776
# -*- encoding: utf-8 -*- #!/usr/bin/python import numpy as np import phoebeBackend as phb # so it doesn't get confused with the new phoebe import pickle import sys import scipy.stats as st #from phoebe.atmospheres.roche import binary_potential #import phoebe.algorithms.marching as marching #from phoebe.utils.coordi...
StarcoderdataPython
3235031
<reponame>Hacker-1202/Selfium import asyncio from discord.ext import commands from app.vars.client import client from app.helpers import Notify from app.filesystem import ignore, error @client.command(aliases=['removeAllRoles']) @commands.guild_only() @commands.has_permissions(manage_channels=True) async def deleteAl...
StarcoderdataPython
107081
import cv2 as cv import numpy as np import time from timeit import repeat from multiprocessing import Pool import threading backSub = cv.createBackgroundSubtractorMOG2() # list to store clicked coordinates coords = [] # cut the given frame and rect with np array of coords def cut_image(frame, rect, pts): x,y,w...
StarcoderdataPython
3222963
# Copyright 2019 Gradient Health Inc. All Rights Reserved. # Author: <NAME> <<EMAIL>> # # 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 # # Un...
StarcoderdataPython
73084
from tool.runners.python import SubmissionPy class Target: def __init__(self, x_min, x_max, y_min, y_max): self.x_min = x_min self.x_max = x_max self.y_min = y_min self.y_max = y_max def has_missed(self, x, y, v_x, v_y): return x > self.x_max or (y < self.y_min and v_y...
StarcoderdataPython
109525
import unittest import os from xl_helper.Utils import Utils from tests.util.TestingUtils import TestingUtils class UtilsTest(unittest.TestCase): config = TestingUtils.get_test_config() downloads_username = config.get('downloads', 'username') downloads_password = config.get('downloads', 'password') ...
StarcoderdataPython
3371622
import os import json import pathlib import bpy import pprint from . import Global from . import NodeArrange from . import Versions from . import MatDct from . import Util from . import BumpToNormal # region top-level methods def srgb_to_linear_rgb(srgb): if srgb < 0: return 0 elif srgb < 0.04045: ...
StarcoderdataPython
1733615
# 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
1635215
<reponame>tonythott/tonnewcode<filename>tony-ds-readthroughtext.py<gh_stars>0 alice_file = open("alice.txt") #import alice.txt from internet as txt file words_count = {} for line in alice_file: words = line.split() for word in words : if words_count.get(word) == None: words_count[word] = 1 else: ...
StarcoderdataPython
3280558
<filename>nevow/flat/ten.py # Copyright (c) 2004 Divmod. # See LICENSE for details. import types import warnings from zope.interface import declarations, interface from twisted.python import compat import twisted.python.components as tpc from nevow import inevow from nevow import tags from nevow import util from n...
StarcoderdataPython
127291
import gym from gym.wrappers import TimeLimit env = TimeLimit(gym.make('gym_custom:pomdp-mountain-car-episodic-easy-v0'), max_episode_steps=15) print(env.observation_space.shape) print(env.action_space.shape) print(env.action_space.high) rewards = [] for i in range(1): state = env.reset() done = False ep...
StarcoderdataPython
3388419
import numpy as np from sklearn.base import BaseEstimator, TransformerMixin import pytz import dateutil.parser from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler class DeriveVariable(BaseEstimator, TransformerMixin): """ derive variables """ def __i...
StarcoderdataPython
76339
from marshmallow import ValidationError from marshmallow.fields import Field class PolyField(Field): """ A field that (de)serializes to one of many types. Passed in functions are called to disambiguate what schema to use for the (de)serialization Intended to assist in working with fields that can cont...
StarcoderdataPython
3378849
<filename>application/__init__.py<gh_stars>0 from .main import proc_main
StarcoderdataPython
3246438
# -*- coding: utf-8 -*- """Unittests for code in the board module. This module contains code to test the content of the pycheese.core.board module using pytest. """ def case_napoleon_attack() -> dict: """Test case for the boards `move` funtion. To test the function the follow chess game will be played: ...
StarcoderdataPython
3350066
from django.db import connection # https://stackoverflow.com/questions/1074212/how-can-i-see-the-raw-sql-queries-django-is-running def dump_queries(): qs = connection.queries for q in qs: print(q)
StarcoderdataPython
3375567
<filename>CUADERNOS DE TRABAJO/CUADERNO 3/ej 14 cuaderno 3 hasta -9999.py #<NAME> #Ejercicio 14 - Cuaderno 3 """ Escribe un programa que lea una serie de números enteros hasta que se introduzca el número -9999, y cuente el total de números introducidos, el total de valores positivos y el total de valores negativos (no...
StarcoderdataPython
3391200
<filename>weighted_mean_doctest.py import numpy as np def weighted_mean(dataset1, dataset2, weight1=1., weight2=5.): """Calculate a weighted mean of data items. Examples -------- >>> data1 = np.array([1., 2., 3.]) >>> data2 = np.array([2., 3., 4.]) >>> ans = np.array([4./3., ...
StarcoderdataPython
4834240
<reponame>LiquidNalee/MiniPkmnShowdown<gh_stars>0 from unittest import TestCase from models.game.battle.BattleGameState import BattleGameState from models.game.trainer.PokemonTrainer import PokemonTrainer from models.game.trainer.utils.ArenaBadge import ArenaBadge from models.pkmn.PokemonModel import PokemonModel from...
StarcoderdataPython
4805139
class A: def __init__(self,starting,finishing): self.starting=starting self.finishing=finishing def __lt__(self,other): #operator overloading to sort objects according to finish time return self.finishing < other.finishing class Find: def cal(self,start,finish): ...
StarcoderdataPython
3270449
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class CalendarItem(scrapy.Item): title = scrapy.Field() link = scrapy.Field() class WebItem(scrapy.Item): def __setitem__(self, key, v...
StarcoderdataPython
140001
<filename>challenges/solving_project_euler/imadken/imadken_22.py with open("p022_names.txt","r") as names: names = names.read().replace("\"","").split(",") names.sort() Sum = 0 length = len(names) for position in range(length): alphavalue=0 for j in names[position]: alphavalue += (ord(j)-64) Su...
StarcoderdataPython
134881
<reponame>olklymov/valkka-examples """<rtf> First, business as usual (and like in tutorial example 3) <rtf>""" import time from valkka.core import * glthread =OpenGLThread ("glthread") gl_in_filter =glthread.getFrameFilter() avthread =AVThread("avthread",gl_in_filter) av_in_filter =avthread.getFram...
StarcoderdataPython
1786905
import numpy as np ##################################################################################### # Python implementation of gausshermite.pro and lsf_gh.pro # # Reference: # # (1) https://github.com/callendeprieto/ferre/blob/master/src/lsf_gh.f90 # # (2) https://github.com/callendepriet...
StarcoderdataPython
1714971
from typing import Union from aioredis import Redis from aiogram.utils.json import json from tgbot.db.metrics import metrics_table class Repo: def __init__(self, db_conn, redis_conn: Redis): # db_conn, self._db_conn = db_conn self._redis_conn = redis_conn self._redis_pipeline = self._re...
StarcoderdataPython
1689178
from unittest import TestCase from tempfile import TemporaryDirectory from pathlib import Path from unittest import mock from io import StringIO from datetime import date as Date from busy.plugins.todo import Task from busy.commander import Commander class TestCommandAdd(TestCase): def test_by_parameter(self): ...
StarcoderdataPython
140471
<reponame>klinux/fab-oidc<filename>setup.py import os import sys from setuptools import setup, find_packages def fpath(name): return os.path.join(os.path.dirname(__file__), name) def read(fname): return open(fpath(fname)).read() def desc(): return read('README.md') setup( name='fab_oidc', ve...
StarcoderdataPython
160267
<gh_stars>1-10 # Problem 6 MIT Midterm # # The function isMyNumber is used to hide a secret number (integer). # It takes an integer guess as a parameter and compares it to the secret number. # It returns: # -1 if the parameter x is less than the secret number # 0 if the parameter x is correct # 1 if the parameter x is ...
StarcoderdataPython
1729066
<reponame>jordansatler/SNPtoAFS #!/usr/bin/env python """This script will convert a SNP output file from pyRAD to an input SNP file ready for use in AFS_FSC_total.py for conversion to an observed AFS. author: <NAME> date: 18 Jan 2016 python SNPtoAFSready.py file(s) """ import sys #dictionary of ambiguity codes a...
StarcoderdataPython
3238143
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # 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 agr...
StarcoderdataPython
144025
from math import ceil, floor from collections import Counter def mean(numLS): """ Finds the sum of a list of numbers and divided by the length of the list leaving the mean. """ return sum(numLS) / float(len(numLS)) def median(numLS): """ The middle value of a set of ordered data. """ ...
StarcoderdataPython
186537
import json from time import sleep from collections import deque from os import makedirs from os import path from dataflows import PackageWrapper, load, dump_to_path, Flow from kvfile import KVFile from datapackage import Package from dataflows_serverless.constants import * # runs the source_chain with steps marked a...
StarcoderdataPython
1661482
import cv2 import numpy as np class ImageProcessing: @staticmethod def __contour_is_bad(c): epsilon = 5.0 approx = cv2.approxPolyDP(c, epsilon, True) return len(approx) <= 3 @staticmethod def findContours(img, sort = True): im_copy = img.copy() gray = cv2.cvtCo...
StarcoderdataPython
1785315
<reponame>PaddlePaddle/PaddleCLS<filename>deploy/paddleserving/test_cpp_serving_client.py # Copyright (c) 2020 PaddlePaddle Authors. 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 ...
StarcoderdataPython
3248515
import socket from .thread import SocketThread class ListenThread(SocketThread): def before_actions(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(('', 5342)) s...
StarcoderdataPython
1669788
def firstOccurrence(src, pattern): # Write your code here start = i = j = 0 match = False while(i != len(pattern) - 1): print("start = ", start, ", patetrn char = ", pattern[i]) while(j < len(src)): # 如果為不為星號 # 有匹配到 if pattern[i] == "*" or pattern[i]...
StarcoderdataPython
3224756
r''' Copyright 2014 Google Inc. 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 i...
StarcoderdataPython
1721728
# Example Python script for automated API token rotation in combination # with a HashiCorp vault server import requests # CONFIGURATION # configure list of all secrets we want to rotate SECRETS = [ 'dynatrace/automation_script1', 'dynatrace/automation_script2' ] # HashiCorp vault information VAULT = 'http://YOUR_VA...
StarcoderdataPython
3217995
<reponame>jianzhnie/AutoTabular from autotabular.pipeline.components.base import AutotabularPreprocessingAlgorithm from autotabular.pipeline.components.feature_preprocessing.select_percentile import SelectPercentileBase from autotabular.pipeline.constants import DENSE, INPUT, SPARSE, UNSIGNED_DATA from ConfigSpace.conf...
StarcoderdataPython
3294358
<reponame>MichaelGoodale/opensauce-python<filename>tools/convert_json_to_mat.py # Script to convert json into proprietary .mat files # Licensed under Apache v2 (see LICENSE) import sys import os import glob import json from scipy.io import savemat def main(json_dir, out_dir): """ Script to convert all .json fil...
StarcoderdataPython
3373346
<filename>lib/blocks.py from pathlib import Path import dash_mantine_components as dmc from dash import dcc from lib.parser import load_example def IntroBlock(text): title, descr = text.split("|") layout = [ dmc.Text(title, style={"fontSize": 40, "fontWeight": 300}), dmc.Text( d...
StarcoderdataPython
3207710
<reponame>geospatial-services-framework/gsfpy ''' Created on Feb 1, 2016 @author: elefebvre ''' # Define the gsf implementation you want to use here. from .ese.server import Server from .ese.service import Service from .ese.task import Task from .ese.job import Job
StarcoderdataPython
84378
<filename>melissa/actions/imgur_handler.py import os import sqlite3 from datetime import datetime from imgurpython import ImgurClient # Melissa from melissa import profile from melissa.tts import tts WORDS = {'image_uploader': {'groups': ['upload']}, 'show_all_uploads': {'groups': [['all', 'uploads'], ...
StarcoderdataPython
1711952
""" Course units API forms """ from django.core.exceptions import ValidationError from django.forms import CharField, Form from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey class UnitListGetForm(Form): """ A form to validate query parameters in the course list retrieval endpo...
StarcoderdataPython
30590
import os import zipfile import zlib def make_rel_archive(a_parent, a_name): archive = zipfile.ZipFile("release/" + a_name + ".zip", "w", zipfile.ZIP_DEFLATED) def do_write(a_relative): archive.write(a_parent + a_relative, a_relative) do_write("F4SE/Plugins/" + a_name + ".dll") do_write("F4SE/Plugins/" + a_name...
StarcoderdataPython
118516
<filename>django_project/simple_django_logger/constants.py class Keys(): ERROR = 'ERROR' DEBUG = 'DEBUG' WARN = 'WARN' INFO = 'INFO' URL = 'url' TAG = 'tag' MESSAGE = 'message' LOG_LEVEL = 'level' REQUEST_METHOD = 'method' RESPONSE_STATUS = 'status' PAGE = 'page' SHOW = '...
StarcoderdataPython
1738253
from .Input import * from .LIF import * from .Output import *
StarcoderdataPython
1686497
import pytest import io from megastone import BufferMemory, ARCH_ARM, SegmentMemory, Memory, ISA_X86, MemoryAccessError, AccessType, ARCH_X86, MegastoneError, MappableMemory, Access from .conftest import TEMP_FILE_DATA SEG_NAME = 'seg' SEG_ADDRESS = 0x1000 SEG_SIZE = len(TEMP_FILE_DATA) INITIAL_DATA = b'A' * SEG_S...
StarcoderdataPython
1770170
<reponame>bogdanvuk/pygears from pygears.lib import qcnt, check, drv from pygears.typing import Uint, Queue drv(t=Queue[Uint[4]], seq=[[1, 2, 3, 4, 5]]) \ | qcnt \ | check(ref=[5])
StarcoderdataPython
3246900
<reponame>Deliangus/fiwGAN-ciwGAN<gh_stars>0 import tensorflow as tf print("Checking for GPU in list of system devices:") print("Num of GPUs available: ", len(tf.test.gpu_device_name()))
StarcoderdataPython
1629115
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'main_windowNew.ui' # # Created: Fri Apr 5 19:24:26 2013 # by: PyQt4 UI code generator 4.9.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except ...
StarcoderdataPython
125547
<reponame>coinmessage/coinmessage<gh_stars>1-10 import hashlib from base64 import b64encode, b64decode from pycoin.encoding import sec_to_public_pair, wif_to_secret_exponent from encrypt import PubKey, PrivKey, BasePoint from services import get_public_key_from_address, get_private_key_from_address def encrypt_messa...
StarcoderdataPython
1611757
<filename>accounts/migrations/0012_user__unsubscribe_key.py # Generated by Django 2.2.6 on 2019-11-11 02:40 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('accounts', '0011_user_is_premium_member'), ] operations = [ migratio...
StarcoderdataPython
29554
import tensorflow as tf from data_types.training_result import TrainingResult from data_types.training_set import TrainingSet from timeseries.build import compile_and_fit from timeseries.window_generator import WindowGenerator def evaluate_linear( training_set: TrainingSet ) -> TrainingResult: ## LINEAR ...
StarcoderdataPython
12234
<reponame>lucaruzzola/pyfunds from __future__ import annotations from abc import ABC, abstractmethod from typing import Callable, Generic, TypeVar T = TypeVar("T") U = TypeVar("U") class NoElement(Exception): pass class Option(ABC, Generic[T]): def __init__(self): super().__init__() @staticme...
StarcoderdataPython
1702844
from ariadne import ObjectType from django.db.models import QuerySet from core.graphql import GraphQLResolveInfo from core.models import Launch, User user = ObjectType("User") @user.field("trips") def resolve_user_trips(obj: User, info: GraphQLResolveInfo) -> QuerySet[Launch]: return obj.profile.trips.all()
StarcoderdataPython
3303253
<filename>berserker_resolver/utils.py import threading class LockedIterator(object): def __init__(self, it): self.lock = threading.Lock() self.it = it.__iter__() def __iter__(self): return self def __next__(self): self.lock.acquire() try: return self.i...
StarcoderdataPython
184967
from django.utils.translation import ugettext_lazy as _ from notification.backends.base import NotificationBackend from push_notifications.models import APNSDevice, GCMDevice import json import copy class MobileBackend(NotificationBackend): """ Mobile (IOS/Android) delivery backend. """ title = _("M...
StarcoderdataPython
3316116
<gh_stars>0 # coding: utf-8 from __future__ import unicode_literals from .box_object_collection import BoxObjectCollection class LimitOffsetBasedObjectCollection(BoxObjectCollection): """ An iterator of Box objects (BaseObjects) that were retrieved from a Box API endpoint that supports limit-offset type...
StarcoderdataPython
96348
import os from django.db import transaction import csv from django.core.management.base import BaseCommand, CommandError from api.models import Country def get_bool(value): if value == 't': return True elif value == 'f': return False else: return None def get_int(value): # pri...
StarcoderdataPython
3314405
<reponame>arpith-jacob/sandbox<filename>isl-poly/emitter.py import islpy as isl INT_FUN_TYPE = { '<': 'infix', '>': 'infix', '<=': 'infix', '>=': 'infix', '==': 'infix', '!=': 'infix', '&&': 'infix', '||': 'infix', '+': 'infix', '-': 'infix', '*': 'infix', '/': 'infix',...
StarcoderdataPython
4809456
"""Create progressions through a sequentially built graph.""" from typing import Any, Callable, Dict, List, Optional, Union from .selectors import first, last, randomness # noqa: F401 class DFSProgressor: """Progressor for Depth First Search.""" def __init__(self, graph: Optional[Dict[Any, Any]] = None) -...
StarcoderdataPython
1652201
import re from random import randrange def test_compare_home_edit_user_page(app): old_contacts = app.contact.count() index = randrange(old_contacts) contact_data_edit_page = app.contact.data_edit_page_index(index) contact_data_home_page = app.contact.get_contact_list()[index] assert clear(contact_d...
StarcoderdataPython
53546
import sys, inspect class Tutorial: flow = "TUTORIAL" type = "embed" title = "__TUTORIAL HELP__" colour = "green" def __init__(self, player=None): self.fields = (('Official Discord Server:', ''' https://discord.com/invite/discord-developers...
StarcoderdataPython
27623
from flask_wtf import FlaskForm from wtforms import StringField,PasswordField,SubmitField,BooleanField from flask_wtf.file import FileAllowed,FileRequired,FileField from wtforms.validators import DataRequired,Length,EqualTo,Email,ValidationError from App.models import User from App.extensions import file class Regist...
StarcoderdataPython
1718009
#No próximo final de semana seu time de futebol entrará em campo. #Escreva um programa que leia o seu nível de empolgação para a partida, #um número inteiro entre 1 e 10, #e mostre a empolgação do lado de fora do estádio #representando por letras “O” ao gritar GOL. #Por exemplo: Empolgação nível 1 >>> Gol! Empolga...
StarcoderdataPython
141412
# <NAME> 25/09/18 import datetime today = datetime.datetime.today() dayofweek = today.weekday() if dayofweek == 1: print("It's Tuesday!") else: print("Unfortunately, it's not Tuesday.")
StarcoderdataPython
95586
import numpy as np from util.gym import action_size from util.logger import logger from motion_planners.sampling_based_planner import SamplingBasedPlanner class PlannerAgent: def __init__( self, config, ac_space, non_limited_idx=None, passive_joint_idx=[], ignored_...
StarcoderdataPython
3395413
# %% import torch import math from UnarySim.stream.gen import RNG, SourceGen, BSGen from UnarySim.metric.metric import NormStability, NSbuilder import matplotlib.pyplot as plt import time import math # %% def worst_stb(dep_it=[6],threshold=0.05,mod="unipolar"): for dep in dep_it: plt.figure(figsize = (4,3)...
StarcoderdataPython
1658637
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2012 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # 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 L...
StarcoderdataPython
110886
import pytest from qtoggleserver.core.expressions import parse from qtoggleserver.core.expressions import UnknownFunction, UnbalancedParentheses, UnexpectedEnd, UnexpectedCharacter from qtoggleserver.core.expressions import EmptyExpression async def test_parse_complex_expression(num_mock_port1, num_mock_port2): ...
StarcoderdataPython
118698
import os class Config(object): ENABLE_USER_REGISTRATION = \ (os.getenv("ENABLE_USER_REGISTRATION").lower() == "true")
StarcoderdataPython
131348
from __future__ import print_function from __future__ import absolute_import from __future__ import division import os import compas_rhino from compas._os import remove_symlink __all__ = ['uninstall_plugin'] def uninstall_plugin(plugin, version=None): """Uninstall a Rhino Python Command Plugin. Paramete...
StarcoderdataPython
32876
from .utils import * from .models import * from .dna import *
StarcoderdataPython
3361833
######################################## # Automatically generated, do not edit. ######################################## from pyvisdk.thirdparty import Enum LinkDiscoveryProtocolConfigOperationType = Enum( 'advertise', 'both', 'listen', 'none', )
StarcoderdataPython
1612418
from data import Data from utils import data_corr if '__main__' == __name__: data = Data('../csv/train.csv', '../csv/test.csv') #data.train_disp() #data.test_disp() train = data.train test = data.test ntrain = train.shape[0] train_id = data.drop_train_id() test_id = data.drop_test_i...
StarcoderdataPython
3230068
<reponame>midas-research/calling-out-bluff import tensorflow as tf import data_utils from qwk import quadratic_weighted_kappa import time import os import sys import pandas as pd import numpy as np graph = tf.get_default_graph() essay_set_id = 1 num_tokens = 42 embedding_size = 300 num_samples = 1 is_regression = Fal...
StarcoderdataPython
3290928
<gh_stars>0 import tensorflow as tf config = tf.compat.v1.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.15 session = tf.compat.v1.Session(config=config) from flask import Flask, request, render_template from tensorflow.keras.models import load_model from skimage.transform import resize from ten...
StarcoderdataPython
3313719
<reponame>chrisdjscott/Atoman<filename>atoman/filtering/filters/acnaFilter.py """ Adaptive common neighbour analysis ================================== The ACNA calculator/filter performs the adaptive common neighbour analysis of Stutowski [1]_, which classifies an atom as either: 0. Disordered 1. FCC 2. HCP 3. BCC ...
StarcoderdataPython
45901
<filename>pythia/opal/weaver/BodyMill.py #!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute of Technology # (C) 1998-2005 All Rights Reserved # # {LicenseText} #...
StarcoderdataPython
1686485
# -*- coding: utf-8 -*- """ zang.connectors.conferences_connector ~~~~~~~~~~~~~~~~~~~ Module for communication with `SMS/Messages` endpoint """ from zang.connectors.base_connector import BaseConnector from zang.helpers.helpers import flatDict from zang.domain.sms_message import SmsMessage from zang.domain.list.sms_me...
StarcoderdataPython
1756229
<reponame>KennethSoelberg/AOS-Switch import pytest def test_get_snmpv3(client): print(client.snmpv3.get_snmpv3()) def test_get_snmpv3_users(client): print(client.snmpv3.get_snmpv3_users()) @pytest.mark.asyncio async def test_get_snmpv3_async(async_client): await async_client.snmpv3.get_snmpv3() @pyt...
StarcoderdataPython
74901
''' This code finds the synonyms of the words in search quesries. Returns "ForgetIt" if the search query consists of stop words only (e.g. search_query = 'or'), or no synomyms are found for the search query INPUT FILES: Hamid_data_trimmed/training_data_trimmed.csv Hamid_data_trimmed/test_data_trimmed.csv OUTPUTS: al...
StarcoderdataPython
4800012
<filename>stay_awake.py<gh_stars>0 import time import pyautogui from datetime import datetime from pynput import keyboard, mouse from threading import Thread pyautogui.FAILSAFE = False MAX_NON_ACTIVE_TIME = 600 # in seconds LAST_ACTIVITY_TIME = time.time() LAST_MOUSE_POSITION = mouse.Controller().position def acti...
StarcoderdataPython
43659
import json from pprint import pprint filename = "readfile_4.json" with open(filename) as f: readdata = json.load(f) new_dict = {} for a_keys, a_values in readdata.items(): if a_keys == "ipV4Neighbors": for nei_list in a_values: for nei_keys, nei_values in nei_list.items(): ...
StarcoderdataPython
3373158
<gh_stars>1-10 from integration.helpers.base_test import BaseTest class TestFunctionWithSns(BaseTest): def test_function_with_sns_bucket_trigger(self): self.create_and_verify_stack("combination/function_with_sns") sns_client = self.client_provider.sns_client sns_topic_arn = self.get_phys...
StarcoderdataPython
183412
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from six.moves import xrange from wtte import transforms as tr def timeline_plot(padded, title='', cmap="jet", plot=True, fig=None, ax=None): if fig is ...
StarcoderdataPython
18845
from flask import render_template, Flask, flash, redirect, url_for, abort, request from flask_login import login_user, logout_user, login_required from werkzeug.urls import url_parse from app import app, db from app.forms import * from app.models import * @app.route('/') @app.route('/landing') def landing(): ret...
StarcoderdataPython
3277652
# Copyright (c) 2021 Microsoft Corporation. Licensed under the MIT license. # Written by <NAME>, <EMAIL> from .longformer2d import Long2DSCSelfAttention from .performer import FastAttention, PerformerSelfAttention from .linformer import LinformerSelfAttention from .srformer import SRSelfAttention
StarcoderdataPython
1715440
<reponame>gmr/pglifecycle # coding=utf-8 """Common constants and shared methods""" import logging import sys LOGGER = logging.getLogger(__name__) def exit_application(message=None, code=0): """Exit the application displaying the message to either INFO or ERROR based upon the exist code. :param str messa...
StarcoderdataPython
1761953
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Jan 21 15:53:23 2019 @author: gaomingda """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import defaultdict import cv2 import date...
StarcoderdataPython
1724783
# -*- coding: utf-8 -*- # This software is distributed under the two-clause BSD license. import unittest from volatildap import core # A valid LDIF. # Note that entries are sorted by increasing DN length, then by alphabetical # DN order. # Attributes are sorted in alphabetical order. VALID_LDIF = b"""version: 1 dn:...
StarcoderdataPython
4838445
<gh_stars>0 import os import subprocess from subprocess import PIPE, Popen import json import time import shutil import zmq import joe_destination def move(data): print("Module imported.") print(data) paths = joe_destination.get_dest(data) orig = paths[0] dest = paths[1] folder_del = paths[...
StarcoderdataPython
88989
# Generated by Django 2.2.12 on 2020-05-18 11:43 import account.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0005_auto_20200518_1120'), ] operations = [ migrations.AlterField( model_name='userprofile', ...
StarcoderdataPython
1757783
import re from typing import Union KEYSEPARATOR = "/" ID_REGEX = r"[1-9]\d*" ID_PATTERN = re.compile(ID_REGEX) class Collection: """ The first part of a full qualified field (also known as "key"), e. g. motion_change_recommendation. """ def __init__(self, collection: str) -> None: self....
StarcoderdataPython