id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
179449
<filename>__main__.py import os from pathlib import Path import socketserver from server import * from auth import * from smarthome import * class ThreadingSimpleServer(socketserver.ThreadingMixIn, http.server.HTTPServer): pass def requestDevicesSync(): SmartHomeReqHandler.forceDevicesSync() ...
StarcoderdataPython
1770848
""" Testing """ from setuptools import setup, find_packages setup( name="ostur", version="0.1", description="Ostur python libraries", url="https://github.com/alvarop/ostur", author="<NAME>", author_email="<EMAIL>", license="MIT", packages=find_packages(), include_package_data=True, ...
StarcoderdataPython
3255865
"""initial revision Revision ID: <KEY> Revises: <PASSWORD> Create Date: 2022-01-20 13:04:42.464001 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'ab8ca6ee9963' down_revision = '<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### comm...
StarcoderdataPython
158530
<reponame>macdaliot/exist from rest_framework.routers import DefaultRouter from apps.reputation.api import blViewSet from apps.twitter.api import twViewSet from apps.exploit.api import exViewSet from apps.threat.api import threatEventViewSet, threatAttrViewSet router = DefaultRouter(trailing_slash=False) router.regist...
StarcoderdataPython
1787988
from architect.version import __version__
StarcoderdataPython
3358350
#!/usr/bin/env python3 import argparse import glob import operator import shutil import os import sys from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score def main(): parser = argparse.ArgumentParser(description="") parser.add_argument("--di...
StarcoderdataPython
3300821
<gh_stars>0 from .canvas_sizes import MinHelper, MaxHelper
StarcoderdataPython
3238077
<filename>HW3/randomforest.py # -*- coding: utf-8 -*- import pandas as pd from sklearn import tree from sklearn.model_selection import cross_val_score from sklearn.model_selection import train_test_split from sklearn import model_selection from sklearn import metrics import numpy as np from sklearn import linear_mode...
StarcoderdataPython
2653
<reponame>HaujetZhao/Caps_Writer<filename>src/moduels/gui/Tab_Help.py # -*- coding: UTF-8 -*- from PySide2.QtWidgets import QWidget, QPushButton, QVBoxLayout from PySide2.QtCore import Signal from moduels.component.NormalValue import 常量 from moduels.component.SponsorDialog import SponsorDialog import os, webbrowser ...
StarcoderdataPython
1790096
<gh_stars>100-1000 from django.contrib import messages from django.contrib.auth.decorators import user_passes_test from django.shortcuts import render from django.http import HttpResponseRedirect from vaas.cluster.cluster import ServerExtractor from vaas.cluster.models import LogicalCluster from .forms import PurgeFor...
StarcoderdataPython
3305355
<reponame>vyahello/quotes """ASGI config for manager project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application from django.c...
StarcoderdataPython
3316170
<filename>configserver/tools/__init__.py # Initial server source code from <NAME> (<EMAIL>) (Many thanks for showing me a great scaffold for CherryPy) # All levels of the XSS challenge are under the MIT license; Good luck learning! # Follow me on twitter @infosec_au or take a visit to http://shubh.am
StarcoderdataPython
3358989
<gh_stars>1-10 """ Implements a simple version check for a client/server pair. Used when you want to verify if your server version is a minimum value. The decorator allows arguments within the decorator itself. """ # Map version tuple to MAPDL release version VERSION_MAP = {(0, 0, 0): '2020R2', (0, 3...
StarcoderdataPython
172385
import liquepy as lq import numpy as np import eqsig import pysra import sfsimodels as sm class EqlinStockwellAnalysis(object): def __init__(self, soil_profile, in_sig, rus=None, wave_field='outcrop', store='surface', gibbs=0, t_inc=1.0, t_win=3.0, strain_at_incs=True, strain_ratio=0.9): """ Equi...
StarcoderdataPython
3269844
import datetime from nasdaq_100_ticker_history import tickers_as_of def test_basics() -> None: assert 'AMZN' in tickers_as_of(2020, 6, 1) assert len(tickers_as_of(2020, 6, 1)) >= 100 def _test_one_swap(as_of_date: datetime.date, removed_ticker: str, added_ticker: str, ...
StarcoderdataPython
3215720
from aiocloudflare.commons.auth import Auth class Policies(Auth): _endpoint1 = "accounts" _endpoint2 = "access/apps" _endpoint3 = "policies"
StarcoderdataPython
99592
<filename>marlin-firmware/buildroot/share/PlatformIO/scripts/mks_encrypt.py import os,sys Import("env") from SCons.Script import DefaultEnvironment board = DefaultEnvironment().BoardConfig() # Encrypt ${PROGNAME}.bin and save it as build.firmware ('Robin.bin') def encrypt(source, target, env): key = [0xA3, 0xBD, 0x...
StarcoderdataPython
4804402
# cableController.py # shotmanager # # The cable movement controller. # Runs as a DroneKit-Python script. # # Created by <NAME> and <NAME> on 1/21/2015. # Copyright (c) 2016 3D Robotics. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the L...
StarcoderdataPython
3235792
<gh_stars>0 import aiohttp_cors from aiohttp_graphql import GraphQLView from graphql.execution.executors.asyncio import AsyncioExecutor from ..schema import schema from ..middlewares import AuthenticationMiddleware, dataloader_middleware async def startup(app): authentication = AuthenticationMiddleware(whitelist...
StarcoderdataPython
1743695
<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('census_paleo', '0007_auto_20170321_1632'), ] operations = [ migrations.AddField( model_name='functio...
StarcoderdataPython
74982
import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import torch.utils.data as Data import numpy as np import time import sys import utils print('生成测试数据') n_train, n_test, num_inputs = 20, 100, 200 t...
StarcoderdataPython
1713101
<reponame>wszeborowskimateusz/model-free-episodic-control<gh_stars>0 #!/usr/bin/env python3 import os import random import time import gym from mfec.agent import MFECAgent from utils import Utils from dqn.agent import DQNAgent, preprocess ENVIRONMENT = "MsPacman-v0" # More games at: https://gym.openai.com/envs/#at...
StarcoderdataPython
3345757
<reponame>vhirtham/weldx """Contains the serialization class for the weldx.core.TimeSeries.""" import numpy as np import pint from weldx.asdf.types import WeldxType from weldx.constants import WELDX_QUANTITY as Q_ from weldx.core import TimeSeries class TimeSeriesTypeASDF(WeldxType): """Serialization class for ...
StarcoderdataPython
3217051
<reponame>mrmanishprasadroy/Dash_Celery_Redis<gh_stars>0 import glob import os import datetime import json import numpy as np import pandas as pd from pandas import DataFrame import time from telegram_definition_L1 import * from golabal_def import Dir_Path # telegram directory (default) tel_directory = D...
StarcoderdataPython
1627136
<filename>maths/factorial_recursive.py '''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE S...
StarcoderdataPython
51715
#coding:UTF-8 import os import discord from discord.ext import tasks from datetime import datetime token = os.environ['DISCORD_BOT_TOKEN'] #トークン channel_id = os.environ['CHANNEL_ID'] #チャンネルID # 接続に必要なオブジェクトを生成 client = discord.Client() @tasks.loop(seconds=60) async def loop(): print(datetime.now().strftime("%Y/%...
StarcoderdataPython
4829363
<reponame>mayashap/tasking-manager import geojson import json import os from typing import Tuple import xml.etree.ElementTree as ET from backend.models.dtos.project_dto import DraftProjectDTO from backend.models.postgis.project import Project from backend.models.postgis.statuses import TaskStatus from backend.models.po...
StarcoderdataPython
1772721
<reponame>INGEOTEC/Python-Course a = 2 // 3 print(type(a)) assert type(a) != int assert isinstance(a, int) def add(a, b): """Add two numbers""" return a + b add(12, "23") def add(a, b): for x in [a, b]: f = isinstance(x, float) f = f or isinstance(x, int) assert f return a + ...
StarcoderdataPython
1739667
<gh_stars>1-10 from spotipy.oauth2 import SpotifyClientCredentials from spotipy import Spotify import json from sys import argv def spotify_authentication(client_id, client_secret, playlist_id): """ This part verifies the credentials for the spotify-api usage Args: client_id: client_secret: playlist...
StarcoderdataPython
16807
import unittest import pycqed as pq import os import matplotlib.pyplot as plt from pycqed.analysis_v2 import measurement_analysis as ma class Test_SimpleAnalysis(unittest.TestCase): @classmethod def tearDownClass(self): plt.close('all') @classmethod def setUpClass(self): self.datadir...
StarcoderdataPython
3275547
<reponame>malaterre/vtk-dicom """ Generate tables for converting GB18030 multi-byte to Unicode The input arguments should be the gb-18030-2005.ucm file from here: http://source.icu-project.org/repos/icu/data/trunk/charset/data/ucm/ Two tables must be generated. One for the 24066 two-byte codes, and another for the f...
StarcoderdataPython
3381814
<gh_stars>0 import numpy as np class Agent(object): def __init__(self, dim_action): self.dim_action = dim_action def act(self, ob, reward, done): return np.tanh(np.random.randn(self.dim_action)) # random action
StarcoderdataPython
3376842
import itertools import os import unittest import parameterized from generator import rand from exact_string_matching import forward, backward, other from string_indexing import lcp, suffix_tree, suffix_array def lcp_lr_contains(t, w, n, m): SA = suffix_array.skew(t, n) LCP_LR = lcp.build_lcp_lr(lcp.kasai(SA, t,...
StarcoderdataPython
3378022
#!/usr/bin/env python import os import sqlite3 print 'Creating directories ...', path = os.path.join('data') try: os.stat(path) except OSError: os.makedirs(path) print 'done' else: print 'already done' print 'Initialising database ...', path = os.path.join('data', 'db.sqlite') try: os.stat(path) except OSErro...
StarcoderdataPython
3312769
# # Copyright (C) 2022 Databricks, Inc. # # 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
3249769
import numpy as np import pandas as pd import time, copy import pickle as pickle import sklearn from sklearn.linear_model import LogisticRegression from sklearn.metrics import log_loss from scipy.special import expit import matplotlib.pyplot as plt from sklearn.ensemble import AdaBoostClassifier import statsmodels...
StarcoderdataPython
97005
<filename>torrent.py import urllib, requests, os from bs4 import BeautifulSoup ''' The base class for all torrent downloaders to derive from. It shares an interface that is used throughout all download instances. ''' # TODO: abstract class TorrentDownloader(object): ''' # ''' def __init__...
StarcoderdataPython
3282659
#!/usr/bin/env python """ .. module:: TestRunner :synopsis: Runs the unit test suite. .. moduleauthor:: <NAME> <<EMAIL>> """ import os import subprocess import sys from enum import Enum from baseline import BaseLine from environment import EnvironmentNames, Environment from logger import Logger from tools import...
StarcoderdataPython
1737881
# Generated by Django 3.1.8 on 2021-04-24 01:11 import core.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("core", "0101_new_availability_tags"), ] operations = [ migrations.AddField( model_name="report", ...
StarcoderdataPython
164695
<filename>recommend.py #-*- coding:utf-8 -*- import svdRec import numpy as np from numpy import * import MySQLdb import sys def loadMatrixFromMysql(conn): cur = conn.cursor() cur.execute("select count(*) from ot_book")#读取书本的总数 totalbook=cur.fetchone()[0]; cur.execute("select count(*) from ot_member")#读取用户总数 tota...
StarcoderdataPython
1739955
<reponame>niyunsheng/Mtianyan-AdvancePython #python为了将语义变得更加明确,就引入了async和await关键词用于定义原生的协程 # async def downloader(url): # return "bobby" import types @types.coroutine def downloader(url): yield "bobby" async def download_url(url): #dosomethings html = await downloader(url) return html if __name__...
StarcoderdataPython
3353731
''' Kattis - fraction A relatively elementary problem, but it's worth knowing how to solve it. Simply convert between fractions and continued fractions. Way easier with python fraction library compared to C++. Time: O(len of continued fraction), Space: O(len of continued fraction) ''' from fractions import Fraction im...
StarcoderdataPython
3362876
# -*- coding: utf-8 -*- # # This file is part of Karesansui. # # Copyright (C) 2009-2012 HDE, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without lim...
StarcoderdataPython
3240967
<filename>django_settings/api.py<gh_stars>1-10 # -*- coding: utf-8 -*- # Public module API from .moduleregistry import RegisterError # noqa from .dataapi import DataAPI, data # noqa # shortcuts get = data.get set = data.set exists = data.exists all = data.all type_names = data.type_names # django settings-depende...
StarcoderdataPython
3303835
<reponame>kailas-rathod/Retinet<filename>models/basic_model.py import os import numpy as np import pandas as p import theano.tensor as T import lasagne as nn from lasagne.layers import dnn from lasagne.nonlinearities import LeakyRectify from layers import ApplyNonlinearity from utils import (oversample_set, ...
StarcoderdataPython
171968
import numpy as np import SimpleITK as sitk from napari_imsmicrolink.data.image_transform import ImageTransform def test_ImageTransform_add_points(): test_pts = np.array([[50.75, 100.0], [20.0, 10.0], [10.0, 50.0], [60.0, 20.0]]) itfm = ImageTransform() itfm.output_spacing = (1, 1) itfm.add_points(t...
StarcoderdataPython
1775773
from matplotlib.colors import ListedColormap,LogNorm import matplotlib.pyplot as plt import numpy as np import seaborn as sns import cmasher as cma import pandas as pd from matplotlib.ticker import LogLocator,AutoLocator,AutoMinorLocator,MaxNLocator from .sampler import to_time_series, TigressWindSampler discrete_cm...
StarcoderdataPython
1644103
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020 <NAME> # 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...
StarcoderdataPython
1779814
<reponame>JoshuaJoost/GNN_SS20 import numpy as np import tensorflow as tf print(f"numpy version: {np.__version__}") # print(f"tensorflow version: {tf.__verion__}")
StarcoderdataPython
1784584
<reponame>srp-31/Face-Mask-Detection<filename>src/front_end_app/main.py import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input,Output,State,MATCH,ALL,ALLSMALLER from flask import Flask, Response import cv2 from PIL import Image, ImageEnhance import numpy a...
StarcoderdataPython
13279
<filename>configutator/__version.py __version__ = [1, 0, 2] __versionstr__ = '.'.join([str(i) for i in __version__]) if __name__ == '__main__': print(__versionstr__)
StarcoderdataPython
1741003
import re import sys from web3 import Web3 # TODO: This was copy-pasted from one of my other projects, # need to refactor, add tests etc regex = re.compile(r"error\s(\w+)\(.+\;") def errors_on_file(path): file = open(path, mode='r') contents = file.read() file.close() return regex.findall(contents) ...
StarcoderdataPython
1787209
<filename>proj/pretrain_rnn.py # Author: bbrighttaer # Project: IReLeaSE # Date: 3/23/2020 # Time: 12:03 PM # File: pretrain.py from __future__ import absolute_import, division, print_function, unicode_literals import argparse import math import os import random import time from datetime import datetime ...
StarcoderdataPython
3392653
import os import random import subprocess import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from dja...
StarcoderdataPython
4805843
<filename>jotter/set_remote.py """set_remote The functionality for the jotter set-remote command. Author: Figglewatts <<EMAIL>> """ import git from jotter import util def run(remote_url: str) -> None: """Run the set-remote command. Args: remote_url: The remote URL to use. """ if no...
StarcoderdataPython
38284
<reponame>MSLNZ/msl-loadlib """ Creates a 32-bit server to use for `inter-process communication <https://en.wikipedia.org/wiki/Inter-process_communication>`_. This module must be run from a 32-bit Python interpreter with PyInstaller_ installed. If you want to re-freeze the 32-bit server, for example, if you want a 32...
StarcoderdataPython
3200221
from xml.etree import ElementTree def parse_nsrr_annotations(file_path): tree = ElementTree.parse(file_path) root = tree.getroot() return root def parse_nsrr_scored_events(file_path): root = parse_nsrr_annotations(file_path) scored_events = root.find('ScoredEvents').getchildren() return scor...
StarcoderdataPython
3383326
import numpy as np import matplotlib.pyplot as plt import lightFunctions as light dataPath = '12-light/data/' plotsPath = '12-light/plots/' ######################################## # Wavelength calibration ######################################## filename = 'white-mercury.png' brightness = light.readIntensity(da...
StarcoderdataPython
155712
# Licensed under the Unlicense (http://unlicense.org) # Made by <EMAIL> # Chat Program import socket import threading # Config MODE = "SERVER" # Modes can either be SERVER or CLIENT HOST = "" # Symbolic name meaning all available interfaces PORT = 1337 # Arbitrary non-privileged port...
StarcoderdataPython
3398392
<reponame>jerryrwu/harvest<filename>plugins/redacted/utils.py<gh_stars>1-10 import html import re from dataclasses import dataclass import bs4 from upload_studio.upload_metadata import MusicMetadata class JoinedArtistsBuilder(object): def __init__(self, joined_artists_builder=None): if joined_artists_bu...
StarcoderdataPython
3217315
<gh_stars>0 def split_line(line, length): items = [ line[length * i : length * (i + 1)] for i in range(len(line) // length + 1) ] return [i for i in items if i.lstrip()]
StarcoderdataPython
1657996
<reponame>racheliurui/vscode-hello-python #!/usr/bin/env python3 from ev3dev2.sound import Sound sound = Sound() def speakout(message): sound.speak(message)
StarcoderdataPython
3359680
<gh_stars>1-10 """Definition of the ModelConfiguration class.""" import os from dataclasses import dataclass from typing import Dict, Optional @dataclass class ModelConfiguration: """Container for a path to a Stan model and some configuration. For example, you may want to compare how well two stan programs ...
StarcoderdataPython
3387955
<reponame>stoman/gym-cards from gym.envs.registration import register register( id='Wizards-v0', entry_point='gym_cards.envs:WizardsEnv', )
StarcoderdataPython
1649692
<gh_stars>0 def func(a, b, c): deter = b**2 - 4*a*c if(deter > 0): print("Distinct real roots") elif(deter == 0): print("One real root") else: print("Complex root") a = int(input("First Coef")) b = int(input("Second Coef")) c = int(input("Third Coef")) func(a, b, c)
StarcoderdataPython
118136
from django.core.management.base import BaseCommand from main.views import get_csv class Command(BaseCommand): help = 'Gets data from CSV file' def handle(self, *args, **options): get_csv() self.stdout.write(self.style.SUCCESS('Successfully imported data from CSV'))
StarcoderdataPython
3266236
def replace_text(file,old_word,new_word): file_data = '' with open(file)as f: for i in f: if old_word in i: i=i.replace(old_word,new_word) file_data+=i with open(file,'w',encoding='utf-8')as f: f.write(file_data) replace_text('test_replace.txt','test...
StarcoderdataPython
27891
n = int(input()) c = [0]*n for i in range(n): l = int(input()) S = input() for j in range(l): if (S[j]=='0'): continue for k in range(j,l): if (S[k]=='1'): c[i] = c[i]+1 for i in range(n): print(c[i])
StarcoderdataPython
41914
<filename>wxpusher/tests/test_send_message.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ Unittest for sending message. File: test_send_message.py Author: huxuan Email: <EMAIL> """ import unittest from wxpusher import WxPusher from . import config class TestSendMessage(unittest.TestCase): """Unittest for...
StarcoderdataPython
25772
# $language = "python" # $interface = "1.0" # ################################################ SCRIPT INFO ################################################### # Author: <NAME> # Email: <EMAIL> # # This script will grab the route table information from a Cisco IOS or NXOS device and export details about each # ne...
StarcoderdataPython
3243551
<filename>data-structures/linked_list.py class Element(object): def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def append(self, new_element): # Add new element to the t...
StarcoderdataPython
3288692
"""This contains all of the views for the Ghostwriter application's various webpages. """ # Import logging functionality import logging # Django imports for generic views and template rendering from django.urls import reverse from django.views import generic from django.core.files import File from django.shortcuts im...
StarcoderdataPython
1775164
#!/usr/bin/env python # coding: utf-8 import sys from time import time from time import sleep import xarray as xr import boto3 import os import rioxarray import rasterio import argparse def _split_full_path(bucket_full_path): if 's3://' in bucket_full_path: bucket_full_path=bucket_full_path.replace('s3:/...
StarcoderdataPython
1750351
<reponame>sattwik21/Hacktoberfest2021-1 import statistics import numpy as np # fungsi untuk mengurutkan bilangan def sort(num): num.sort() print("Urutkan angka: ", end = "") for i in num: if i < len(num): print(i, end=", ") else: print(i) # fungsi untuk menghitung rata-rata def average(num): result = su...
StarcoderdataPython
4838301
name = 'EMBL2checklists' __all__ = ['ChecklistOps', 'globalVariables', 'EMBL2checklistsMain', 'PrerequisiteOps']
StarcoderdataPython
3306737
<filename>libs/utils/auth.py import json import logging import os from datetime import datetime, timedelta from jose import jwt from passlib.context import CryptContext logger = logging.getLogger(__name__) API_USER_CREDENTIALS_FOLDER = "/repo/data/auth/" API_USER_PATH = f"{API_USER_CREDENTIALS_FOLDER}/api_user.txt" ...
StarcoderdataPython
3255287
<reponame>Pittsy24/Python-Vectors<filename>vectors.py #!/usr/bin/python3 # By <NAME> import math class vector2D(object): def __init__(self, x_coord, y_coord): super().__init__() self.x = x_coord self.y = y_coord def set(self, x_coord, y_coord): """Sets the x, y ...
StarcoderdataPython
1757914
#!/usr/bin/env python # -*- coding: utf-8 -*- """ cc_licences.py Script to create cc_licence records. Script can be re-run without creating duplicate records, but will update/replace existing records. The --clear is not recommended if books already have cc_licences. """ import os import sys import traceback from opt...
StarcoderdataPython
3322779
<filename>ofanalysis/notion/notion_fund_pool_update.py<gh_stars>0 from datetime import datetime from loguru import logger import requests from ofanalysis import const import ofanalysis.utility as ut from ofanalysis.notion import notion_operation import pandas as pd def update_profit_ratio_to_notion(): def get_pro...
StarcoderdataPython
1621727
<reponame>Roibal/Geotechnical_Engineering_Python_Code<filename>Ventilation-Mining-Engineering/VentSurveyProgram.py<gh_stars>1-10 class VentilationSurvey(object): """ The purpose of this program is to automate the data analysis portion of a ventilation survey performed in an underground mine. Accepts a...
StarcoderdataPython
1763647
def is_iterable(item): try: iter(item) return True except TypeError: return False def as_json(item): if is_iterable(item): return {i.id: i.serialize() for i in item} return item.serialize() # @auth.error_handler() # def error_handler(callback): # return jsonify({ ...
StarcoderdataPython
61338
<gh_stars>1-10 """Tests the feature extraction""" # Tests are verbose. # pylint: disable=too-many-statements, too-many-locals import math import numpy as np from pytest import approx from infrastructure import InfrastructureNetwork from overlay import OverlayNetwork from embedding import PartialEmbedding, ENode fro...
StarcoderdataPython
3319775
#!/usr/bin/env python from flask import Flask, jsonify, render_template, request, send_file, make_response import json from influxdb import InfluxDBClient import numpy as np from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplo...
StarcoderdataPython
1788148
import typing import asyncpg from databases.core import Connection from tvsched.adapters.repos.actor.models import ActorRecord from tvsched.adapters.repos.actor.utils import ( map_actor_record_to_model, ) from tvsched.application.exceptions.actor import ( ActorAlreadyInShowCastError, ActorNotFoundError, ...
StarcoderdataPython
139658
import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn import linear_model plt.style.use('fivethirtyeight') datafile = 'datafile.txt' data = np.loadtxt(datafile,delimiter=',',usecols=(0,1,2),unpack=True) X = np.transpose(np.array(data[:-1])) Y = np.transpose(np.array(data[-1:])) pos = np...
StarcoderdataPython
3370603
<reponame>brendanhoran/nmea_faker # Author <NAME> # License : BSD 3-Clause # Description : Get a NMEA setence from the NMEA faker sever import wifi_setup import nmea_client import time wifi_setup = wifi_setup.WIFI_setup('YOUR_SSID','YOUR_PASSWORD') wifi_setup.connect() # format is, RX pin, TX pin, IP address and port...
StarcoderdataPython
3313083
<reponame>jianershi/algorithm<gh_stars>1-10 """ 404. Subarray Sum II https://www.lintcode.com/problem/subarray-sum-ii/description prefix sum definition including itself """ class Solution: """ @param A: An integer array @param start: An integer @param end: An integer @return: the number of possibl...
StarcoderdataPython
28982
import os import enum import hashlib from urllib.parse import urljoin from flask import url_for, current_app as app from mcarch.app import db, get_b2bucket class StoredFile(db.Model): """Represents a file stored in some sort of storage medium.""" __tablename__ = 'stored_file' id = db.Column(db.Integer, p...
StarcoderdataPython
1764501
from copy import deepcopy from django.urls import reverse from django.utils import timezone from core.utils import getEbayStrGotDateTimeObj from .base import SetupUserItemsFoundAndUserFindersWebTest from ..forms import ( ItemFoundForm, UserItemFoundUploadFo...
StarcoderdataPython
66798
"""create exchange market table Revision ID: 76f253d77eba Revises: 4d9ca085df42 Create Date: 2019-09-22 01:32:11.855978 """ from antalla.settings import TABLE_PREFIX from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "76f253d77eba" down_revision = "4d9ca085df42" branc...
StarcoderdataPython
3346180
<filename>Arquivos/Lendo as linhas do arquivo.py """ Programa 116 Área de estudos. data 13.12.2020 (Indefinida) Hs @Autor: <NAME> """ # Abrimos o arquivo para leitura. arquivo = open('/home/abraao/Documentos/testando.txt', 'rt') # Ou 'r' modo que nos permite ler. for linha in arquivo: # Lendo linha por linha...
StarcoderdataPython
3344670
""" This file is part of pysofar: A client for interfacing with Sofar Oceans Spotter API Contents: Classes for representing devices and data grabbed from the api Copyright (C) 2019 Sofar Ocean Technologies Authors: <NAME> """ from pysofar.sofar import SofarApi, WaveDataQuery # --------------------- Devices -------...
StarcoderdataPython
3220443
from eICU_preprocessing.split_train_test import create_folder from torch.optim import Adam from models.tpc_model import TempPointConv from models.experiment_template import ExperimentTemplate from models.initialise_arguments import initialise_tpc_arguments from models.final_experiment_scripts.best_hyperparameters impor...
StarcoderdataPython
1784102
# Generated by Django 3.0.6 on 2020-06-22 13:14 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("components", "0001_initial"), ("cases", "0024_auto_20200525_0634"), ("algorithms", "0025_algorithmimage_queue...
StarcoderdataPython
3299033
<filename>python/python-008/lambda_function.py import json def lambda_handler(event, context): print(json.dumps(event)) return { 'status': 200, 'headers': { 'Content-Type': 'application/json' }, 'body': json.dumps({'message': 'OK'}) }
StarcoderdataPython
27349
#!/usr/bin/env python # -------- BEGIN LICENSE BLOCK -------- # Copyright 2022 FZI Forschungszentrum Informatik # # 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 the ab...
StarcoderdataPython
133806
<gh_stars>0 """ Functions and classes related to working with Python's native asyncio support To avoid issues with the ``async`` keyword, this file is named ``asyncx`` instead of ``async`` **Copyright**:: +===================================================+ | © 2019 Privex Inc. ...
StarcoderdataPython
1686217
<filename>exe1103_teste.py import unittest from exe1103_employee import Employee class TestEmployee(unittest.TestCase): """[Testes para a classe Employee] """ def setUp(self): """[Cria dois testes para Employee.] """ self.junior = Employee('junior', 'pedroso', 10000) def test...
StarcoderdataPython
1636583
#!/usr/bin/env python from ecmwfapi import ECMWFDataServer import datetime import dateutil.parser import sys erai_info = {} erai_info["class"] = "ei" erai_info["dataset"] = "interim" erai_info["expver"] = "1" erai_info["grid"] = "0.75/0.75" erai_info["levtype"] = "sfc" erai_info["param"] = "39.128/40.128/41.128/42.128...
StarcoderdataPython
117570
from suds.client import Client from suds.plugin import MessagePlugin from suds.cache import FileCache from .http import HttpTransport from . import settings import logging logger = logging.getLogger(__name__) #: Cache of :class:`suds.client.Client <suds.client.Client>` objects #: When unit-testing SOAP APIs it's pr...
StarcoderdataPython