id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3328883
<reponame>adrianmoo2/leetcode-workthroughs def helperFunction(self, root, result): if root: self.helperFunction(root.left, result) result.append(root.val) self.helperFunction(root.right, result) def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """...
StarcoderdataPython
168604
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import mptt.fields class Migration(migrations.Migration): dependencies = [ ('development', '0035_developmentproject_misc_textareas'), ] operations = [ migrations.CreateModel( ...
StarcoderdataPython
3346077
'''create files contains estimated generalization errors for model INPUT FILE WORKING/transactions-subset2.pickle OUTPUT FILES WORKING/ege_week/YYYY-MM-DD/MODEL-TD/HP-FOLD.pickle dict all_results WORKING/ege_month/YYYY-MM-DD/MODEL-TD/HP-FOLD.pickle dict all_results ''' import collections import cPickle as pickl...
StarcoderdataPython
177047
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: object_detection/protos/region_similarity_calculator.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google....
StarcoderdataPython
3223338
import os import math import sys import time from os.path import abspath, basename, join from seisflows.tools import msg from seisflows.tools import unix from seisflows.tools.tools import call, findpath, saveobj from seisflows.config import ParameterError, custom_import PAR = sys.modules['seisflows_parameters'] PATH...
StarcoderdataPython
1774118
<reponame>cjdsj/RDN-for-SR-by-keras<filename>test.py import cv2 import numpy as np import tensorflow as tf from matplotlib import pyplot as plt from tensorflow.keras.models import load_model from data_processing import get_test_data, imgappend, getYimg, psnr from model import RDN, L1_loss ''' Set parameters ''' scale...
StarcoderdataPython
113978
__version_info__ = ( 1, 0, 0 ) __version__ = '.'.join( map( str, __version_info__ ))
StarcoderdataPython
3352379
from .custom_component_server import setup_view from .parser import Parser MODULE = "custom_icons" DATA_EXTRA_MODULE_URL = 'frontend_extra_module_url' async def async_setup(hass, config): setup_view(hass, MODULE) parser = Parser() if parser.checkIfNeeded(): parser.do() parser.cleanUnusedCacheFile...
StarcoderdataPython
50387
<filename>SIGNUS/modules/crawler/etc/driver_agent.py<gh_stars>0 from selenium import webdriver from platform import platform import os # def chromedriver(): # options = webdriver.ChromeOptions() # options.add_argument('headless') # options.add_argument('window-size=1920x1080') # options.add_argument("disable-gpu") ...
StarcoderdataPython
3213399
<gh_stars>1-10 from unittest import TestCase from neo.Prompt import Utils from neocore.Fixed8 import Fixed8 from neocore.UInt160 import UInt160 class TestInputParser(TestCase): def test_utils_1(self): args = [1, 2, 3] args, neo, gas = Utils.get_asset_attachments(args) self.assertEqual(...
StarcoderdataPython
3278612
class Solution: def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ cs, ct = collections.Counter(s), collections.Counter(t) for ch in string.ascii_lowercase: if cs[ch] < ct[ch]: return ch
StarcoderdataPython
30420
import os import scipy.io.wavfile import matplotlib.pyplot as plt import numpy as np import os import random ''' Create a random dataset with three different frequencies that are always in fase. Frequencies will be octave [440, 880, 1320]. ''' fs = 16000 x1 = scipy.io.wavfile.read('corpus/Analysis/a440.wav')[1] x2 ...
StarcoderdataPython
30689
<gh_stars>1-10 import os import logging import pdb import time import random from multiprocessing import Process import numpy as np from client import MilvusClient import utils import parser from runner import Runner logger = logging.getLogger("milvus_benchmark.local_runner") class LocalRunner(Runner): """run lo...
StarcoderdataPython
1653056
<reponame>xhchrn/D-LADMM<filename>mu_updater.py """ File: mu_updater.py Created: September 19, 2019 Revised: December 2, 2019 Authors: <NAME>, <NAME> Purpose: Define a set of mu updaters in Safeguarded KM method. We implement 5 types of mu updaters, named `Geometric Series`, `Arithmetic Average...
StarcoderdataPython
3368277
<filename>multiinstance/distanceApproaches.py # AUTOGENERATED! DO NOT EDIT! File to edit: 04_Distribution_Distance_Approaches.ipynb (unless otherwise specified). __all__ = ['fitKDE', 'KLD', 'JSD', 'getJSDDistMat', 'getKLDMat', 'getWassersteinMat', 'getOptimalAdjacency'] # Cell from .utils import * import seaborn as ...
StarcoderdataPython
3341645
#!/usr/bin/env python # -*- coding: utf-8 -*- #...the usual suspects. import os, inspect #...for the unit testing. import unittest #...for the logging. import logging as lg # The wrapper class to test. from blb import BLB class TestBLB(unittest.TestCase): def setUp(self): pass def tearDown(self):...
StarcoderdataPython
11461
""" Bayes sensor code split out from https://github.com/home-assistant/home-assistant/blob/dev/homeassistant/components/binary_sensor/bayesian.py This module is used to explore the sensor. """ from collections import OrderedDict from const import * def update_probability(prior, prob_true, prob_false): """Update ...
StarcoderdataPython
3214297
<filename>community/cloud-foundation/templates/gcs_bucket/gcs_bucket.py # Copyright 2018 Google 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 copy of the License at # # http://...
StarcoderdataPython
3279114
import os import re def create_results_dir(): results_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../results') os.makedirs(results_root, exist_ok=True) max_num = -1 for root, subdirs, files in os.walk(results_root): for subdir in subdirs: numbers = re.finda...
StarcoderdataPython
1742892
import sqlite3 try: import tkinter except ImportError: # python 2 import Tkinter as tkinter conn = sqlite3.connect('lesson_176_music.sqlite') class Scrollbox(tkinter.Listbox): def __init__(self, window, **kwargs): # tkinter.Listbox.__init__(self, window, **kwargs) # Python 2 super()._...
StarcoderdataPython
1631383
def processing(mode, text, key): key_ints = [ord(i) for i in key] text_ints = [ord(i) for i in text] finished_text = "" for i in range(len(text_ints)): adder = key_ints[i % len(key)] if mode == 1: adder *= -1 char = (text_ints[i] - 32 + adder) % 95 finished_te...
StarcoderdataPython
3216821
#!/usr/bin/env python __version__ = '3.3.1' __author__ = "<NAME> (<EMAIL>)" __date__ = '2014-February-4' __url__ = 'https://engineering.purdue.edu/kak/dist/BitVector-3.3.1.html' __copyright__ = "(C) 2014 Avinash Kak. Python Software Foundation." __doc__ = ''' BitVector.py Version: ''' + __version__ ...
StarcoderdataPython
1673007
import argparse from datetime import timedelta import json import requests from colorama import Fore, Style from bs4 import BeautifulSoup import numpy as np import pandas as pd from pandas.core.frame import DataFrame import yfinance as yf from gamestonk_terminal.helper_funcs import ( check_positive, get_user_a...
StarcoderdataPython
62997
import torch import torch.nn as nn from .segmentation import deeplabv3_resnet50, deeplabv3_resnet101 __ALL__ = ["get_model"] BatchNorm2d = nn.BatchNorm2d BN_MOMENTUM = 0.01 class Transform(nn.Module): def forward(self, input): return 2 * input / 255 - 1 def load_pretrain_model(model, pretrain: str, cit...
StarcoderdataPython
4833869
<gh_stars>0 class Methods: USER_GET = 'users.get' FRIENDS_GET = 'friends.get'
StarcoderdataPython
1737623
# Combo helpers independent of GUI framework - these operate on # SelectionCallbackProperty objects. from __future__ import absolute_import, division, print_function import weakref from glue.core import Data, Subset from glue.core.hub import HubListener from glue.core.message import (DataReorderComponentMessage, ...
StarcoderdataPython
3296824
from django.shortcuts import get_object_or_404, render_to_response from django.shortcuts import render from registration.models import * from events.models import EventNew from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.template import Context from djang...
StarcoderdataPython
3215924
from enum import Enum, auto from xzero import ZeroBase class EventType(Enum): MARKET = auto() EXECUTION = auto() SIGNAL = auto() ORDER = auto() MKT_ORDER = auto() LMT_ORDER = auto() FILL = auto() TRANSACTION = auto() class Event(ZeroBase): """ Base class for events that wil...
StarcoderdataPython
3379057
<reponame>mikekwright/py-type-registry<gh_stars>0 """ This is a simple function to allow us to easily load yaml and have it construct an object is specified """ import logging import yaml import os from pprint import pprint from string import Template from .registrar import find_type __all__ = ['load_yaml', 'load_...
StarcoderdataPython
1766686
import maya.cmds as mc import maya.api.OpenMaya as om from dcc.abstract import afnskin from dcc.maya import fnnode from dcc.maya.libs import dagutils, skinutils from dcc.maya.decorators import undo import logging logging.basicConfig() log = logging.getLogger(__name__) log.setLevel(logging.INFO) class FnSkin(afnskin...
StarcoderdataPython
26620
""" You work for a retail store that wants to increase sales on Tuesday and Wednesday, which are the store's slowest sales days. On Tuesday and Wednesday, if a customer's subtotal is greater than $50, the store will discount the customer's purchase by 10%. """ # Import the datatime module so that # it can be used in t...
StarcoderdataPython
1627216
<gh_stars>0 import pickle import sys import tensorflow as tf from tqdm import tqdm def get_labels(): """Return a list of our trained labels so we can test our training accuracy. The file is in the format of one label per line, in the same order as the predictions are made. The order can change betw...
StarcoderdataPython
1652501
<reponame>althayr/pyomr import cv2 import numpy as np import matplotlib.pyplot as plt def to_rgb(img): return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) def to_bgr(img): return cv2.cvtColor(img, cv2.COLOR_RGB2BGR) def plot_rgb(img): plt.figure(figsize=(9, 6)) return plt.imshow(img) def plot_bgr(img): ...
StarcoderdataPython
4820203
<gh_stars>0 import pytest import rumps from src.app_functions.exceptions.login_failed import LoginFailed from src.app_functions.menu.change_credentials import change_credentials @pytest.fixture(name="basic_app") def create_app(): """Creates a basic app object with some variables to pass to functions Returns:...
StarcoderdataPython
3332732
# -*- coding: utf-8 -*- from smartPeak.core.SequenceHandler import SequenceHandler from smartPeak.core.SequenceProcessor import SequenceProcessor from smartPeak.io.SequenceWriter import SequenceWriter class __main__(): def example_LCMS_MRM_Unknowns( self, dir_I, delimiter_I=",", v...
StarcoderdataPython
3343150
<reponame>cnm06/Competitive-Programming f = open('sample-input.in') o = open('sample-output.out', 'w') t = int(f.readline().strip()) for i in xrange(1, t + 1): x = [str(j) for j in f.readline().strip().split(" ")] x[1] = int(x[1]) for j in xrange(0, len(x[0])-x[1]): if x[0][j] == '-': for k in xrange(j, j+x[1])...
StarcoderdataPython
3332184
import operator from OOSML import SmlObject, SmlPredicate import Python_sml_ClientInterface as sml def iterator_is_empty(iter): try: iter.next() except StopIteration: return True return False def output_event_handler(id, userData, kernel, runFlags): userData.update() def init_event_ha...
StarcoderdataPython
159242
<reponame>factioninc/snmp-unity-agent<filename>snmpagent_unity/unity_impl/HostInitiators.py class HostInitiators(object): def read_get(self, name, idx_name, unity_client): return unity_client.get_host_initiators(idx_name) class HostInitiatorsColumn(object): def get_idx(self, name, idx, unity_client): ...
StarcoderdataPython
3287467
<gh_stars>10-100 # -------------------------------------------------------- # (c) Copyright 2014 by <NAME>. # Licensed under BSD 3-clause licence. # -------------------------------------------------------- import unittest from pymonad.Reader import * @curry def neg(x): return -x @curry def sub(x, y): return x - y @c...
StarcoderdataPython
3323960
<filename>dnv_rp_c205_functions.py<gh_stars>0 # -*- coding: utf-8 -*- """ Éd<NAME> Ceci est un script temporaire. """ import numpy as np from scipy import interpolate def am_3d_square_prism(a,b): """ """ xi = b/a data = np.array([[1.00,0.68], [2.00,0.36], [3.0...
StarcoderdataPython
3318261
<gh_stars>0 from application import app#, login_manager from flask import render_template, request, redirect, url_for, flash, make_response, session, abort, json, jsonify # from sqlalchemy import or_ from werkzeug.security import generate_password_hash, check_password_hash from flask_login import login_required, lo...
StarcoderdataPython
89665
<gh_stars>0 import typing from functools import partial import six from dagster import check from dagster.core.storage.type_storage import TypeStoragePlugin from .builtin_config_schemas import BuiltinSchemas from .builtin_enum import BuiltinEnum from .config import List as ConfigList from .config import Nullable as ...
StarcoderdataPython
196997
#!/usr/bin/env python ''' napalm-logs client, without authentication. Listens to the napalm-logs server started using the following settings: napalm-logs --publish-address 127.0.0.0.1 --publish-port 49017 --transport zmq --disable-security This client example listens to messages p...
StarcoderdataPython
73386
import setuptools setuptools.setup( name="ngboost", version="0.1.3", author="<NAME>", author_email="<EMAIL>", description="Library for probabilistic predictions via gradient boosting.", long_description="Please see Github for full description.", long_description_content_type="text/markdown"...
StarcoderdataPython
1781032
<reponame>t-persson/jsontas # Copyright 2020 Axis Communications AB. # # For a full list of individual contributors, please see the commit history. # # 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 Licens...
StarcoderdataPython
135670
<reponame>joshuaroot/chaostoolkit-lib<gh_stars>10-100 # just keep this as-is def not_an_activity(): print("boom")
StarcoderdataPython
113913
<reponame>wbthomason/minigrade from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from minigrade import minigrade, PORT_NUMBER import logging logging.basicConfig(filename='grader.log',level=logging.DEBUG) logging.debug('Started logging on port: ' + str(PO...
StarcoderdataPython
32006
# Copyright 2018 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
4802923
<reponame>hassanakbar4/ietfdb<gh_stars>10-100 # Copyright The IETF Trust 2015, All Rights Reserved from inspect import getsourcelines from django.shortcuts import render, get_object_or_404 from ietf.mailtrigger.models import MailTrigger, Recipient def show_triggers(request, mailtrigger_slug=None): mailtriggers ...
StarcoderdataPython
129959
<gh_stars>0 from django.urls import path, re_path app_name = 'mainapp' import mainapp.views as mainapp urlpatterns = [ path('', mainapp.index, name='index'), path('about/', mainapp.about, name='about'), path('find/', mainapp.find, name='find'), path('select-products/<int:pk>/', mainapp.select_product...
StarcoderdataPython
138013
import cmocean import matplotlib.pyplot as plt import numpy as np from matplotlib import cm from scipy import interpolate cmap = cm.ScalarMappable(cmap=cmocean.cm.phase) cmap.to_rgba([0., 0.5, 1.]) def make_item(c, f, n=None): theta = [0] clr = cmap.to_rgba(c) if not n: n = np.random.randint(3, 9...
StarcoderdataPython
3222522
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 25 16:32:24 2021 @authors: moritz, marlin """ import pysam as ps import argparse #for deduplicating lists, will be used to calculate number of distinct clusters and output files def deduplicateList (listWithDuplicates): deduplicated=[] for...
StarcoderdataPython
1653327
<reponame>Haiiliin/PyAbaqus<filename>src/abaqus/PlotOptions/MdbDataInstance.py class MdbDataInstance: """The MdbDataInstance object instance data. It corresponds to same named part instance with a mesh in the cae model. Attributes ---------- name: str A String specifying the instance name....
StarcoderdataPython
1648087
<reponame>lanl/MPRAD import numpy as np from numba import jit from matplotlib import pyplot as plt import yt from mpl_toolkits.axes_grid1 import AxesGrid @jit(nopython=True, nogil=True, cache=True, parallel=True) def cal_div(x, y): return x / y @jit(cache=True, parallel=True, nogil=True) def cal_sum(x, axis): ...
StarcoderdataPython
30645
#!/usr/bin/env python import sys import string import re for line in sys.stdin: if '"' in line: entry = re.split(''',(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', line) else: entry = line.split(",") licence_type = entry[2] amount_due = entry[-6] print("%s\t%s" % (licence_type, amount_due))
StarcoderdataPython
3307086
<reponame>theroyakash/AKDPRFramework<gh_stars>1-10 import av class Extractor(object): def __init__(self): pass def extract_frames(self, path): ''' Extract frames from a video from a given path. Args: - path: path to the video ...
StarcoderdataPython
4808562
# Title: ex_real_data_errors.py # Description: Testing online PSP algorithm population and batch error on artificially generated data # Author: <NAME> (<EMAIL>) and <NAME> (<EMAIL>) # Notes: Adapted from code by <NAME> # Reference: None # imports from online_psp.online_psp_simulations import run_simulation import os ...
StarcoderdataPython
168874
import numpy as np from scipy.spatial import Voronoi from scipy.spatial import Delaunay from ..graph import Graph from ...core.utils import as_id_array class VoronoiGraph(Graph): """Graph of a voronoi grid. Examples -------- >>> from landlab.graph import VoronoiGraph """ def __init__(self,...
StarcoderdataPython
160855
from __future__ import division import pywt import numpy as np import itertools as itt from scipy.interpolate import interp1d from functools import partial from .common import * class SimpleWaveletDensityEstimator(object): def __init__(self, wave_name, j0=1, j1=None, thresholding=None): self.wave = pywt.Wa...
StarcoderdataPython
3352179
<reponame>sofiavegaz/Bringing-Old-Photos-Back-to-Life # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import os.path import io import zipfile from data.base_dataset import BaseDataset, get_params, get_transform, normalize from data.image_folder import make_dataset from PIL import Image import ...
StarcoderdataPython
1723428
""" Double-entry Bookkeeping System Copyright (c) 2021 <NAME> MIT License """ from collections import namedtuple from urllib.parse import parse_qs from datetime import date from html import escape import os try: from pysqlcipher3 import dbapi2 as sqlite3 except ImportError: import sqlite3 from math import ceil...
StarcoderdataPython
3212780
#!/usr/bin/python import argparse import plistlib import subprocess import fileinput PLIST_PATH = "MVVMKit/Info.plist" def increment_version(version): components = str(version).split('.') init, last = components[:-1], components[-1:] init.append(str(int(last[0]) + 1)) return ".".join(init) def get_...
StarcoderdataPython
1714470
import ada as ada from datetime import datetime import time from random import randint from instamanager import InstaManager as SocialGuard import toml import argparse if __name__ == "__main__": parser = argparse.ArgumentParser( description='It is a console interface for InstaManager') parser.add_arg...
StarcoderdataPython
3278845
<filename>pytorch_get_started/1_install/verification.py<gh_stars>0 import torch def verify(): x = torch.rand(5, 3) print(type(x)) print(x) if __name__ == '__main__': verify()
StarcoderdataPython
4810965
class Response: __url: str __status_code: int __header: dict __time_elapsed: str __content_length: int __html: str def __init__(self, url: str, status_code: int, header: dict, time_elapsed: str, content_length: int, html: str): self.__url = url self.__status_code = status_co...
StarcoderdataPython
3238871
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] pos = [] char = [] new_s = list(s) for i in xrange(len(s)): if s[i] in vowels: ...
StarcoderdataPython
3357723
#!/usr/bin/python -i import numpy as np from NuclearNormMinimization import NuclearNormMinimization from sklearn.metrics import mean_squared_error U = np.random.random((10,10)) S = np.zeros((10,10)) S[0,0] = 500 S[1,1] = 100 S[2,2] = 50 V = np.random.random((10,20)) matrix = np.matmul(U, np.matmul(S, V)) incomplete_m...
StarcoderdataPython
176071
# CloudShell L1 resource autoload XML helper # # It should not be necessary to edit this file. # # - Generates the autoload XML resource format to return to CloudShell # - Subresources are also represented with nested instances of this class # - See example usage in <project>_l1_handler.py class L1DriverReso...
StarcoderdataPython
3381808
<reponame>jsaied99/sentimint from flask import Flask, jsonify, escape, g,request from flask_cors import CORS import db_conn from time import time from twitter_api import get_tweets app = Flask(__name__) CORS(app, resources={r"/*": {"origins": "*"}}) app.config["CORS_HEADER"] = "Content-Type" @app.before_request def i...
StarcoderdataPython
3225355
from flask import Flask, request, render_template import pandas as pd import pickle import numpy as np from sklearn.externals import joblib from sklearn.preprocessing import StandardScaler import re app = Flask(__name__, template_folder="templates") # Load the model model = joblib.load('./models/model.p') scaler = jo...
StarcoderdataPython
1623979
import logging import re from netmiko import ConnectHandler from time import sleep log = logging.getLogger(__name__) class SSHSession(object): """ Generic SSHSession which can be used to run commands """ def __init__(self, host, username, password, timeout=60): """ Establish S...
StarcoderdataPython
73947
<filename>tasks.py #!/usr/bin/env python3 """ Task execution tool & library """ import os import re import sys from datetime import datetime from logging import basicConfig, getLogger from pathlib import Path import docker import git from bumpversion.cli import main as bumpversion from easy_infra import __project_nam...
StarcoderdataPython
3300095
from typing import Any import aws_cdk as cdk from constructs import Construct from api.infrastructure import Api class UuidGeneratorBackend(cdk.Stack): def __init__(self, scope: Construct, id_: str, **kwargs: Any) -> None: super().__init__(scope, id_, **kwargs) api = Api(self, "Api") cd...
StarcoderdataPython
1744888
<reponame>robert-anderson/pyscf<gh_stars>1-10 #!/usr/bin/env python # Copyright 2014-2019 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ht...
StarcoderdataPython
1671207
<filename>gui/notes-to-text.py #!/usr/bin/env python3 # GUI automation. For Mac only. import os, sys FILE_EXT_IN, FILE_EXT_OUT = '.notesairdropdocument', '.txt' USAGE = '''%s source-dir dest-dir This uses GUI automation to open note files (using the Mac `open` command) from source-dir and copy their text. It then p...
StarcoderdataPython
1747752
<reponame>AwesomeGitHubRepos/adventofcode import os.path import re from collections import deque HERE = os.path.dirname(os.path.abspath(__file__)) def create_bot(source, low, high): def bot(namespace): chips = namespace.get(source) if chips is not None and len(chips) > 1: return {hig...
StarcoderdataPython
1649883
<filename>test/end_to_end_test/test_delete_operation.py #!/usr/bin/env python from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import ...
StarcoderdataPython
3208639
<reponame>iubica/wx-portfolio<filename>agw/PyProgress.py #!/usr/bin/env python import wx import wx.lib.colourselect as csel import os import sys try: dirName = os.path.dirname(os.path.abspath(__file__)) except: dirName = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path.append(os.path.split(dirName)[0]...
StarcoderdataPython
100158
# -*- coding: utf-8 -*- """ Display the battery level. Configuration parameters: - ac_info : path to adapter info (default: '/sys/class/power_supply/ADP0') - battery_info : path to battery info (default: '/sys/class/power_supply/BAT0') - cache_timeout : seconds between battery checks (default: 5) - cap...
StarcoderdataPython
130220
def get_string_count_to_by(to, by): if by < 1: raise ValueError("'by' must be > 0") if to < 1: raise ValueError("'to' must be > 0") if to <= by: return str(to) return get_string_count_to_by(to - by, by) + ", " + str(to) def count_to_by(to, by): print(get_string_count_to_by(t...
StarcoderdataPython
3314540
import json import numpy as np import matplotlib.pyplot as plt with open('zip.json') as data_file: mapping = json.load(data_file) data = eval("""[['43537', '91344', '05201', '01002', '90703', '06405', '55106', '10309', '02138', '94533', '55107', '55369', '55436', '10003', '27510', '42141', '93117', '55105', '5446...
StarcoderdataPython
3247745
""" Make html galleries from media directories. Organize by dates, by subdirs or by the content of a diary file. The diary file is a markdown file organized by dates, each day described by a text and some medias (photos and movies). The diary file can be exported to: * an html file with the text and subset of medias a...
StarcoderdataPython
191335
<gh_stars>1-10 import pytest # see also issue https://github.com/amsico/pyqtschema/issues/12 from pydantic import BaseModel from pyqtschema.utils import build_example_widget class Simple(BaseModel): string: str integer: int schema = Simple.schema() def test_hide_widget(qtbot): ui_schema = {'string':...
StarcoderdataPython
70398
# -*- coding: utf-8 -*- import os import sublime import sublime_plugin class CopyPythonPathCommand(sublime_plugin.TextCommand): def run(self, edit): python_path_items = [] head, tail = os.path.split(self.view.file_name()) module = tail.rsplit('.', 1)[0] if module != '__init__':...
StarcoderdataPython
3349944
<gh_stars>10-100 # GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Component: DESCRIPTION = "Add scan results from a third-party vulnerability scanner" class Input: OPERATION = "operation" SCAN_RESULTS = "scan_results" class Output: COMMANDS_PROCESSED = "commands_processe...
StarcoderdataPython
158876
<filename>src/units/_cluster_multiple.py import logging import numpy as np from joblib import Parallel, delayed from ..log import setup_logger from ..units._evaluation import Eval_Silhouette from ..utils.validation import _validate_n_jobs def cluster_multiple(x, obj_def, k_list=np.array([2, 4, 8, 16]), ...
StarcoderdataPython
1796500
from m5stack import * # from m5stack_ui import M5Screen, M5Label, M5Dropdown, M5Switch from m5stack_ui import * from uiflow import * from menu_screen import MenuScreen def default_protocol(): protocol = { 'n_animals': 4, 'n_stims': 30, 'paw_left': True, 'paw_right': True, } ...
StarcoderdataPython
1767693
<reponame>muyuuuu/PyQt-learn """ .. moduleauthor:: <NAME> and <NAME> (active) .. default-domain:: py .. highlight:: python Version |release| """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals from __future__ import absolute_import from builtins import st...
StarcoderdataPython
3379145
<filename>pydm/widgets/embedded_display.py from qtpy.QtWidgets import QFrame, QApplication, QLabel, QVBoxLayout, QWidget from qtpy.QtCore import Qt, QSize from qtpy.QtCore import Property import json import os.path import logging from .base import PyDMPrimitiveWidget from ..utilities import (is_pydm_app, establish_widg...
StarcoderdataPython
80786
<filename>gb.py import numpy as np from math import floor import h5py duration = 300.0 dt = 1e-3 with h5py.File('data_gb/Achilles_10252013_sessInfo.mat', 'r') as f: # epoch info pre_epoch = f['sessInfo']['Epochs']['PREEpoch'][:].flatten() maze_epoch = f['sessInfo']['Epochs']['MazeEpoch'][:].flatten() post_ep...
StarcoderdataPython
3258337
<reponame>LucasLaibly/Intrusion from flask import jsonify from app.src.server import create from app.src.profanity.profanity_check import ProfanityCheck from browser_history.browsers import Firefox, Chrome, Safari app = create('development') profanity_checker = ProfanityCheck() @app.route('/user', methods=['GET']) d...
StarcoderdataPython
1744582
<filename>wagtail/wagtailredirects/migrations/0001_initial.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0002_initial_data'), ] operations = [ migration...
StarcoderdataPython
3387780
import os import discord ENTILZHA_ID = 200801932728729600 class BD1(discord.Client): async def on_ready(self): print("Logged on as {0}!".format(self.user)) async def on_message(self, message): print("Message from {0.author}: {0.content}".format(message)) print(f"{message.author.id}"...
StarcoderdataPython
148471
<reponame>hluk/product-definition-center<filename>pdc/apps/releaseschedule/tests.py<gh_stars>10-100 # # Copyright (c) 2017 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # from datetime import date, datetime, timedelta from django.core.urlresolvers import reverse from rest_framework...
StarcoderdataPython
293
<gh_stars>0 import discord client = discord.Client() # 接続に使用するオブジェクト # 起動時 @client.event async def on_ready(): print('ログイン成功') # メッセージを監視 @client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question = message....
StarcoderdataPython
190045
<reponame>Aditya-aot/ION from django import forms from django.forms import ModelForm from .models import stock_port , crypto_port class stock_port_form(ModelForm) : name = forms.CharField(label='',widget=forms.TextInput(attrs={"placholder":"write here"})) price = forms.CharField(label='',widget=forms.TextInput...
StarcoderdataPython
3351116
<reponame>Yat-o/Aoi from dataclasses import dataclass from sqlite3 import Row from typing import List class GuildSettingModel: def __init__(self, ok_color: int = 0x00aa00, error_color: int = 0xaa0000, info_color: int = 0x0000aa, perm_errors: bool = True, ...
StarcoderdataPython
3373968
import threading import time from random import randint from sense_hat import SenseHat sense = SenseHat() #Define the colours red and green red = (255, 0, 0) green = (0, 255, 0) black = (0,0,0) orange = (255, 255, 0) white = (255,255,255) blue = (0, 0, 255) exitFlag = 0 class TestThread(threading.Thread): def __...
StarcoderdataPython
1715377
<reponame>Consolatis/wl_framework<filename>examples/wlctrl.py<gh_stars>1-10 #!/usr/bin/env python3 from wl_framework.network.connection import ( WaylandConnection, WaylandDisconnected ) from wl_framework.protocols.foreign_toplevel import ForeignTopLevel class WlCtrl(WaylandConnection): def __init__(self, sys_args,...
StarcoderdataPython
3316333
#coding:utf-8 import os import configparser configName='config.conf' def init(): print('init config') confEdit=os.path.isfile(configName) if not confEdit: print('creat config') open(configName,'w') global conf conf=configparser.ConfigParser() conf.read(configName,'utf-8') def w...
StarcoderdataPython