id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3359080
<reponame>caglar/Arcade-Universe<filename>arcade_universe/perlin.py<gh_stars>10-100 from __future__ import division import Image, ImageDraw import numpy as np #This is a perlin noise generating script class PerlinNoiseGenerator(object): """ The constructor for the PerlinNoiseGenerator, w is th...
StarcoderdataPython
152502
<gh_stars>10-100 import ftfy import sys from tqdm import tqdm filename = sys.argv[1] filename_out = sys.argv[2] with open(filename, 'r') as f: with open(filename_out, 'w') as w: for l in tqdm(f): # ftfy might introduce additional line breaks & tabs (!) from html sequences splits = l...
StarcoderdataPython
1727128
<reponame>Lyncs-API/lyncs.cppyy<gh_stars>0 """ Cppyy interface for Lyncs In this package we provide some additional tools for the usage of [cppyy](https://cppyy.readthedocs.io/en/latest/) in the Lyncs API. """ __version__ = "0.2.0" from cppyy import nullptr, cppdef, gbl, include, c_include, set_debug from .lib impor...
StarcoderdataPython
198347
from unittest import TestCase from ECDSA.ECDSA import GenerateSignature, GenerateKeyPair, VerifySignature class EcdsaTest(TestCase): def test_sig_with_correct_parameters(self): bits, sig, message, pub = self.createSut() verifier = VerifySignature(bits, pub, sig, message) result = verifier...
StarcoderdataPython
1719246
<filename>tests/twitter_tests.py import unittest from freezegun import freeze_time from datetime import datetime from twitterrail.railtweeter import RailTweeter, emoji_cross, emoji_tick, emoji_train, emoji_late, emoji_skull class MockTweeterApi: def __init__(self): self.tweets = [] self.messages...
StarcoderdataPython
3380598
<gh_stars>0 import time import numpy as np import Problem import Grid import Solver import Result import IOData class PoissonEquation: def __init__(self, problem): self.problem = Problem.Problem(problem) def generateGrid(self, grid, mode="All"): self.grid = Grid.Grid(self.prob...
StarcoderdataPython
40237
## 1. Introduction to the data ## import pandas as pd cars = pd.read_csv("auto.csv") unique_regions = cars['origin'].unique() print(unique_regions) ## 2. Dummy variables ## dummy_cylinders = pd.get_dummies(cars["cylinders"], prefix="cyl") cars = pd.concat([cars, dummy_cylinders], axis=1) print(cars.head()) dummy_yea...
StarcoderdataPython
83514
import pandas as pd import numpy as np import os import matplotlib.pyplot as plt from matplotlib.image import imread images = os.listdir('') flow =os.listdir('') data_1 = [] for i in range (0,22873): curr = [] if(i<10): curr_file_1 = '0000'+str(i)+"_img1.ppm" curr_file_2 = '0000' + str(i) + "...
StarcoderdataPython
66370
<filename>a10sdk/core/admin/admin_session.py from a10sdk.common.A10BaseClass import A10BaseClass class AdminSession(A10BaseClass): """ :param clear: {"default": 0, "optional": true, "type": "number", "description": "clear admin session", "format": "flag"} :param all: {"default": 0, "optional": true, "...
StarcoderdataPython
1781575
import asyncio import unittest from unittest.mock import ANY from aiobeanstalk.proto import Client from aiobeanstalk.packets import Using, Inserted def btalk_test(fun): fun = asyncio.coroutine(fun) def wrapper(self): @asyncio.coroutine def full_test(): cli = yield from Client.c...
StarcoderdataPython
154734
import py from pypy.rpython.lltypesystem import lltype from pypy.jit.timeshifter import rvalue from pypy.jit.timeshifter import rcontainer from pypy.jit.timeshifter.test.support import * def test_create_int_redbox_var(): jitstate = FakeJITState() gv = FakeGenVar() box = rvalue.IntRedBox("dummy kind", gv) ...
StarcoderdataPython
180203
<reponame>pekt00p/camunda_flask_portal __author__ = '<NAME>' import app.forms.wind_farm_manager as wind_farm_manager import app.camunda.user_task as ut class FormFactory: def get_start_form(self, process_key): if process_key == 'Utilities_Wind_Farm_Manager': return wind_farm_manager.StartProc...
StarcoderdataPython
1654313
<filename>tests/tcex_ti/test_campaign_interface.py<gh_stars>0 # -*- coding: utf-8 -*- """Test the TcEx Threat Intel Module.""" from ..tcex_init import tcex # pylint: disable=W0201 class TestCampaignGroups: """Test TcEx Host Groups.""" def setup_class(self): """Configure setup before all tests.""" ...
StarcoderdataPython
92272
<gh_stars>0 from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class User(db.Model): __tablename__ = 'user' user_id = db.Column(db.Integer, autoincrement=True) username = db.Column(db.Unicode(64), primary_key=True) password = db.Column(db.Unicode(128)) def __init__(self, username, passwo...
StarcoderdataPython
3365257
<filename>test/test_doctest_wrapper.py """ This is a wrapper for the doctests in pyproj """ import doctest import warnings import pytest from mock import patch import pyproj from test.conftest import proj_network_env @patch.dict("os.environ", {"PROJ_NETWORK": "ON"}, clear=True) def test_doctests(): """run the e...
StarcoderdataPython
3285215
# # 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 in writing, software # ...
StarcoderdataPython
1656583
import os import pygame as pg import asyncio as aio def load_image(name, *, alpha=None, colorkey=None): """Load an image file into memory.""" try: image = pg.image.load(os.path.join('assets', 'textures', name)) except pg.error: print('Image loading failed: ') raise if alpha is N...
StarcoderdataPython
3231569
<reponame>hadikoub/BMW-TensorFlow-Training-GUI import uvicorn from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from starlette.middleware.cors import CORSMiddleware from api.controllers import jobs_controller, infrastructure_controller, dataset_controller, models_controller, \ tensorboard_con...
StarcoderdataPython
51652
#Ex 1041 Coordenadas de um ponto 10/04/2020 x, y = map(float, input().split()) if x > 0 and y > 0: print('Q1') elif x < 0 and y > 0: print('Q2') if x > 0 and y < 0: print('Q4') elif x < 0 and y < 0: print('Q3') elif x == 0 and y == 0: print('Origem')
StarcoderdataPython
3217868
from pymoo.model.termination import Termination from pymoo.util.misc import to_numpy from pymoo.util.termination.sliding_window_termination import SlidingWindowTermination class ConstraintViolationToleranceTermination(SlidingWindowTermination): def __init__(self, n_last=20, tol=...
StarcoderdataPython
1721883
<gh_stars>1-10 import logging from aiohttp import web from . import __version__ from . import settings from .app import app log_format = "%(asctime)s - %(name)s %(levelname)s: %(message)s" logging.getLogger("disnake").setLevel(logging.WARNING) logging.basicConfig( format=log_format, level=settings.LOG_LEVEL,...
StarcoderdataPython
4824829
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
StarcoderdataPython
3367685
class Subset(object): # implements ISnpSetList ''' Returns a subset of the originally specified sets to test. See the Bed class's 'read' method of examples of its use. See __init__.py for specification of interface it implements. ''' def __init__(self, altset_list, subset_list): s...
StarcoderdataPython
58626
""" A container to store latest known prices for a list of symbols """ import logging from datetime import datetime from market.tick_data import TickData class MarketData: def __init__(self): self.__recent_ticks__ = dict() def add_last_price(self, time: datetime, ...
StarcoderdataPython
3238147
import flask_login as login import requests from flask import url_for, redirect, Blueprint, request, make_response from flask_admin import Admin, AdminIndexView, expose, helpers as admin_helpers from flask_admin.contrib.sqla import ModelView from wtforms import form, fields, validators from app.models import db from a...
StarcoderdataPython
3312080
''' Created on Nov 22, 2021 @author: Japi42 ''' import threading from struct import pack from Outputs.Output import Output condition = threading.Condition() inited = False x_axis = 0 y_axis = 0 my_buttons = 0 dirty = False devhandle = None # Need a thread for working # Need a condition for thread safety # Need an...
StarcoderdataPython
3334082
import json import os HOME = os.environ['HOME'] HOME = './' # read in connection profiles for both orgs BCPLAN = "starter" SCFileObject = {} SCFileObject['fabric'] = {} SCFileObject['fabric']['network'] = {} SCFileObject['fabric']['network']['orderer'] ={} # starter plan use apikeys.json # ibp plan use network.json wi...
StarcoderdataPython
1783475
<gh_stars>0 f = open('n.txt','w') i=1 while i<=32: f.write(" <comp lib=\"4\" loc=\"(260,") f.write(str(i*60)) f.write(")\" name=\"Register\">\n") f.write(" <a name=\"width\" val=\"32\"/>\n") f.write(" <a name=\"label\" val=\"GR") f.write(str(i)) f.write("\"/>\n") f.write(" ...
StarcoderdataPython
1616824
import torch from typing import List from torch.utils.data import Dataset, DataLoader from utils.Vocab import Vocab class NMTDataset(Dataset): def __init__(self, src_data, tgt_data): self.data = list(zip(src_data, tgt_data)) def __getitem__(self, item): return self.data[item]...
StarcoderdataPython
1636087
import torch import torch.nn as nn import torch.nn.functional as F from typing import List, Dict, Union from yacs.config import CfgNode from .jenson_shannon_divergence import jensen_shannon_divergence from .build import LOSS_REGISTRY class LabelSmoothingCrossEntropy(torch.nn.Module): """ Code copied from fa...
StarcoderdataPython
4835609
<gh_stars>1-10 # ***************************************************************************** # ***************************************************************************** # # Name: testarr2.py # Author: <NAME> (<EMAIL>) # Date: 7th March 2021 # Purpose: Test arrays(multi dimension) # # **********************...
StarcoderdataPython
1656209
import mistune from flask import Flask from pygments import highlight from pygments.formatters import html from pygments.lexers import get_lexer_by_name from api import m_f import http.client http.client._MAXLINE = 655360 m_f.init(is_log=True) app = Flask(__name__) # pagination = Pagination(app) app.config["SECRET...
StarcoderdataPython
3267227
import _origen from origen.controller import Base class Controller(_origen.standard_sub_blocks.arm_debug.ArmDebug, Base): def __init__(self): Base.__init__(self) _origen.standard_sub_blocks.arm_debug.ArmDebug.__init__(self)
StarcoderdataPython
1724778
import re from collections.abc import Mapping from functools import reduce from copy import deepcopy from arpoc.plugins._lib import Obligation, Optional, deep_dict_update from arpoc.ac.common import Effects from typing import Dict import logging """ Obligation Log Module. The classes here will either - log every...
StarcoderdataPython
4812251
import logging import subprocess import shutil import sys import os import timeit from mongoengine import connect from mecoshark.utils import find_correct_processor from pycoshark.utils import create_mongodb_uri_string logger = logging.getLogger('mecoshark_main') class MecoSHARK(object): """ Main app for t...
StarcoderdataPython
3262204
"""This module contains various utility functions for MythX domain models.""" from datetime import datetime from os import path from typing import Dict import dateutil.parser def deserialize_api_timestamp(timestamp_str: str): """Deserialize a JavaScript API timestand into Python datetime format. :param tim...
StarcoderdataPython
4642
""" Unit tests for module `homework_1.tasks.task_3`. """ from tempfile import NamedTemporaryFile from typing import Tuple import pytest from homework_1.tasks.task_3 import find_maximum_and_minimum @pytest.mark.parametrize( ["file_content", "expected_result"], [ pytest.param( "0\n", ...
StarcoderdataPython
121147
import unittest from github_network import GithubNetwork class Test_GithubNetwork(unittest.TestCase): def setUp(self): pass if __name__ == '__main__': unittest.main()
StarcoderdataPython
1796962
<filename>Python/visualization.py ###---Visualization---### def date_visualization(queries,query_results,graph_filename,csv_filename,month_flag=False,year_flag=True,weight_flag=False,cite_flag=False,database='CrossRef'): import numpy as np def counts(dates): import pandas as pd if month_fla...
StarcoderdataPython
85374
<reponame>xxxcreato/HackChat #!/usr/bin/env python # -- coding: utf-8 -- import json import websocket import threading import random import os import time os.system("figlet HACK CHAT") oda = input("Enter room ID:") print("Url:https://hack.chat/?{}".format(oda)) ws=websocket.create_connection("wss://hack.ch...
StarcoderdataPython
3350489
# Copyright 2016 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. """Quest and Execution for running a test in Swarming. This is the only Quest/Execution where the Execution has a reference back to modify the Quest. """ i...
StarcoderdataPython
1740040
class MyList(object): def __init__(self): self.size = 0 self.container = [] self._iterIndex = 0 def add(self, obj): self.container.append(obj) self.size += 1 def pop(self): obj = self.container.pop() self.size -= 1 return obj def __len__...
StarcoderdataPython
4818941
<filename>Fenier/apps/users/test.py a = {'name':'Bob'} name = 'Bob' print(a['name']!=name)
StarcoderdataPython
1601226
<filename>Tree Data Structure/bst_iterator.py # Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. # The first call to next() will return the smallest number in BST. Calling next() again will return the next smallest number in the BST, and so on. # No...
StarcoderdataPython
26704
<gh_stars>0 # -*- coding: utf-8 -*- from trade_results_loader import * from model import * loader = TradeResultsLoader() data = TradeResults(loader.retrieve_trade_data()) with Trainer() as trainer: trainer.train(10001, data) trainer.save("./model.ckpt")
StarcoderdataPython
1645773
<filename>Arbie/Variables/token.py<gh_stars>10-100 """Basic token representation.""" from typing import List, NewType class Token(object): """Token is a light weight representation of a ERC20 token.""" def __init__(self, name: str, address: str, price: float = None): self.name = name self.pri...
StarcoderdataPython
16267
import warnings from typing import Callable, List, Optional, Union import mpmath import numpy as np import paramak import sympy as sp from paramak import RotateMixedShape, diff_between_angles from paramak.parametric_components.tokamak_plasma_plasmaboundaries import \ PlasmaBoundaries from scipy.interpolate import...
StarcoderdataPython
116335
<gh_stars>0 #!/usr/bin/env python3 """ Optical flow over phase movies Process all the movies under a specific directory: .. code-block:: bash $ ./calc_optical_flow.py ~/data/new_ana_movie/* This will load all movies under ``~/data/new_ana_movie/`` and then write the results to ``~/data/new_ana_movie_optical_fl...
StarcoderdataPython
3384419
from django.conf import settings from rest_framework import permissions, viewsets class BumfViewSet(viewsets.ModelViewSet): """ This base class allows the view to be displayed in the browsable API in DEBUG mode. """ permission_classes = [ permissions.AllowAny if settings.DEBUG else permissions...
StarcoderdataPython
108612
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/19 3:37 下午 # @Author : kewen # @File : ColorUtils_test.py import unittest from utils.ColorUtils import toHex, get_n_rgb_colors class Test(unittest.TestCase): def test_toHex(self): rgb = [244, 255, 196] self.assertEqual(toHex(...
StarcoderdataPython
1687813
<reponame>mohnjahoney/website_source<filename>plugins/random_article/random_article.py<gh_stars>10-100 # -*- coding: utf-8 -*- """ Random Article Plugin For Pelican ======================== This plugin generates a html file which redirect to a random article using javascript's window.location. The generated html file ...
StarcoderdataPython
3365947
<filename>System/Streams/teststreams.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------------------------------------------------- @Name: teststreams.py @Desc: @Author: <EMAIL> @Create: 2020.05.11 19:12 ----------------------------------------------------...
StarcoderdataPython
4838880
<reponame>edmundsj/sugarplot<gh_stars>0 import pint ureg = pint.get_application_registry() # Change global settings of all plots generated in the future import matplotlib.pyplot as plt cmap = plt.get_cmap('tab10') from sugarplot.source.fitters import * from sugarplot.source.prettify import * from sugarplot.source.norm...
StarcoderdataPython
3271265
from setuptools import setup, find_packages setup( name='dockerfile-parser', keywords='docker dockerfile parser parsing', version='0.0.2', url='https://github.com/eg0r/dockerfile-parser', license='MIT', author='<NAME>', author_email='<EMAIL>', description='Library for parsing Dockerfile...
StarcoderdataPython
3342105
<reponame>xUndero/noc<gh_stars>1-10 # -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # Healthcheck endpoint # ---------------------------------------------------------------------- # Copyright (C) 2007-2017 The NOC Project # See LICENSE for details # ---------------------...
StarcoderdataPython
3214713
<gh_stars>1-10 # Generated by Django 3.1.7 on 2021-03-30 18:18 import uuid import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ("auth", "0012_alter_user_first_name_max_leng...
StarcoderdataPython
3337585
<filename>mass_circular_weighing/gui/widgets/__init__.py<gh_stars>1-10 from .browse import label from .aw_pos_allocator import AllocatorDialog
StarcoderdataPython
3231740
TARGET_MODULE = "common.utils.util" def test_is_sshable_returns_false(get_handler): subject = get_handler(TARGET_MODULE) assert subject.is_sshable("127.0.0.1", "username", "password") is False assert subject.is_sshable("www.google.com", "username", "password") is False
StarcoderdataPython
3244663
from securityheaders.models.cors import CORSDirective from securityheaders.models.annotations import * @anydirective class AccessControlExposeHeadersDirective(CORSDirective): @classmethod def isDirective(cls, directive): """ Checks whether a given string is a directive Args: direct...
StarcoderdataPython
1602648
import torch from torch.optim import Optimizer from torch.distributions import Normal import numpy as np class SGLD(Optimizer): def __init__(self, params, lr, norm_sigma=0.0, alpha=0.99, eps=1e-8, centered=False, addnoise=True, p=True): weight_decay = 1/(norm_sigma ** 2 + eps) if weight_de...
StarcoderdataPython
1613181
<filename>vkrine/bots.py import time from concurrent.futures import ThreadPoolExecutor import requests from requests.exceptions import ReadTimeout from vk_api import Captcha, VkApi, VkUpload from vk_api.bot_longpoll import VkBotEventType, VkBotLongPoll from vk_api.longpoll import VkLongPoll import vkrine import vkrin...
StarcoderdataPython
3265903
<filename>apps/users/urls.py from django.contrib.auth.views import logout from django.conf.urls.defaults import patterns, url from shared.utils import reverse_lazy from users import views urlpatterns = patterns('', url(r'^login/?$', views.login, name='users.login'), url(r'^logout/?$', logout, {'next_page': r...
StarcoderdataPython
3316039
#!/usr/bin/env python from os import getenv from os.path import join from subprocess import call prefix = getenv('MESON_INSTALL_PREFIX', '/usr/local') datadir = join(prefix, 'share') destdir = getenv('DESTDIR') if not destdir: print('Updating icon cache...') call(['gtk-update-icon-cache', '-qtf', join(datadi...
StarcoderdataPython
3289930
<reponame>ninideol/French-Wordle """ --> WordleHelper : Core of the functions """ import Utils # Numbers of the words in "mots.txt" WORDS_NUMBER = 411430 def countLetterByWordsWithCriterias(size, temoin = [],goodLetter = []): '''Count all the letter if all words following the criterias in parameters :pa...
StarcoderdataPython
45801
<filename>src/ModuleManager.py #!/usr/bin/env python3 """ModuleManager.py: This file contains the code for the module managing aspect of the RhysRoom software.""" __author__ = "<NAME>" __copyright__ = "Copyright 2018, <NAME>" import logging import os from importlib.machinery import SourceFileLoader import threading...
StarcoderdataPython
177883
<gh_stars>1-10 import unittest from PyFLOTRAN.readers import StreamlineReader from PyFLOTRAN.config import config from PyFLOTRAN.utils import test_data_path from pathlib import Path class StreamlineReaderCase(unittest.TestCase): def setUp(self) -> None: self.stream_line_reader = StreamlineReader(filename=...
StarcoderdataPython
4829586
<reponame>culbertm/NSttyPython # # Copyright (c) 2008-2016 Citrix Systems, 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 # # ...
StarcoderdataPython
3336581
#!/usr/bin/env python3 ''' USFM to HTML is a script designed to make it easier to print Scripture from USFM files. The suite of tags supported is currently limited because the tool is developed by Wycliffe Associates, and the number of tags our tools use is limited. Developed by <NAME> and released for general use. ''...
StarcoderdataPython
3285072
""" Scripts for validation """ from __future__ import division import logging import copy import matplotlib.pyplot as pl import numpy as np from sklearn.metrics import explained_variance_score, r2_score from revrand.metrics import lins_ccc, mll, msll, smse from uncoverml.models import apply_multiple_masked from unc...
StarcoderdataPython
1630515
<gh_stars>1-10 """ Boolability is about whether a value can be used as a boolean. Objects like functions are always true, so it is likely an error to use them in a boolean context. This file helps figure out whether a particular type is usable as a boolean. """ import asynq import enum from pyanalyze.safe import sa...
StarcoderdataPython
1613559
<gh_stars>0 """Library for exceptions using the Google Nest SDM API and subscriber.""" class GoogleNestException(Exception): """Base class for all client exceptions.""" class SubscriberException(GoogleNestException): """Raised during problems subscribing to events and updates.""" class ApiException(Google...
StarcoderdataPython
4835826
import logging from django.db import models from traffic_monitor.models.detector_factory import DetectorFactory from traffic_monitor.models.model_detector import Detector from traffic_monitor.models.feed_factory import FeedFactory from traffic_monitor.models.model_feed import Feed logger = logging.getLogger('monitor...
StarcoderdataPython
1605971
<reponame>Galieve/algebra_computacional from sage.all import * import Structures.FieldPolynomial import Structures.Rationals from Algorithms.SortPolynomials import graded_lexicografic_mon Q = Structures.Rationals.Rationals() R = Structures.FieldPolynomial.FieldPolynomial(Q, 'y') S = Structures.FieldPolynomial.FieldPol...
StarcoderdataPython
3357884
#!/usr/bin/python #-*- coding: utf-8 -*- #import csv # #with open('testd.csv') as f: # reader = csv.reader(f) # print list(reader) import csv csvfile = file('csvtest.csv', 'wb') writer = csv.writer(csvfile) writer.writerow(['id', 'url', 'keywords']) data = [ ('1', 'http://www.xiaoheiseo.com/', '小黑'), ('2', 'http:...
StarcoderdataPython
93622
<reponame>Wangvory/NLP-Final-Project<gh_stars>0 import collections import numpy as np from sklearn.externals import joblib from news_scraper_update.utils.relevance_score import get_tags, preprocess def tag_documents(doc, bad_tags=[]): word2tag, _ = get_tags() tag = '' c = collections.Counter() for wo...
StarcoderdataPython
3399989
class Curriculum(object): def __init__(self, intervention_actors, actives): """ This corresponds to a curriculum object where it takes in the intervention actor and when are they supposed to be activated. :param intervention_actors: (list) list of intervention actors :param...
StarcoderdataPython
3212814
<gh_stars>1-10 from django.conf.urls import url from .views import TeamView, PartnersView urlpatterns = [ url(r'^team/$', TeamView.as_view()), url(r'^partners/$', PartnersView.as_view()), ]
StarcoderdataPython
104553
<reponame>ROB7-StayHumble/multi_tracker from optparse import OptionParser import sys, os import imp import rosbag, rospy import pickle import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph.ptime as ptime import time import numpy as np import read_hdf5_file_to_pandas import data_slicing #impo...
StarcoderdataPython
3391036
<gh_stars>1-10 #创建元组 tup1 = ("苹果" , "香蕉", "葡萄", "橙子", "梨") #显示元组中所有数据信息 print("\n我喜欢吃的水果是:",tup1) #使用下标索引显示元组中的数据信息 print ("\n\n元组中的第二个值: ", tup1[1]) #使用中括号的形式截取字符 print ("元组中的第二和第五个值: ", tup1[1:5]) #利用for循环语句来遍历元组中的值 print("\n\n利用for循环语句来遍历元组中的值:") for i in tup1: print(i)
StarcoderdataPython
3312995
<reponame>AleksZavg/Admin-telegram-bot<gh_stars>0 from . import admin_panel from . import admin_add_user from . import admin_check_user from . import admin_remove_user from . import admin_all_info
StarcoderdataPython
3327912
import time import json import requests from bs4 import BeautifulSoup import re import pytz from datetime import datetime _http_headers = {'Content-Type': 'application/json'} class SPOJUnsolvedProblems: def get_unsolved_problems(self, username): rs = requests.session() start = 0 ...
StarcoderdataPython
1668159
class Config: def __init__(self): self.debug = False self.noindex = False self.target = 'gitbook' self.hints = True self.show_func_sig = False self.hide_files_page = False self.hide_class_list_expansion = False config = Config()
StarcoderdataPython
8830
import copy import json from ghcl.models.pull_request import PullRequest class PRData: def __init__(self, data: dict = None): if data is None: with open('./tests/models/empty_pr_data.json') as file: self._data = json.load(file) else: self._data = data ...
StarcoderdataPython
1601259
if __name__ == '__main__': n = int(raw_input()) arr = map(int, raw_input().split()) arr = sorted(arr, reverse=True) temp = arr[0] count = 0; for i in range(len(arr)): if arr[i] == temp: count +=1; else: break for i in range(count): arr.pop(0); print arr[0]
StarcoderdataPython
3216737
<reponame>lachmann12/westrace from units import unit from items import item import time going = True coins = 10 player_score = 0 player_round = 0 n_shop_items = 2 n_shop_units = 4 n_roster = 5 roster = [] for i in range(n_roster): roster.append(0) shop_units = [] shop_items = [] shop_units = [] for i in range...
StarcoderdataPython
3220119
from socket import socket, AF_INET, SOCK_STREAM from threading import Thread import time from person import Person # GLOBAL CONSTANTS (Sabitler) HOST = "localhost" PORT = 5500 ADDR = (HOST, PORT) MAX_CONNECTIONS = 10 BUFSIZE = 512 # aktarılan data'nın byte sayısı TIME = time.ctime(t...
StarcoderdataPython
3324967
# -*- coding: utf-8 -*- # # K2HDKC DBaaS based on Trove # # Copyright 2020 Yahoo Japan Corporation # # K2HDKC DBaaS is a Database as a Service compatible with Trove which # is DBaaS for OpenStack. # Using K2HR3 as backend and incorporating it into Trove to provide # DBaaS functionality. K2HDKC, K2HR3, CHMPX and K2HASH ...
StarcoderdataPython
24607
<gh_stars>0 from datadog.api.resources import GetableAPIResource, CreateableAPIResource, \ UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource class Screenboard(GetableAPIResource, CreateableAPIResource, UpdatableAPIResource, DeletableAPIResource, ...
StarcoderdataPython
162585
from os import environ as env from typing import Dict, Optional, Tuple import requests from pyno.models import CreatePageRequestModel, PropertyModel from requests.models import Response TOKEN = env['TOKEN'] URL = 'https://api.notion.com/v1' def add_query_param(url: str, **params) -> str: for k, v in params.ite...
StarcoderdataPython
159875
<filename>helios/datatypes/core.py """ core data types """ from helios.datatypes import LDObject class BigInteger(LDObject): """ A big integer is an integer serialized as a string. We may want to b64 encode here soon. """ WRAPPED_OBJ_CLASS = int def toDict(self, complete=False): i...
StarcoderdataPython
3229081
<gh_stars>10-100 from __future__ import absolute_import, division, print_function import logging import os import json import random import glob import torch import tqdm import array import collections import torch.utils.data from transformers.file_utils import WEIGHTS_NAME try: import lmdb except: pass OPTIM...
StarcoderdataPython
78129
#https://leetcode.com/problems/time-needed-to-inform-all-employees/ #Source: https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/532560/JavaC%2B%2BPython-DFS class Solution: def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: children = [[] f...
StarcoderdataPython
3229904
<reponame>pnsn/squac_api<filename>app/core/migrations/0014_auto_20220405_1619.py # Generated by Django 3.1.12 on 2022-04-05 16:19 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0013_contact_name'), ] operations = [ migrations.RemoveFie...
StarcoderdataPython
3210681
<reponame>elephantmipt/bert-distillation<gh_stars>10-100 from catalyst import dl from catalyst.contrib.data.nlp import LanguageModelingDataset from catalyst.core import MetricAggregationCallback import pandas as pd import pytest # noqa: F401 import torch from torch.utils.data import DataLoader from transformers import...
StarcoderdataPython
1714258
# -*- coding: utf-8 -*- """ @author: hkaneko """ import math import sys import numpy as np import pandas as pd import sample_functions from sklearn import tree, metrics from sklearn.ensemble import RandomForestClassifier # RF モデルの構築に使用 from sklearn.model_selection import cross_val_predict method_name...
StarcoderdataPython
1619847
import re import fitz from leitordenotas.builder.clear_reader_builder import ClearReaderBuilder from leitordenotas.builder.easynvest_reader_builder import EasynvestReaderBuilder from leitordenotas.builder.inter_reader_builder import InterReaderBuilder from leitordenotas.models import NotaDeCorretagem class NotaDeCo...
StarcoderdataPython
1682480
import py, os, sys from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase currpath = py.path.local(__file__).dirpath() test_dct = str(currpath.join("crossingDict.so")) def setup_module(mod): if sys.platform == 'win32': py.test.skip("win32 not supported so far") err = os.system("cd...
StarcoderdataPython
139798
import datetime as dt import logging import time import os def date_hash(): return dt.datetime.now().strftime('%y%m%d%H%M') + str(hash(time.time()))[:4] def print_log(fname, content): logging.basicConfig(filename=os.path.join(fname + '.log'), level=logging.ERROR) logger = logging.getLogger('model') ...
StarcoderdataPython
1744903
<filename>api/models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class Bucketlist(models.Model): """ Bucketlist model class """ name = models.CharField(max_length=50, blank=False) description = models.CharField(max_length=100, blank=...
StarcoderdataPython
3346122
<gh_stars>10-100 #MenuTitle: Copy Kerning Pairs... # -*- coding: utf-8 -*- from __future__ import print_function, division, unicode_literals __doc__=""" (GUI) Copies kerning patterns to another. It supports pair-to-pair and preset group copying. """ import vanilla import GlyphsApp import re try: f = Glyphs.font # F...
StarcoderdataPython