id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
4990973
<reponame>tombenke/py-msgp """Test the mpa module""" import unittest import asyncio from loguru import logger from nats_messenger import Messenger from mpa import MessageProcessorActor from mpa.tests.config_test import ( URL, CREDENTIALS, CLUSTER_ID, PRODUCER_CLIENT_ID, CONSUMER_CLIENT_ID, PROCE...
StarcoderdataPython
8098739
<filename>backend/api/models/user.py<gh_stars>0 from datetime import datetime from core.db import Base from sqlalchemy import Column, DateTime, Integer, String class User(Base): __tablename__ = "user" id = Column(Integer, primary_key=True, index=True) username = Column(String(250), nullable=False) pa...
StarcoderdataPython
9778324
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 6 13:05:11 2020 @author: francesco """ import numpy as np import sys import pandas as pd import matplotlib.pyplot as plt from matplotlib import rc ## for Palatino and other serif fonts use: #rc('font',**{'family':'serif','serif':['Palatino']}) rc('...
StarcoderdataPython
3468686
<reponame>thorben-flapo/pandera """Utility functions for validation.""" from typing import Optional, Tuple, Union import pandas as pd def prepare_series_check_output( check_obj: Union[pd.Series, pd.DataFrame], check_output: pd.Series, ignore_na: bool = True, n_failure_cases: Optional[int] = None, ) ...
StarcoderdataPython
4966264
from functools import reduce # Time: O(m * n) # Space: O(1) class Solution(object): # @param matrix, a list of lists of integers # RETURN NOTHING, MODIFY matrix IN PLACE. def setZeroes(self, matrix): first_col = reduce(lambda acc, i: acc or matrix[i][0] == 0, xrange(len(matrix)), False) ...
StarcoderdataPython
38766
import numpy as np import networkx as nx import argparse import random from models.distance import get_dist_func def get_fitness(solution, initial_node, node_list): """ Get fitness of solution encoded by permutation. Args: solution (numpy.ndarray): Solution encoded as a permutation ini...
StarcoderdataPython
1679456
<reponame>cfculhane/autorest.python<gh_stars>10-100 # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by M...
StarcoderdataPython
5132818
<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Tue Oct 19 17:04:08 2021 @author: wanjinyu """ import numpy as np import sklearn.svm as svm from sklearn.model_selection import train_test_split,cross_val_score import scipy.io as sio import time from sklearn.ensemble import RandomForestClassifier, Random...
StarcoderdataPython
3214347
import json from nltk.tokenize import RegexpTokenizer def read_raw_data(filename): with open(filename, "r", encoding="utf8") as data_file: data_file_lines = data_file.readlines() recipe_list = [] for line in data_file_lines: recipe_list.append(json.loads(line)) return recipe_list def...
StarcoderdataPython
1690899
import sys import json import datetime import time import os from azure.eventhub import EventHubClient, Sender, EventData # Address can be in either of these formats: # "amqps://<URL-encoded-SAS-policy>:<URL-encoded-SAS-key>@<mynamespace>.servicebus.windows.net/myeventhub" # "amqps://<mynamespace>.servicebus.windows....
StarcoderdataPython
9673079
<filename>python/ml4ir/applications/classification/tests/test_classification_serving.py import os import numpy as np import tensorflow as tf from tensorflow.keras import models as kmodels from ml4ir.applications.classification.pipeline import ClassificationPipeline from ml4ir.applications.classification.tests.test_bas...
StarcoderdataPython
126653
<filename>tests/pytest/test_nj_all_noise.py # standard libraries import json # third party libraries import pytest import tqdm # project libraries from speech import dataset_info from speech.utils.wave import array_from_wave from speech.utils.signal_augment import audio_with_sox import utils def test_main(): ...
StarcoderdataPython
9606855
import time import network # the class starts a WiFi access point class AccessPoint: """ Initialize a new WiFi access point Notes: Make sure that the password is not too short. Otherwise, an OSError may occur while staring the access point. """ def __init__(self, access_point_ssid, acc...
StarcoderdataPython
11235592
from itertools import combinations import re class Order: ######################## #from order import Order ##names_list = ['A','B','C','D', 'E'] # Names of files ##relations = ["E<C=B", "E<C<A", "E<C<D", "E<B<A", "E<B<D", "E<A<D"] #ord = Order(names_list, relations) #[order, ineq, scores] = or...
StarcoderdataPython
4985780
# -*- coding: utf-8 -*- """ This software is licensed under the License (MIT) located at https://github.com/ephreal/rollbot/Licence Please see the license for any restrictions or rights granted to you by the License. """ import re from subprocess import Popen, PIPE async def is_url(url): if re.findall('http[s]?...
StarcoderdataPython
5150196
from django.contrib import admin from django.urls import path, include from home import views from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView urlpatterns = [ path("", views.index, name="home"), path("home", views.index, name="home"), pat...
StarcoderdataPython
8112018
import ctypes attribute_hide = 0x02 retorno = ctypes.windll.kernel32.SetFileAttributesW('concealer.txt', attribute_hide) if retorno: print('File has been hidden') else: print('ile was not hidden')
StarcoderdataPython
1701783
# Generated by Django 3.0.3 on 2020-03-05 19:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('booking', '0006_booking_booked_on'), ] operations = [ migrations.RemoveField( model_name='rooms', name='status', ), ...
StarcoderdataPython
3418976
import sys from datetime import datetime from walt.server.threads.main.images.image import NodeImage, format_image_fullname from walt.server.threads.main.network import nfs # About terminology: See comment about it in image.py. MSG_IMAGE_IS_USED_BUT_NOT_FOUND=\ "WARNING: image %s is not found. Cannot attach it t...
StarcoderdataPython
9680885
<gh_stars>0 # TODO : Decorate all print thing import os import time import datetime import mysql.connector # Modularized parts import fileIO import config import compileScript import gradingScript import abb import cmdMode import importlib import sys from kbhit import KBHit from colorama import Style, Fore, init #...
StarcoderdataPython
347134
<gh_stars>0 import unittest from flask_restbolt.utils.crypto import encrypt, decrypt class CryptoTestCase(unittest.TestCase): def test_encrypt_decrypt(self): key = '<KEY>' seed = 'deadbeefcafebabe' message = 'It should go through' self.assertEqual(decrypt(encrypt(message, key, seed...
StarcoderdataPython
150863
from sklearn.ensemble import RandomForestRegressor from sklearn.utils.validation import check_is_fitted from joblib import Parallel, delayed from sklearn.ensemble._base import _partition_estimators import threading import numpy as np class RandomForestRegressor2(RandomForestRegressor): def __init__(self, ...
StarcoderdataPython
9623715
<reponame>ziegltob/tool-competition-av from keras.preprocessing.image import load_img, img_to_array import pandas as pd import numpy as np from skimage.exposure import rescale_intensity from matplotlib.colors import rgb_to_hsv from sklearn.model_selection import train_test_split import os from models.rambo.config impo...
StarcoderdataPython
5060711
import os import torch import numpy as np from torch_geometric.data import InMemoryDataset, download_url, Data from torch_geometric.utils import from_scipy_sparse_matrix class AirUSA(InMemoryDataset): r"""This dataset is the airport traffic network in the USA from the `"Data Augmentation for Graph Neural Netw...
StarcoderdataPython
3288586
import typing as types def Main(): a: types.List[types.Any] = []
StarcoderdataPython
3359439
from django.shortcuts import render from django.http import HttpResponse,Http404 from .models import Image from django.core.exceptions import ObjectDoesNotExist # Create your views here. def start(request): pictures = Image.objects.all() return render(request,'start.html',{"pictures":pictures}) def search_res...
StarcoderdataPython
3234599
<reponame>cydenix/OpenGLCffi<gh_stars>0 DEF = ''' typedef int32_t khronos_int32_t; typedef uint32_t khronos_uint32_t; typedef int64_t khronos_int64_t; typedef uint64_t khronos_uint64_t; typedef signed char khronos_int8_t; typedef unsigned char ...
StarcoderdataPython
8032393
<filename>newrelic_api/users.py from .base import Resource class Users(Resource): """ An interface for interacting with the NewRelic user API. """ def list(self, filter_email=None, filter_ids=None, page=None): """ This API endpoint returns a paginated list of the Users associat...
StarcoderdataPython
9655606
import json from flask import Flask, request, render_template, url_for from interface import Interface app = Flask(__name__) _interface = Interface() _interface.query('machine learning') @app.route("/") def welcome(): return render_template('index.html') @app.route("/query", methods=['POST']) def query(): a...
StarcoderdataPython
9629664
<filename>seed_message_sender/settings.py """ Django settings for seed_message_sender project. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import dj...
StarcoderdataPython
9665558
# -*- coding: utf-8 -*- # Copyright 2020 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...
StarcoderdataPython
4944024
<filename>cm_custom/doc_events/customer.py # -*- coding: utf-8 -*- from __future__ import unicode_literals import frappe def before_insert(doc, method): if not doc.mobile_no: doc.mobile_no = doc.cm_mobile_no
StarcoderdataPython
5136900
<reponame>shongololo/aiovectortiler from aiovectortiler.config_handler import Recipe, Layer, Query def test_basic_recipe(): recipe = Recipe({ "name": "myrecipe", "layers": [{ "name": "mylayer", "queries": [{ "sql": "SELECT * FROM table" }] ...
StarcoderdataPython
6508943
# coding: latin-1 # This program converts a folder of OBS text files # in the older(?) format (one .txt file per OBS story) # to a set of corresponding, OBS story files in Markdown format. # Outputs .md files to a content folder under the input folder. import re # regular expression module import io impo...
StarcoderdataPython
8033642
from django.urls import include, path from rest_framework.authtoken import views from rest_framework.routers import DefaultRouter from .views import UserCreate, UserViewSet router = DefaultRouter() router.register('users', UserViewSet) urlpatterns = [ path('', include(router.urls)), path('register/', UserCre...
StarcoderdataPython
6554775
<reponame>ngc92/branchedflowsim<gh_stars>0 import os try: import unittest.mock as mock except ImportError: import mock as mock from ..test_utils import * from .result_file import ResultFile from . import DataSpec, write_int class Dummy(ResultFile): _SPEC_ = () _FILE_NAME_ = "default_name" def _...
StarcoderdataPython
1885127
""" General functions to handle permutations, cyclic shifts, etc Look for major bottlenecks here """ def create_keystring(key, size): return bin(key)[2:].zfill(size) def permute_key(key, permutation): rstring="" for i in permutation: rstring+=key[i] return rstring def left_shift(key, shift): ...
StarcoderdataPython
6688271
# Global Settings.If finished deployments,just reset the items below. # LOCAL_ASDATA_PATH should be a Navigraph data of Aerosoft. SET_NAVDAT_PATH = "navidata_2201.map" SET_APDAT_PATH = "airport_2201.air" LOCAL_ASDATA_PATH = "/path/to/your/asdata" NAVDAT_CYCLE = "AIRAC;2201,27JAN24FEB/22,2113,30DEC26JAN/22" # Website f...
StarcoderdataPython
12814091
<reponame>helotism/plarin # -*- coding: utf-8 -*- """ An implementation of a ring buffer. """ # #http://forum.micropython.org/viewtopic.php?t=601#p3491 #https://forum.micropython.org/viewtopic.php?t=1702 # import array class Circularbuffer: """A ring buffer that may be queried piecewise or by a threshold value. ...
StarcoderdataPython
272389
<filename>unpack/unpack.py #!/bin/env python3 import argparse, os import fileformats, romfs, exefs, slb2, scecaf, self, ncch, ncsd modes = { "guess": fileformats.guess, "romfs": romfs.process, "exefs": exefs.process, "slb2": slb2.process, "scecaf": scecaf.process, "self": self.process, "n...
StarcoderdataPython
86543
"""Configuration for developing the remote project feature in TARGET mode""" from .local import * # noqa import socket import os # DATABASE CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases # Uses djan...
StarcoderdataPython
1925137
<filename>c3bottles/views/user.py from json import loads from re import sub from flask import Blueprint, redirect, render_template, request, url_for from flask_babel import lazy_gettext from flask_login import current_user, login_user, logout_user from werkzeug.routing import BuildError from c3bottles.model.user impo...
StarcoderdataPython
3371614
""" It's somewhat of a fool's errand to introduce a Python ORM in 2013, with `SQLAlchemy`_ ascendant (`Django's ORM`_ not-withstanding). And yet here we are. SQLAlchemy is mature and robust and full-featured. This makes it complex, difficult to learn, and kind of scary. The ORM we introduce here is simpler: it targets...
StarcoderdataPython
4913195
# Generated by Django 2.0.8 on 2019-05-13 18:44 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('blitz_api', '0017_actiontoken_data_change_email'), ] operations = [ migrat...
StarcoderdataPython
330566
<reponame>osolovyoff/pixelate<filename>clear.py import os import shutil files = ['Pixelate.sln','Pixelate.VC.db'] folders = ['Intermediate', 'Binaries', 'Saved'] for file in files: if os.path.exists(file): os.remove(file) for folder in folders: if os.path.exists(folder): shutil.rmtree(folder)
StarcoderdataPython
6610420
from driver import ( db_msg, ) contacts_map = dict() def load_contacts(): for doc in db_msg.contact_cleansed.find({}, {'NickName': 1}): contacts_map[doc['_id']] = doc['NickName'] def get_nickname(username): if username not in contacts_map: load_contacts() return contacts_map.get(...
StarcoderdataPython
9628387
''' ''' ''' ISC License Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all c...
StarcoderdataPython
11342693
import datetime import uuid from datetime import timezone from app.main import db from app.main.model.channel import Channel norilsk_time = timezone(datetime.timedelta(0, 25200), 'Asia/Krasnoyarsk') def add_channel(data): channel = None if data.get('public_id'): channel = Channel.query.filter_by(pub...
StarcoderdataPython
1600405
<reponame>DrugoLebowski/nram-executor # Vendor import numpy as np # Project from tasks.Task import Task class TaskListK(Task): """ [ListK] Given a pointer to the head of a linked list and a number k, find the value of the k-th element on the list. List nodes are represented as two adjacent memory cells: a...
StarcoderdataPython
11322385
<reponame>mcnigno/gea from flask_appbuilder.widgets import ListWidget, FormWidget class MyListWidget(ListWidget): template = 'widgets/listRev1.html' class MyEditWidget(FormWidget): template = 'widgets/edit_form_sub.html'
StarcoderdataPython
1736022
<gh_stars>1-10 from __future__ import annotations import logging import typing from typing import Any, Dict, List import fileseq from silex_client.action.command_base import CommandBase from silex_client.utils.parameter_types import ListParameterMeta, PathParameterMeta if typing.TYPE_CHECKING: from silex_client...
StarcoderdataPython
11253148
from dks.base.activation_getter import ( get_activation_function as _get_numpy_activation_function, ) from dks.base.activation_transform import _get_activations_params def subnet_max_func(x, r_fn): depth = 7 res_x = r_fn(x) x = r_fn(x) for _ in range(depth): x = r_fn(r_fn(x)) + x retur...
StarcoderdataPython
1700382
<filename>nlgen/tests/cfg/test_terminal.py from nlgen.cfg import CFG, PTerminal def test_simple_terminal(): cfg = CFG([ ("S", PTerminal("foo")) ]) assert list(cfg.permutation_values("S")) == [("foo",)] def test_equal(): assert (PTerminal("I", features={"person": "1"}) == PTermina...
StarcoderdataPython
11309920
<gh_stars>10-100 from hashlib import sha256 from charm.schemes.pk_vrf import VRF10 from charm.toolbox.pairinggroup import PairingGroup from pai.pouw.ticket_selection.similarity import cosine_similarity # ticket preferences vector ticket_prefs = [0, 7, 100] # corresponding task properties vector task_props = [0, 2, ...
StarcoderdataPython
11324574
<reponame>GaoSida/Neural-SampleRank import os import pytest from collections import Counter from torchtext.vocab import Vocab @pytest.fixture() def dummy_vocabs(): token_list = ["at", "happy", "is", "peter", "such", "won"] char_list = [chr(c) for c in range(ord('A'), ord('Z') + 1)] char_list += [chr(c) f...
StarcoderdataPython
3351611
<gh_stars>1-10 # coding=utf-8 # Copyright 2022 The Google Research 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 License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
StarcoderdataPython
1642317
<filename>baseline/tilscore.py from .utils import dist_to_px, get_mask_area, write_json from .nms import slide_nms, to_wsd from .constants import TUMOR_STROMA_MASK_PATH def create_til_score(image_path, xml_path, output_path): """slide_level_nms""" points = slide_nms(image_path, xml_path, 256) wsd_points = ...
StarcoderdataPython
3378746
<gh_stars>100-1000 import json from concurrent.futures import ThreadPoolExecutor from retry import RetryOnException as retry from proxypool import ( ProxyPoolValidator, ProxyPoolScraper, RedisProxyPoolClient ) from airflow.models.baseoperator import BaseOperator from airflow.utils.decorators import apply_d...
StarcoderdataPython
1718989
import threading import time def func_1(): while True: print(f"[{threading.current_thread().name}] Printing this message every 2 seconds") time.sleep(2) # initiate the thread with daemon set to True daemon_thread = threading.Thread(target=func_1, name="daemon-thread", daemon=True) # or # daemon_th...
StarcoderdataPython
3599458
<gh_stars>10-100 # Exercise 7.10 # Author: <NAME> class Hello: def __call__(self, string): print 'Hello, ' + string + '!' def __str__(self): return 'Hello, World!' a = Hello() print a('students') print a """ Sample run: python Hello.py Hello, students! None Hello, World! """
StarcoderdataPython
176362
<reponame>kkcookies99/UAST def XXX(self, nums1: List[int], nums2: List[int]) -> float: def findKthElement(arr1,arr2,k): len1,len2 = len(arr1),len(arr2) if len1 > len2: return findKthElement(arr2,arr1,k) if not arr1: return arr2[k-1] ...
StarcoderdataPython
12845685
# Nested Lists and Dictionaries def run(): my_list = [1, "Hello", True, 4.5] my_dict = { "firstname": "Mauricio", "lastname": "Valadez" } super_list = [ {"firstname": "Mauricio", "lastname": "Valadez"}, {"firstname": "Carlos", "lastname": "García"}, {"firstname":...
StarcoderdataPython
5075378
# -*- coding:utf-8 -*- import re import SpiderUtils class ImageSpider(object): num = 0 def __init__(self): pass def getImageFormUrl(self, url): print "--------------------------------解析网页代码" print "--网页地址 | url = " + url content = SpiderUtils.getHtmlContent(url) #...
StarcoderdataPython
3541885
<filename>gpytorch/lazy/interpolated_lazy_tensor.py #!/usr/bin/env python3 import torch # from .block_diag_lazy_tensor import BlockDiagLazyTensor from .lazy_tensor import LazyTensor from .non_lazy_tensor import lazify, NonLazyTensor from .root_lazy_tensor import RootLazyTensor from ..utils import sparse from ..utils.b...
StarcoderdataPython
9682704
<filename>resources/profiles.py from os import environ import jwt from flask import request from flask_restful import Resource from marshmallow import ValidationError from sqlalchemy.exc import IntegrityError from werkzeug.exceptions import BadRequest, NotFound from werkzeug.security import generate_password_hash, che...
StarcoderdataPython
3214503
#!/usr/bin/env python # # Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in...
StarcoderdataPython
8077449
import unittest from src.factory import DayFactory, TransactionsFactory from src.value_objects import Stock, StockTransaction, CashTransaction class FactoryTest(unittest.TestCase): def test_create_day(self): """ Assert factory method returns a dictionary :return: """ D0 = ...
StarcoderdataPython
4822415
<filename>src/application/__init__.py from flask import Flask from config import configure_app application = Flask(__name__) configure_app(application) @application.errorhandler(500) def internal_server_error(error): application.logger.error('Server Error: %s', (error)) error = 'Server Error: %s', (error) ...
StarcoderdataPython
76373
import re import os import posixpath from fabric.api import cd, sudo, puts from fabric.contrib import files from .containers import conf, MissingVarException from .task import Task from .users import list_users from .files import read_file, exists from .utils import home_path, split_lines __all__ = [ 'push_key'...
StarcoderdataPython
3209587
<gh_stars>0 idade = int(input('Insira a idade do Gato: ')) castrado = input('O gato é Castrado (sim/não) ?') sexo = input('Insira o sexo do gato (f/m): ') fivFelv = input('Possui Fiv e Felv?(positivo/negativo): ') if idade >= 0 and sexo == 'm' and fivFelv == 'positivo': print('SalaD') elif idade >= 0 and fivFe...
StarcoderdataPython
185426
<gh_stars>0 from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, ValidationError from django.contrib.auth.models import User from django.db import models from django.conf import settings class Config(models.Model): petrol_bonus_limit = models.PositiveSmallIntegerField(default=500) d...
StarcoderdataPython
6600028
from views import view from PyInquirer import prompt class MainView(view.View): """ A base class for views which is not intended to be instantiated """ def getMainAction(self): """ Asks the user what course of action they want to take Returns ------- 'Post a question' or 'Search for posts' or 'Exit' ...
StarcoderdataPython
3522472
<gh_stars>10-100 import random import pysam import os import sys import argparse import util class ReadStats(object): def __init__(self): # number of reads discarded becaused not mapped self.discard_unmapped = 0 # number of reads discarded because mate unmapped self.disc...
StarcoderdataPython
11376250
""" mlperf inference benchmarking tool """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import os import time import numpy as np from PIL import Image import dataset import imagenet import coco from backend_tf import BackendTensorflow ...
StarcoderdataPython
1831011
# MIT License # # Copyright (c) 2019 74wny0wl # # 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, modify, merg...
StarcoderdataPython
11212254
# coding: utf-8 # ---------------------------------------------------------------------------- # <copyright company="Aspose" file="imaging_base.py"> # Copyright (c) 2019 Aspose Pty Ltd. All rights reserved. # </copyright> # <summary> # Permission is hereby granted, free of charge, to any person obtaining a #...
StarcoderdataPython
3387545
"""This module implements methods to load dictonaries from text-based configuration files. """ # noqa: E501 import sys import os import io from os import PathLike import errno from pathlib import Path import yaml import toml import json from functools import partial from typing import Any, MutableMapping, Dict, Calla...
StarcoderdataPython
5177122
import os import json from .grades import AssignmentComponentGrade from .constants import SUBMISSION_META_FILE, SUBMISSION_FILES_DIRECTORY from .utils import ConfigDictMixin, datetime_to_string, copy_globs, \ FileNotFoundError class BrokenSubmissionError(Exception): def __init__(self, message,...
StarcoderdataPython
1875459
<reponame>ljmcgann/python-ironicclient<filename>ironicclient/tests/functional/osc/v1/test_baremetal_deploy_template_basic.py # 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 # # ...
StarcoderdataPython
5074436
<gh_stars>1-10 ### Kmeans Algorithm for IRIS dataset #This is easily extandable to any problem/dataset ### author: Dr. <NAME> ### year: 2015 ### contact: <EMAIL> import numpy as np class KMeans: def __init__(self, dataraw): #make sure that the iris dataset is located in the current directo...
StarcoderdataPython
1928352
# LIBTBX_SET_DISPATCHER_NAME mmtbx.ssm_rmsd_for_chains from __future__ import absolute_import, division, print_function import sys from mmtbx.geometry_restraints.torsion_restraints import utils from libtbx.utils import Sorry def run(args): if len(args) != 2: raise Sorry("mmtbx.ssm_rmsd_for_chains requires two PD...
StarcoderdataPython
8077609
# ----------------------------------------------------- # Simulation Constants # ----------------------------------------------------- # Simulation steps MAX_TIME = 60 ACTION_REPEAT = 10 # Simulation timing NUM_BULLET_SOLVER_ITERATIONS = 30 SIMULATION_TIME_STEP = 0.001 # Camera RENDER_HEIGHT = 360 RENDER_WIDTH = 480...
StarcoderdataPython
3547008
a = int(input("Please enter a whole number for variable 'a': ")) b = None c = None if a < 10: b = 0 c = 1 print(f'Since a is less than 10, b = {b} and c = {c}') else: if b is None and c is None: b = "'Nothing'" c = "'Nothing'" print(f'Since a is greater than or equal to 10, b = {b}...
StarcoderdataPython
5189490
<filename>pyscf/pbc/gto/_pbcintor.py #!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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....
StarcoderdataPython
159893
<gh_stars>0 import click import pickle from tqdm import tqdm import os import numpy as np import matplotlib.pyplot as plt from multiprocessing import Pool from utility.dataset import Preprocess_Dataset, buildPreprocessDataset from utility.transform import ExtractCliques, ExtractMel from utility.algorithmsWrapper impor...
StarcoderdataPython
9663249
import ast import re from django.utils.deprecation import MiddlewareMixin from django.utils.timezone import now from .conf import settings, TrackingConfig from .models import RequestLog class LoggingMiddleware(MiddlewareMixin): """ Adapted from DRF-Tracking - drf-tracking.readthedocs.io Applied as middl...
StarcoderdataPython
264308
<reponame>mkduer/code-nibbles from helpers import Helpers def fibonacci_recurse(flist: [int], limit: int) -> [int]: """ Recursively calculates the fibonacci sequence up to the defined limit value (inclusive) :param flist: the list of fibonacci numbers :param limit: the maximum value for the fibonacci ...
StarcoderdataPython
6556502
""" Serializers for course advanced settings""" from typing import Type, Dict as DictType from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework.fields import Field as SerializerField from xblock.fields import ( Boolean, DateTime, Dict, Field ...
StarcoderdataPython
8059946
<filename>tests/test_py_examples.py<gh_stars>10-100 """ Validate all shaders in our examples. This helps ensure that our exampples are actually valid, but also allows us to increase test coverage simply by writing examples. """ import os import types import importlib.util import pyshader import pytest from testutils...
StarcoderdataPython
6601573
"""Utility functions to help other callback functions""" import base64 from PIL import Image import io from pathlib import Path from skimage import draw, morphology from skimage.transform import resize from scipy import ndimage import numpy as np import matplotlib.image as mpimg import json def b64_2_numpy(string)...
StarcoderdataPython
6420421
<reponame>StylishTriangles/adversarial_patch<gh_stars>1-10 from keras import Model from keras import backend as K from keras.preprocessing import image import numpy as np import os # Assumes 3 channels in input def get_input_shape(img_width: int, img_height: int): if K.image_data_format() == 'channels_first': ...
StarcoderdataPython
9650299
import os from time import sleep from Big_Data_Platform.Kubernetes.Cognition.example.src.classes.KubeAPI import KubeAPI from Big_Data_Platform.Kubernetes.Kafka_Client.Confluent_Kafka_Python.src.classes.CKafkaPC import KafkaPC def send_job_metrics(): print("Entering function send_job_metrics()") job_res = k_a...
StarcoderdataPython
1610233
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
StarcoderdataPython
1818393
<reponame>tpudlik/sbf """Spherical Bessel function algorithms developed by <NAME> (2011). """ import numpy as np def recurrence_pattern(n, z, f0, f1): if n == 0: return f0 if n == 1: return f1 start_order = order(n, z) jlp1 = 0 jl = 10**(-305) zinv = 1/z # Complex division is...
StarcoderdataPython
8007761
#coding=utf-8 #-*- coding: utf-8 -*- import os import re import sys import time import math import pytz import numpy import talib import datetime import urllib2 sys.path.append("../frame/") import fetch_data from loggingex import LOG_INFO from loggingex import LOG_ERROR from loggingex import LOG_WARNING from job_bas...
StarcoderdataPython
1667609
# 1. gpu id gpu_id = 0 # 2. preprocess img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[1,1,1], to_rgb=True) size_divisor = 32 preprocess = dict( typename='Compose', pipeline=[ dict(typename='Resize', dst_shape=(1100, 1650), keep_ratio=True), dict(typename='ToFloat', keys=['img'])...
StarcoderdataPython
9703417
import pandas as pd import matplotlib.pylab as plt import numpy as np filepath = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Data%20files/auto.csv" headers = ["symboling","normalized-losses","make","fuel-type","aspiration", "num-of-doors","b...
StarcoderdataPython
4893028
# Copyright (c) 2014-present PlatformIO <<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 # # Unless required by applicable law or ag...
StarcoderdataPython
4812204
<reponame>The-CJ/Phaazebot from datetime import datetime from Utils.Classes.undefined import UNDEFINED from Utils.Classes.contentclass import ContentClass class OsuUser(ContentClass): """ Represents a osu! user with all its stats in a specific game mode """ def __repr__(self): return f"<{self.__class__.__name__}...
StarcoderdataPython
3449953
<gh_stars>0 """JSON plugin module.""" from dataclasses import asdict from json import dumps from dbsg.lib.plugin import PluginABC REGISTRY_NAME = 'json' class Plugin(PluginABC): """JSON plugin.""" def __init__(self, configuration, introspection, ir, **kwargs): """Initialize JSON plugin.""" ...
StarcoderdataPython