id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
3066
""" tweet stuff in intervals """ import time import datetime import twitter from markov_chains import german_text from config import config_no, config_yes MAX_TWEET_LENGTH = 280 greeting = ' Sehr geehrte/r Anstragssteller/in.' ending = ' MfG' num_tweets = 3 class FoiaBot: def __init__(self, config): s...
StarcoderdataPython
9767860
from .templates import ContextControl, ContextValue, Data, QuickReply from .buttons import BlockButton, MessageButton, PhoneButton, WeblinkButton, ShareButton from .simples import SimpleText, SimpleImage from .cards import BasicCard, CommerceCard, ListCard, Carousel, ListItem from .commons import CarouselHeader, Link, ...
StarcoderdataPython
1690480
import os # Import os and sys python modules from api import create_app # import create_app fxn for api(local) module config_name = os.getenv("APP_SETTINGS") # Get the app settings defined in the .env file app = create_app(config_name) # defining the configuration to be used if __name__ == "__main__": # the interpr...
StarcoderdataPython
6445920
<filename>tests/test_objects.py import unittest @unittest.skip("showing class skipping") class MySkippedTestCase(unittest.TestCase): def test_not_run(self): pass
StarcoderdataPython
122694
<gh_stars>1-10 import numpy as np import os import csv import librosa from scipy.signal import lfilter import matplotlib.pyplot as plt import pandas as pd attribute_file = 'attribute/train_zsl_linear.csv' dataroot = 'train_zsl_linear' if os.path.isdir(dataroot) == False: os.makedirs(dataroot) data = pd.read_csv...
StarcoderdataPython
4935365
<filename>ivf/scene/layer.py # -*- coding: utf-8 -*- ## @package ivf.scene.layer # # ivf.scene.layer utility package. # @author tody # @date 2016/01/27 import numpy as np from ivf.scene.data import Data class Layer(Data): ## Constructor def __init__(self, name="", color=(1.0, 0.0, 0.0, 0.4), ...
StarcoderdataPython
3418270
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Implements a simple service using cx_Freeze. See below for more information on what methods must be implemented and how they are called. """ import threading class Handler(object): # no parameters are permitted; all configuration should be placed in the # c...
StarcoderdataPython
6705673
<filename>{{cookiecutter.project_type}}/__cc_fastAPI/{{cookiecutter.directory_name}}/app/src/api/endpoints/user.py import datetime as dt from typing import Any, List from fastapi import APIRouter, Depends, HTTPException # from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from app.src.db...
StarcoderdataPython
8101851
<reponame>l3p-cv/lost_ds<gh_stars>1-10 from shapely.geometry import Point as Pt, MultiPoint import numpy as np import cv2 from lost_ds.geometry.api import Geometry from lost_ds.vis.geometries import draw_points class Point(Geometry): def __init__(self): super().__init__() def to_shapely(self, ...
StarcoderdataPython
3472037
<filename>test/mocks.py import json import shutil import os import cdsapi class CDSClientMock: """A simple mock of the cdsapi.Client class This mock class uses predefined requests from on-disk JSON files. When the retrieve method is called, it checks if the request matches one of these known reques...
StarcoderdataPython
3419788
<reponame>team-oss/dspg20oss #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 20 19:47:13 2020 @author: dnb3k """ lesserCompanies=multiCoWorkerTable.iloc[15000:-1] lesserCompanies['guesses']="" import difflib df['Name_r'] = df.Name_x.map(lambda x: (difflib.get_close_matches(x, dfF.Name)[:1] or ...
StarcoderdataPython
203838
<filename>sentry/commands/manage.py<gh_stars>0 """ sentry.commands.manage ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from sentry.commands.utils import consume_args @consume_args def manage(args): from django.core....
StarcoderdataPython
12801463
<gh_stars>0 class Person(): # 创建一个类 def __init__(self, name): # 定义初始化信息。 self.name = name __slots__ = ('name', 'age') li = Person('李') # 实例化Person('李'),给变量li li.age = 20 # 再程序没有停止下,将实例属性age传入。动态语言的特点。 Person.age = None # 这里使用类名来创建一个属性age给类,默认值是None。Python支持的动态属性添加。 li.ss = 222
StarcoderdataPython
6608611
while 1: try: print(input()) except: break;
StarcoderdataPython
5026813
<filename>usaspending_api/common/retrieve_file_from_uri.py import boto3 import io import requests import tempfile import urllib from shutil import copyfile from django.conf import settings VALID_SCHEMES = ("http", "https", "s3", "file", "") SCHEMA_HELP_TEXT = ( "Internet RFC on Relative Uniform Resource Locators...
StarcoderdataPython
1948481
import socket import sys import time port = int(sys.argv[1]) conn = socket.socket() conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) conn.bind( ('localhost', port)) conn.listen(500) while 1: client = conn.accept()[0] client.recv(32 * 1024) client.send( 'HTTP/1.0 200 OK\r\n' 'Cont...
StarcoderdataPython
6554158
<filename>ros/src/twist_controller/test_twist_controller.py from unittest import TestCase from twist_controller import Controller import numpy as np PKG = 'twist_controller' class TestTwistController(TestCase): def setUp(self): v_mass = 1736.35 decel_limit = -5.0 wheel_radius = 0.2413 ...
StarcoderdataPython
1618546
<gh_stars>1-10 class Loader: def __init__(self, sample_rate, duration, mono): self.sample_rate = sample_rate self.duration = duration self.mono = mono def load(self, file_path): signal = librosa.load(file_path, sr=self.sample_rate, ...
StarcoderdataPython
6509926
#!/usr/bin/env runaiida # -*- coding: utf-8 -*- from __future__ import print_function from aiida.orm.data.bool import Bool from aiida.orm.data.float import Float from aiida.orm.data.int import Int from aiida.work import run from complex_parent import ComplexParentWorkChain if __name__ == '__main__': result = run(...
StarcoderdataPython
3324115
<gh_stars>100-1000 from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.db import models from django.utils.translation import gettext_lazy as _ from .fields import TreeNodeForeignKey from .query import TreeQuerySet class TreeNode(models.Model): parent = TreeNode...
StarcoderdataPython
4940805
<filename>tensorbackends/extensions/rsvd.py from ..utils.svd_absorb_s import svd_absorb_s def rsvd(backend, a, rank, niter, oversamp, absorb_s): dtype = a.dtype m, n = a.shape r = min(rank + oversamp, m, n) # find subspace q = backend.random.uniform(low=-1.0, high=1.0, size=(n, r)).astype(dtype) ...
StarcoderdataPython
5104631
<filename>themessage_server/themessage_server_test.py import os import themessage_server def test_themessage_server_has_current_version_of_module(): with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'version.txt')) as version_file: assert themessage_server.__version__ == version_file.rea...
StarcoderdataPython
4966358
<reponame>agustingianni/CoverageReport<filename>report.py<gh_stars>1-10 #!/usr/bin/env python import re import os import sys import logging import argparse import subprocess import collections class CoverageReport(object): def __init__(self, dr_path, output, path_maps, src_filter, debug_level=0): # Tools ...
StarcoderdataPython
6440959
<gh_stars>0 import os import logging import logging.config from pythonjsonlogger import jsonlogger from datetime import datetime; import boto3 import requests import time from botocore.client import Config from botocore.exceptions import ClientError from os import listdir from os.path import isfile, join class ElkJson...
StarcoderdataPython
11304650
from __future__ import annotations import multiprocessing import os from dataclasses import asdict from dataclasses import dataclass from typing import Any from typing import Tuple from typing import Union import numpy as np import pandas as pd from PIL import Image from CCAgT_utils.categories import Categories from...
StarcoderdataPython
61903
""" Generate all synonymous mutants for a input protein <NAME> """ # Ensure Python 2/3 compatibility from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import itertools import argparse import sys from signal import signa...
StarcoderdataPython
266731
#!/bin/python import i3ipc i3 = i3ipc.Connection() splitv_text = '' splith_text = '' split_none = '' parent = i3.get_tree().find_focused().parent if parent.layout == 'splitv' : print( splitv_text ) elif parent.layout == 'splith' : print( splith_text ) else : ...
StarcoderdataPython
1817059
""" Reads a stream from a stream (files) @author rambabu.posa """ from pyspark.sql import SparkSession import logging logging.debug("-> start") # Creates a session on a local master spark = SparkSession.builder.appName("Read lines from a file stream") \ .master("local[*]").getOrCreate() df = spark.readStre...
StarcoderdataPython
5134402
from matplotlib import pyplot as plt import numpy as np import pandas as pd class GraphProcessor: def __init__(self, dataframe: pd.DataFrame, cols=[]): if dataframe is None or not cols: raise Exception("Dataframe must not be None or Cols is empty") self.data_frame = dataframe ...
StarcoderdataPython
9627167
<reponame>VladimirsHisamutdinovs/Advanced_Python_Operations import requests def main(): # url = 'http://httpbin.org/xml' # res = requests.get(url) # print_results(res) # url_post = 'http://httpbin.org/post' # data_vals = { # 'key1': 'Ave', # 'key2': 'Coder' # } ...
StarcoderdataPython
8023999
<filename>tests/test_stream.py from __future__ import print_function import io import sys import pytest import progressbar def test_nowrap(): # Make sure we definitely unwrap for i in range(5): progressbar.streams.unwrap(stderr=True, stdout=True) stdout = sys.stdout stderr = sys.stderr ...
StarcoderdataPython
5048462
<gh_stars>0 # You are given a list of n-1 integers and these integers are in the range of 1 to n # There are no duplicates in the list. One of the integers is missing in the list # Write an efficient code to find the missing integer. arry = [1,2,3,5,4,8,6,7,10,9,12,13,16,15,14]
StarcoderdataPython
3230610
import datetime from json import loads, JSONDecodeError import re from .net.http import ApiRequester from .models.response import Response from .models.request import Fields from .exceptions.error import ParameterError, EmptyApiKeyError, \ UnparsableApiResponseError class Client: __default_url = "https://reg...
StarcoderdataPython
3373551
<filename>scripts/type_extractor/tests/merge_files_tests.py """Unit tests for the merge_files module.""" import json import unittest from type_extractor.merge_files import choose_one_type from type_extractor.merge_files import merge_functions from type_extractor.merge_files import merge_types class ChooseOneTypeTes...
StarcoderdataPython
1997307
<gh_stars>1-10 """""" """ Copyright (c) 2021 <NAME> as part of Airlab Amsterdam 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 Unl...
StarcoderdataPython
49410
<filename>qnarre/prep/tokens/perceiver.py<gh_stars>0 # Copyright 2022 Quantapix 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 License at # # http://www.apache.org/lic...
StarcoderdataPython
1978849
<filename>open_discussions_api/utils_test.py<gh_stars>0 """Tests for api utils""" import jwt import pytest from open_discussions_api.utils import get_token def test_get_token(): """Test that get_token encodes a token decodable by the secret""" token = get_token( 'secret', 'username', ...
StarcoderdataPython
6549839
#------------------------------------------------------------------------------# # hsd: package for manipulating HSD-formatted data # # Copyright (C) 2011 - 2020 DFTB+ developers group # # ...
StarcoderdataPython
4935546
<reponame>wilsaj/flask-admin-old import sys from flask import Flask, redirect from flask.ext import admin from flask.ext.admin.datastore.sqlalchemy import SQLAlchemyDatastore from sqlalchemy import create_engine, Table from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import decl...
StarcoderdataPython
6556940
<gh_stars>1-10 # Generated by Django 3.1.6 on 2021-02-20 01:06 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='City', fields=[ ('id', model...
StarcoderdataPython
364548
<filename>main.py from torchvision.transforms import transforms #from RandAugment import RandAugment import RandAugment normalize = transforms.Normalize(mean=[x / 255.0 for x in [125.3, 123.0, 113.9]], std=[x / 255.0 for x in [63.0, 62.1, 66.7]]) transform_train = transforms.Compose([...
StarcoderdataPython
1799832
<reponame>titikid/mmsegmentation<gh_stars>1-10 from .builder import DATASETS from .custom import CustomDataset @DATASETS.register_module() class publaynet_split1Dataset(CustomDataset): """table_structure1 """ # CLASSES = ('title', 'text', 'figure', 'table', 'list') # PALETTE = [[50, 255, 0],[255, 0, 0...
StarcoderdataPython
12808500
<filename>aiotunnel/tunnel.py<gh_stars>10-100 # BSD 3-Clause License # # Copyright (c) 2018, <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain...
StarcoderdataPython
3319026
<filename>Idat_Python2022/Semana_6/PRACTICA/1_EJERCICIO.py<gh_stars>0 """Analizar los siguientes ejercicios de condiciones, representarlos mediante algoritmos en Python. """ #1.-Leer 2 números; si son iguales que los multiplique, si el primero es mayor que el segundo que los reste y si no que los sume. Numero01=int(inp...
StarcoderdataPython
3531796
class Solution: def alienOrder(self, words: List[str]) -> str: child = collections.defaultdict(set) parent = collections.defaultdict(int) chars = set() for w1,w2 in zip(words[:-1], words[1:]): if len(w1)>len(w2) and w1[:len(w2)] == w2: ##invalid case['abc', 'ab'] ...
StarcoderdataPython
8027244
<gh_stars>10-100 # -*- coding: utf-8 -*- __author__ = '<NAME>' __copyright__ = 'Copyright (C) 2019, Nokia' __email__ = '<EMAIL>' import pytest from moler.exceptions import CommandFailure from moler.cmd.unix.unzip import Unzip def test_unzip_returns_fail(buffer_connection): """ Test if proper alarm is raised...
StarcoderdataPython
11360373
from django.db import models from django.urls import reverse from django.utils import timezone from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill from uuslug import uuslug class Tag(models.Model): name = models.CharField(max_length=48) def __str__(self): return s...
StarcoderdataPython
11396213
from base64 import b64encode import googleapiclient.discovery from oauth2client.client import GoogleCredentials # Change this values to match your project IMAGE_FILE = "text.png" CREDENTIALS_FILE = "credentials.json" # Connect to the Google Cloud-ML Service credentials = GoogleCredentials.from_stream(CREDENTIALS_FIL...
StarcoderdataPython
9757240
from datetime import datetime from typing import Optional import mongoengine as ME # type: ignore[import] from mongoengine.queryset.visitor import Q # type: ignore[import] class ProductBooking(ME.Document): """Model for storing product booking information "...
StarcoderdataPython
8132307
import setuptools from setuptools import setup LONG_DESCRIPTION = \ '''Converts nifti files (raw and mask) and mrtrix tck files to DICOM format readable by Brainlab surgical planning and navigation systems. Tck files are converted to 3D objects that can be manipulated by Brainlab tools. Label images are converted to a...
StarcoderdataPython
6646065
<filename>LeetCode/top_interview_easy/array/array_08.py class Solution: def moveZeroes(self, nums: List[int]) -> None: # assign non-zero elements in increasing order # remember the number of non-zero elements non_zero = 0 for i in nums: if i != ...
StarcoderdataPython
8009019
<filename>tests/test_scaler.py from unittest import TestCase from fffw.scaler import Scaler class ScalerTestCase(TestCase): """ Tests for scaling helpers class.""" def test_scaler(self): """ Scaler smoke test and feature demo * Source video 1280x960, square pixels * Scaled to 640x480...
StarcoderdataPython
4914076
"""GaussianFeaturesWithKmenasテストケース Copyright (c) 2020, <NAME>, All rights reserved. """ import unittest import numpy as np import pandas as pd from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler from numpy.testing import assert_array_equal from gauss_kmeans import GaussianFeaturesW...
StarcoderdataPython
11309642
import numpy as np from .wrap.array_data import ArrayData from .wrap import array_ops from . import elementwise from . import base from . import helpers class ndarray(object): def __init__(self, shape, dtype=None, np_data=None, array_data=None, array_owner=None): shape = helpers.require_i...
StarcoderdataPython
11237895
""" Imagine you are constructing roads, you need to figure out how many of them are connected""" # Interesting practical application class DisjointSetUnionFast: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.num_sets = n def find(self, a): acopy = ...
StarcoderdataPython
6648958
<reponame>matthiasrohmer/grow """Grow local development server.""" import logging import mimetypes import os import re import sys import traceback import urllib import jinja2 import webob # NOTE: exc imported directly, webob.exc doesn't work when frozen. from webob import exc as webob_exc from werkzeug import routing ...
StarcoderdataPython
12827022
# -------------- import pandas as pd from collections import Counter # Load dataset data = pd.read_csv(path) data.isnull().sum() # -------------- import seaborn as sns from matplotlib import pyplot as plt sns.set_style(style='darkgrid') # Store the label values label = data.iloc[:,-1] label.head(5) sns.countplot(d...
StarcoderdataPython
8145710
# Codejam 2021, Qualification Round: Median Sort import sys def query(*x): print(*x, sep=" ", flush=True) response = input() if response == '-1': sys.exit() return int(response) def split_list(L, pivots): left, middle, right = [], [], [] while L: val = L.pop() media...
StarcoderdataPython
6478706
import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from .models import Message class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): ''' Connect to a chat room ''' # Get and initialize variables self.room_name ...
StarcoderdataPython
9792657
#!/usr/bin/env python import torch import torch.nn as nn from colossalai.nn import CheckpointModule from .utils.dummy_data_generator import DummyDataGenerator from .registry import non_distributed_component_funcs class NetWithRepeatedlyComputedLayers(CheckpointModule): """ This model is to test with layers w...
StarcoderdataPython
9789277
<filename>installer/lambda_function.py """ Installs the AWS Integration bundle on the target Reveal(x) and creates an Open Data Stream endpoint to Amazon SNS. """ # COPYRIGHT 2020 BY EXTRAHOP NETWORKS, INC. # # This file is subject to the terms and conditions defined in # file 'LICENSE', which is part of this source c...
StarcoderdataPython
6571429
"""Test cases for Multitrack class.""" import numpy as np from pytest import fixture from pypianoroll import BinaryTrack, Multitrack, StandardTrack from .utils import multitrack def test_repr(multitrack): assert repr(multitrack) == ( "Multitrack(name='test', resolution=24, " "downbeat=array(shap...
StarcoderdataPython
1875214
<reponame>MingboPeng/honeybee-schema from honeybee_schema.energy.simulation import SimulationParameter import os # target folder where all of the samples live root = os.path.dirname(os.path.dirname(__file__)) target_folder = os.path.join(root, 'samples', 'simulation_parameter') def test_detailed_simulation_par(): ...
StarcoderdataPython
6642201
from flask import Flask,make_response,request,jsonify app = Flask(__name__) @app.route('/peticion_get',methods=['GET']) def peticion_get(): if request.method=='GET': return "Es una petición GET" @app.route('/peticion_post',methods=['POST']) def peticion_post(): if request.method=='POST': usuario=request.form....
StarcoderdataPython
4853098
from django.conf.urls import url from . import views urlpatterns = [ url(r'^customer/$', views.CustomerList.as_view()), url(r'^customer/(?P<pk>[0-9]+)/$', views.CustomerDetail.as_view()), ]
StarcoderdataPython
5173723
import math import torch from torch.nn import Module, Parameter import torch.nn.init as init import torch.nn.functional as F class _BayesBatchNorm(Module): r""" Applies Bayesian Batch Normalization over a 2D or 3D input Arguments: prior_mu (Float): mean of prior normal distribution. prio...
StarcoderdataPython
4830855
<filename>plugins/zenhub/komand_zenhub/actions/get_issue_events/schema.py # GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Component: DESCRIPTION = "Get the ZenHub Events for a GitHub Issue" class Input: ISSUE_NUMBER = "issue_number" REPO_ID = "repo_id" class Output: EVE...
StarcoderdataPython
11218722
<reponame>Miryad3108/schema.data.gouv.fr BASE_DOMAIN = "https://schema.data.gouv.fr" VALIDATION_DOC_URL = "https://schema.data.gouv.fr/documentation/validation-schemas"
StarcoderdataPython
3558369
<filename>models.py<gh_stars>0 """ 모델을 빌드한다. """ import tensorflow as tf import options as opt def build_model(): # 모델을 반환한다. model = tf.keras.Sequential([ tf.keras.layers.Input(shape=(opt.SIGHT, 1)), tf.keras.layers.LSTM(16, return_sequences=True, dropout=0.2), tf.keras.la...
StarcoderdataPython
349117
n = int(input("Enter n: ")) x = 2 y = 2 x1 = 0 flag = False ''' Gives false at 2 and 3 because powers start from 2''' if n == 1: print("Output: True\n" + str(n) + " can be expressed as " + str(1) + "^(0, 1, 2, 3, 4, 5, ......)") else: while x <= n: #print(x) while x1 < n: ...
StarcoderdataPython
8193997
<reponame>MSAdministrator/art-parser import os from ..core import Core from jinja2 import Template from pyattck import Attck class Base(Core): atomic_markdown_template = os.path.join( os.path.abspath( os.path.dirname(os.path.dirname(__file__)) ), 'data', 'atomic_doc...
StarcoderdataPython
12831600
<filename>distribution.py """ distribution.py Author: <NAME> Credit: https://developers.google.com/edu/python/sorting Assignment: Write and submit a Python program (distribution.py) that computes and displays the distribution of characters in a given sample of text. Output of your program should look like this: Pl...
StarcoderdataPython
1916900
""" Wrap up PostgreSQL and PostGIS into a convenient class. Examples -------- Create a database and import a shapefile: >>> import postgis_helpers as pGIS >>> db = pGIS.PostgreSQL("my_database_name") >>> db.create() >>> db.import_geodata("bike_lanes", "http://url.to.shapefile") >>> bike_gdf = db....
StarcoderdataPython
1629244
#!/usr/bin/env python # encoding: utf-8 from .converter import Csv2Weka # noqa from .version import __version__ # noqa __all__ = ['Csv2Weka', '__version__']
StarcoderdataPython
3267967
<filename>gravity/state.py """ Classes to represent and manipulate gravity's stored configuration and state data. """ import enum import errno import yaml from gravity.util import AttributeDict class GracefulMethod(enum.Enum): DEFAULT = 0 SIGHUP = 1 class Service(AttributeDict): service_type = "servic...
StarcoderdataPython
5096805
<reponame>rdg7739/coronavirus_bot from .app import CoronaBot if __name__ == '__main__': CoronaBot.run()
StarcoderdataPython
8177916
from django.shortcuts import render,redirect,get_object_or_404 from django.contrib.auth.models import User from django.http import HttpResponse from django import template def tags(request): return render(request,'tags/index.html')
StarcoderdataPython
9798543
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved. # # This work is made available under the Nvidia Source Code License-NC. # To view a copy of this license, check out LICENSE.md import os import requests import torch.distributed as dist import torchvision.utils from imaginaire.utils.distributed import is...
StarcoderdataPython
6606738
<gh_stars>100-1000 import redis import json from util.utils import login_expire class RedisUtil(object): def __init__(self): self.client = redis.Redis() def check_user_registered(self, user): return self.client.sadd('qa_system:user:duplicate', user) == 0 def save_session(self, session_id...
StarcoderdataPython
3568869
############################################### #### Written By: <NAME> #### #### Written On: 04-Apr-2020 #### #### #### #### Objective: This script is a config #### #### file, contains all the keys for #### #### Azure 2 OCI API. Application wi...
StarcoderdataPython
11222999
<filename>usage/api/models/skipgram.py import argparse import sys import tensorflow as tf def read_dictionary(): with open('models/skipgram/skipgram.tsv', 'r') as file: words = file.read().split() dictionary = {} for (i, word) in enumerate(words): dictionary[word] = i r...
StarcoderdataPython
8089274
import os import sys from imageio import imread, imwrite from skimage.transform import resize target_dir = sys.argv[1] if sys.argv[2] == 'omniglot': img_size = [28, 28] else: img_size = [84, 84] _ids = [] for root, dirnames, filenames in os.walk(target_dir): for filename in filenames: if filename...
StarcoderdataPython
370650
<reponame>awslabs/improving-forecast-accuracy-with-machine-learning # ##################################################################################################################### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ...
StarcoderdataPython
3373285
import json import logging import pika from message import IncomingMessage from message_forwarder import MessageForwarder class AmqpForwarder(MessageForwarder): def __init__(self, name: str, host: str, username: str, password: str, exchange: str): self.log = logging.getLogger(name) self.log.inf...
StarcoderdataPython
3479672
<filename>backend/apps/csyllabusapi/helper/webscraping/generate-fixtures/generate_fixtures_from_columbia_dump.py import requests from lxml import html import json columbia_fixtures_json = open("/Volumes/SSD-Thomas/Documents/GitHub/csyllabus/webapp/backend/apps/csyllabusapi/fixtures" "/columb...
StarcoderdataPython
5191600
import unittest from .test_object_decoder import CapsuleLayerTestCase, CapsuleLikelihoodTestCase, CapsuleObjectDecoderTestCase from .test_part_decoder import TemplateBasedImageDecoderTestCase, TemplateGeneratorTestCase from .test_part_encoder import CapsuleImageEncoderTestCase from .test_scae import SCAETestCase from ...
StarcoderdataPython
4800317
#!/usr/bin/env python # -*- coding: utf-8; indent-tabs-mode: nil; python-indent: 2 -*- """Read bookmarks saved in a "Netscape bookmark" format as exported by Microsoft Internet Explorer or Delicious.com (and initially of course by Netscape). Assumptions: - The file is a Netscape bookmark file. See a doc at http://m...
StarcoderdataPython
1800144
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'chengzhi' import datetime from tqsdk import TqApi, TqSim from tqsdk.ta import * api = TqApi(TqSim()) # 获得 cu1906 10秒K线的引用 klines = api.get_kline_serial("SHFE.cu1906", 10, data_length=3000) print("K线时间", datetime.datetime.fromtimestamp(klines.iloc[-1]["date...
StarcoderdataPython
4813043
<filename>pyknotid/spacecurves/__init__.py '''.. image:: random_walk_length_30.png :scale: 50% :alt: A closed random walks with 30 steps :align: center This module contains classes and functions for working with knots and links as three-dimensional space curves, or calling functions elsewhere in pyknotid to p...
StarcoderdataPython
4976557
<filename>tests/test_models/test_loss_compatibility.py # Copyright (c) OpenMMLab. All rights reserved. """pytest tests/test_loss_compatibility.py.""" import copy from os.path import dirname, exists, join import numpy as np import pytest import torch def _get_config_directory(): """Find the predefined ...
StarcoderdataPython
9751199
def quick_sort(arr): from random import randint #If length of array is <=1 , The Array is itself sorted if len(arr) <=1: return arr #Store Values After Comparing With Pivot smaller,equal,larger= [],[],[] #Selecting Random Pivot Point pivot = arr[randint(0, len(arr)-1)] for value in arr: if value < pivot: ...
StarcoderdataPython
11377593
import requests import re import json class Neihan: def __init__(self): self.temp_url = "https://www.haha.mx/topic/13648/new/{}" self.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)\ AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"} def parse_url(...
StarcoderdataPython
114962
from django.apps import apps from django.forms import inlineformset_factory from cv.models import Book, BookEdition, \ Chapter, ChapterEditorship, \ Grant, GrantCollaboration, \ Talk, Presentation, \ Course, CourseOffering def ge...
StarcoderdataPython
184561
""" Routine to add Moster et al. 2013 stellar masses python3 lc_add_Ms_Mo13.py 115 MD10 """ import sys ii = int(sys.argv[1]) env = sys.argv[2] # 'MD10' status = sys.argv[3] import h5py # HDF5 support import os import glob import numpy as n h5_dir = os.path.join(os.environ[env], 'cluster_h5/' ) input_list = n.arra...
StarcoderdataPython
11241644
from DavesLogger import Color from DavesLogger import Logs class Log: def __init__ (self, Message = '', Prefix = '', Suffix = ''): self.Message = Message self.IPrefix = Prefix self.ISuffix = Suffix def __call__ (self, _Message = '', _AutoReset = True): if _Message != '' and _Me...
StarcoderdataPython
6663258
import os import numpy from numpy import * import math from scipy import integrate, linalg from matplotlib import pyplot from pylab import * def build_freestream_rhs(panels, freestream): """ Builds the right-hand side of the system arising from the freestream contribution. Parameters ---...
StarcoderdataPython
3235494
<filename>morepath/tests/test_internal.py import morepath from webtest import TestApp as Client def test_internal(): class app(morepath.App): pass @app.path(path='') class Root(object): pass @app.json(model=Root) def root_default(self, request): return {'internal': reques...
StarcoderdataPython
8046781
import torch.nn as nn import pandas as pd import torch def create_loss (): return nn.CrossEntropyLoss()
StarcoderdataPython
4990364
import sys import py from pypy.translator.llvm.test.runtest import * def setup_module(mod): py.test.skip('skipping somewhat futile tests') def test_GC_malloc(): def tuple_getitem(n): x = 666 i = 0 while i < n: l = (1,2,i,4,5,6,7,8,9,10,11) x += l[2] ...
StarcoderdataPython
1856910
import pytest from graphene.test import Client from blapp.api.schema import schema @pytest.fixture def schema_client(): return Client(schema)
StarcoderdataPython