id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
1848239 | <reponame>ButterAndButterfly/H-Breaker
#!/usr/bin/env python
# coding:utf-8
import os
def break_tail(path: str, keys):
if not isinstance(keys, bytes):
keys = bytes(keys, encoding = "utf8")
tail_lenth = len(keys)
file_lenth = os.path.getsize(path)
pointer = file_lenth - tail_lenth
... | StarcoderdataPython |
3401103 | <gh_stars>1-10
#!/usr/bin/env python3
# <NAME> 2021 - Phage Annotation Workshop
"""
Read a GenBank file (gbk) and return the upstream sequences of each feature
"""
import sys, os
import argparse
from Bio import SeqIO
if __name__ == "__main__":
args = argparse.ArgumentParser(description="Read a GenBank file (gbk)... | StarcoderdataPython |
3319973 | from styx_msgs.msg import TrafficLight
import rospy
import tensorflow as tf
import numpy as np
import os
import cv2
class TLClassifier(object):
def __init__(self, model_name):
# Variables
PATH_TO_CKPT = os.path.join(model_name, 'frozen_inference_graph.pb')
self.tl_colors = ['Red', 'Yello... | StarcoderdataPython |
9791235 | from .share_record import ShareRecord | StarcoderdataPython |
9680687 | """
********************************************************************************
* Name: files_tab.py
* Author: gagelarsen
* Created On: December 03, 2020
* Copyright: (c) Aquaveo 2020
********************************************************************************
"""
import json
import mimetypes
import os
import ... | StarcoderdataPython |
11395546 | <filename>09Ajax/10lagou.py
from selenium import webdriver
from lxml import etree
import re
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
class LagouSpider(object):
def __init__(self):... | StarcoderdataPython |
6660616 | import ui
class RootView(ui.View):
def __init__(self):
'''Children must call RootView.__init__(self), in order to set up hidden webview!'''
self.__w=ui.WebView(frame=(1,1,1,1))
self.add_subview(self.__w)
@staticmethod
def convert_point(point=(0,0),from_view=None,to_view=Non... | StarcoderdataPython |
9640309 | <reponame>eladc-git/model_optimization<filename>model_compression_toolkit/common/constants.py
# Copyright 2021 Sony Semiconductors Israel, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a c... | StarcoderdataPython |
6584127 | # Advanced Multi-Mission Operations System (AMMOS) Instrument Toolkit (AIT)
# Bespoke Link to Instruments and Small Satellites (BLISS)
#
# Copyright 2017, by the California Institute of Technology. ALL RIGHTS
# RESERVED. United States Government Sponsorship acknowledged. Any
# commercial use must be negotiated with the... | StarcoderdataPython |
8183965 | <filename>knox/models.py<gh_stars>100-1000
from django.conf import settings
from django.db import models
from django.utils import timezone
from knox import crypto
from knox.settings import CONSTANTS, knox_settings
User = settings.AUTH_USER_MODEL
class AuthTokenManager(models.Manager):
def create(self, user, exp... | StarcoderdataPython |
1797981 | from django.views.generic import RedirectView, FormView
from django.contrib.auth import authenticate, login
from django.shortcuts import Http404, redirect
from django.core.urlresolvers import reverse
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.contrib.auth.models import User
f... | StarcoderdataPython |
6672056 | from textual.app import App
from textual import events
from textual.view import View
from textual.widgets import Placeholder
from textual.layouts.grid import GridLayout
import logging
from logging import FileHandler
logging.basicConfig(
level="NOTSET",
format="%(message)s",
datefmt="[%X]",
handlers=[F... | StarcoderdataPython |
3380375 | <filename>lib/galaxy/managers/quotas.py<gh_stars>1-10
"""
Manager and Serializers for Quotas.
For more information about quotas: https://galaxyproject.org/admin/disk-quotas/
"""
import logging
from typing import (
cast,
Optional,
Tuple,
Union,
)
from sqlalchemy import (
false,
true
)
from gal... | StarcoderdataPython |
5159097 | import numpy as np
from abc import ABC, abstractmethod
from sklearn.base import BaseEstimator
from regain.utils import namedtuple_with_defaults
convergence = namedtuple_with_defaults("convergence", "iter obj iter_norm iter_r_norm")
def build_adjacency_matrix(neighbours, how="union"):
out = np.eye(len(neighbour... | StarcoderdataPython |
9778430 | # Generated by Django 2.1.3 on 2018-12-28 05:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20181222_1252'),
]
operations = [
migrations.RenameField(
model_name='document',
old_name='document',
... | StarcoderdataPython |
6600485 | <gh_stars>0
# coding=utf-8
from common.constant import *
run_venv = 1
if run_venv == RUN_EVEN_TEST:
pass
else:
pass
DOC_DIR = "docs/"
DOC_TEMPLATE_DIR = "doc_templates/" | StarcoderdataPython |
1689481 | # -*- encoding: utf-8 -*-
from django.conf.urls import patterns, include, url
from .views import RecomendacionView
urlpatterns = patterns('',
url(r'^recomendacion/$', RecomendacionView.as_view(), name='recmendacion_url'),
)
| StarcoderdataPython |
5000798 | <filename>src/huggingmolecules/featurization/featurization_grover.py
from dataclasses import dataclass
from typing import *
import torch
from rdkit import Chem
from .featurization_api import RecursiveToDeviceMixin, PretrainedFeaturizerMixin
from .featurization_common_utils import stack_y, generate_additional_features... | StarcoderdataPython |
8137840 | #this file is just a tank of utilities for ploting stuff mainly.
#It creates the figures and the plots
import os
import pickle#5 as pickle
#import pickle5
import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model imp... | StarcoderdataPython |
3263537 | <filename>netrd/distance/hamming.py
"""
hamming.py
--------------
Hamming distance, wrapper for scipy function:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.hamming.html#scipy.spatial.distance.hamming
"""
import scipy
import numpy as np
import networkx as nx
from .base import BaseDista... | StarcoderdataPython |
11341108 | <gh_stars>1-10
import json
import sys
import traceback
import policy
def load_config():
with open('config.json', 'r') as config_file:
raw = config_file.read()
return json.loads(raw)
def lambda_handler(event, context): # pylint: disable=unused-argument
try:
tmp = event['methodArn'].spli... | StarcoderdataPython |
1782169 | # -*- coding: utf-8 -*-
# $Id: wuiadmintestbox.py 69111 2017-10-17 14:26:02Z vboxsync $
"""
Test Manager WUI - TestBox.
"""
__copyright__ = \
"""
Copyright (C) 2012-2017 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free softwa... | StarcoderdataPython |
9650595 | <gh_stars>0
########################################
#### Licensed under the MIT license ####
########################################
import torch
import torch.nn as nn
import torch.optim as optim
import os
import numpy as np
import cv2
from numpy import prod
from datetime import datetime
from model import CapsuleN... | StarcoderdataPython |
12843381 | <reponame>vail130/norm
from __future__ import absolute_import, unicode_literals
import unittest
from mason import Param, ANY, SELECT, COUNT, SUM, AND, OR, Table, NUMERIC, DATE, COALESCE, CASE
class TheSelectClass(unittest.TestCase):
def test_returns_string_for_select_query(self):
purchases = Table('purc... | StarcoderdataPython |
8073719 | <reponame>adelekap/ModelingBehavior_QLearning
"""
Theses are the learning functions that your
agent can utilize.
Returns the value of alpha.
"""
def constant(agent,state):
return agent.alpha[8:]
def decreasingLinear(agent,state):
return (1/(agent.episodesSoFar+state.trial))
def decreasingExponential(agent,... | StarcoderdataPython |
8108160 | <reponame>pivotal-energy-solutions/docusign-python-client<filename>docusign_esign/models/reminders.py
# coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
OpenAPI spec version: v2
Contact: <EMA... | StarcoderdataPython |
1957274 | from __future__ import print_function, absolute_import, division
if not hasattr(__builtins__, 'bytes'):
bytes: bytes = str
| StarcoderdataPython |
3550479 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | StarcoderdataPython |
1875347 | __name__ = "scratchconnect"
__version__ = "2.4"
__author__ = "<NAME>"
__documentation__ = "https://sid72020123.github.io/scratchconnect/"
__doc__ = f"""
scratchconnect is a Python Library to connect Scratch API and much more.
This library can show the statistics of Users, Projects, Studios, Forums and also connec... | StarcoderdataPython |
8152810 | <filename>bioconda_utils/bot/views.py
"""
HTTP Views (accepts and parses webhooks)
"""
import logging
from aiohttp import web
from aiohttp_session import get_session
from aiohttp_security import check_authorized, forget, permits, remember, authorized_userid
from aiohttp_jinja2 import template, render_template
from .... | StarcoderdataPython |
4886188 | <filename>red/inara/turtle/__init__.py
from .lib import CoolTurtle as CoolTurtle | StarcoderdataPython |
8110882 | # -*- coding: utf-8 -*-
"""
oss2.defaults
~~~~~~~~~~~~~
全局缺省变量。
"""
#: 连接超时时间
connect_timeout = 10
#: 缺省重试次数
request_retries = 3
#: 对于某些接口,上传数据长度大于或等于该值时,就采用分片上传。
multipart_threshold = 10 * 1024 * 1024
#: 缺省分片大小
part_size = 10 * 1024 * 1024 | StarcoderdataPython |
110066 | class FeeValidator:
def __init__(self, specifier) -> None:
super().__init__()
self.specifier = specifier
def validate(self, fee):
failed=False
try:
if fee != 0 and not 1 <= fee <= 100:
failed=True
except TypeError:
failed=True
... | StarcoderdataPython |
4918818 | from setuptools import setup, find_packages
setup(
name="ell-pkg-mcon",
version="0.0.1",
author="<NAME>",
author_email="<EMAIL>",
description="Python3 bindings for Ell lib",
packages=find_packages(),
setup_requires=["cffi>=1.0.0"],
cffi_modules=["ell_build.py:ffibuilder"], # "filename:... | StarcoderdataPython |
4828789 | <gh_stars>1-10
from argparse import ArgumentTypeError as err
import os
# modified from https://stackoverflow.com/a/33181083/1052418
class PathType(object):
def __init__(self, type='file'):
'''
exists:
True: a path that does exist
False: a path that does not exist, in a val... | StarcoderdataPython |
12819886 | # Copyright (c) 2017 <NAME>, All rights reserved.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
... | StarcoderdataPython |
91403 | <reponame>Alacrate/the-tale<gh_stars>10-100
import smart_imports
smart_imports.all()
class RoadChangeTests(helpers.BaseTestPrototypes):
def setUp(self):
super().setUp()
self.new_path = 'rddr'
self.old_road = roads_logic.road_between_places(self.place1, self.place2)
self.asser... | StarcoderdataPython |
9649540 | <filename>tests/recursivity/test_p6.py
import unittest
from recursivity.p6 import towers_of_hanoi
class TestTowersOfHanoi(unittest.TestCase):
def test_move(self):
"""
Input:
stack1: [3, 2, 1]
stack2: []
stack3: []
Output:
stack1: []
... | StarcoderdataPython |
3400812 | import can
import cantools
import time
import os
if os.name == 'nt':
#bus = can.interface.Bus(channel='PCAN_USBBUS1', bustype='pcan', bitrate=250000, fd=True)
bus = can.interface.Bus(channel=0, bustype='vector', bitrate=250000, fd=True)
else:
bus = can.interface.Bus(channel='vcan0', bustype='socketcan', b... | StarcoderdataPython |
12858392 | '''
- Leetcode problem: 352
- Difficulty: Hard
- Brief problem description:
Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of
disjoint intervals.
For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will... | StarcoderdataPython |
8129795 | class Node:
nxt = None
def __init__(self, data):
self.data = data
def __str__(self) -> str:
nxt_notation = 'Node' if self.nxt is not None else 'None'
return f'Node {{ data: {self.data}, nxt: {nxt_notation} }}'
"""
Singly linked list.
"""
class LinkedList:
length = 0
head = None
tail = None
d... | StarcoderdataPython |
344266 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.5
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2, 6, 0):
def swig_import_helper():
from os.path imp... | StarcoderdataPython |
4875414 | #!/usr/bin/env python3
import cgi, cgitb, os
from secret import username, password
from templates import _wrapper, secret_page, after_login_incorrect
# Create insatnce of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
user_name = form.getvalue('username')
pwd = form.getvalue('password')
# check if the... | StarcoderdataPython |
3257884 | <reponame>lcsm29/project-euler<filename>py/py_0597_torpids.py<gh_stars>0
# Solution of;
# Project Euler Problem 597: Torpids
# https://projecteuler.net/problem=597
#
# The Torpids are rowing races held annually in Oxford, following some curious
# rules:A division consists of $n$ boats (typically 13), placed in order ... | StarcoderdataPython |
6612989 | <filename>__init__.py<gh_stars>0
from mycroft import MycroftSkill, intent_file_handler
class Fry(MycroftSkill):
def __init__(self):
MycroftSkill.__init__(self)
@intent_file_handler('fry.intent')
def handle_fry(self, message):
self.speak_dialog('fry')
def create_skill():
return Fry()... | StarcoderdataPython |
6525 | # -*- coding: utf-8 -*-
import os
from django.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver
from .base import Pessoa
from djangosige.apps.login.models import Usuario
from djangosige.configs.settings import MEDIA_ROOT
def logo_directory_path(inst... | StarcoderdataPython |
3242243 | <reponame>NikhilNarayana/pyforms-lite
# !/usr/bin/python
# -*- coding: utf-8 -*-
from pyforms_lite.gui.controls.ControlBase import ControlBase
from AnyQt.QtWidgets import QTreeWidget, QTreeWidgetItem, QTreeView, QAbstractItemView, QAction
from AnyQt.QtGui import QIcon, QKeySequence
from AnyQt import QtCore
class Cont... | StarcoderdataPython |
8132580 | import tqdm
import argparse
import numpy as np
import datetime
import time
import spacy
import pandas as pd
from sklearn.metrics import f1_score
from torch import optim
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from preprocess_utils import *
from train import trai... | StarcoderdataPython |
5057778 | <filename>backend/sellers/tests/test_models.py
from django.contrib.auth import get_user_model
from django.test import TestCase
from sellers.models import Seller
class SellerModelTest(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
username="testuser",
... | StarcoderdataPython |
3294122 | <reponame>yihenghu/Aristolochia_fimbriata_genome_analysis<gh_stars>1-10
import glob
import re
from Bio import SeqIO
def rm_3(seq):
new = ''
for index, i in enumerate(str(seq)):
if (index + 1) % 3 != 0:
new += i
return new
def save_3(seq):
new = ''
for index, i in enumerate(st... | StarcoderdataPython |
3247424 | <gh_stars>0
from launch import LaunchDescription
from launch_ros.actions import Node
from launch.actions import ExecuteProcess
def generate_launch_description():
return LaunchDescription([
ExecuteProcess(
# cmd=['gazebo', '--verbose', 'sdf/world.sdf', '-s libgazebo_ros_factory.so'],... | StarcoderdataPython |
11273805 | <reponame>HelloAny/nwalgo<gh_stars>0
import itertools
import copy
def compile(seq1, seq2, score_dic, method):
score_matrix = [[0 for column in range(len(seq1))]
for row in range(len(seq2))]
trace_back = [[[]for column in range(len(seq1))]
for row in range(len(seq2))]
# 打分矩... | StarcoderdataPython |
6656573 | <reponame>bukun/TorCMS<filename>torcms/handlers/wiki_ajax_handler.py
# -*- coding:utf-8 -*-
'''
Handler for wiki, and page.
'''
from .wiki_handler import WikiHandler
class WikiAjaxHandler(WikiHandler):
'''
Handler for wiki, and page.
'''
def initialize(self):
super().initialize()
self... | StarcoderdataPython |
94574 | # Copyright The PyTorch Lightning team.
#
# 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 |
9636494 | <filename>test/test_transposition.py
import unittest
from romanyh.transposition import findKeysInRomanTextString
from romanyh.transposition import transposeKeys
transpositionTest = """
Composer: <NAME>
Title: Changing keys
Time signature: 4/4
m1 b1 C: I a: b4 i
m2 G: I e: b3 i
m3 b1 D: I b: b4 I
m4 A: I f#: b3 i
m5... | StarcoderdataPython |
8179899 | <reponame>oronnir/CAST<filename>EvaluationUtils/descriptive_stats.py
import os
import shutil
import json
import math
from EvaluationUtils.detection_mapping import DetectionMapping
from Animator.utils import eprint
from EvaluationUtils.image_utils import crop_image, save_image
from Animator.consolidation_api import Char... | StarcoderdataPython |
4974986 | <gh_stars>10-100
# Simple example showing how to use the MidasServer Python class
from midasserver import * # Make sure you have this and midassocket on your
# PYTHONPATH so the import picks this up
class MyServer(MidasServer) :
""" MyServer demonstrates how to write your own MidasServ... | StarcoderdataPython |
6570126 | import psycopg2
from datetime import datetime
from typing import Union
from ..data import ReserveDataAdapter
from ...entities import Supboard, User
class PostgressSupboardAdapter(ReserveDataAdapter):
"""Supboard PostgreSQL data adapter class
Attributes:
connection:
A PostgreSQ... | StarcoderdataPython |
8123999 | #pylint: disable=invalid-name
""" Sample MARI reduction script """
import os,sys
from numpy import *
from mantid import *
from Direct.ReductionWrapper import *
from mantid.simpleapi import *
from mantid.kernel import funcinspect
from mantid.dataobjects import EventWorkspace
import six
import types
from Direct.PropertyM... | StarcoderdataPython |
12803453 | """
"""
import numpy as np
from ..nfw_evolution import lgc_vs_lgt, get_bounded_params
from ..fit_nfw_helpers import fit_lgconc, get_loss_data
from ..fit_nfw_helpers_fixed_k import fit_lgconc as fit_lgconc_fixed_k
from ..fit_nfw_helpers_fixed_k import get_loss_data as get_loss_data_fixed_k
from ..fit_nfw_helpers_fixed_k... | StarcoderdataPython |
4984699 | GRCH_VERSION = 'GRCh37'
GRCH_SUBVERSION = '13'
ENSEMBL_VERSION = '88'
COSMIC_VERSION = '81'
DBSNP_VERSION = '150'
SPIDEX_LOCATION = 'spidex_public_noncommercial_v1.0/spidex_public_noncommercial_v1_0.tab.gz'
TRANSCRIPT_DB_PATH = 'ensembl/v' + ENSEMBL_VERSION + '/Homo_sapiens.' + GRCH_VERSION + '.cds.all.fa'
vcf_mutation... | StarcoderdataPython |
3560099 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Mon May 11 14:28:57 2020
@author: fgp35
"""
import os
from collections import OrderedDict
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import numpy as np
import torchvision
import pytorch_lightning as pl
from scipy.linalg import sqrt... | StarcoderdataPython |
3299697 | <gh_stars>10-100
from queue import Queue
from collections import defaultdict, namedtuple
Subscriber = namedtuple('Subscriber', 'queue, properties')
class Publisher(object):
"""
Contains a list of subscribers that can can receive updates.
Each subscriber can have its own private data and may subscribe to
... | StarcoderdataPython |
11231029 | import os
import subprocess
import sys
import time
import pytest
import torch
from elasticsearch import Elasticsearch
from haystack.document_store.elasticsearch import ElasticsearchDocumentStore
from haystack.reader.transformers import TransformersReader
from haystack.retriever.dense import EmbeddingRetriever, DensePa... | StarcoderdataPython |
6455296 | ##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to ... | StarcoderdataPython |
8197342 | <gh_stars>0
import os
import re
from flask import jsonify, request
"""Check whether password is valid"""
def password_validator(password):
if re.match(
r'^(?=.{6,}$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).*',
password):
return True
"""Check whether the email is vali... | StarcoderdataPython |
301360 | from django.conf.urls import url
from main import views
urlpatterns = [
url(r'^parse$', views.parse, name='parse'),
url(r'^reading$', views.reading, name='reading'),
]
| StarcoderdataPython |
1658292 | <filename>teste.py
from fixed_files_parse import Fixed_files
ff = Fixed_files('record', )
records = open('record.txt').readlines()
rec_in = []
for record in records:
rec_in.append(ff.parse(record))
# rec_in
# for rec in rec_in:
# print rec
#
# for n, r in enumerate(rec_in):
# print ff.unparse(r) == records[... | StarcoderdataPython |
296847 | <filename>tools/map_classes.py
#!/usr/bin/env python3
import argparse
import inspect
import json
import os
from pathlib import Path
from typing import Dict, List
import boto3
import botocore
from botocore import xform_name
parser = argparse.ArgumentParser(
description="Gathers data needed for annotating classes ... | StarcoderdataPython |
1780448 | # Copyright 2018 Open Source Robotics Foundation, 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... | StarcoderdataPython |
8129481 | """
Installation configuration.
"""
import os
import json
import setuptools
# Fetch the root folder to specify absolute paths to the "include" files
ROOT = os.path.normpath(os.path.dirname(__file__))
# Specify which files should be added to the installation
PACKAGE_DATA = [
os.path.join(ROOT, "surface", "res", "m... | StarcoderdataPython |
1955072 | <gh_stars>1-10
from pyrogram import filters
from pyrogram.types import Message
from wbb import SUDOERS, app, arq
from wbb.utils.filter_groups import autocorrect_group
@app.on_message(filters.command("autocorrect"))
async def autocorrect_bot(_, message: Message):
if not message.reply_to_message:
return aw... | StarcoderdataPython |
5048710 | from scipy.io import loadmat, savemat
annots = loadmat('../data/color150.mat')
annots['colors'] = annots['colors'][2:4]
print(annots['colors'])
savemat("../data/color2.mat", annots)
| StarcoderdataPython |
11337618 | # -*- coding: utf-8 -*-
import cv2
import zbar
scanner = zbar.ImageScanner()
scanner.parse_config('enable')
cap = cv2.VideoCapture(0)
captured = False
while True:
ret, camera = cap.read()
gray = cv2.cvtColor(camera, cv2.COLOR_BGR2GRAY)
rows, cols = gray.shape[:2]
image = zbar.Image(cols, rows, 'Y800',... | StarcoderdataPython |
3405186 | <reponame>ramoseh/wizeline-challenge
from fastapi.testclient import TestClient
from app import app
client = TestClient(app)
def test_hello():
response = client.get("/hello")
assert response.status_code == 200
assert response.json() == {"payload": "Hello World!"}
def test_get_table():
response = cl... | StarcoderdataPython |
12827487 | <reponame>drylikov/mappad.ru<gh_stars>0
from datetime import datetime
from webapp import db
class Track(db.Model):
__tablename__ = 'tracks'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(140))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
user_... | StarcoderdataPython |
9682760 | <filename>tests/common_mocks/mock_policy/mock_policy.py
from continual_rl.policies.policy_base import PolicyBase
from tests.common_mocks.mock_policy.mock_policy_config import MockPolicyConfig
from tests.common_mocks.mock_environment_runner import MockEnvironmentRunner
class MockPolicy(PolicyBase):
"""
A mock ... | StarcoderdataPython |
4804555 | <filename>egs/mini_librespeech/s5/test-cross-entropy.py
#!/usr/bin/env python3
# Results with this script
# 2 layer TDNN, no bn, Adam, lr=0.001: valid loss was 2.8642 after 6 epochs
# 3 layer TDNN, no bn, Adam, lr=0.001: valid loss was 2.4447 with <4 epochs. Stopped training as the trend was clear.
# 3 layer TDNN, bn... | StarcoderdataPython |
9766783 | <gh_stars>10-100
#!/usr/bin/env python3
"""
This implements a simple Evolutionary Programming (EP) system, but it
does not evolve state machines as done with the original EP approach.
TODO convert to a state machines problem
"""
import os
from toolz import pipe
from leap_ec import Individual, context, t... | StarcoderdataPython |
4852024 | """
Contains the TemplateProcessor class for handling template input file data
"""
from ..utils import regex
import re
class Template(object):
"""
A class for handling template input files for electronic structure theory codes
Parameters
----------
template_path : str
A pat... | StarcoderdataPython |
9765549 | <filename>tools/util.py
# Copyright (C) 2015 The Minorminor Open Source Project
#
# 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 |
93964 | """
h2o2_mk2012_ad.py
Hydrogen peroxide, H2O2, ground state surface from
Ref [1]_. The coefficients are available from the references
supplementary information as the 'adiabatic PES', which
corresponds to the "V+C+R+H+D" results.
The surface is implemented in internal coordinates.
X1 ... O1 -- H1 bond length (Angst... | StarcoderdataPython |
5016609 | <gh_stars>0
#!/usr/bin/python3
import plac
MODELS = [
'BernoulliNB',
'KNN',
'LinearSVC_L1',
'LinearSVC_L2',
'MultinomialNB',
'NearestCentroid',
'PassiveAggresive',
'Perceptron',
'Ridge',
'SGDClassifierElastic',
'SGDClassifierL2',
]
@plac.annotations(
event_sel=("Events to select", "positional", None, int),
)
... | StarcoderdataPython |
8142696 | #!/usr/bin/env python3
# Copyright 2021 Universität Tübingen, DKFZ and EMBL
# for the German Human Genome-Phenome Archive (GHGA)
#
# 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 |
3238766 | '''
creates the Movie class which receives three arguments
1. Title of the Movie
2. Link to the poster image of the Movie
3. YouTube Link to youtube trailer video
'''
class Movie:
def __init__(self, title, poster_image_url, trailer_youtube_url):
self.title = title
self.poster_image_url = poster_im... | StarcoderdataPython |
5091653 | <gh_stars>0
# pull the bindings
from . import isce3 as extisce3
# end of file
| StarcoderdataPython |
6513379 | <filename>src/masonite_permission/models/permission.py
"""Permission Model."""
from masoniteorm.models import Model
from masoniteorm.query import QueryBuilder
from ..exceptions import PermissionException
class Permission(Model):
"""Permission Model."""
__primary_key__ = "id"
__fillable__ = ["name", "slu... | StarcoderdataPython |
3561199 | <filename>app/fsm.py
from enum import Enum
# Класс перечислений(константы состояний)
class States(Enum):
S_START = 0 # Начало нового диалога
S_SETTINGS = 1
S_SEND_USERNAME = 2
S_SEND_PASSWORD = 3
S_SEND_SECURITY_TYPE = 4
S_SEND_HIDDEN_NET = 5
states_dict = {}
# Получение текущего состояния
d... | StarcoderdataPython |
5092799 | <reponame>EnerwhereIT/erpnext_operations
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('requirements.txt') as f:
install_requires = f.read().strip().split('\n')
# get version from __version__ variable in erpnext_operations/__init__.py
from erpnext_operations import __version__ as vers... | StarcoderdataPython |
3344997 | <filename>filter01.py
from db.mysql_conn import MysqlDb
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score
from scipy import stats
import numpy as np
import pickle
from row_index import RowIndex
def read_line(file_name):
lines = [line.rstrip('\n') for line in open(file_name)]... | StarcoderdataPython |
237900 | from flask import Blueprint
from flask import current_app
from flask import make_response
from flask import request
from flask import send_from_directory
from fedservice.exception import UnknownEntity
sigserv_views = Blueprint("sig_serv", __name__, url_prefix='')
@sigserv_views.route("/static/<path:path>")
def send... | StarcoderdataPython |
11347963 | """ Class definition for Combustor."""
import numpy as np
import openmdao.api as om
from pycycle.cea.set_total import SetTotal
from pycycle.cea.set_static import SetStatic
from pycycle.cea.species_data import Thermo, janaf
from pycycle.constants import AIR_FUEL_MIX, AIR_MIX
from pycycle.elements.duct import Pressure... | StarcoderdataPython |
5139850 | <gh_stars>10-100
import typing
from collections import defaultdict
import graph_tool
import graph_tool.draw
import graph_tool.inference
import graph_tool.search
import graph_tool.topology
import matplotlib.colors as colors
import numpy as np
import pandas as pd
import seaborn as sns
from cytoolz import sliding_window,... | StarcoderdataPython |
11266227 | <filename>simple_qt/gui/control_button_frame.py
#!/usr/bin/env python3
#version 2.1
from PyQt5 import Qt
from PyQt5 import QtCore
from PyQt5 import Qt
from PyQt5.QtCore import pyqtSignal
class control_button_frame(Qt.QFrame):
def __init__(self, parent=None, az_el = None):
super(control_button_frame, self... | StarcoderdataPython |
6645830 | <reponame>bodnar-e/bimcloud-api
import requests
from .errors import raise_bimcloud_manager_error, HttpError
from .url import is_url, join_url
class ManagerApi:
def __init__(self, manager_url):
if not is_url(manager_url):
raise ValueError('Manager url is invalid.')
self.manager_url = manager_url
self._api_ro... | StarcoderdataPython |
133622 | <filename>algorithms/leetcode/easy/0504_七进制数.py<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
给定一个整数 num,将其转化为 7 进制,并以字符串形式输出。
示例 1:
输入: num = 100
输出: "202"
示例 2:
输入: num = -7
输出: "-10"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/base-7
著作权归领扣网络所有。商业转载请联系官方授权,非商业转... | StarcoderdataPython |
12859625 | import os
import pkg_resources
import shutil
from ..equations import equations
from ..definitions import EQN_DEFINITIONS
def generate_equations_doc(docfile):
"""
Helper function to automatically generate a documentation page containing
all the available equations within cweqgen.
Parameters
-----... | StarcoderdataPython |
3591369 | from . import heads | StarcoderdataPython |
11355557 | <reponame>EarthOnline/ICS2000-Python<filename>ics2000/Devices.py
from typing import Optional
class Device:
def __init__(self, name, entity_id, hb):
self._hub = hb
self._name = name
self._id = entity_id
print(str(self._name) + " : " + str(self._id))
def name(self):
ret... | StarcoderdataPython |
11245133 | from app import app, db
class Sessions(db.Model):
__tablename__ = 'sessions'
session_id = db.Column(db.Integer, primary_key=True)
app = db.Column(db.String(255))
r_id = db.Column(db.Integer, db.ForeignKey('researchers.r_id'))
user_id = db.Column(db.Integer, db.ForeignKey('players.user_id'))
session_date = db.Col... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.