id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
11202139
<filename>src/com/oltpbenchmark/benchmarks/chbenchmark/queries/get_queries.py for num, pre in enumerate(hxs.select('//pre[span[contains(text(), "select")]]')): with open("q{0}.txt".format(num + 1), "w") as q: print >>q, " ".join(pre.select(".//text()").extract())
StarcoderdataPython
5176721
<filename>src/utils/geocoder.py import googlemaps class Geocoder: def __init__(self, key: str): self.maps = googlemaps.Client(key=key) def get_geocode(self, address: str): result = self.maps.geocode(address) if len(result) == 0: return {} return { 'for...
StarcoderdataPython
1982669
<reponame>KarthikUdyawar/Sorting-Visualizer<gh_stars>0 import time def cocktail(data, drawData, timer): swapped = True start = 0 end = len(data) - 1 while swapped == True: swapped = False for i in range(start, end): if (data[i] > data[i+1]): data[i], data[i+1]...
StarcoderdataPython
5096888
<filename>src/honorary_gui/button.py from tkinter import * root = Tk() def myClick(): myLabel = Label(root, text="Clicked a Button") myLabel.grid(row=1, column=1) myButton = Button(root, text="Click Me!", #state=DISABLED, padx=50, pady...
StarcoderdataPython
1932443
<gh_stars>0 text = "hello_cruel_world._This_is_a_sample_textttttt" l = {i:text.count(i) for i in text} print(l.values()) # answer = sorted(l.items(), key=lambda (k,v): v['rates']['correctRate']) print(l) print(sorted(l, key=lambda x: l[x], reverse=True)) print(text) chars = "abcdefghijklmnopqrstuvwxyz" check_string = ...
StarcoderdataPython
11342391
<reponame>Wongjx/PUPpy import plotly.plotly as py import plotly.tools as tls from plotly.graph_objs import * import numpy as np # (*) numpy for math functions and arrays import time import datetime # def to_unix_time(dt): # epoch = datetime.datetime.utcfromtimestamp(0) # return (dt - epoch).total_seconds() *...
StarcoderdataPython
9706553
import pygame import random class ScreenDetails: screen_color = (100, 100, 100) screen_width = 720 screen_height = 480 screen = pygame.display.set_mode((screen_width, screen_height)) class PlayerDetails: player_width = 30 player_color = (100, 0, 255) player_length = 0 ...
StarcoderdataPython
5179710
from eventlet import patcher from eventlet.green import socket from eventlet.green import SocketServer patcher.inject('BaseHTTPServer', globals(), ('socket', socket), ('SocketServer', SocketServer)) del patcher if __name__ == '__main__': test()
StarcoderdataPython
1927509
import datetime import decimal import json from typing import Any class CASDataEncoder(json.JSONEncoder): """CAS Data encoder class for json output.""" def default(self, o: Any) -> Any: """Encode custom datatype to json format.""" if isinstance(o, decimal.Decimal): return str(o) ...
StarcoderdataPython
1686248
# Common imports import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import sklearn.linear_model as skl from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer from sklea...
StarcoderdataPython
3417841
<filename>tests/cdli_corpus_test.py """ This file tests methods in cdli_corpus.py. """ import unittest import os from Importer.file_importer import FileImport # pylint: disable =import-error from Importer.cdli_corpus import CDLICorpus # pylint: disable =import-error __author__ = ['<NAME> <<EMAIL>>'] __license__ = '...
StarcoderdataPython
1970170
""" This file should be run from Python shell. Do it like this: >>> import Polymer >>> import sys >>> polymer = Polymer.Polymer('5dn7.pca') >>> sys.argv = ['plt.py','50', '80', '110'] >>> execfile('plt.py') for exit: >>> exit() You can close the figure and try other configurations, by repeating 2 last steps. you ca...
StarcoderdataPython
6544432
<filename>tests/daos/test_dao_git_metric.py from app.models import GitMetric from app.daos.dao_git_metric import ( dao_get_git_metrics, dao_get_git_metrics_between_daterange, dao_upsert_git_metric ) def test_dao_get_git_metrics(dbsession): m1 = { 'team_id': 'fake_team_id', 'team_name':...
StarcoderdataPython
6560491
"""Provides the repository macro to import absl.""" load("//third_party:repo.bzl", "tf_http_archive", "tf_mirror_urls") def repo(): """Imports absl.""" # Attention: tools parse and update these lines. # LINT.IfChange ABSL_COMMIT = "997aaf3a28308eba1b9156aa35ab7bca9688e9f6" ABSL_SHA256 = "35f22ef5...
StarcoderdataPython
213399
import discord import random import re import json import time import asyncio from discord.ext import commands from random import choice from pathlib import Path from importlib import import_module SPACE = re.compile(r' +') class BaseLocale(object): def __init__(self, name, code, data): assert len(code....
StarcoderdataPython
8005474
# Copyright 2019-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
StarcoderdataPython
8040506
<reponame>Viktoriia-Zakharova/CS91-project<gh_stars>1-10 #*----------------------------------------------------------------------------* #* Copyright (C) 2020 ETH Zurich, Switzerland * #* SPDX-License-Identifier: Apache-2.0 * #* ...
StarcoderdataPython
9774512
<filename>VGG19.py<gh_stars>0 import torch import torch.nn as nn from torchvision.models import vgg19 class Model(nn.Module): def __init__(self, device): super(Model, self).__init__() self.device = device self.norm_mean = torch.tensor([0.485, 0.456, 0.406]).to(device) self.norm_s...
StarcoderdataPython
4898942
"""About this package.""" __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ] __title__ = "argo-workflows" __summary__ = "Client for Argo Workflows" __uri__ = "https://github.com/CermakM/argo-client-python" __v...
StarcoderdataPython
6699764
<reponame>oguzhan2142/Youtube-Spotify-Music-Downloader #!/usr/bin/env python3 """ Recursively search and download album covers for a music library. """ import argparse import asyncio import contextlib import base64 import collections import inspect import itertools import logging import operator import os import stri...
StarcoderdataPython
5016434
<filename>src/util/segment.py # We know every chars in the image is always about the same size. # And there are often only few grayscale values in the adhesions edge. # Based on this, we implement the segment method as follow: # 1.We find the characters inside the image by connected domain. # 2.When two characters adhe...
StarcoderdataPython
160143
#!/usr/bin/env python import os import random # download dataset print('downloading graph dataset...') os.system('wget https://snap.stanford.edu/data/soc-pokec-relationships.txt.gz') os.system('gunzip soc-pokec-relationships.txt.gz') # reformat and shuffle print('re-formating and shuffling graph dataset...') node_siz...
StarcoderdataPython
11342980
#!/usr/bin/env python3.5 """ NRF5-parser tool. This script will parse the development kits of Nordic Semiconductor from the 'developer.nordicsemi.com/' directory """ import fnmatch import os import urllib.request import zipfile import hashlib from pathlib import Path from bs4 import BeautifulSoup from sqlalchemy im...
StarcoderdataPython
88413
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 24 21:20:52 2021 @author: greydon """ import os from bids import BIDSLayout import pyedflib import numpy as np import re import pandas as pd pd.set_option('display.float_format', lambda x: '%.3f' % x) from multiprocessing import Pool fr...
StarcoderdataPython
4936783
AUTHOR = '<EMAIL>' DESCRIPTION = 'Experiment with rnaseq jobs completed' # MONGODB_VIEW_NAME = 'experiment_rnaseq_jobs_view'
StarcoderdataPython
1717770
#!/usr/bin/python # # usage: ./rcon.py "command" # please put the command in quotations! import sys from socket import * # q3server details host = "localhost" port = 27960 buf = 2084 addr = (host,port) rconpass = "password" # packet header header = ("\xff" * 4) + "rcon " # open socket to speak to server UDPSock = s...
StarcoderdataPython
11309461
<reponame>ThibaultLatrille/AdaptaPop<filename>Contrasts/rm_unecessary.py import os def is_float(i): try: float(i) return True except: return False if __name__ == '__main__': for species_f in os.listdir(): if not os.path.isdir(species_f): continue for m...
StarcoderdataPython
1656774
<filename>snowddl/blueprint/stage.py from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING if TYPE_CHECKING: from .ident import SchemaObjectIdent @dataclass class StageWithPath: stage_name: "SchemaObjectIdent" path: str @dataclass class StageUploadFile: local_p...
StarcoderdataPython
6460644
<gh_stars>1-10 import os import json import redis import utils from hashlib import md5 db = redis.from_url(os.environ.get("REDIS_URL")) def get_empty_user(): return dict( wanted=[], collection=[], transactions={}, past_transactions=[] ) def get_empty_card(id): return dict(id=id, whished=[], ow...
StarcoderdataPython
6495730
<reponame>rakhi2001/ecom7<gh_stars>100-1000 __________________________________________________________________________________________________ sample 316 ms submission class Solution: def totalHammingDistance(self, nums: List[int]) -> int: xmap = map("{:032b}".format, nums) total, N = 0, len(nums) ...
StarcoderdataPython
9782336
import os TEAM_MAP = {} def init_team_map(): dir = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(dir, 'teams.txt') with open(path) as fhnd: for line in fhnd: name, custom_name = line.strip().split(':') TEAM_MAP[name] = custom_name #initializes the global...
StarcoderdataPython
228368
from ..tasks import video, task_base TASKS = [ video.SingleVideo("data/videos/bourne_test.mkv", name="testshort"), ]
StarcoderdataPython
140213
<filename>losses/mdrnn_loss.py """Definitions for various loss functions used in this project. """ import torch import torch.nn as nn from torch.distributions.normal import Normal def MixtureDensityLSTMLoss(trueLatents, predMu, predSigma, predMDLogProbs): """Computes the loss for a MixtureDensityLSTM model Lo...
StarcoderdataPython
8073541
from itertools import permutations from queue import Queue from threading import Thread from day7 import Program def main(): input_file = 'input.txt' with open(input_file, 'r') as f: contents = f.read().split(',') prog = [int(c) for c in contents] part_1(prog.copy()) part_2(prog) def...
StarcoderdataPython
9725467
<gh_stars>0 # coding=utf-8 # Copyright 2021 The Balloon Learning Environment Authors. # # 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 # # Un...
StarcoderdataPython
5146825
<filename>pictures/programs/hem_exp7_d.py import matplotlib import matplotlib.pyplot as plt import numpy as np from matplotlib import rc from matplotlib.pyplot import MultipleLocator rc('mathtext', default='regular') plt.rcParams['axes.unicode_minus'] = False plt.rcParams['font.family'] = ['Times New Roman'] # Name =...
StarcoderdataPython
1634000
#!/usr/bin/env python # A logFileParser class to parse VistA FileMan Schema log files and generate # the FileMan Schema and dependencies among packages. #--------------------------------------------------------------------------- # Copyright 2012 The Open Source Electronic Health Record Agent # # Licensed under the Ap...
StarcoderdataPython
9772073
<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-18 13:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bdo_profile', '0002_userprofile_business_role'), ] operations = [ ...
StarcoderdataPython
12808771
from iterators import *
StarcoderdataPython
9639778
<filename>Pipes/sensor for counting the heating and quantity/sensor-master/sensor/SHT20.py from sensor.HTU21D import HTU21D class SHT20(HTU21D): TEMPERATURE_DELAY = 0.1 HUMIDITY_DELAY = 0.04
StarcoderdataPython
6602834
from flask import g from graphene import Int, ObjectType class WhoAmI(ObjectType): @property def description(self): return "Description of the user making the query." user_id = Int(description='User id.') def resolve_user_id(self, info): return g.user.user_id
StarcoderdataPython
9654269
<reponame>pjamesjoyce/lcoptview from .modelview import LcoptModelView from .parameters import parameter_sorting from .excel_functions import create_excel_summary, create_excel_method from collections import OrderedDict from flask import Flask, send_file, request, render_template, session import json def uc_first(stri...
StarcoderdataPython
6525932
# coding=UTF-8 # __author__ == <EMAIL> src_struct = ''' F_OS_SEND_FILLDATA { char account[14]; int ord_match_qty; int ord_match_amt; int ord_match_avg_prc; int update_qty; int cancel_qty; char match_time[8]; char mtype[1]; /* O : Oversea, I : Inside */ char firm[7]; ...
StarcoderdataPython
318831
<gh_stars>0 from selenium_api.selenium_api import SeleniumApi from pages.dashboard import Dashboard class DashboardTests(SeleniumApi): def test_verify_dashboard_loaded(self): self.wait_for_visible("XPATH", Dashboard._launch_instance_button_css) def test_from_dashboard_goto_keypairs_lp_vi...
StarcoderdataPython
4945151
<gh_stars>1-10 # -*- coding: utf-8 -*- from HTMLParser import HTMLParser from goose.text import StopWords, innerTrim from goose.parsers import Parser from copy import deepcopy class OutputFormatter(object): def __init__(self): self.topNode = None def getTopNode(self): return self...
StarcoderdataPython
1636278
import tensorflow as tf from services.common import save_array PREFETCH_COUNT = 2560 class Base: def __init__(self, n_features, n_classes): self.batch_size = tf.Variable(32, dtype=tf.int32, trainable=False, name='batch_size') self.input_ = tf.placeholder(tf.float32, [None, n_features, None], n...
StarcoderdataPython
5172642
<reponame>frassom/prnu-copy-attack<filename>test/test_utils.py # Copyright (c) 2021 <NAME> # # Licensed under the MIT license: https://opensource.org/licenses/MIT # Permission is granted to use, copy, modify, and redistribute the work. # Full license information available in the project LICENSE file. import unittest i...
StarcoderdataPython
3483360
<filename>tutorials/complete3d.py # vim: set et sw=4 ts=4 nu fdm=indent: # coding: utf8 import sys sys.path.insert(1, "../src") from system import System from island import Island from kerr import MOKE import numpy as np import random # we create the system system = System("3D") R = 5 N = 6 # we create a nanowa...
StarcoderdataPython
374132
<filename>sv.py import time, threading import configparser as cfg from telegram_bot import telegram_bot from mobile_de.methods import surface_search class SEARCH: def input_wait(self, offset_update): update_id = offset_update while True: updates = bot.get_updates(offset=update_id) ...
StarcoderdataPython
232998
from setuptools import setup DESCRIPTION = "Jupyter VVP: Flink SQL in Jupyter Notebooks via Ververica Platform" NAME = "jupyter-vvp" VERSION = '0.1.0' PACKAGES = ['jupytervvp'] AUTHOR = "Ververica" AUTHOR_EMAIL = "<EMAIL>" URL = 'https://github.com/ververica/jupyter-vvp' DOWNLOAD_URL = 'https://github.com/ver...
StarcoderdataPython
11375677
from uuid import UUID, uuid4 from galaxy import model def test_get_uuid(): my_uuid = uuid4() rval = model.get_uuid(my_uuid) assert rval == UUID(str(my_uuid)) rval = model.get_uuid() assert isinstance(rval, UUID)
StarcoderdataPython
6532795
from .nwbextractors import NwbRecordingExtractor, NwbSortingExtractor
StarcoderdataPython
11378645
from abc import ABC, abstractmethod from typing import Optional from dpsniper.classifiers.feature_transformer import FeatureTransformer from dpsniper.utils.my_logging import log from sklearn import preprocessing class StableClassifier(ABC): """ A classifier for two classes 0 and 1. The classifier is stable ...
StarcoderdataPython
4992317
<reponame>sharon1321/studio<filename>function/python/brightics/function/statistics/duncan_test.py<gh_stars>0 """ Copyright 2019 Samsung SDS 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 L...
StarcoderdataPython
9651449
# Generated by Django 3.2.13 on 2022-05-02 11:06 from django.db import migrations from django.db.models import F import uuid import datetime import pytz BATCH_SIZE = 10000 def set_order_discount_token_and_created_at(apps, _schema_editor): OrderDiscount = apps.get_model("discount", "OrderDiscount") Order = a...
StarcoderdataPython
1619251
<reponame>Rksseth/MagicHand<filename>moveMouse.py import time, os from objc import NULL from Quartz.CoreGraphics import CGEventCreate, CGEventCreateMouseEvent, \ CGEventGetLocation, CGEventPost, CGEventSetFlags, CGEventSetIntegerValueField, \ CGEventSourceCreate, CGPointMake, kCGEventFlagMaskAlternate, ...
StarcoderdataPython
4807559
# -*- coding: utf-8 -*- """ Created on Fri Jun 28 08:33:36 2019 @author: Thiago """ import numpy as np import pylab as pl import sympy as sp #%% s = 3000 for n in [100]: #[1, 2, 3, 5, 10, 200, 400] z=np.zeros(s); for k in range(n): x = np.random.uniform(-1,1,s) z += x #aqui entra funções ...
StarcoderdataPython
6603404
from unittest import TestCase import requests import json base_url = "http://localhost:5001/" req_format = '.json' funder_submit = base_url + 'describe_funder' + req_format fundopp_submit = base_url + 'share_fundopp' + req_format slugify = base_url + 'slugify' suggest = base_url + 'suggest' suggest_projects = base_url...
StarcoderdataPython
3514719
<gh_stars>10-100 # -*- coding: utf-8 -*- """ Package initialization. Created on Fri Jul 20 11:00:00 2018 Author: <NAME> | CVPRU-ISICAL (http://www.isical.ac.in/~cvpr) GitHub: https://github.com/prasunroy/cnn-on-degraded-images """ __version__ = '0.1.0'
StarcoderdataPython
387591
<filename>protobuf-json-read-only/test_writer.py #! /usr/bin/env python import os, sys # set import path to app root sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) import protobuf_json_writer from pprint import pprint import test_pb2 as pb_test # print protobuf_json_writer._msg2json(pb_test.TestM...
StarcoderdataPython
6513494
from io import BytesIO, SEEK_END from tokenize import tokenize, INDENT UTF_8_BOM = "\ufeff" LINE_ENDINGS = { "crlf": "\r\n", "lf": "\n", "cr": "\r", } def validate_file(path, properties, is_python=True): errors = 0 indent_style = properties.get("indent_style") indent_size = properties.get("i...
StarcoderdataPython
6401000
<reponame>jnthn/intellij-community<filename>python/testData/postfix/main/print.py print("I want to be inside main").main<caret>
StarcoderdataPython
3525135
<reponame>5in4/django-couchdb-storage name = "django_couchdb_storage" from .CouchDBStorage import CouchDBStorage
StarcoderdataPython
1689255
<filename>adb/systrace/catapult/devil/devil/utils/zip_utils.py # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import json import logging import os import sys import zipfile if __name__ ==...
StarcoderdataPython
4822201
<filename>MICRO_CPU_profiling/plot_SIFT1000M/plot_profiling_experiment_5_topK.py import matplotlib import matplotlib.pyplot as plt import numpy as np import os from analyze_perf import group_perf_by_events, filter_events_after_timestamp, \ classify_events_by_stages, get_percentage from profiling_stages import dra...
StarcoderdataPython
6448761
''' 实验名称:画各种图形和写字符 版本: v1.0 日期: 2019.12 作者: 01Studio ''' import sensor, image, time, lcd lcd.init(freq=15000000) sensor.reset() #复位摄像头 #sensor.set_vflip(1) #将摄像头设置成后置方式(所见即所得) sensor.set_pixformat(sensor.RGB565) # 设置像素格式 RGB565 (or GRAYSCALE) sensor.set_framesize(sensor.QVGA) #...
StarcoderdataPython
1917723
# !/usr/local/python/bin/python # -*- coding: utf-8 -*- # (C) <NAME>, 2019 # All rights reserved # @Author: '<NAME> <<EMAIL>>' # @Time: '2020-03-09 17:40' import datetime import decimal import json try: from bson import ObjectId except ImportError: ObjectId = None class JSONEncoder(json.JSONEncoder): def...
StarcoderdataPython
1801117
# coding=utf-8 #!/usr/bin/env python """ Copyright (c) 2020 Baidu.com, Inc. All Rights Reserved File: neck.py func: bottle neck Author: yuwei09(<EMAIL>) Date: 2021/07/20 """ import paddle.nn as nn class BottleNeck(nn.Layer): """bottleneck""" def __init__(self, input_dim, num_bottleneck, droprate=0.5, inp_bn=...
StarcoderdataPython
8154201
<reponame>statagain/build_db from inspect import getmembers, isfunction import sqlite3 import datasets DB_PATH = 'statagain.db' if __name__ == '__main__': loaders = [func for name, func in getmembers(datasets, isfunction) if name.startswith('load_')] con = sqlite3.connect(DB_PATH) datasets....
StarcoderdataPython
5130444
<gh_stars>0 import pandas as pd import matplotlib.pyplot as plt import sys def main(): df = pd.read_csv(sys.argv[1]) df.plot(y=['loss', 'val_loss'], use_index=True) plt.xlabel('epochs') plt.ylabel('loss function') plt.show() df.plot(y=['acc', 'val_acc'], use_index=True) plt.xlabel('epochs...
StarcoderdataPython
5123161
<gh_stars>0 # Generated by Django 3.0.8 on 2020-08-06 19:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recipes', '0013_auto_20200806_1731'), ] operations = [ migrations.AddField( model_name='ingredient', nam...
StarcoderdataPython
3568079
import logging l = logging.getLogger("archinfo.arch_aarch64") try: import capstone as _capstone except ImportError: _capstone = None try: import keystone as _keystone except ImportError: _keystone = None try: import unicorn as _unicorn except ImportError: _unicorn = None from .arch import A...
StarcoderdataPython
4870370
<reponame>GuijonGustavo/ads-explorer<gh_stars>0 import ads import itertools from metaphone import doublemetaphone import numpy as np import pandas as pd fl = ['ack', 'aff', 'alternate_bibcode', 'alternate_title', 'arxiv_class', 'citation_count', 'bibcode', 'bibgroup', 'c...
StarcoderdataPython
99391
''' config.py Written by <NAME> ''' import argparse import yaml import os import glob def get_parser(): parser = argparse.ArgumentParser(description='Point Cloud Segmentation') parser.add_argument('--config', type=str, default='config/pointgroup_default_scannet.yaml', help='path to config file') ### pret...
StarcoderdataPython
6552423
# forms.py from wtforms import Form, StringField, SelectField from wtforms.ext.sqlalchemy.fields import QuerySelectField from models import airports class AirportSearchForm(Form): startairport = StringField('') endairport = StringField('')
StarcoderdataPython
4818136
<gh_stars>0 import pandas as pd #tech = ['sharpen','elasticdeformation','horizontalline','diagonalline','diagonalinverseline','verticalleftline','verticalrightline','severalrowsline', # 'severalcolsline', 'severalcolsrowsline', 'superpixel', 'gaussianblur', 'additivegaussiannoise','dropout','translation','rotation9...
StarcoderdataPython
6670665
<reponame>Loris-C/twitterbotpython # -*- coding: utf-8 -*- """ Created on Thu Oct 31 12:28:19 2019 @author: mctwn """ #=== MORNING ROUTINE === from myFirstTwitterBot import TwitterBot from time import sleep #Fire ppl I follow who do not follow me anymore #TB.unfollow_back_who_not_follow_me() #First ...
StarcoderdataPython
8090504
<filename>votingsite/urls.py """votingsite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', view...
StarcoderdataPython
11338424
'''start_beep(note=60) Starts playing a beep. The beep will play indefinitely until stop() or another beep method is called. Parameters note The MIDI note number. Type:float (decimal number) Values:44 to 123 ("60" is the middle C note) Default:60 (middle C note) Errors TypeError note is not an integer. ValueError note ...
StarcoderdataPython
6655031
import re import pwd import grp def get_gid_for_name(group, default=0): """ returns gid for a given name string """ if not group is None: try: gid = grp.getgrnam(group).gr_gid except KeyError: gid = default return gid def get_uid_for_name(username, default...
StarcoderdataPython
3581155
<gh_stars>1-10 import random import time import sys import os from PIL import Image import numpy as np from scipy.misc import imsave, imread sys.path.append('utils') from config import * from data_augmentation import * print("\nPreprocessing Cat Breeds...") train_samples, test_samples = [], [] breeds = { 'abyssi...
StarcoderdataPython
6507130
"""Returns simulation from component.""" import inspect import warnings from typing import Any, Dict, Optional import meep as mp import numpy as np import pydantic import gdsfactory as gf from gdsfactory.component import Component from gdsfactory.components.extension import move_polar_rad_copy from gdsfactory.simulat...
StarcoderdataPython
1944766
import rhinoscriptsyntax as rs import scriptcontext as sc def HideSpecial(): ids = rs.GetObjects("Select objects to hide.", preselect=True) if not ids:return sc.sticky['HIDE_SPECIAL'] = ids rs.HideObjects(ids) HideSpecial()
StarcoderdataPython
9695757
<html> <head><title>{{ title }} </title></head> <body> <pre> {{ json_pretty }} </pre> </body>
StarcoderdataPython
210544
import unittest import datetime import sys from . import input_ from . import process from . import format_ class TestProcessCommitMessage(unittest.TestCase): def test_empty_message(self): expected_result = {} self.assertEqual(process._process_commit_message( '43065958923a14a05936887cc...
StarcoderdataPython
11286411
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ipam', '0055_servicetemplate'), ] operations = [ # Model IDs migrations.AlterField( model_name='aggregate', name='id', field=models.BigAutoField(...
StarcoderdataPython
360600
# author: <NAME>, <NAME>, <NAME>, <NAME> # date: 2020-06-06 import pandas as pd import numpy as np import os import pickle def subset_data(label_name, X, y, dataset_type = "train"): """ Subsets a dataser for the provided label of question 1 for subtheme classification and saves these datasets. P...
StarcoderdataPython
1959318
from handlers.base_handler import BaseHandler from lib.objects import Message class MeHandler(BaseHandler): def _set_pattern(self): self.pattern = 'я' def needs_reply(self): return True async def handle(self, message: Message): await super().handle(message) answer_text =...
StarcoderdataPython
8137411
import csv import json from akamaiopen.cloudlets.CloudletRule import CloudletRule from akamaiopen.cloudlets.VisitorPrioritizationRule import VisitorPrioritizationRule from akamaiopen.cloudlets.matches.CookieMatch import CookieMatch from akamaiopen.cloudlets.matches.Match import MatchOperator from akamaiopen.cloudlets....
StarcoderdataPython
8140180
import os from flask import Flask app = Flask("hello") app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("DB_URI") or 'sqlite://' app.config["DEBUG"] = True app.config["SECRET_KEY"] = 'development key'
StarcoderdataPython
4971158
<gh_stars>0 """ A module to show off a long-running function as a coroutine. In this module, we use a yield expression to give the coroutine a time budget. After the time budget is up, it has to yield to give us an update. We will see why this is useful later. Author: <NAME> Date: November 2, 2020 """ import time ...
StarcoderdataPython
38552
<reponame>Dephilia/poaurk<filename>tests/test_oauth.py #! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2021 dephilia <<EMAIL>> # # Distributed under terms of the MIT license. """ """ import unittest from poaurk import (PlurkAPI, PlurkOAuth) class TestOauthMethods(unittest.TestCase):...
StarcoderdataPython
11302447
#!/usr/bin/evn python3 from pylib import * from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() data = (rank+1)**2 data = comm.gather(data, root=0) if rank == 0: for i in range(size): assert data[i] == (i+1)**2 else: assert data is None
StarcoderdataPython
5194070
from mypy_extensions import TypedDict Movie = TypedDict('Movie', {'name': str, 'year': int}) blade_runner: Movie = {'name': 'Blade Runner', 'year': 1982} toy_story = Movie(name='Toy Story', year=1995)
StarcoderdataPython
4838238
import json from pathlib import Path from typing import Union import click from avrogen import write_schema_files autogen_header = """# flake8: noqa # This file is autogenerated by /metadata-ingestion/scripts/avro_codegen.py # Do not modify manually! # fmt: off """ def suppress_checks_in_file(filepath: Union[str,...
StarcoderdataPython
11358000
<filename>2016/day_03/triangles.py def check_triangle(a, b, c): a, b, c = sorted((a, b, c)) if a + b > c: return True return False def count_correct_triangles(triangles): return sum([check_triangle(*tri) for tri in triangles]) def parse_line(line): return [int(val) for val in line.strip...
StarcoderdataPython
9681485
import numpy as np import cv2 import math ############################## # # # ### RBox gt ### # # # ############################## def rbox2poly(rboxes): ctr_x = rboxes[:, 0:1] ctr_y = rboxes[:, 1:2] width = rboxes[:, 2:3] height = rbo...
StarcoderdataPython
1937308
from .base_test import BaseTest class TestTicketNew(BaseTest): """Test TicketNew""" def setUp(self): super(TestTicketNew, self).setUp() self.response = self.client_get('tickets:new') def test_get(self): """GET /tickets/new/ must return status code 200""" self.assertEqual(...
StarcoderdataPython
5007418
''' Much like websites, this library collects anonymous usage statistics. It ONLY collects import and function call events. It does NOT collect any of your data. Example: {'profile': 'prod', 'package': 'd6tmodule', 'module': 'd6tmodule.utils', 'classModule': 'd6tmodule.utils.MyClass', 'class': 'MyClass', 'function': 'M...
StarcoderdataPython
11306236
<filename>FASTQ_Preprocess.py """ @author: <NAME> University of North Carolina at Chapel Hill Chapel Hill, NC 27599 @copyright: 2019 """ import datetime import os import collections import subprocess import argparse import sys import time from distutils.util import strtobool from scipy.stats import ...
StarcoderdataPython