id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1740369 | from load_data import LoadData
from preprocess_data import PreprocessData
from model_data import CNNClassificationModel
from sklearn.metrics import accuracy_score
from sklearn.utils import shuffle
import pandas as pd
import time
import datetime
import sys
import numpy as np
import torch
import argparse
import os
import... | StarcoderdataPython |
50663 | <reponame>ASUPychron/pychron
# ===============================================================================
# Copyright 2021 ross
#
# 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:/... | StarcoderdataPython |
1675588 | """
设备操作业务
"""
from app.models.equipment import Equipment
from app.db import water_heater
from typing import List
def get_all() -> List[Equipment]:
"""获取所有设备
"""
data: List[Equipment] = []
collection = water_heater.get_equipment()
for item in collection.find():
equip = Equipment(**item)... | StarcoderdataPython |
3386659 | <reponame>pugsatoshi/opencv-camera
#!/usr/bin/env python
import cv2
deviceid=0 # it depends on the order of USB connection.
capture = cv2.VideoCapture(deviceid)
ret, frame = capture.read()
cv2.imwrite('test.jpg', frame)
| StarcoderdataPython |
1647483 | <filename>app.py
from aws_cdk import core
from stacks.api_stack import ApiStack
from stacks.lambda_stack import LambdaStack
from stacks.state_machine_stack import StateMachineStack
class InferenceStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scop... | StarcoderdataPython |
1656748 | __all__ = ["MicroTools", "TimerTools"] | StarcoderdataPython |
186483 | import boto3
from thundra_demo_localstack.utils import Singleton
from thundra_demo_localstack.config import EnvironmentConfig
class DynamoDbClient(metaclass=Singleton):
def __init__(self):
self.dynamodbClient = boto3.client('dynamodb', endpoint_url=EnvironmentConfig.LOCALSTACK_URL, region_name=Environmen... | StarcoderdataPython |
39880 | # -*- coding: utf-8 -*-
# Fonte https://realpython.com/k-means-clustering-python/
# Clustering is a set of techniques used to partition data into groups, or clusters. Clusters are loosely defined as groups of data objects that are more similar to other objects in their cluster than they are to data objects in oth... | StarcoderdataPython |
135477 | #!/usr/bin/python
# Takes a CSV from HSBCnet's Excel output and transforms it into OFX
# TODO: spec says account info is required: FID, INTU.BID, INTU.USERID
# SEE SPEC:
# https://fi.intuit.com/ofximplementation/dl/wc_spec.pdf
import csv
import math
import sys
import time
# Substitute your bank ID and account ID ... | StarcoderdataPython |
65906 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | StarcoderdataPython |
3316654 | <gh_stars>0
from unittest import TestCase
import model
class TestJoke(TestCase):
def test_is_dict(self):
s = model.my_model(1,100)
print(s)
self.assertTrue(isinstance(s, dict))
def test_is_inRange(self):
s = model.my_model(1,100)
self.assertTrue(s, dict) | StarcoderdataPython |
1641275 | import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader
from typing import Optional, Tuple, Dict, Any
import numpy as np
from collections import defaultdict
from mdlearn.utils import PathLike
from mdlearn.nn.utils import Trainer
class LSTM(nn.Module):
"""LSTM... | StarcoderdataPython |
3396272 | import mysql.connector
from configuration.config import config
from pprint import pprint
import os
#################################################################################
# EXAMPLE USAGE - Exploring what's in the database.
################################################################################... | StarcoderdataPython |
4834399 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Project : stock_quant
# @Date : 2022/1/2 17:34
# @Author : Adolf
# @File : __init__.py.py
# @Function:
| StarcoderdataPython |
14100 | <gh_stars>0
#!/usr/bin/env python
"""
Example:
$ python ./ncdf2bp.py netcdf_file
"""
from adios import *
from scipy.io import netcdf
import numpy as np
import sys
import os
import operator
def usage():
print os.path.basename(sys.argv[0]), "netcdf_file"
if len(sys.argv) < 2:
usage()
sys.exit(0)
##fname ... | StarcoderdataPython |
1751017 | <filename>1138_05_15-attr-sel.py<gh_stars>0
""""Attribute selection for subset""""
import shapefile
# Create a reader instance
r = shapefile.Reader("MS_UrbanAnC10")
# Create a writer instance
w = shapefile.Writer(r.shapeType)
# Copy the fields to the writer
w.fields = list(r.fields)
# Grab the geometry and reco... | StarcoderdataPython |
38847 | # -*- coding: utf-8 -*-
"""
Low level tool for writing percent difference reports. Typically, this
is called via: :func:`cla.DR_Results.rptpct`.
"""
from io import StringIO
from types import SimpleNamespace
import warnings
import numpy as np
import matplotlib.pyplot as plt
from pyyeti import ytools, locate, writer
from... | StarcoderdataPython |
128077 | <filename>built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/mmdet/core/__init__.py
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 t... | StarcoderdataPython |
3204347 | import cv2
from scipy import ndimage
import time
import math
import matplotlib.pyplot as plt
from skimage.measure import label
from skimage.measure import regionprops
from skimage import color
import numpy as np
import Tkinter as tk
import tkFileDialog as filedialog
from sklearn.datasets import fetch_mldata
# otvaramo... | StarcoderdataPython |
3375867 | from django.conf import settings
from django.contrib.sitemaps import Sitemap
from blog.models import Post
class BlogSitemap(Sitemap):
changefreq = "never"
priority = 0.9
def items(self):
return Post.published_objects.all()
def lastmod(self, obj):
return obj.date_modified
def lo... | StarcoderdataPython |
133199 |
from mrjob.job import MRJob
class MRMappersideRightJoin(MRJob):
countries = {}
ex_list = []
def mapper_init(self):
with open('/media/notebooks/SP18-1-maynard242/HW5/Countries.dat', 'r') as f:
for line in f:
tokens = line.strip().split('|')
self... | StarcoderdataPython |
188905 | <reponame>weiwee/mypy-protobuf
"""
This file serves two purposes
1) Run a test which ensures that mypy is producing the expected output. For
developer convenience, in the case which it doesn't, it'll copy over the
output to the expected output, so you can view the output diff in your
code reviews. This will fail in CI ... | StarcoderdataPython |
1784919 | <filename>WriteCSVFiles/WriteCSVFilesWithDictionary.py
import csv
users = [{"name":"SolMansi", "username": "solm", "department": "IT infrastructure"},{"name":"<NAME>", "username": "lion", "department": "User Experience Research"},{"name":"<NAME>", "username": "greyc", "department": "Development"}]
keys = ["name", ... | StarcoderdataPython |
4808065 | def rotate(display, axis, index, amount):
if axis == "row":
display[index] = display[index][-amount:] + display[index][:-amount]
else:
column = [r[index] for r in display]
column = column[-amount:] + column[:-amount]
for r, colVal in zip(display, column):
r[index] = c... | StarcoderdataPython |
1705025 | <gh_stars>1000+
import android
import sys
import threading
import time
droid = android.Android()
droid.toggleBluetoothState(True)
droid.bluetoothMakeDiscoverable()
print 'Connecting...'
result = droid.bluetoothAccept()
if result.error is not None:
print 'Connection failed!'
time.sleep(1)
sys.exit(1)
def receiv... | StarcoderdataPython |
1711059 | #!/usr/bin/python
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parses /proc/[pid]/smaps on a device and shows the total amount of swap used.
"""
import argparse
import collections
import logging
imp... | StarcoderdataPython |
139337 | import os
import string
import random
from django.core.management.base import BaseCommand
from django.utils import six
from django.utils.six.moves import input
from django.conf import settings
class Command(BaseCommand):
help = "Generate/regenerate a random 50-character secret key stored in a file specified by the `S... | StarcoderdataPython |
34112 | """ Code to implement ScaleFactor:: decorator supported
in gtlike.
The gtlike feature is documented here:
https://confluence.slac.stanford.edu/display/ST/Science+Tools+Development+Notes?focusedCommentId=103582318#comment-103582318
Author: <NAME>
"""
import operator
from copy import deepcopy
... | StarcoderdataPython |
116880 | """
Provides Python modules such as;
* LiteXXX referenced as submodules.
* (Maybe?) pip installable libraries like;
- colorterm
- hexfile
- etc
"""
| StarcoderdataPython |
4832997 | <reponame>kofakira/Chess-python<gh_stars>1-10
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def create_game_room(request):
username = request.user.username
url = request.build_absolute_uri()
request.user.profile.game... | StarcoderdataPython |
56644 | <reponame>AndrewPotap/Coursera_Python_Course
import re
handler = open('Assignement text.txt')
total = 0
for line in handler:
line = line.strip()
words = re.findall('[0-9]+', line)
for i in words:
total += int(i)
print(total)
| StarcoderdataPython |
3335321 | import common as c
from config import qt_modules, qt_version, qt_dir, os_name
import sys
import xml.etree.ElementTree as ET
import shutil
import os
qt_modules_list = list(qt_modules.split())
c.print('>> Downloading Qt {} ({}) for {}'.format(qt_version, qt_modules_list, os_name))
# 5.9.9 : mingw53
# 5.10.1 : mingw53
... | StarcoderdataPython |
58407 | <reponame>balder2046/my-program
import queue
import threading
class Task:
def __init__(self,id,func):
self.id = id
self.func = func
def run(self):
self.func()
class TaskQueue:
def __init__(self):
self.tasks = queue.Queue()
pass
def add_task(self,task):
... | StarcoderdataPython |
1703556 | # Copyright 2018 Alibaba Group. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | StarcoderdataPython |
141223 | import numpy as np
########################## method used - "1env_1jet", or "1env_njet" ##################################################
method='1env_1jet'
########################## nature of neural network - "mlp", "mlp_shared" or "cnn" ##################################################
policy_name='mlp'
####... | StarcoderdataPython |
3394636 | import pygame
import random
import math
ancho_celda = 50
columnas = filas = 10
width = columnas * ancho_celda
height = filas * ancho_celda
class snake:
bbody = []
dirx = 0
diry = 1
cap = pygame.Vector2(math.ceil(columnas/2), math.ceil(filas/2))
def move(self):
for i in range( len(self.bbo... | StarcoderdataPython |
3214060 |
from flask import Flask, render_template, request, url_for, redirect, jsonify
from flask_cors import CORS
from decouple import config
import joblib
from model import *
import pandas as pd
application = Flask(__name__,static_url_path="/static/")
CORS(application)
loadcv = joblib.load('models/tf.joblib')
loaddf = jobl... | StarcoderdataPython |
1758918 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
import json
from cclib.parser.data import ccData
class CJSON:
""" CJSON log file"""
def __init__(self, source,... | StarcoderdataPython |
1614845 | <filename>starter_code/api_keys.py
# OpenWeatherMap API Key
weather_api_key = "<KEY>"
# Google API Key
g_key = "<KEY>"
| StarcoderdataPython |
80387 | <reponame>mas-dse-ringhilt/DSE-American-Gut-Project<gh_stars>1-10
# -*- coding: utf-8 -*-
# Body Site Classification
from american_gut_project_pipeline.persist import load_dataframe, download_file, save_dataframe, upload_file
import pandas as pd
import numpy as np
import luigi
from american_gut_project_pipeline.pipeli... | StarcoderdataPython |
1761707 | # Have you seen that Windows screensaver?
from pyalleg import *
from random import randint
from math import sqrt,atan,atan2,sin,cos
try:
import psyco
psyco.full()
except:
pass
def getRgb(c):
return (c&0xFF0000)>>16,(c&0xFF00)>>8,c&0xFF
def applyWarper(target,warper,bx,by,scale=1.0):
w,h=warper.size()
tw,th=flo... | StarcoderdataPython |
1724980 | <reponame>MarsRobotics/Experiments<filename>LIDAR Data Extraction/LidarCommands/Currently Used/rpi/control.py
__author__ = '<NAME>, <NAME>, and <NAME>'
import raspi_threads as rasp
from rasp import *
from constants import *
def __main__():
#TODO implement publisher... Also check timing (main may take time to run)... | StarcoderdataPython |
4820369 | <reponame>trompamusic/ce-import-muziekweb
"""
Import per data type
"""
from .artist import import_artist
from .music_album import import_album
from .audio_object import import_tracks
from .musicbrainz import load_person_from_musicbrainz
from .isni import load_person_from_isni
from .viaf import load_person_from_viaf
fro... | StarcoderdataPython |
3337629 | from .uiserver import UiServer
from ..config import Config, Startable
from asyncio import create_task, Event
from injector import inject, singleton
from ..logger import getLogger
logger = getLogger(__name__)
@singleton
class Restarter(Startable):
@inject
def __init__(self, server: UiServer, config: Config):
... | StarcoderdataPython |
86400 | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if not s:
return True
m, n = 0, len(s) - 1
i, j = 0, len(t) - 1
while i <= j and m <= n:
if t[i] == s[m]:
m += 1
i += 1
else:
i += 1
... | StarcoderdataPython |
3300360 | <reponame>EduardRosert/skinnywms
# Copyright (C) ECMWF 2018
import logging
import os
import traceback
import threading
from skinnywms import datatypes
from skinnywms.fields.NetCDFField import NetCDFReader
from skinnywms.fields.GRIBField import GRIBReader
__all__ = [
"Availability",
]
LOCK = threading.Lock()
... | StarcoderdataPython |
162758 | <reponame>bocklund/database-concepts
from pycalphad import Database, Model, calculate, variables as v
import ion_parser
dbf_ion = Database('test.ion')
mod = Model(dbf_ion, ['AL', 'ZN'], 'LIQUID')
res = calculate(dbf_ion, ['AL', 'ZN'], 'LIQUID', T=600, P=1e5)
print(res) | StarcoderdataPython |
3215638 | <gh_stars>1-10
"""Platform for sensor integration."""
from __future__ import annotations
from homeassistant.components.sensor import (
DEVICE_CLASS_TEMPERATURE,
STATE_CLASS_MEASUREMENT,
SensorEntity,
)
from homeassistant.const import TEMP_CELSIUS
from homeassistant.core import HomeAssistant
from homeassist... | StarcoderdataPython |
3277340 | import face_recognition
import cv2
import os
import numpy as np
from keras.models import load_model
from statistics import mode
from utils.datasets import get_labels
from utils.inference import detect_faces
from utils.inference import draw_text
from utils.inference import draw_bounding_box
from utils.inference import a... | StarcoderdataPython |
1790994 | import numpy as np
import astropy.io.ascii as ascii
import matplotlib.pyplot as plt
pyout = ascii.read('test.pyout')
idlout = ascii.read('test.idlout')
fig, axarr = plt.subplots(4, 2, figsize=(10, 10))
fig.suptitle("python")
axarr[0,0].plot(pyout['alpha'])
axarr[0,0].set_ylabel('alpha')
axarr[0,1].plot(pyout['beta']... | StarcoderdataPython |
1634136 | #functions to help with running fiberassign, using SV3 parameters/targets
import fitsio
import numpy as np
from astropy.table import Table,join
# system
import os
import subprocess
import sys
import tempfile
import shutil
import re
# time
from time import time
from datetime import datetime, timedelta
#import some f... | StarcoderdataPython |
172928 | """
From <NAME>'s lecture 11 Jun 2020
Given the head of a sll and a node, return its index (position).
Assume that indexing starts at 0.
Return -1 if index is not found.
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
def find_index(head, node):
# Edge cases
... | StarcoderdataPython |
115899 | <reponame>nabiirah/advent-of-code<gh_stars>10-100
"""Advent of Code Day 4 - The Ideal Stocking Stuffer"""
import hashlib
def mine_adventcoins(part_two=False):
"""Calculates and returns MD5 Hash with five leading zeroes."""
number = 0
while True:
hexed = hashlib.md5('{}{}'.format(key, number).encod... | StarcoderdataPython |
3378608 | #!/usr/bin/env python
from . import main as m
import sys
def main():
sys.exit(m.main(sys.argv))
| StarcoderdataPython |
3312655 | from . import client, connection, token, schema_main, ParentPart
from flask.wrappers import Response
import datajoint as dj
def test_list_tables(token, client, ParentPart):
ScanData, ProcessScanData = ParentPart
REST_tables = client.get(
f"/schema/{ScanData.database}/table",
headers=dict(Autho... | StarcoderdataPython |
3224736 | import logging
import gevent
from volttron.platform.vip.agent import Agent
from volttrontesting.utils.platformwrapper import start_wrapper_platform
from volttron.platform.agent import json
import pytest
import random
import requests
import os
import tempfile
from volttrontesting.fixtures.volttron_platform_fixtures im... | StarcoderdataPython |
1673316 | <reponame>soumickmj/Tricorder
import SimpleITK as sitk
def FileRead(file_path, return_sitkImg = False, ImageIO=None):
reader = sitk.ImageFileReader()
if bool(ImageIO): reader.SetImageIO(ImageIO)
reader.SetFileName(file_path)
image = reader.Execute()
arr = sitk.GetArrayFromImage(image)
if not re... | StarcoderdataPython |
1773612 | <filename>scripts/keras_to_syrenn.py
"""Script for converting sequential Keras models to SyReNN Networks.
"""
import tensorflow.keras as keras
import numpy as np
import pysyrenn
def keras_to_syrenn(model):
"""Converts a sequential Keras model to a SyReNN Network.
Note that this conversion code makes a number ... | StarcoderdataPython |
16073 | #!/usr/bin/env python
"""
Generate the file classes_to_be_wrapped.hpp, which contains includes,
instantiation and naming typedefs for all classes that are to be
automatically wrapped.
"""
import os
import ntpath
class CppHeaderCollectionWriter():
"""
This class manages generation of the header collection f... | StarcoderdataPython |
3377419 | import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule, Request
from douban.items import DoubanMovieItem
from douban.dns_cache import _setDNSCache
from scrapy.http import FormRequest
from faker import Factory
import numpy as np
f = Factory.create()
class DoubanMovieS... | StarcoderdataPython |
130173 | <filename>setup.py<gh_stars>0
from setuptools import find_packages
from setuptools import setup
setup(
name='crosswordpy',
version='0.0.1',
packages=find_packages(),
install_requires=('numpy', 'pytest', 'flask', 'flask-wtf', 'wtforms', 'pillow', 'gunicorn'),
author='<NAME>',
author_email='<EMA... | StarcoderdataPython |
3368863 | import logging
from flask import request
from flask_restplus import Resource
from ontobio.golr.golr_sim import subject_pair_simj
from biolink.api.restplus import api
from biolink import USER_AGENT
log = logging.getLogger(__name__)
parser = api.parser()
parser.add_argument('object_category', help='e.g. disease, pheno... | StarcoderdataPython |
1620044 | #!/usr/bin/env python
from turtlebot import Turtlebot
import numpy as np
import cv2
x_range = (-0.3, 0.3)
z_range = (0.3, 3.0)
WINDOW = 'obstacles'
def main():
turtle = Turtlebot(pc=True)
cv2.namedWindow(WINDOW)
while not turtle.is_shutting_down():
# get point cloud
pc = turtle.get_poin... | StarcoderdataPython |
1686522 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 3 17:35:44 2019
@author: koesa
"""
from keras.preprocessing.image import ImageDataGenerator
from keras.applications.vgg16 import VGG16
from keras.models import Model
from keras.layers import Dense, Flatten, Dropout
import matplotlib.pyplot as plt
dataset_Dir = 'C:\Data... | StarcoderdataPython |
164035 | import util as u
import re
import StringIO
def get_reg(invoke_param):
"""Return the parameter registry list"""
if invoke_param == '':
return
reg_list = re.finditer(r'(v|p)\d{1,3}', invoke_param)
for reg_value in reg_list:
yield reg_value.group()
def is_range(invoke_type):
"""Rang... | StarcoderdataPython |
1793736 | #
# Copyright 2011-2014 Ning, Inc.
# Copyright 2014-2017 Groupon, Inc.
# Copyright 2014-2017 The Billing Project, LLC
#
# The Billing Project, LLC licenses this file to you 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 ... | StarcoderdataPython |
1768466 | import time
from beerDatabase import *
from brewDatabase import *
def homePage():
print("\033[1;35;49m-----------------------------------------")
print("--- \U0001F37B \033[1;37;49m Welcome to Nikki's Brewery \U0001F37B \033[1;35;49m---")
print("-----------------------------------------")
print("\033[0... | StarcoderdataPython |
3318726 | """
Utility functions for building neural networks in theano.
Most of these are taken from http://deeplearning.net/tutorial/.
"""
from __future__ import print_function
import os
import sys
import timeit
import gzip
import pickle
import numpy as np
import theano
import theano.tensor as T
def load_data(dataset):
... | StarcoderdataPython |
3337262 | import Main
try:
Main.bot.run(Main.TOKEN)
except Exception:
Main.save()
raise
| StarcoderdataPython |
134516 | <filename>sskl_webui/my_hisapi.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
import json
import redis
import requests
from frappe.model.document import Document
from frappe.utils import cint
from frappe import... | StarcoderdataPython |
64046 | from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Q
from django.utils import timezone
from django.core.validators import MaxValueValidator, MinValueValidator
from django.shortcuts import get_object_or_404
from itertools import chain
... | StarcoderdataPython |
1680437 | <filename>molecular/preprocessing/mapping.py
# -*- coding: utf-8 -*-
from bioservices import biomart
from io import StringIO
import pandas as pd
class Mapping:
def __init__(self, host='www.ensembl.org'):
self.s = biomart.BioMart(host=host)
def ensembl_to_hgnc(self, ensembl_ids):
# building query
s... | StarcoderdataPython |
1743029 | <gh_stars>1-10
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import binascii
import sys
import warnings
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Callable, TypeVar
T = TypeVar('T')
SMS_DATETIME_FORMAT = '%d/%m/%Y %H:%M %z'
class EventType(Enum):
NEW_M... | StarcoderdataPython |
1734442 | #!/usr/bin/env python2
"""
this program shows how the proto1 -> proto2 upgrade looks like for
all metrics given as cmdline arguments.
very convenient to verify the working of plugins etc.
"""
import sys
from pprint import pprint
import logging
from graph_explorer import structured_metrics
from graph_explorer import c... | StarcoderdataPython |
1643187 | # Rao-Blackwellised particle filtering for jump markov linear systems
# Based on: https://github.com/probml/pmtk3/blob/master/demos/rbpfManeuverDemo.m
# Author: <NAME> (@gerdm)
# !pip install matplotlib==3.4.2
import jax
import numpy as np
import jax.numpy as jnp
import seaborn as sns
import matplotlib.pyplot as plt
... | StarcoderdataPython |
134815 | <filename>OpenSees/EXAMPLES/ExamplePython/Example4.1.py
# OpenSees -- Open System for Earthquake Engineering Simulation
# Pacific Earthquake Engineering Research Center
# http://opensees.berkeley.edu/
#
# 2 Story Multi Bay Frame Example 4.1
# -----------------------------------
# Reinforced concrete multi-bay, two-sto... | StarcoderdataPython |
1735877 | <filename>src/pretix/plugins/sendmail/signals.py<gh_stars>1-10
from django.dispatch import receiver
from django.urls import resolve, reverse
from django.utils.translation import gettext_lazy as _
from pretix.base.signals import logentry_display
from pretix.control.signals import nav_event
@receiver(nav_event, dispat... | StarcoderdataPython |
180067 | #!/usr/bin/python
import os, re, sys, getopt
lmstat="/path/to/flexlm/lmutil"
lmopts="lmstat"
def print_usage():
print "Usage:"
print os.path.basename(__file__), '-f <feature> -c <lic_server>'
def main(argv):
lic_server = ''
feature = ''
try:
opts, args = getopt.getopt(argv,"hf:c:",["feature=","lic_server="])
... | StarcoderdataPython |
169221 | <reponame>MohammadJavadD/dn3
import torch
from torch import nn
class _SingleAxisOperation(nn.Module):
def __init__(self, axis=-1):
super().__init__()
self.axis = axis
def forward(self, x):
raise NotImplementedError
# Some general purpose convenience layers
# -------------------------... | StarcoderdataPython |
1733904 | import torch
t = torch
import torch.nn as nn
import torch.nn.functional as F
from torchcv.models.dsod.densenet import DenseNet
from torch.autograd import Variable
import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd import Variable
import torch.nn.init as init
class L2Norm(nn.Mod... | StarcoderdataPython |
153381 | <reponame>Manuelinux/kubeh<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from unittest import mock
import pytest
from h.services.annotation_stats import AnnotationStatsService
from h.services.annotation_stats import annotation_stats_factory
from h.search import Search
from h.search impo... | StarcoderdataPython |
1738093 |
__all__ = ["fasta_file_validator",
"sequence_extractor",
"Data_frame",
"predict_sequence",
"Predict_frame",]
import os
import pandas as pd
def fasta_file_validator(file):
if os.path.isfile(file):
return True
return TypeError("File doesn't exist.")
def... | StarcoderdataPython |
1666106 | <gh_stars>0
from random import randint as randint
class Character(object):
def __init__(self, race, health, power, coins, items=[], attacked=False, armor=0):
self.race = race
self.health = health
self.power = power
self.coins = coins
self.items = items
self.attacked ... | StarcoderdataPython |
1771712 | """
module for TLE processing
"""
from ephem import readtle
import numpy as np
from cssrlib.gnss import id2sat
def loadname(file):
""" load satellite list from file """
satlist = {}
with open(file, 'r') as f:
for line in f:
if line[0] == '#':
continue
... | StarcoderdataPython |
1734894 | import pytest
def test_default(docker_compose, nginxproxy):
r = nginxproxy.get("http://nginx-proxy.test/port")
assert r.status_code == 200
assert r.text == "answer from port 81\n"
def test_simple_path_not_stripped(docker_compose, nginxproxy):
r = nginxproxy.get("http://nginx-proxy.test/foo/port")
... | StarcoderdataPython |
3297405 | # Copyright 2015 The TensorFlow 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/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
25282 | import base64
import json
import activity
import os
import requests
import boto.sqs
from boto.sqs.message import Message
from provider import eif
"""
ConvertJATS.py activity
"""
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0, parentdir)
class activity_ApprovePublication(... | StarcoderdataPython |
3386060 | <filename>enstools/clustering/wrapper.py
"""
Wrapper around sklearn cluster methods for more convenience.
"""
import sklearn.cluster
from sklearn.metrics import silhouette_score
import numpy as np
import xarray
import dask.delayed
import dask.array
methods = {"kmeans": sklearn.cluster.KMeans,
"aprop": sklea... | StarcoderdataPython |
3286023 | def lengthOfLongestSubstring(s):
"""
:type s: str
:rtype: int
"""
substring = ""
previous = ""
length = 0
for char in s:
if char not in substring:
print(char, 'not in ', substring)
substring += char
length = len(substring) if length < len(subst... | StarcoderdataPython |
1786723 | <reponame>karthik20122001/docker-python
import unittest
import fasttext
class TestFastText(unittest.TestCase):
def test_tokenize(self):
tokens = fasttext.FastText.tokenize("Hello World")
self.assertEqual(["Hello", "World"], tokens)
| StarcoderdataPython |
3201926 | <gh_stars>0
import pkg_resources
from PyQt5.QtSvg import QGraphicsSvgItem
from numpy.random import choice
from os.path import join
from ScotlandPYard.config.gameconfig import icons
from .abstractplayer import AbstractPlayer
class AbstractDetective(AbstractPlayer):
def __init__(self, engine, is_ai=False, name=Non... | StarcoderdataPython |
1668222 | <filename>hm_web/tests/test_navtags.py
"""
Tests for navtags
"""
import pytest
assert pytest
from django.http import HttpRequest
from hm_web.templatetags import navtags
def build_request(path):
"""
Build an HttpRequest object with the given path
"""
request = HttpRequest()
request.path = path
... | StarcoderdataPython |
3214385 | <gh_stars>1-10
# Generated by Django 3.0.3 on 2020-04-02 14:21
import comments.models
from django.db import migrations, models
import storages.backends.s3boto3
class Migration(migrations.Migration):
dependencies = [
('comments', '0025_projectattachment_projectattachmentcategory_projectcomment_projectcom... | StarcoderdataPython |
73360 | # Copyright 2018, <NAME> LLC
# License: Apache License Version 2.0
# -------------------------------------------------------------------------
# logger.py - basic wrapper around Python standard logging just so in
# case we need to change this behavior it is all in one place
# -------------------------------------... | StarcoderdataPython |
1784064 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name='metaerg',
version='2.0.17',
packages=setuptools.find_packages(where='src'),
url='https://github.com/kinestetika/MetaErg',
license='MIT',
author='<NAME>',
author_e... | StarcoderdataPython |
3299528 | #scatter plots of the FWHM growth x-intercept vs. C/ZLES, C, and ZLES
#plot file directory/name at end of each function definition
from __future__ import division
import numpy as np
from data_tools import get_inputFileParameter
import matplotlib
matplotlib.use('PDF')
import matplotlib.pyplot as plt
from data_tools im... | StarcoderdataPython |
120393 | <reponame>ArneKramerSunderbrink/ratio<gh_stars>0
"""Defines how knowledge is structured in python.
Specifically the translation of an rdf ontology into Python classes
"""
from ast import literal_eval
from collections import defaultdict
from itertools import count
from re import fullmatch, DOTALL
from flask import g
f... | StarcoderdataPython |
7026 | from test.vim_test_case import VimTestCase as _VimTest
from test.constant import *
# Anonymous Expansion {{{#
class _AnonBase(_VimTest):
args = ''
def _extra_options_pre_init(self, vim_config):
vim_config.append('inoremap <silent> %s <C-R>=UltiSnips#Anon(%s)<cr>'
% (EA, se... | StarcoderdataPython |
1658510 | #!/usr/bin/python
# coding=utf-8
import os
HOME = os.path.expanduser("~")
CURRENT_FOLDER = "/".join(__file__.split("/")[:-1])
DATASETS_CONFIG_FOLDER = os.path.join(CURRENT_FOLDER, "..", "datasets-configs")
DATASETS_FOLDER = os.path.join(HOME, ".dafter")
VERSION_FILE = os.path.join(CURRENT_FOLDER, "..", "VERSION.txt"... | StarcoderdataPython |
1631420 | from redis import Redis, StrictRedis
from . import BaseCache, BaseStorage, get_valid_kwargs
class RedisCache(BaseCache):
"""Redis cache backend.
Args:
namespace: redis namespace (default: ``'requests-cache'``)
connection: Redis connection instance to use instead of creating a new one
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.