id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3352086
<reponame>kfields/robocute import sys from pyglet.window import key from robocute.mailbox import Mailbox class Keybox(Mailbox): def __init__(self): super().__init__() def exit(self): sys.exit() def on_key_press(self, symbol, modifiers): pass class Mult...
StarcoderdataPython
3373316
<reponame>waikato-datamining/wai-spectral-io from enum import Enum from typing import List class InstrumentType(Enum): SER_4250 = 0 SER_51A = 1 SIC_4250 = 2 SIC_6250 = 3 SIC_6250V = 4 PARALLEL_6250 = 5 PARALLEL_6250V = 6 BL_500 = 7 BL_400 = 8 SIC_6500 = 9 SIC_5500 = 10 ...
StarcoderdataPython
43923
<gh_stars>0 from django.urls import path from rest_framework.authtoken.views import obtain_auth_token from employee.views import EmployeeCreateView, EmployeeListView, EmployeeUpdateView, login_view, register_view, logout_view app_name = 'employee' urlpatterns = [ path('e/create', EmployeeCreateView.as_view(), nam...
StarcoderdataPython
3308835
<gh_stars>0 import pymongo import os from socialcar.settings import MONGO_DBNAME TABLE_OF_ZONES = [[1,1,3,1,1,2,3,2,2,1], [1,1,2,1,1,2,3,2,2,1], [3,2,1,3,3,3,3,3,3,3], [1,1,3,1,1,2,2,2,2,1], [1,1,3,1,1,2,3,2,2,1], [2,2,3,2,2,1,3,...
StarcoderdataPython
3307442
import fasttext from collections import Counter from project.server.main.bso_category import get_bso_category from project.server.main.pf_classifier import get_pf_label from project.server.main.utils import download_file import pickle import os os.system("mkdir -p /src/models/") if os.path.exists("/src/models/all_cate...
StarcoderdataPython
134797
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "<NAME>" class PT(TREElement): def __init__(self, value): super(PT, self).__init__() self.add_field('LON', 's', 15, value) self.add_field('LAT', 's', 15, value) class ACVT(TREElement): ...
StarcoderdataPython
1776337
import copy from typing import Any, Dict, List from pytest import lazy_fixture # type: ignore from pytest import fixture, mark, param from omegaconf import OmegaConf from omegaconf._utils import ValueKind, _is_missing_literal, get_value_kind def build_dict( d: Dict[str, Any], depth: int, width: int, leaf_value...
StarcoderdataPython
3367092
<filename>src/robobase/converters.py import math import numpy as np def rotate_matrix_to_axis_and_angle(r): theta = math.acos((np.trace(r) - 1) / 2) if round(theta, 5) == 0: return theta, np.array([None, None, None]), None if math.pi - 0.001 <= round(theta, 5) <= math.pi + 0.001: wx = math...
StarcoderdataPython
3378338
<gh_stars>0 import time from typing import Callable, Optional, Tuple from .states import * class Job: """ Generic job for the scheduler. Jobs that can be scheduled in the scheduler-kernel to run at a particular time and a given number of times. This is done calling schedule() and unschedule() and se...
StarcoderdataPython
65404
q=str(raw_input("give the number...\n")) a=0 v=0 print("0") while(a<len(a)): b=int(a) c=q(a) v=v+c a+=1 print v
StarcoderdataPython
1610170
""" test_correct_year ~~~~~~~~~~~~~~~~~ Test copyright year adjustment :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import pytest @pytest.fixture( params=[ # test with SOURCE_DATE_EPOCH unset: no modification (No...
StarcoderdataPython
3375996
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def colorize(text, color): colors = { "black" : 30, "red" : 31, "green" : 32, "yellow" : 33, "blue" : 34, "purple" : 35, "cyan" : 36, ...
StarcoderdataPython
1622823
<reponame>ladsantos/Eureka import numpy as np import scipy.interpolate as spi from scipy.constants import arcsec from astropy.io import fits def dn2electrons(data, meta): """ This function converts the data, uncertainty, and variance arrays from raw units (DN) to electrons. Parameters: ---------...
StarcoderdataPython
3294005
# food100_split_for_yolo.py # # This script will split the food100 dataset into 2 files of images list # accourding to the 'percentage_test'. The default is 10% will be assigned to test. # (1) train.txt - the list of training images # (2) test.txt - the list of validating images # # Credit: script is originated from bl...
StarcoderdataPython
3372948
<gh_stars>1-10 """UniFi services.""" from homeassistant.core import callback from .const import DOMAIN as UNIFI_DOMAIN SERVICE_REMOVE_CLIENTS = "remove_clients" @callback def async_setup_services(hass) -> None: """Set up services for UniFi integration.""" async def async_call_unifi_service(service_call) -...
StarcoderdataPython
178900
<filename>dvm/prob_votes.py """ This module implements the prob_votes subroutine for the Discrete Voter Model for ecological inference. """ import functools import tensorflow as tf import tensorflow_probability as tfp import elect import tools @functools.lru_cache(maxsize=None) def get_vote_probability(flat_index, ...
StarcoderdataPython
98194
<reponame>keenhenry/pda #!/usr/bin/env python """ ``Config`` module holds all the configuration-related implementations used in ``listdb`` package. """ try: import configparser as ConfigParser # python 3.3, 3.4 except ImportError: import ConfigParser # python 2.6, 2.7 import os from ..utils import die_msg,...
StarcoderdataPython
159094
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from datetime import datetime, date, timedelta import calendar def get_month_range(start_date = None): if start_date is None: start_date = date.today().replace(day = 17) _, days_in_month = calendar.monthrange(start_date.year,start_date.month) end...
StarcoderdataPython
170695
<gh_stars>0 import gc import sys from typing import Callable, List, Optional, Tuple class Undoable: def __init__(self): self._undo_stack: List[Tuple[Callable, Callable]] = [] self._counter_uncommitted_undo = 0 def add_undo(self, thing_to_undo: Callable, purge_callback: Callable = lambda: None...
StarcoderdataPython
3284268
<filename>examples/01_quick_start.py from compas_cem.diagrams import TopologyDiagram from compas_cem.elements import Node from compas_cem.elements import TrailEdge from compas_cem.elements import DeviationEdge from compas_cem.loads import NodeLoad from compas_cem.supports import NodeSupport from compas_cem.plotters ...
StarcoderdataPython
3240899
<gh_stars>1-10 # -*- coding: utf-8 -*- import logging def basicConfig(**kwargs): logging.basicConfig( format=("%(asctime)s.%(msecs)03d UTC | %(levelname)-8s | %(message)s"), level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", **kwargs )
StarcoderdataPython
145153
<filename>architectures/bobo/model_base.py # UCF Senior Design 2017-18 # Group 38 import json import os import tflearn import time CHECKPOINT_DIR = "checkpoints" CONFIG_DIR = "config" HYPERPARAMETER_FILENAME = "hyperparameters.json" OUTPUT_DIR = "output" class Hyperparameters(object): """ This class wil...
StarcoderdataPython
1776951
<gh_stars>1-10 import os import pkg_resources ## Paths DATA_CACHE_DIR = os.path.expanduser(os.path.join('~', '.wc', 'data', 'datanator')) ## Endpoints CURRENT_VERSION_ENDPOINT = '/v0' # Speed Contstants METABOLITE_REACTION_LIMIT = 5 # Common Schema Constants DATA_DUMP_PATH = os.path.join(DATA_CACHE_DIR , 'CommonSch...
StarcoderdataPython
3386557
<filename>app/app.py from flask import Flask, render_template, request, redirect from pymongo import MongoClient from bson.objectid import ObjectId from datetime import datetime import os app = Flask(__name__) user = 'username' # username as set for the mongodb admin server (the username used in secret.yaml - ...
StarcoderdataPython
3237911
<reponame>mpi2/vpv import numpy as np from PyQt5 import QtGui, QtCore from PyQt5.QtWidgets import QDialog import pyqtgraph as pg from vpv.lib.qrangeslider import QRangeSlider from vpv.utils.lookup_tables import Lut from vpv.ui.views.ui_datatab import Ui_data from vpv.ui.views.ui_change_vol_name import Ui_VolNameDialog ...
StarcoderdataPython
3329178
# Copyright (c) 2021, NVIDIA CORPORATION. # # 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...
StarcoderdataPython
23344
<gh_stars>0 #!/usr/bin/env python u""" read_iceye_h5.py Written by <NAME>' (03/2022) Read ICEYE Single Look Complex and Parameter file using GAMMA's Python integration with the py_gamma module. usage: read_iceye_h5.py [-h] [--directory DIRECTORY] TEST: Read ICEye Single Look Complex and Parameter. optional argument...
StarcoderdataPython
1738031
# https://app.codility.com/programmers/lessons/3-time_complexity/ # FrogJmp #solution 1 import math # use of math def solution(X, Y, D): if( X == Y): return 0 return math.ceil( (Y - X) / D) #solution 2 def solution(X, Y, D): location = X counter = 0 while( location < Y): location...
StarcoderdataPython
101848
import os import numpy as np from PIL import Image from eratosthenes.generic.mapping_io import read_geo_image from eratosthenes.preprocessing.shadow_transforms import mat_to_gray, gamma_adjustment, log_adjustment rgi_id = 'RGI60-01.19773' # Red Glacier bbox = (4353, 5279, 9427, 10980) # 1000 m buffer f2018 = "T05VM...
StarcoderdataPython
117180
""" <NAME> descriptor.py Takes in a directory of sub-directories of images and produces a descriptor file for all the images found in the sub-directories. ,:'/ _..._ // ( `""-.._.' \| / 6\___ ...
StarcoderdataPython
1723748
n = int(input().strip()) a = list(map(int, input().strip().split(' '))) # track number of elements swapped during a single array transversal totalNumberOfSwaps = 0 for i in range(n): currentSwaps = 0 for j in range(0, n - 1): if a[j] > a[j + 1]: a[j], a[j + 1] = a[j + 1], a[j] # swap adja...
StarcoderdataPython
137373
import connector_pb2_grpc import connector_pb2 import grpc import prom class Service(connector_pb2_grpc.ConnectorServicer): def GetMetaInfo(self, request, context): return connector_pb2.MetaInfo( name = 'Prometheus Connector', version = '0.0.1', developer = 'Qlik' ) def GetData(self, req...
StarcoderdataPython
3377017
<gh_stars>0 import csv import numpy as np from sklearn.svm import SRV import matplotlib.pyplot as plt dates = [] prices = [] def get_data(filename): with open(filename, 'r') as csvfile: csvFileReader = csv.reader(csvfile) next(csvFileReader) for row in csvFileReader: dates.append(int(row[0].s...
StarcoderdataPython
57509
<filename>project/data/hoc.py import pandas as pd import re from pathlib import Path from collections import defaultdict, OrderedDict class HOC(): def __init__(self, source_dir, target_dir, replace_csv=True) -> None: self.source_dir = Path(source_dir) if type( source_dir) is str else...
StarcoderdataPython
1787520
"""Request builders.""" from typing import List import dacite import safe_browsing.access.external.contracts as contracts from safe_browsing.access.external.contracts import SafeBrowsingRequest def build(threat_entries: List[str]) -> SafeBrowsingRequest: """Build a SafeBrowsingRequest.""" payload = dict( ...
StarcoderdataPython
3325557
<reponame>darrengardner-sfc/SnowAlert<gh_stars>0 from os import environ import uuid from runners.helpers.dbconfig import DATABASE ENV = environ.get('SA_ENV', 'unset') # generated once per runtime RUN_ID = uuid.uuid4().hex # schema names DATA_SCHEMA_NAME = environ.get('SA_DATA_SCHEMA_NAME', "data") RULES_SCHEMA_NAME...
StarcoderdataPython
3206709
from sys import path from os.path import dirname as dir path.append(dir(path[0])) from optimization.genOptimized import optimizeCode # print(result[0].execute(None)) # print(result[1].execute(None)) # print(grammar.returnPostgreSQLErrors()) s = ''' from goto import with_goto from interpreter import execution from c3...
StarcoderdataPython
198030
<filename>regexlib/python_re2_test_file/regexlib_4184.py # 4184 # ((http|https|ftp|telnet|gopher|ms\-help|file|notes)://)?(([a-z][\w~%!&amp;',;=\-\.$\(\)\*\+]*)(:.*)?@)?(([a-z0-9][\w\-]*[a-z0-9]*\.)*(((([a-z0-9][\w\-]*[a-z0-9]*)(\.[a-z0-9]+)?)|(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9...
StarcoderdataPython
150653
from flask import render_template, url_for from . import main # from app import app from ..request import get_source, get_source_articles # Views @main.route('/') def index(): ''' View root page function that returns the index page and its data ''' # Getting news headlines news_source = get_source...
StarcoderdataPython
3210955
def calc(num1, num2): return num1+num2 print(calc(5,6))
StarcoderdataPython
3254702
<reponame>luovkle/FastAPI-Note-Taking<filename>backend/app/app/api/api_v1/endpoints/login.py from fastapi import APIRouter, Depends from fastapi.security import OAuth2PasswordRequestForm from sqlalchemy.orm import Session from app.api.deps import get_db from app.crud import crud_user from app.core.security import crea...
StarcoderdataPython
3357535
import pytest from runrex.text import Document from apanc_nlp.algo.pain import AbdPain, extract_duration, RADIATING_TO_BACK, CHRONIC, CHEST_PAIN, DURATION, \ is_close_to_pain, has_abdominal_pain @pytest.mark.parametrize('exp, text', [ (AbdPain.RECENT, '1 week'), (AbdPain.VERY_RECENT, '2 days'), (AbdP...
StarcoderdataPython
155813
<reponame>yuanyan3060/arknights-mower import time import schedule from arknights_mower.strategy import Solver from arknights_mower.utils.log import logger, init_fhlr from arknights_mower.utils import config # 指定无人机加速第三层第三个房间的制造 drone_room='room_3_3' # 指定关卡序列的作战计划 ope_lists = [['AP-5', 1], ['1-7', -1]] # 使用信用点购买东西的优...
StarcoderdataPython
130736
<gh_stars>0 # vim: tabstop=4 shiftwidth=4 softtabstop=4 # OpenCenter(TM) is Copyright 2013 by Rackspace US, Inc. ############################################################################## # # OpenCenter is licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file exce...
StarcoderdataPython
3235884
<filename>nailgun/nailgun/objects/release.py # -*- coding: utf-8 -*- # Copyright 2013 Mirantis, 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...
StarcoderdataPython
1733672
#-------------------------------------------------------------------------------------------------- # Import required libraries from tkinter import * from tkinter import colorchooser from tkinter import messagebox from tkinter import ttk from tkinter import filedialog import cv2 from PIL import Image, ImageTk import n...
StarcoderdataPython
1751973
<filename>server/wrappers/StorageService.py from abc import ABC, abstractmethod class StorageService(ABC): @abstractmethod def test_connection(api): pass @abstractmethod def saveData(data): pass @abstractmethod def insert_node(data): pass @abstractmethod de...
StarcoderdataPython
3328890
#!/usr/bin/python import GTFBasics import sys # Pre: A GTF filename, for a file with 'exon' features, and 'gene_id' and 'transcript_id' attributes. # Post: Prints to stdout a genepred with transcripts def main(): if len(sys.argv) < 2: sys.stderr.write("gtf_to_genepred.py <gtf filename>\n") return gtf = ...
StarcoderdataPython
3318160
<reponame>Mog333/CMPUT551_ML_Project<gh_stars>0 scores = open("finalScore2.txt",'r') ids = open("tes",'r') output = open("final.csv",'w') parsing = True for i in range(0, 4000): score = scores.readline().strip() scoreID = ids.readline().strip() output.write(str(scoreID) + "\t" + str(score) + "\n") output....
StarcoderdataPython
40265
from pvapy import Channel, CA, PvTimeStamp, PvAlarm print('DBRdouble') channel = Channel('DBRdouble') timestamp = PvTimeStamp(10, 100) alarm = PvAlarm(1,1,"mess") print(channel.get('value')) print('here 1') channel.put(alarm,'record[process=false]field(alarm)') print('here 2') print(channel.get('value')) channel.put(ti...
StarcoderdataPython
3360215
<filename>GOES/downloads/download_data.py # -*- coding: utf-8 -*- #----------------------------------------------------------------------------------------------------------------------------------- ''' Description: Downloads GOES-16/17 data from amazon Author: <NAME> E-mail: <EMAIL> Created date: Mar 23, 2020 Modifica...
StarcoderdataPython
4840924
<reponame>LaudateCorpus1/python-redfish-utility # ## # Copyright 2016-2021 <NAME>, 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://www.apache.org/license...
StarcoderdataPython
1607539
#!/usr/bin/env python2 # coding: utf-8 TEMPLATE="""<html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="index.css"> </head> <body> <div class="main"> <table> <tr><td class="header" colspan="3">{{ title }}</td></tr> {% if coming_soon %} <tr><td class="title" colspan="3">Co...
StarcoderdataPython
1648985
<filename>Binary_Search_Tree/2-bst-deletion.py class Node: def __init__(self, key): self.key = key self.left = None self.right = None def inorder(root): if root is not None: inorder(root.left) print(root.key, end=" ") inorder(root.right) def insert(node, key): if node is None: return Node(key) if...
StarcoderdataPython
1615875
# -*- coding: utf-8 -*- """ @author: clausmichele """ import time import tensorflow as tf import cv2 import numpy as np from tqdm import tqdm def SpatialCNN(input, is_training=False, output_channels=3, reuse=tf.AUTO_REUSE): with tf.variable_scope('block1',reuse=reuse): output = tf.layers.conv2d(input, 128, 3, padd...
StarcoderdataPython
3309896
#!/usr/bin/env python3 import argparse import mwbot import vowi def count_excluded_resources(): current_lvas = [] for title in site.get('askargs', conditions='Category:LVAs|Ist veraltet::0', parameters='limit=9999')['query']['results']: current_lvas.append(title) duplicates = [] excluded = 0 for page in sit...
StarcoderdataPython
1621534
# -*- coding: utf-8 -*- """ Created on Tue Dec 22 01:59:25 2020 @author: nacer """ """ Problem link : https://leetcode.com/problems/palindrome-number/ """ class Solution: def isPalindrome(self, x: int) -> bool: if(x<0): return False return x - reverse(x) == 0 def reverse(x): ...
StarcoderdataPython
4835944
# -*- coding: utf-8 -*- # pylint: disable=superfluous-parens,too-many-locals,too-many-statements,too-many-branches """Functions to create, inspect and manipulate profiles in the configuration file.""" import os import sys import click def setup_profile(profile, only_config, set_default=False, non_interactive=False, ...
StarcoderdataPython
1605021
from subprocess import check_output import sys objects = check_output(["ar", "-t", sys.argv[1]]).decode().split("\n") for object in objects: if not object.endswith(".o") or object.endswith("lso.o"): continue check_output(["ar", "-xv", sys.argv[1], object])
StarcoderdataPython
1641290
from dexy.doc import Doc from dexy.node import Node from dexy.node import PatternNode from dexy.wrapper import Wrapper from tests.utils import wrap import dexy.doc import dexy.node import os import time def test_create_node(): with wrap() as wrapper: node = dexy.node.Node.create_instance( "...
StarcoderdataPython
3398609
<gh_stars>1-10 from http import HTTPStatus from typing import Union from flask import make_response, Response, Flask from webargs import ValidationError from webargs.flaskparser import parser from werkzeug.exceptions import BadRequest from src.extensions import jwt_manager AUTH_ERROR = 'Authentication failed' def ...
StarcoderdataPython
115694
<reponame>robscetury/hbos import typing from typing import Dict from pandas import DataFrame from hbos_server.outputbase import OutputBase class DeleteSourceOutput(OutputBase): def output(self, name: str, input_data: Dict[str,DataFrame]) -> typing.Tuple[str, object]: """ This output filter will d...
StarcoderdataPython
1614666
<filename>commands/__init__.py from . import get_runtimes from . import get_help from . import run_code from . import remind from . import inspiration from . import roll from . import alerts from . import update_presence from . import add_bad_reply
StarcoderdataPython
3371666
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
StarcoderdataPython
1715326
from unittest import SkipTest, skip, skipIf import holoviews as hv import pandas as pd from holoviews.core.options import Store from holoviews.selection import link_selections from holoviews.element.comparison import ComparisonTestCase try: from holoviews.operation.datashader import datashade, dynspread except: ...
StarcoderdataPython
3315617
<reponame>mrkraimer/testPvaPy # GenerateCurve.py import numpy as np import sys def getCurveNames() : return ("line","circle","ellipse","clover","heart","lissajous","figureight") def generateCurve(argv) : nargs = len(argv) if nargs==1 : print('argument must be one of: ',getCurveNames()) ex...
StarcoderdataPython
1684061
<gh_stars>1-10 from unittest import TestCase from core.odoorpc import OdooRPC from core.models import Version from config import ODOO_TEST_URL, ODOO_TEST_DB, ODOO_TEST_USERNAME, ODOO_TEST_PASSWORD class OdooRPCTest(TestCase): def __init__(self, *args, **kwargs): super(OdooRPCTest, self).__init__(*args, *...
StarcoderdataPython
3271188
import os import re import json import requests import colorama from time import sleep from alive_progress import alive_bar if 'PYCHARM_HOSTED' in os.environ: convert = False strip = False else: convert = None strip = None colorama.init( convert=convert, strip=strip ) conf...
StarcoderdataPython
4807449
#collections.py from collections import ChainMap car_parts = {'hood': 500, 'engine': 5000, 'front_door': 750} car_options = {'A/C': 1000, 'Turbo': 2500, 'rollbar': 300} car_accessories = {'cover': 100, 'hood_ornament': 150, 'seat_cover': 99} car_pricing = ChainMap(car_accessories, car_options, car_parts) print (car_p...
StarcoderdataPython
3275032
<filename>check/validate/apps/gstwebrtc.py # Copyright (c) 2020, <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option...
StarcoderdataPython
3363041
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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 applic...
StarcoderdataPython
1705320
import sys import math import gym from gym import spaces, logger from gym.utils import seeding import numpy as np from feh_simulator.simulator import Simulator class fehEnv(gym.Env): def __init__(self): self.width = 6 self.height = 8 # input are row, col, verbose, difficulty self.simulator = Simulator() se...
StarcoderdataPython
3354658
<gh_stars>0 from django.conf import settings from django.db import models class Category(models.Model): "Generated Model" name = models.CharField( max_length=255, ) icon = models.URLField() description = models.TextField( null=True, blank=True, ) is_recurring = mode...
StarcoderdataPython
4841063
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import parlai.utils.testing as testing_utils from parlai.core.agents import create_agent @testing_util...
StarcoderdataPython
1719351
'''Test rsync SSH helper''' import pytest from hazelsync.ssh import Unauthorized from hazelsync.ssh.rsync import RsyncSsh def test_authorize_allow(): cmd_line = 'rsync --server --sender -logDtpArRe.iLsfxC --numeric-ids . /opt/data' helper = RsyncSsh(dict(allowed_paths=['/opt/data'])) helper.authorize(cmd...
StarcoderdataPython
3363661
<filename>transom-elevation/elevations_utils.py import cv2 import numpy as np import csv def corrected_perspective(image): """Return image with corrected perspective""" # convert BGR to RGB img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # project image to vertical plane # this is based on first f...
StarcoderdataPython
3244643
<gh_stars>0 # ----------------------------------------------------------------------------------------- # Plot functions for MILP MESPP RISK-AWARE # ----------------------------------------------------------------------------------------- import os from matplotlib import pyplot as plt # TODO IMPORT FROM THE ORIGINAL MI...
StarcoderdataPython
1653726
A, B = map(int, input().split()) print(A * B - (A + B - 1))
StarcoderdataPython
1614431
<filename>ros/src/tl_detector/light_classification/tl_classifier.py import rospy from styx_msgs.msg import TrafficLight import tensorflow as tf import numpy as np import datetime import cv2 class TLClassifier(object): def __init__(self, is_sim): if is_sim: #PATH_TO_MODEL = 'light_clas...
StarcoderdataPython
30093
<reponame>JcDelay/pycr<gh_stars>1-10 """This module provides convenient use of EDITOR""" import os import subprocess import tempfile from libpycr.config import Config def get_editor(): """Return the user's editor, or vi if not defined :rtype: str """ return os.environ.get('EDITOR') or os.environ.g...
StarcoderdataPython
92746
<gh_stars>1-10 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License")...
StarcoderdataPython
1701293
<reponame>Tachyu/PythonCodes #encoding:utf-8 import re import string import sys import os import io import urllib import urllib2 import cookielib import requests import getpass import pytesser from lxml import etree from pytesser import * import lxml.html.soupparser as soupparser import splinter import time import rand...
StarcoderdataPython
3330500
""" Setup script for failnozzle. """ from setuptools import setup if __name__ == '__main__': setup(name='failnozzle', version='1.0', packages=['failnozzle'], package_dir={'failnozzle': 'failnozzle'}, install_requires=['gevent', 'Jinja2'], package_data={'failnozzle'...
StarcoderdataPython
1633848
import os import random from statistics import mean import string import uuid import sys import tracery import spacy import pyocr import pyocr.builders from PIL import Image, ImageDraw, ImageFilter BOUND_PADDING = 50 BOX_PADDING = 50 # 10 WOBBLE_MAX = 2 nlp = spacy.load('en') def draw_vertical_lines(draw, boxes, d...
StarcoderdataPython
3260238
<reponame>repasics/js-test-generators #!/usr/bin/env python from os import path SCRIPTS_DIR = path.dirname(path.abspath(__file__)) TEMPLATE_DIR = path.normpath(path.join(SCRIPTS_DIR, 'templates')) PROJECT_DIR = path.normpath(path.join(SCRIPTS_DIR, '..', '..')) NUMBER_DIR = path.normpath(path.join(PROJECT_DIR, 'src', '...
StarcoderdataPython
3344234
<gh_stars>0 """ use the trained model to predict personality """ import pickle as pkl import re import numpy as np from nltk import WordNetLemmatizer from nltk.corpus import stopwords from numpy import ndarray from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.svm imp...
StarcoderdataPython
4822470
#!/usr/bin/env python3 from lark import Lark program = open('program.txt').read() rule = open('sip.lark').read() # 文法規則をパーサジェネレータに渡してパーサを生成(字句解析もやってくれる) parser = Lark(rule, start='generic_message', parser='lalr') # プログラムを字句解析&構文解析 tree = parser.parse(program) print(tree.pretty())
StarcoderdataPython
100690
import logging from getpass import getpass import keyring from mysql import connector from mysql.connector.errors import ProgrammingError log = logging.getLogger(__name__) class CursorProvider: instance = None @classmethod def get(cls): if CursorProvider.instance is None: raise Attr...
StarcoderdataPython
1648197
<filename>kernfab/start.py """ Module for starting kernel VM(s) """ from kernfab import config, network, qemu def start(base_image: bool = False) -> None: """ Start kernel """ network.start() if base_image: vm_image = config.qemu_get_base_image() vm_id = 0 qemu.run_vm(vm_...
StarcoderdataPython
4827373
""" and or not && || != == >= <= True False """ result = 5 == 5 print("\n", result)
StarcoderdataPython
1785041
<reponame>Likitha-Seeram/Naive-Bayes-Text-Classification import os, glob path = '20_newsgroups' #path of the dataset folders = os.listdir(path) #list of folders present in the dataset #Function to check the probability of a file for a praticular place. #It takes ...
StarcoderdataPython
3354418
from traits.api import HasTraits, Directory, Bool import traits.api as traits from ....base import MetaWorkflow, load_config, register_workflow from wip_diffusion import config as pconfig """ Part 1: MetaWorkflow """ mwf = MetaWorkflow() mwf.help = """ Diffusion tracking workflow =========================== """ mwf.u...
StarcoderdataPython
14118
from marshmallow import fields, Schema from .provision import ProvisionActionSchema class InstanceSchema(Schema): type = fields.String(required=True) image_id = fields.String(required=True) availability_zone = fields.String(required=True) ebs_optimized = fields.Boolean() iam_fleet_role = fields.String(required=...
StarcoderdataPython
3372671
"""Test unimodal vision and speech models on Flickr one-shot multimodal task. Author: <NAME> Contact: <EMAIL> Date: October 2019 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import datetime import os from absl import app from absl import flags f...
StarcoderdataPython
91692
#!/usr/bin/python3 import subprocess, os import re def get_output(cmd): my_env = os.environ.copy() if(variant == 'windows'): my_env['PKG_CONFIG_PATH'] = '/tmp/gtk_download_test/lib/pkgconfig' p = subprocess.Popen(cmd, env = my_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() ...
StarcoderdataPython
128184
from .exceptions import BaseSnappyError, CorruptError, TooLargeError # noqa: F401 from .main import compress, decompress # noqa: F401
StarcoderdataPython
1793256
<reponame>Devil-619/pymovies-project<gh_stars>0 from django.urls import path from .views import MovieListView, GenreMovieListView, MovieSearchResult, WatchListView, RecommendListView from . import views urlpatterns = [ path('', MovieListView.as_view(), name='movie-home'), path('genre/<str:genre>/', GenreMovieL...
StarcoderdataPython
23770
#!/usr/bin/env python # convert jpg tp png from glob import glob import cv2 pngs = glob('./*.jpg') for j in pngs: img = cv2.imread(j) cv2.imwrite(j[:-3] + 'png', img) # delete jpg files import glob import os dir = "/Users/wangmeijie/ALLImportantProjects/FlameDetectionAPP/Models/MaskRCNN/02_26_2020/Mask_RCNN...
StarcoderdataPython
3227842
<reponame>SaidAlvarado/Cygnus_Quadcopter #!/usr/bin/env python # Script that listen to a Geometry Pose Message, transforms it into a Euler rotation, ans publishes it as a # Vector3 message. with x = ROLL, y = PITCH and z = YaW. # Reference = http://answers.ros.org/question/69754/quaternion-transformations-in-python/ im...
StarcoderdataPython
3381711
class NotSupportedException(Exception): def __init__(self, message): super(NotSupportedException, self).__init__(message)
StarcoderdataPython