id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
8065068 | <reponame>hasindu2008/NA12878<gh_stars>100-1000
import h5py
import pandas as pd
import numpy as np
def smooth_pore(arr, cutoff=1500):
m = int(np.mean(arr))
arr[arr > cutoff] = m
return arr
def export_read_file(channel, start_index, end_index, bulkfile, output_dir, remove_pore=False):
"""Generate a r... | StarcoderdataPython |
11334881 | import numpy as np
import pickle
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
def get_barycentric_coords(tensor):
"""
:param tensor: 3x3 anisotropic Reynolds stress tensor
:return: x and y barycentric coordinates
"""
# Compute barycentric coordinates from the eigenvalues ... | StarcoderdataPython |
11299191 | import os
os.environ["TF_CPP_MIN_LOG_LEVEL"]='3'
import warnings
warnings.filterwarnings('ignore')
import AlexNetCompleted
import AlexNetForUsers
rightModelPath = 'step4/modelInfo/AlexNet'
userModelPath = 'step4/userModelInfo/AlexNet'
# print(os.path.exists(rightModelPath))
# print(os.path.exists(userModelPath))
#... | StarcoderdataPython |
3455408 | import feedparser
import re
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from moneyed import Currency
from typing import List
@dataclass
class CurrencyRate:
source_currency: Currency
target_currency: Currency
rate: Decimal
uploaded: datetime
class ECBC... | StarcoderdataPython |
1788899 | <gh_stars>1-10
import sys
chars = "ACGT"
## check neighbors
def neighbors(pattern, d):
assert(d <= len(pattern))
if d == 0:
return [pattern]
r2 = neighbors(pattern[1:], d-1)
r = [c + r3 for r3 in r2 for c in chars if c != pattern[0]]
if (d < len(pattern)):
r2 = neighbors(patter... | StarcoderdataPython |
6570914 | #! /usr/bin/env python
from tornado import ioloop
from tornado import web
from jinja2 import Environment, FileSystemLoader
import os, argparse
from lsst.sims.maf.viz import MafTracking, dbController
import lsst.sims.maf.db as db
import json
class RunSelectHandler(web.RequestHandler):
def get(self):
sele... | StarcoderdataPython |
11359657 | TOP10_DATA_TITLE = {
"jumps" : "Number of Hyperspace Jumps",
"ly" : "Light Years Travelled",
"bought" : "Cargo Bought",
"sold" : "Cargo Sold",
"points" : "Mission Points Earned",
"bounty" : "Bountys Handed in",
"bonds" : "Combat Bonds Handed in",
"explodata" : "Exploration Data",
"pa... | StarcoderdataPython |
5007825 | <filename>PortScanner.py<gh_stars>1-10
import threading,socket,argparse
from sys import exit
from queue import Queue
lock = threading.Lock()
q = Queue()
parser=argparse.ArgumentParser()
group=parser.add_mutually_exclusive_group()
group.add_argument("-i", "--ip", help="Target's ip", action="store")
group.add_argument... | StarcoderdataPython |
66010 | #!/usr/bin/env python
from __future__ import with_statement
from geode import Prop,PropManager,cache
from geode.value import Worker
import sys
def worker_test_factory(props):
x = props.get('x')
y = props.add('y',5)
return cache(lambda:x()*y())
def remote(conn):
inputs = conn.inputs
x = inputs.get('x')
as... | StarcoderdataPython |
6435994 | ########################################################################
#
# Copyright (c) 2017, STEREOLABS.
#
# All rights reserved.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHA... | StarcoderdataPython |
8056189 | <reponame>AmanMishra148/python-repo
print("Hello")
print("Python")
| StarcoderdataPython |
3361051 | #!/usr/bin/env python3
# Quantopian, Inc. 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 of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | StarcoderdataPython |
9763264 | <filename>ss.py
import os
from flask import Flask, request, render_template, redirect, url_for, g
from flask_pymongo import PyMongo
import flask_pymongo
from flask_babel import Babel
from storyzer import storyze, format_story
from bson.objectid import ObjectId
app = Flask(__name__)
app.debug = True
babel = Babel(app)... | StarcoderdataPython |
79435 | import unittest
import numpy as np
import logging
from dsbox.ml.neural_networks.keras_factory.text_models import LSTMFactory
from dsbox.ml.neural_networks.processing.workflow import TextNeuralNetPipeline, ImageNeuralNetPipeline
logging.getLogger("tensorflow").setLevel(logging.WARNING)
np.random.seed(42)
class T... | StarcoderdataPython |
3254963 | <gh_stars>0
#!/usr/bin/env python
import sys,nuri,os,numpy
import matplotlib.pyplot as plt
import matplotlib.dates as md
from datetime import datetime,timedelta
def check24hrs(date):
"""
This operation will display the active periods for which data are
available from every sensors.
Parameters
----... | StarcoderdataPython |
5081430 |
class Message(object):
def __init__(self, processor, *args):
self.content = args
self.processor = processor
self.keywords = (processor.logger._ident,
processor.name)
def strcontent(self):
return " ".join(map(str, self.content))
def strprefix(sel... | StarcoderdataPython |
8076955 | <filename>byterun/pyobj.py<gh_stars>10-100
"""Implementations of Python fundamental objects for Byterun."""
# TODO(ampere): Add doc strings and remove this.
# pylint: disable=missing-docstring
import collections
import inspect
import types
import six
PY3, PY2 = six.PY3, not six.PY3
def make_cell(value):
# Th... | StarcoderdataPython |
9621601 | """
This file sets default constants that are used throughout the package.
Objects set as defaults are set in classes (so that we don't have to import anything here).
Mostly I did this so I could easily reuse defaults and change them to match my data structure.
Don't look at me like that.
"""
"""Default Environmental ... | StarcoderdataPython |
12847996 |
import sys
import time
import threading
import platform
import subprocess
import os
try:
if platform.system() == 'Windows':
import win32console
# TODO: we should win32console anyway so we could just omit colorama
import colorama
colorama.init()
except ModuleNotFoundError:
print... | StarcoderdataPython |
1997937 | <gh_stars>0
import logging
import time
import uuid
from pydoc import locate
from minifi.core.InputPort import InputPort
from minifi.core.DockerTestCluster import DockerTestCluster
from minifi.core.DockerTestDirectoryBindings import DockerTestDirectoryBindings
from minifi.validators.EmptyFilesOutPutValidator import ... | StarcoderdataPython |
6440726 | <filename>test/test_retinanet.py
import unittest
import torch
import numpy as np
from mitorch.models import *
class TestRetinaNet(unittest.TestCase):
def test_mobilenetv2(self):
self._test_model(MobileNetV2, 320)
def test_mobilenetv3(self):
self._test_model(MobileNetV3, 320)
def test_mob... | StarcoderdataPython |
4949444 | <gh_stars>1-10
import ghalton
import numpy as np
from src.autoks.distance.sampling.sampler import Sampler
from src.autoks.distance.sampling.scramble import scramble_array
def generate_halton(n: int, d: int):
sequencer = ghalton.Halton(d)
return sequencer.get(n)
def generate_generalized_halton(n: int, d: in... | StarcoderdataPython |
3294314 | from __future__ import division
from __future__ import print_function
import datetime
import json
import logging
import os
import pickle
import time
import numpy as np
import optimizers
import torch
from config import parser
from models.base_models import NCModel, LPModel
from utils.data_utils import load_data
from u... | StarcoderdataPython |
3310925 | # -*- coding: utf-8 -*-
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021 davfsa
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the right... | StarcoderdataPython |
6641574 | <filename>S4/S4 Library/simulation/traits/trait_commands.py
import sims4
from server_commands.argument_helpers import OptionalTargetParam, get_optional_target, TunableInstanceParam, RequiredTargetParam
from traits.trait_type import TraitType
@sims4.commands.Command('traits.show_traits', command_type=sims4.commands.Com... | StarcoderdataPython |
6611675 | <filename>Mr.Lin/0002/0002.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: 30987
# @Date: 2015-01-12 17:22:35
# @Last Modified by: 30987
# @Last Modified time: 2015-01-12 22:33:53
#第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
import uuid
import MySQLdb
def creat_code(number=20):
result = [... | StarcoderdataPython |
6537562 | <filename>backend.py<gh_stars>0
from enum import Enum
import tui
import console
import gui
class GuiBackendType(Enum):
NONE = 0
TUI = 1
GUI = 2
CONSOLE = 3
def from_str(string: str) -> int:
if (string == "tui"):
return GuiBackendType.TUI
elif (string == "gui"):
... | StarcoderdataPython |
4950474 | <filename>simple_rl/agents/LinearQLearningAgentClass.py
''' QLearningAgentClass.py: Class for a basic QLearningAgent '''
# Python imports.
import random
import numpy
import os
import math
import time
from collections import defaultdict
from sklearn.linear_model import SGDRegressor
from sklearn.multioutput import Multi... | StarcoderdataPython |
6522091 | from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
mcuser = db.Column(db.String(16), index=True, unique=True)
mcemail = db.Column(db.String(120), index=True, unique=True)
applicant_age = db.Column(db.SmallInteger(), default=15)
applicant_skills = db.Column(db.Str... | StarcoderdataPython |
3475719 | <gh_stars>1-10
import sys
import uctypes
if sys.byteorder != "little":
print("SKIP")
sys.exit()
desc = {
"ptr": (uctypes.PTR | 0, uctypes.UINT8),
"ptr16": (uctypes.PTR | 0, uctypes.UINT16),
"ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}),
}
bytes = b"01"
addr = uctypes.addressof(bytes)
buf ... | StarcoderdataPython |
254958 | <gh_stars>0
from math import sqrt
from fn import *
#find = 3.14159265
find = 1.414213
#find = 7
acc = 0.005
expr_len = (3, 10)
nms = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
#nms = ['2']
mfn = ['+', '-', '*', '/']
fnc = ['sqrt(']
brc = ['(', ')']
use_brc = True
fll = nms + mfn + fnc + brc*use_brc
if __name... | StarcoderdataPython |
9766404 | <reponame>unmonoqueteclea/pygame-search-algorithms-visualizer<filename>util.py
# -*- coding: utf-8 -*-
'''
title :util.py
description :Utilities for different parts of the project
author :<NAME> (unmonoqueteclea)
date :20160623
notes :
python_version :2.7.6
'''
from __futur... | StarcoderdataPython |
385571 | <filename>Code/EYESensors/microphone.py
import pyaudio
import wave
class audio:
def __init__(self,RECORD_TIME):
self.FORMAT = pyaudio.paInt16
self.CHANNELS = 1
self.RATE = 44100
self.CHUNK = 512
self.RECORD_SECONDS = RECORD_TIME
self.WAVE_OUTPUT_FILENAME = "file.wav"... | StarcoderdataPython |
4928927 | <reponame>dmilos/IceRay
#__all__ = [ 'core' ]
#print( '<' + __name__ + 'name=\'' + __file__ + '\'/>' )
| StarcoderdataPython |
11274348 | #!/usr/bin/env python3
from checkeddeco import checked
@checked
class Movie:
title: str
year: int
box_office: float
if __name__ == '__main__':
# No static type checker can understand this...
movie = Movie(title='The Godfather', year=1972, box_office=137) # type: ignore
print(movie.title)
... | StarcoderdataPython |
1630127 | <filename>Python/Tests/TestData/Grammar/AwaitStmtIllegal.py
await None
def quox():
await fob
class quox:
await fob
| StarcoderdataPython |
1989086 | VALID_RUNNERS = ("manual", "monkey", "grodd", "grodd2")
| StarcoderdataPython |
4826479 | """
Helper methods
"""
class Helper(object):
@classmethod
def parse_definition_string(cls, definition):
'''
Parse the definition string and return the list of dependent classes.
:type definition: str
:param definition: string with a list of dependent classes
... | StarcoderdataPython |
9672845 | # -*- coding: utf-8 -*-
"""
API interfaces.
License: BSD
(c) 2008 ::: www.CodeResort.com - BV Network AS (<EMAIL>)
"""
from trac.core import Interface
class IBlogChangeListener(Interface):
"""Extension point interface for components that should get notified about
creation, change or deletion of blog posts + ... | StarcoderdataPython |
1683462 | <filename>Defs/ex109b/dinheiro/__init__.py
'''
def aumentar(n=0, taxa=0):
soma = n + (n*taxa)/100
return soma
def diminuir(n=0, taxa=0):
dim = n - (n*taxa)/100
return dim
def real(n=0, simbolo='R$'):
return f'\033[31m{simbolo}{n:0.2f}\033[m'.replace('.',',')
'''
def aumento(n=0, taxa=0, formato=... | StarcoderdataPython |
209043 | import time
from typing import List, Dict
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
import board_reader
import expirement_gui.one_dim_control as one_dim
import expirement_gui.tk_plots as tk_plots
import feature_extraction
channels = {"o1": 1, "c3": 2, "fp2": 3, "fp1": 4, "c4": 5, ... | StarcoderdataPython |
12840621 | <gh_stars>0
import atnp.utils as utils
import requests
import csv
import re
import os
def slice_url(url):
match = re.search(utils.LINK_PATTERN, url)
return match.group(1), match.group(2), match.group(3)
def gen_unique_name(domain, path):
return "{}__{}".format(domain, path.replace("/", "_"))
def maker... | StarcoderdataPython |
4877551 | <filename>tests/test_onchain_registry.py
import pytest
from brownie import BadgerRegistry # noqa
from brownie import accounts
from badger_utils.constants import ETHEREUM_NETWORK
from badger_utils.registry import chain_registries
@pytest.mark.parametrize(
"network",
[
"eth", "polygon", "arbitrum",
... | StarcoderdataPython |
94558 | import pickle
from collections import Counter
from math import log
from typing import List, Dict, Tuple
import numpy as np
from scipy.sparse import csr_matrix
from scipy.spatial.distance import cosine
from common import check_data_set, flatten_nested_iterables
from preprocessors.configs import PreProcessingConfigs
fr... | StarcoderdataPython |
8045888 | from crispy_forms.helper import FormHelper
from django import forms
from payroll.models import CSV
class CSVForm(forms.ModelForm):
class Meta:
model = CSV
fields = ("file_name",)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.Helper = FormHelper()... | StarcoderdataPython |
9756207 | <gh_stars>0
import unittest
from models.user import User, pwd_context
from models.error import UserError
class TestUser(unittest.TestCase):
def setUp(self):
self.username = "testuser"
self.password = "<PASSWORD>"
self.wrong_pass = "<PASSWORD>"
self.secret_key = "to test or not to t... | StarcoderdataPython |
3220983 | <filename>Documents/Router/CVE-2017-7494/impacket/Dot11KeyManager.py
# Copyright (c) 2003-2016 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Description:
# IEEE 802.11 Netw... | StarcoderdataPython |
1742286 | <filename>tests/schema/test_checker.py<gh_stars>0
import pytest
from align.schema.checker import Z3Checker, SolutionNotFoundError
@pytest.fixture
def checker():
return Z3Checker()
def test_single_bbox_checking(checker):
b1 = checker.bbox_vars('M1')
checker.append(b1.llx < b1.urx)
checker.solve()
... | StarcoderdataPython |
11397134 | <filename>openbook_posts/migrations/0068_profilepostscommunityexclusion.py
# Generated by Django 2.2.5 on 2020-01-30 13:27
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappab... | StarcoderdataPython |
8095751 | from flask import render_template, url_for, request, redirect
from web_app import app
from web_app import get_stats
@app.route("/", methods=["GET", "POST"])
@app.route("/home.html", methods=["GET", "POST"])
def home():
if request.method == "POST":
band_name = request.form['band']
if get_stats.return_stats(band_n... | StarcoderdataPython |
1941157 | import os
from alive_progress import alive_bar
import numpy as np
import torch
from common.camera import normalize_screen_coordinates, world_to_camera
from common.loss import mpjpe, p_mpjpe
from common.utils import deterministic_random
from model.VideoPose3D import TemporalModel, TemporalModelOptimized1f
def load_d... | StarcoderdataPython |
163721 | """blog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vi... | StarcoderdataPython |
8056396 | from ipyparallel import Client
import sys
import numpy as np
########################################################################################################################
# set up parallel client
rc = Client()
dview = rc[:]
with dview.sync_imports():
from generate_tay_sde_obs import experiment
exps =... | StarcoderdataPython |
1611897 | import pandas as pd
import numpy as np
import statsmodels as sm
import statsmodels.api as smapi
import math
from pyqstrat.pq_utils import monotonically_increasing, infer_frequency
from pyqstrat.plot import TimeSeries, DateLine, Subplot, HorizontalLine, BucketedValues, Plot
import matplotlib as mpl
import matplotlib.fig... | StarcoderdataPython |
211851 | <filename>ProgramsToRead/ExercisesFromClasses/ex001agosto26.py
vogais = {
'a': 0,
'e': 0,
'i': 0,
'o': 0,
'u': 0
}
texto = str(input('insira um texto: ')).strip().lower()
for letra in texto:
if letra in 'a':
vogais['a'] += 1
elif letra in 'e':
vogais['e'] += 1
elif letra ... | StarcoderdataPython |
8106816 | <filename>tests/core/gridftp_test.py
"""
Test script for gridftp
"""
from __future__ import absolute_import, division, print_function
from tests.util import unittest_reporter, glob_tests
import logging
logger = logging.getLogger('gridftp')
import os, sys, time
import shutil
import random
import string
import subpro... | StarcoderdataPython |
4913130 | import re
def translate(code: str) -> (str, str):
"""Translates text with bash escape sequences to normal text
Input: raw shell input
Ouput: (type of line, processed line without control sequences)
"""
code = re.sub('\x07', '', code) # Звук при ошибке. Не нужен
code = re.sub(r'(\s|\S)*:\t'... | StarcoderdataPython |
260930 | import sys
import typing
def copy():
''' Copy the material settings and nodes
'''
pass
def new():
''' Add a new material
'''
pass
def paste():
''' Paste the material settings and nodes
'''
pass
| StarcoderdataPython |
1738530 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
使用自建的接口识别来自网络的验证码
需要配置参数:
remote_url = "https://www.xxxxxxx.com/getImg" 验证码链接地址
rec_times = 1 识别的次数
"""
import datetime
import requests
from io import BytesIO
import time
import json
import os
def recognize_captcha(index, test_path, save_path, image_suffix):
... | StarcoderdataPython |
150587 | from enum import Enum
from typing import Optional
import requests
import typer
class ListType(str, Enum):
blacklist = "blacklist"
whitelist = "whitelist"
class ListAction(str, Enum):
add = "add"
clear = "clear"
class BlacklistSource(str, Enum):
firebog_ticked = "firebog_ticked"
firebog_no... | StarcoderdataPython |
8179676 | from types import SimpleNamespace
from typing import Any
from ikea_api.abc import (
AsyncExecutor,
BaseAPI,
Endpoint,
EndpointInfo,
RequestInfo,
ResponseInfo,
SessionInfo,
SyncExecutor,
endpoint,
)
from tests.conftest import EndpointTester, ExecutorContext, MockResponseInfo
def te... | StarcoderdataPython |
4868209 | import unittest
import xmlrunner
from main import *
from main import database_loader
class all_test_suite(unittest.TestCase):
#def test_android_permission(self):
#from main import platform
#self.assertRaises(AttributeError, platform.request_permissions("android.permission.INTERNET"))
def test... | StarcoderdataPython |
3484022 | <reponame>UPstartDeveloper/Problem_Solving_Practice
"""
Power Set: Write a method to return all subsets of a set.
Clarifying questions:
- so ok, let's start off with an example to make this clearer
- is the input modifiable? no
s = {5, 7, 6, -8, 9, 10}, right?
Assumptions about the set:
- unordered collection
- all... | StarcoderdataPython |
11360397 | <filename>tests/test_api_rename_lines.py
import gfapy
import unittest
class TestAPIRenameLines(unittest.TestCase):
def test_rename(self):
gfa = gfapy.Gfa(["S\t0\t*", "S\t1\t*", "S\t2\t*",
"L\t0\t+\t2\t-\t12M", "C\t1\t+\t0\t+\t12\t12M", "P\t4\t2+,0-\t12M"])
gfa.segment("0").name = "X"
with self.ass... | StarcoderdataPython |
1748850 | <reponame>tienne-B/mit-tab<filename>mittab/libs/backup/__init__.py
import shutil
import time
import os
from wsgiref.util import FileWrapper
from django.conf import settings
from mittab.apps.tab.models import TabSettings
from mittab.libs import errors
from mittab.settings import BASE_DIR
from mittab.libs.backup.strate... | StarcoderdataPython |
1678215 | #!/usr/bin/env python
from distutils.version import LooseVersion
from setuptools import setup, find_packages
def get_docker_client_requirement():
DOCKER_PY_REQUIREMENT = 'docker-py >= 1.8.1, < 2'
DOCKER_RRQUIREMENT = 'docker >= 2.0.0, < 3'
docker_client_installed = True
try:
import docker
... | StarcoderdataPython |
118785 | import abc # Abstract Base Class
from eth_account import Account
from collections import defaultdict
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import f... | StarcoderdataPython |
11221075 | <gh_stars>1-10
# coding=utf-8
import numpy as np
# para metodos regularizados
from numpy.linalg import norm
import scipy.sparse.linalg
from sys import version_info
if(version_info >= (3,0)):
from importlib import reload as reload
import FarFieldSignal
reload(FarFieldSignal)
from FarFieldSignal imp... | StarcoderdataPython |
9682700 | <filename>ConcurrentSpider/demo_multiprocessing.py
import multiprocessing
import time
from multiprocessing import Process
'''
Python 3.X multiprocess 模块演示 Demo
其实完全类似 threading 用法,只不过含义和实质不同而已
multiprocess 的 Process 类基本使用方式(继承重写 run 方法及直接传递方法)
'''
class NormalProcess(Process):
def __init__(self, name=None):
... | StarcoderdataPython |
4807576 | import asyncio
from mavsdk import System
async def _run():
drone = System()
await drone.connect(system_address="udp://:14540")
print("Waiting for drone to connect...")
async for state in drone.core.connection_state():
if state.is_connected:
print(f"Drone discovered with UUID: {st... | StarcoderdataPython |
3273330 | #!/usr/bin/env python3
#
# This file is part of 'Aleph - A Library for Exploring Persistent
# Homology'. It contains code for visualizing extended persistence
# hierarchies (also called interlevel set persistence hierarchies)
# as TikZ pictures.
#
# The file processes _all_ command-line arguments and expects them
# to ... | StarcoderdataPython |
238383 | #!/usr/bin/env python
#
# Check whether there's warning and error in IPMI sensor status
#
# Return CRITICAL or WARNING when there's sensor error or there's PFA alert
#
# <NAME> <<EMAIL>>
import argparse
import re
import subprocess
import sys
STATE_OK = 0
STATE_WARNING = 1
STATE_CRITICAL = 2
def exit_error(criticalit... | StarcoderdataPython |
3401419 | <gh_stars>1-10
#from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
from django.core.exceptions import ValidationError
class CustomUserCreationForm(forms.Form):
username = forms.CharField(min_length=4, max_length=150,required=False, widget=for... | StarcoderdataPython |
324989 | import contextlib
import datetime
import logging
from django.contrib.postgres.fields import JSONField
from django.core import validators
from django.core.files.base import ContentFile
from django.core.files.storage import Storage
from django.db import DEFAULT_DB_ALIAS
from django.db import connection
from django.db im... | StarcoderdataPython |
3378526 | <gh_stars>0
__all__ = ['ListingColumn', 'listing_column']
from dataclasses import dataclass, field
from html import escape as html_escape
from elementary_flask.typing import Callable
@dataclass()
class ListingColumn:
name: str
title: str = None
shrink_cell: bool = False
td_class: str = None
th_cl... | StarcoderdataPython |
8012885 | #!/usr/bin/python
import threading
import math
import config
from time import sleep
from datetime import datetime
IMUtoBTLock = threading.Lock()
class IMUtoBT (threading.Thread):
def __init__(self, imu, bt):
threading.Thread.__init__(self)
self.imu = imu
self.bt = bt
def run(self):
while not config.e... | StarcoderdataPython |
3334167 | <filename>great_expectations/render/renderer/content_block/expectation_string.py
from great_expectations.render.renderer.content_block.content_block import (
ContentBlockRenderer,
)
from great_expectations.render.types import RenderedStringTemplateContent
class ExpectationStringRenderer(ContentBlockRenderer):
... | StarcoderdataPython |
6495003 | <reponame>Ali-Parandeh/Data_Science_Playground<gh_stars>0
'''
Below is the structure of where you'll be working.
working_dir
├── text_analyzer
│ ├── __init__.py
│ ├── counter_utils.py
│ ├── document.py
└── my_script.py
'''
# Import custom text_analyzer package
import text_analyzer
# Create an instance of Do... | StarcoderdataPython |
3254669 | import os
import sys
cd = os.path.abspath('.')
if cd not in sys.path:
# Add the current directory to sys.path so that `python -m`
# is not required to run the helper script
sys.path.insert(0, cd)
SETTINGS = os.environ.get(
"CYPRESS_SETTINGS",
default=f"{os.path.split(cd)[-1]}.settings.cypress",
)
... | StarcoderdataPython |
1944187 | <filename>app/migrations/0005_auto_20190407_1857.py
# Generated by Django 2.1.7 on 2019-04-07 13:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0004_sh0t_severity'),
]
operations = [
migrations.AlterModelOptions(
name='sh... | StarcoderdataPython |
5192549 | <reponame>ZREDU-007/mooc
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
__author__ = 'Kris,QQ:1209304692。QQ群:知尔MOOC,760196377'
from django.db import models
# Create your models here.
class Tag(models.Model):
name = models.CharField(max_length=16, verbose_name='标签')
class Meta:
verbo... | StarcoderdataPython |
9777092 | <filename>train/train.py<gh_stars>1-10
from __future__ import absolute_import, division, print_function
import tensorflow as tf
import numpy
from tensorflow import keras
import numpy as np
from minio import Minio
from minio.error import ResponseError
import os
import sys
import tempfile
import tarfile
import pickle
fr... | StarcoderdataPython |
1650613 | import random
import sys
from MMU import MMU
from BlocoMemoria import BlocoMemoria
from Endereco import Endereco
from Instrucao import Instrucao
from Conjunto import Conjunto
from output import Output
class TP2:
tamanhoRAM: int = 1000 #quantidade de blocos da ram
tamanhoCache1: int = 32 #quantidade de blocos ... | StarcoderdataPython |
11342778 | <reponame>xinming365/LeetCode
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/4/10 1:31 下午
# @Author : xinming
# @File : 78_subsets.py
from typing import List
class Solution:
def subsets(self, nums):
if not nums:
return None
res = []
n = len(nums)
d... | StarcoderdataPython |
3244147 | <filename>QLearning/task0_train.py
#!/usr/bin/env python
# coding=utf-8
'''
Author: John
Email: <EMAIL>
Date: 2020-09-11 23:03:00
LastEditor: John
LastEditTime: 2021-09-23 12:22:58
Discription:
Environment:
'''
import sys,os
curr_path = os.path.dirname(os.path.abspath(__file__)) # 当前路径
parent_path=os.path.dirname(cur... | StarcoderdataPython |
8076177 | from django.contrib import sitemaps
from . import models
class FlatPageSitemap(sitemaps.Sitemap):
changefreq = "daily"
priority = 1.0
def items(self):
return models.FlatPage.objects.filter(is_enabled=True).order_by('id')
def lastmod(self, obj):
return obj.updated_at
| StarcoderdataPython |
12853188 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import json
from collections import OrderedDict
from typing import List
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd
from dash import dash
from dash.dependencies import Input, Output, State
from zvdata import Interv... | StarcoderdataPython |
9608428 | from .hex_ia import HexIA, dotdict, args
from .hex_board import HexBoard, WHITE, BLACK
from .hex_game_manager import HexGameManager
from uct import UCT
from parameters import Params
import time
import traceback
class ConvNetUnableToProduceGame(Exception):
pass
class HexCoach:
average_number_moves = [0]
... | StarcoderdataPython |
1660653 | import utils as u
from collections import deque
from itertools import count
from time import time
puzzle_input = "077201"
# part 1 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_
def debug_position(scores: list, positions: list):
for idx, score in enumerate(scores):
if idx == ... | StarcoderdataPython |
3215648 | from . import db
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin
from . import login_manager
from datetime import datetime
from sqlalchemy import desc
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(UserMi... | StarcoderdataPython |
1924977 | <filename>apps/web/api/views.py
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from apps.web.api.serializers import UpdateModelSerializer
from apps.web.models import AppUser, CallbackQuery, Chat, Message, Update
from apps.web.models.mess... | StarcoderdataPython |
1756510 | """nskipgrams: A lightweight Python package to work with ngrams and skipgrams
Author: <NAME> <<EMAIL>>
License: MIT License
Source: https://github.com/jacksonllee/nskipgrams
"""
from collections import defaultdict, OrderedDict
from itertools import combinations
import pkg_resources
__version__ = pkg_resources.get_d... | StarcoderdataPython |
9607958 | <reponame>WaiNaat/BOJ-Python
### 틀렸습니다 ###
from collections import deque
# functions
'''
문자열 S + tail 이 퀼린드롬인지 판별.
'''
def isQilin():
s = "".join(["".join(S), "".join(tail)])
for i in range(len(s) // 2 + 1):
if change[s[i]] != s[-1-i] and s[-1-i] != '-':
return False
return True
# input
S = list(input())
# pr... | StarcoderdataPython |
4878772 | <reponame>coderMaruf/leetcode-1<gh_stars>10-100
'''
Description:
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written a... | StarcoderdataPython |
8120160 | import os
import dace.library
def _find_mkl_include():
if 'MKLROOT' in os.environ:
return [os.path.join(os.environ['MKLROOT'], 'include')]
else:
return []
@dace.library.environment
class IntelMKL:
cmake_minimum_version = None
cmake_packages = ["BLAS"]
cmake_variables = {"BLA_V... | StarcoderdataPython |
105123 | from django.core.management.base import BaseCommand, CommandError
from dashboard.models import Bin, Dataset
class Command(BaseCommand):
"""for testing only!!"""
help = 'delete all bins'
def add_arguments(self, parser):
parser.add_argument('-ds', '--dataset', type=str, help='name of dataset')... | StarcoderdataPython |
4951826 | # Generated by Django 3.1.7 on 2021-07-09 06:50
import datetime
from django.db import migrations
import django_jalali.db.models
class Migration(migrations.Migration):
dependencies = [
('main', '0018_auto_20210707_1155'),
]
operations = [
migrations.AlterField(
model_name='ad... | StarcoderdataPython |
4907959 | <filename>syft/frameworks/torch/tensors/interpreters/replicated_shared.py
import random
from operator import add, sub
import torch
import syft
from syft.generic.abstract.tensor import AbstractTensor
class ReplicatedSharingTensor(AbstractTensor):
def __init__(
self, shares_map=None, owner=None, id=None, ta... | StarcoderdataPython |
3343615 | <gh_stars>100-1000
from .cspace import CSpace
from .. import robotsim
from ..model import collide
from .cspaceutils import EmbeddedCSpace
import math
import random
class RobotCSpace(CSpace):
"""A basic robot cspace that allows collision free motion.
Args:
robot (RobotModel): the robot that's moving.
... | StarcoderdataPython |
3416977 | <filename>Leetcode/2001-3000/2062. Count Vowel Substrings of a String/2062.py
class Solution:
def countVowelSubstrings(self, word: str) -> int:
def countVowelSubstringsAtMost(goal: int) -> int:
ans = 0
k = goal
count = Counter()
l = 0
for r, c in enumerate(word):
if c not in... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.