id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
149215
import os from flask import Blueprint, request from flask_cors import CORS from service.astra_service import astra_service credentials_controller = Blueprint('credentials_controller', __name__) CORS(credentials_controller) # This controller handles the functionality for connecting to the database # # Here we defin...
StarcoderdataPython
6508174
from kivymd.theming import ThemableBehavior from kivymd.uix.screen import MDScreen class CraneSleepScreen(ThemableBehavior, MDScreen): pass
StarcoderdataPython
3571412
#!/usr/bin/python # -*- coding: UTF-8 -*- """ Criado em 17 de Agosto de 2016. Descricao: esta biblioteca possui as seguintes funcoes: geraDados: esta funcao gera um histograma dos dados fornecida uma imagem em formato numpy (imagem esta resultante da combinacao de uma amostra de imagens da serie de dad...
StarcoderdataPython
1879829
#This problem was asked by Amazon.[EASY} #Given n numbers, find the greatest common denominator between them. #For example, given the numbers [42, 56, 14], return 14. #Solution using numpy import numpy as np A = [14,56,42] print(np.gcd.reduce(A)) #Solution: Scaling for any number of input values n = int(input('HOW...
StarcoderdataPython
5092868
<gh_stars>1-10 # Copyright 2020 Hamal, Inc.
StarcoderdataPython
3215789
# CamJam EduKit 3 - Robotics # Worksheet 7 - Controlling the motors with PWM import time # Import the Time library from gpiozero import CamJamKitRobot # Import the CamJam GPIO Zero Library robot = CamJamKitRobot() # Set the relative speeds of the two motors, between 0.0 and 1.0 motorspeed = 0.5 motorfo...
StarcoderdataPython
5101645
class MetricInterface(object): ID = 'NONE' def __init__(self, **kwargs): pass def evaluate(self, individual, framework): raise NotImplementedError("Function evaluateIndividual has to be inplemented!") @staticmethod def getMetricByName(name='NONE'): stack = [MetricInterface] while stack: ...
StarcoderdataPython
12834551
import copy import crcmod from opendbc.can.can_define import CANDefine from selfdrive.car.tesla.values import CANBUS class TeslaCAN: def __init__(self, dbc_name, packer): self.can_define = CANDefine(dbc_name) self.packer = packer self.crc = crcmod.mkCrcFun(0x11d, initCrc=0x00, rev=False, xorOut=0xff) ...
StarcoderdataPython
11265867
class EventParser: def __init__(): pass def Parse(self, packet): if packet[0] == 'E': print("Hurrah") class Event: def __init__(command, args): pass
StarcoderdataPython
3332263
<filename>src/tests/test_node.py import unittest from gerel.genome.edge import Edge from gerel.genome.node import Node import itertools class TestNodeClass(unittest.TestCase): def setUp(self): # reset innovation number Node.innov_iter = itertools.count() Edge.innov_iter = itertools.count()...
StarcoderdataPython
6514772
<filename>skadi/__init__.py<gh_stars>10-100 from __future__ import absolute_import import collections as c import copy import io as _io import itertools as it import math def enum(**enums): _enum = type('Enum', (), enums) _enum.tuples = enums return _enum Peek = c.namedtuple('Peek', 'tick, kind, tell, size, c...
StarcoderdataPython
1610776
from opencmiss.zinc.context import Context from opencmiss.zinc.material import Material from mapclientplugins.lungmodelstep.model.meshmodel import MeshModel class LungModel(object): def __init__(self): self._context = Context("LungModelView") self._logger = self._context.getLogger() self...
StarcoderdataPython
6629331
<gh_stars>0 """ APIQuery should start by checking if a cached completion exists. If it doesn't- prompt the API for a completion, cache it and use it. """ import openai, os, json, re, IO.io as io from encoder.encoder import get_encoder MAX_TOKENS = 2048; with open('config.json') as configFile: config = json.loads...
StarcoderdataPython
8085536
# Define imports import pygame from pygame import * import random # Define helpers from GameMenu import Menu from GameModel import Model from GameView import View from GameController import Controller if __name__ == "__main__": # Initialize pygame pygame.init() # Initialize m...
StarcoderdataPython
6630746
<reponame>renhongl/electron #!/usr/bin/env python import argparse import os import subprocess import sys from lib.config import LIBCHROMIUMCONTENT_COMMIT, BASE_URL, PLATFORM, \ enable_verbose_mode, is_verbose_mode, get_target_arch from lib.util import execute_stdout, get_atom_shell_version, sco...
StarcoderdataPython
11390299
<reponame>ok97465/spyder # -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ Working Directory widget. """ # Standard library imports import os import os.path as osp # Third party imports from qtpy...
StarcoderdataPython
1611245
<reponame>youssefaz94/leshy<filename>src/resolvers/resolver.py import logging as lg from src.scrap.statusEnum import StateWorker from src.resolvers.resolverFact import ResolverFact _logger = lg.getLogger(__name__) class Resolver: def __init__(self, sources, worker_to_source_map, master, statuskeeper): sel...
StarcoderdataPython
6564830
import contextlib import csv import pprint import sys from datetime import datetime from nesteddict import NestedDict import pymongo class CursorFormatter(object): ''' Output a set of cursor elements by iterating over then. If root is a file name output the content to that file. ''' def __init...
StarcoderdataPython
5150480
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name="rotten_tomatoes_cli_fork", description="Rotten Tomatoes Command Line Tool", long_description=long_description, long_description_content_type="text/markdown", author="<NAME>"...
StarcoderdataPython
6405750
from clearml import Task default_mlops_settings = { 'project_name': 'Default Project', 'task_name': 'default_task', 'connect_frameworks': { 'matplotlib': False, 'tensorflow': False, 'tensorboard': False, 'pytorch': False, 'xgboost': False, 'sciki...
StarcoderdataPython
6632541
from django.http import HttpResponse, HttpResponseRedirect import json from django.core.mail import send_mail from django.core.exceptions import ObjectDoesNotExist from string import letters, digits import random from random import choice from django.conf import settings from grid_user.forms import CreateUserForm impor...
StarcoderdataPython
3502569
import os from tqdm import tqdm import json car_model_dir = '/data/Kaggle/pku-autonomous-driving/car_models_json' obj_output_dir = '/data/Kaggle/pku-autonomous-driving/car_model_obj' car_model_dict = {} for car_name in tqdm(os.listdir(car_model_dir)): with open(os.path.join(car_model_dir, car_name)) as json_file: ...
StarcoderdataPython
140492
import itertools import time import numpy as np import scipy.ndimage as ndi import pytest from mrrt.utils import ImageGeometry, ellipse_im from mrrt.mri import mri_exp_approx __all__ = ["test_mri_exp_approx"] def _test_mri_exp_approx1( segments=4, nx=64, tmax=25e-3, dt=5e-6, autocorr=False, ...
StarcoderdataPython
3355570
# Run Grtrans with rrjet model # The rrjet model is defined in "fluid_model_rrjet.py" # NOTE -- currently the power law emissivity is very slow because paralleization is off # First make grtrans with 'make' # Then run this in python import numpy as np import grtrans_batch as gr import matplotlib.pyplot as plt import...
StarcoderdataPython
6639444
<gh_stars>10-100 from tests.base import TestCase, main, assets, create_ocrd_file, create_ocrd_file_with_defaults from ocrd_utils import MIMETYPE_PAGE from ocrd_models import OcrdMets from ocrd_modelfactory import ( exif_from_filename, page_from_image, page_from_file ) SAMPLE_IMG = assets.path_to('kant_auf...
StarcoderdataPython
3385286
<filename>devices/master/splthread.py #!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import threading from abc import ABCMeta, abstractmethod class SplThread(metaclass=ABCMeta): '''Partly abstract class to implement threading & message handling ''' def __init__(self, msg_handler, child): s...
StarcoderdataPython
3581355
<reponame>kynk94/torch-firewood<gh_stars>1-10 from . import gan, semantic_segmentation
StarcoderdataPython
8129718
from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.gis.db import models from django.contrib.gis.measure import D from django.db.utils import IntegrityError from django.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from djang...
StarcoderdataPython
3242636
<filename>run_experiments.py #!/usr/bin/env python # -*- coding: utf-8 -*- import json from collections import OrderedDict import spam PATHS = [ 'data/csv/enron1_clean_dataset.csv', 'data/csv/enron2_clean_dataset.csv', 'data/csv/enron3_clean_dataset.csv', 'data/csv/enron4_clean_dataset.csv', 'd...
StarcoderdataPython
3516490
<filename>user_test.py import unittest from user import User class TestUser(unittest.TestCase): ''' Test class that defines test cases for our accounts class behaviours. Args: unittest.TestCase: Testcase class that helps in creating test cases ''' def setUp(self): ''' set up method to clear be...
StarcoderdataPython
252755
"""Test cases completing Checkout step 2""" from module_06.src.elements.inventory_item import InventoryItem from module_06.src.pages.inventory import InventorySortOptions from module_06.src.pages.login import LoginPage from module_06.src.pages.cart import CartPage from module_06.tests.common.test_base import TestBase f...
StarcoderdataPython
8127666
# -*- coding: utf-8 -*- from functools import partial from trytond.model import ModelView, ModelSQL, fields, Unique from trytond.pool import PoolMeta from trytond.pyson import Eval from trytond.transaction import Transaction from nereid import url_for, current_website from flask import json from babel import numbers ...
StarcoderdataPython
5157271
import traceback from _pytest.logging import LogCaptureFixture from click.testing import Result def assert_dict_key_and_val_in_stdout(dict_, stdout): """Use when stdout contains color info and command chars""" for key, val in dict_.items(): if isinstance(val, dict): assert key in stdout ...
StarcoderdataPython
12807671
<filename>.leetcode/781.rabbits-in-forest.py # @lc app=leetcode id=781 lang=python3 # # [781] Rabbits in Forest # # https://leetcode.com/problems/rabbits-in-forest/description/ # # algorithms # Medium (55.99%) # Likes: 563 # Dislikes: 446 # Total Accepted: 32.1K # Total Submissions: 57.5K # Testcase Example: '[1...
StarcoderdataPython
5040711
"""Binarized model.""" import numpy as np from .base_model import BaseModel from ...core import Task class BinarizedClassifier(BaseModel): def __init__(self, model, data_type, label_index): """ Initialize a Model. Args: model (torch.nn.Module): model to wrap. dat...
StarcoderdataPython
8130001
class Queen: def __init__(self, row, column): if row < 0 or row > 7 or column < 0 or column > 7: raise ValueError(r".+") self.row = row self.col = column def can_attack(self, another_queen): if self.row == another_queen.row and self.col == another_queen.col: ...
StarcoderdataPython
11374070
# Variables with Global Scope name = 'XXX' employee_id = 0 salary = 0.0 is_manager = False def get_employee_details(): print("Starting the Function") name = input('Enter your name: ') # Creating the Local Variable print(f"Local Name: {name}") print("Starting the Program") get_employee_details() # Invokin...
StarcoderdataPython
3269358
from axiom.test.historic.stubloader import StubbedTest from xmantissa.ixmantissa import INavigableElement from xquotient.compose import Composer, Drafts class DraftsUpgradeTest(StubbedTest): """ Test that the Drafts item has been removed and is no longer a powerup for a composer. """ def test_u...
StarcoderdataPython
8026000
#! /usr/bin/python # # riak_python_delete.py # # Feb/09/2015 # # ------------------------------------------------------------------ import cgi import sys # sys.path.append ('/var/www/data_base/common/python_common') # from cgi_manipulate import parse_parameter from curl_get import curl_delete_proc # ---------------...
StarcoderdataPython
9627250
<filename>run.py<gh_stars>0 import os import yaml import arxiv import textwrap import smtplib, ssl from time import sleep from pathlib import Path from datetime import date, datetime today = date.today() def build_query(domains, keyword): query = '(' for i, domain in enumerate(domains): query += f'...
StarcoderdataPython
5193340
#!/usr/bin/env python3 # coding: utf8 # Author: <NAME>, 2015 ''' Send an email with attachments. ''' # Adapted from: # http://stackoverflow.com/a/3363254/5272432 # http://stackoverflow.com/questions/73781 import smtplib from os.path import basename from collections import namedtuple from subprocess import Popen,...
StarcoderdataPython
8156844
"""! @brief Templates for tests of SyncPR (oscillatory network based on Kuramoto model for pattern recognition). @authors <NAME> (<EMAIL>) @date 2014-2020 @copyright BSD-3-Clause """ # Generate images without having a window appear. import matplotlib; matplotlib.use('Agg'); from pyclustering.nnet i...
StarcoderdataPython
104712
import urllib.request import re import argparse import sys import os from time import sleep __version__ = "1.0" banner = """ \033[1m\033[91m .d888888b. d88888888b 8888 8888 8888 8888 ...
StarcoderdataPython
208929
<gh_stars>0 # -*- coding: utf-8 -*- """save_princess_peach.constants.py Constants for save-princes-peach. """ # Default file used as grid DEFAULT_GRID = '/Users/JFermin/Documents/GitHub/itsMeMario/tests/test_grids/init_grid.txt' # players BOWSER = 'b' PEACH = 'p' MARIO = 'm' PLAYERS = [BOWSER, PEACH, MARIO] # addit...
StarcoderdataPython
3333420
import math print("Calculator") a = int(input("Give the first number: ")) b = int(input("Give the second number: ")) while True: print("(1) +\n(2) -\n(3) *\n(4) /\n(5)sin(number1/number2)\n(6)cos(number1/number2)\n(7) Change numbers\n(8) Quit\nCurrent numbers: ", a, b) choice = int(input("Please select som...
StarcoderdataPython
1998413
info = [] contents = "" with open("AoC4.txt", "r") as File1: for line in File1: contents += line info = contents.split("\n\n") valid = 0 for thing in info: if "byr" in thing and \ "iyr" in thing and \ "eyr" in thing and \ "hgt" in thing and \ "hcl" in ...
StarcoderdataPython
4960811
# Copyright 2006-2021 by <NAME>. All rights reserved. # # This file is part of the Biopython distribution and governed by your # choice of the "Biopython License Agreement" or the "BSD 3-Clause License". # Please see the LICENSE file that should have been included as part of this # package. """Bio.Align support module...
StarcoderdataPython
11371127
def horspool(t, w, n, m): LAST = suffix.last_occurrence(w[:-1]) i = 1 while i <= n - m + 1: c = t[i + m - 1] if w[m] == c: j = 1 while j < m and t[i + j - 1] == w[j]: j = j + 1 if j == m: yield i bad_character = LAST.get(c, 0) i = i + (m - bad_character)
StarcoderdataPython
4907795
from threading import Timer, Thread from time import time class RepeatedTimer(): def __init__(self, interval, function, timelimit = None, countlimit = None, callback = None): # announce interval to class self.interval = interval # announce target function to class self.function = function #...
StarcoderdataPython
6468973
from .load_model import load_model from .SiameseModel import SiameseModel __all__ = [ "load_model", "SiameseModel", ]
StarcoderdataPython
3237279
<filename>web/blueprints/task/__init__.py from dataclasses import asdict from typing import NoReturn from flask import Blueprint, jsonify, url_for, abort, flash, redirect, request, \ render_template from flask_login import current_user from pycroft.exc import PycroftException from pycroft.lib.task import cancel_t...
StarcoderdataPython
11216962
<reponame>fau-fablab/etiketten # -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function """ Performs some tests with pyBarcode. All created barcodes where saved in the tests subdirectory with a tests.html to watch them. """ __docformat__ = 'restructuredtext en' import codecs import os import...
StarcoderdataPython
42802
# NOTE: override the kaolin one from .renderer.base import Renderer as DIBRenderer
StarcoderdataPython
5047246
from dataclasses import dataclass, field from decimal import Decimal from typing import List, Optional, Union @dataclass class Item: class Meta: name = "ITEM" quantity: Optional[int] = field( default=None, metadata={ "type": "Attribute", } ) price: Optional...
StarcoderdataPython
5024307
<gh_stars>0 import pygame import pygame.gfxdraw from typing import List, Union, Tuple from .. import ui_manager from ..core.ui_element import UIElement from ..elements import ui_text_box class UITooltip(UIElement): """ A tool tip is a floating block of text that gives additional information after a user hove...
StarcoderdataPython
345567
import os import pytest from django.conf import settings from django.core.files.uploadedfile import SimpleUploadedFile pytestmark = pytest.mark.django_db def test_image_delete_from_folder(foobar): banner = SimpleUploadedFile( name="banner.png", content=open("artists/tests/test_banner.png", "rb")...
StarcoderdataPython
3314451
# -*- coding: utf-8 -*- import lemoncheesecake.api as lcc from lemoncheesecake.matching import check_that_in, check_that, has_length, is_integer, is_dict, is_list, require_that, \ equal_to from common.base_test import BaseTest SUITE = { "description": "Method 'lookup_account_names'" } @lcc.prop("main", "typ...
StarcoderdataPython
9654488
""" Sort an XML file according to one or more provided schemas. Based on https://github.com/OpenDataServices/iati-utils/blob/master/sort_iati.py Copyright (c) 2013-2014 <NAME> Copyright (c) 2016 Open Data Services Co-operative Limited Permission is hereby granted, free of charge, to any person obtaining a copy of th...
StarcoderdataPython
207792
<filename>test/test_profile.py from flask import url_for from flask_login import current_user from config import TRACKER_PASSWORD_LENGTH_MAX from config import TRACKER_PASSWORD_LENGTH_MIN from tracker.form.user import ERROR_PASSWORD_CONTAINS_USERNAME from tracker.form.user import ERROR_PASSWORD_INCORRECT from tracker....
StarcoderdataPython
3597285
import boto3 exceptions = boto3.client('workmail').exceptions DirectoryServiceAuthenticationFailedException = exceptions.DirectoryServiceAuthenticationFailedException DirectoryUnavailableException = exceptions.DirectoryUnavailableException EmailAddressInUseException = exceptions.EmailAddressInUseException EntityAlrea...
StarcoderdataPython
9665525
# -------------- # Import packages import numpy as np import pandas as pd from scipy.stats import mode # code starts here bank = pd.read_csv(path) categorical_var = bank.select_dtypes(include = 'object') print(categorical_var) numerical_var = bank.select_dtypes(include = 'number') #print(numerical_var) # code en...
StarcoderdataPython
3229962
from botocore.exceptions import ClientError from mock import MagicMock, patch, call from sceptre_s3_packager.s3_packager import KeyResolver, UploadHook from sceptre.stack import Stack class TestKeyResolver(object): def setup_method(self, method): self.key_resolver = KeyResolver() self.key_resolver...
StarcoderdataPython
8027269
import numpy as np import pandas as pd from pandas import DataFrame from sklearn.cluster import DBSCAN from sklearn import preprocessing import traceback from datetime import datetime def LTV_class_probability(value_series): value_list = value_series.values.tolist() class_1_prob = value_list.count(1) cla...
StarcoderdataPython
393670
from .robust_kalman import RobustKalman from . import utils
StarcoderdataPython
3296498
#!/usr/bin/env python3 import argparse import json import requests import sys from datetime import datetime SUPPORTED_BUILDS = { 6002: 'https://support.microsoft.com/en-us/help/4343218', # 2008 SP2 7601: 'https://support.microsoft.com/en-us/help/4009469', # 7 / 2008R2 SP1 9200: 'https://support.microso...
StarcoderdataPython
11356498
"""Test suite for phlsys_textconvert.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import string import unittest import phlsys_textconvert class Test(unittest.TestCase): def _check_unicode_to_ascii(self, src, dst): value = phlsys_textc...
StarcoderdataPython
3250768
<reponame>jonesholger/lbann #!/usr/bin/python import common
StarcoderdataPython
11232827
<reponame>jjacob/DailyPythonScripts<gh_stars>0 ''' Created on Nov 22, 2011 @author: <NAME> Email: <EMAIL> important features: - read MC and data histograms and combine them - set styles and colors - allow switches for log-scale, cumulitative histograms, underflow/overflow bins, error sources ''' import tools.Plot...
StarcoderdataPython
4832023
<reponame>arnoyu-hub/COMP0016miemie<gh_stars>0 import numpy as np import pytest import pandas as pd import pandas._testing as tm from pandas.arrays import BooleanArray from pandas.core.arrays.boolean import coerce_to_array def test_boolean_array_constructor(): values = np.array([True, False, True, Fals...
StarcoderdataPython
4866093
import FWCore.ParameterSet.Config as cms from ElectroWeakAnalysis.ZMuMu.ZMuMuCategoriesSequences_cff import * import copy #### vertex refit for loose cut goodZToMuMuVtxedAtLeast1HLTLoose = cms.EDProducer( "KalmanVertexFitCompositeCandProducer", src = cms.InputTag("goodZToMuMuAtLeast1HLTLoose") ) goodZToMuMu...
StarcoderdataPython
11343162
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'BaseModel' db.create_table('website_basemodel', ( ('id', self.gf('django.db.mode...
StarcoderdataPython
8102827
from easydict import EasyDict as edict # init __C_SHHB = edict() cfg_data = __C_SHHB __C_SHHB.STD_SIZE = (768,1024) __C_SHHB.TRAIN_SIZE = (576,768) __C_SHHB.DATA_PATH = 'ProcessedData/shanghaitech_part_B' __C_SHHB.MEAN_STD = ([0.452016860247, 0.447249650955, 0.431981861591],[0.23242045939, 0.224925786257, 0.2218402...
StarcoderdataPython
8049173
<filename>tricycle_kinematic.py """ Example tricycle_kinematic.py Author: <NAME> <<EMAIL>> GitHub: https://github.com/botprof/agv-examples """ # %% # SIMULATION SETUP import numpy as np import matplotlib.pyplot as plt from mobotpy.models import Tricycle from mobotpy.integration import rk_four # Set the simulation ti...
StarcoderdataPython
1905582
from gather_texts import getTexts from ngrams import classify_text from ngrams import classify_text from server import classifyOffWorld print("Getting text from MongoDB...") texts = getTexts() #[0: 100] print("Finished") print("Concatenating text into a single file..") texts_list = [] for text in texts: ...
StarcoderdataPython
4832870
<reponame>facebookresearch/uimnet<filename>uimnet/modules/spectral_normalization/spectral_embedding.py #!/usr/bin/env python3 # # # Copyright (c) 2021 Facebook, inc. and its affiliates. All Rights Reserved # # import torch import torch.nn as nn import torch.nn.functional as F from uimnet.modules.spectral_normalization....
StarcoderdataPython
195295
from django.apps import AppConfig class CustomThemeDemoAppConfig(AppConfig): name = 'django_cradmin.demo.custom_theme_demo' verbose_name = "Django CRadmin custom theme demo" def ready(self): from django_cradmin.apps.cradmin_kss_styleguide import styleguide_registry styleguide = styleguid...
StarcoderdataPython
1847166
""" Factories for generating edXML for testing XModule import """ import inspect from tempfile import mkdtemp from factory import Factory, Sequence, lazy_attribute, post_generation from fs.osfs import OSFS from lxml import etree from xblock.mixins import HierarchyMixin from xmodule.modulestore import only_xmodules ...
StarcoderdataPython
11231919
<filename>cloudrail/knowledge/rules/aws/context_aware/disallow_resources_in_default_vpc_rule.py from typing import List, Dict from cloudrail.knowledge.context.aws.networking_config.network_entity import NetworkEntity from cloudrail.knowledge.context.aws.aws_environment_context import AwsEnvironmentContext from cloudrai...
StarcoderdataPython
9679520
<filename>main.py import pandas as pd from constants import * from formatting import format_player_data # main execution function to read player list and generate fantasy teams. def main(): data = pd.read_csv('data/fav_players.csv') # Format data = format_player_data(data) print(data[:5]) ...
StarcoderdataPython
1619748
#!/usr/bin/env python # coding: utf-8 # demo """ Author: <NAME> Email: <EMAIL> Create_Date: 2019/05/21 """ import torch import torch.nn as nn import torchvision.transforms as transforms from torch.utils.data import DataLoader torch.backends.cudnn.deterministic = True torch.manual_seed(123) import os, argparse, sys ...
StarcoderdataPython
5173181
#!/usr/bin/python2.5 """ Package for general database editor web interface. """
StarcoderdataPython
317543
<gh_stars>0 import requests # petition get def generate_request_get(url, params={}): response = requests.get(url, params=params) if response.status_code == 200: return response.json() # petition put def generate_request_put(url, data): response = requests.put(url, data=data) ...
StarcoderdataPython
11295642
from django.urls import include, path urlpatterns = [ path('profiles/', include('tango_user.urls')), path('video/', include('video.urls')), ]
StarcoderdataPython
3292299
<gh_stars>1000+ # -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-28 23:15 from hanlp.components.ner_tf import TransformerNamedEntityRecognizerTF from hanlp.datasets.ner.msra import MSRA_NER_CHAR_LEVEL_TRAIN, MSRA_NER_CHAR_LEVEL_DEV, MSRA_NER_CHAR_LEVEL_TEST from tests import cdroot cdroot() recognizer = Transfo...
StarcoderdataPython
1787113
<filename>finalists/jun2tong/utils/train_ni.py import numpy as np import torch from torch.utils import data from .common import check_ext_mem, check_ram_usage from .wrapper import CustomTensorDataset def train_net(optimizer, scheduler, model, criterion, data_loader, reg_coef, train_ep, device="cpu"): ...
StarcoderdataPython
9618254
from random import randint from time import sleep def sorteia(lista): print('Sorteando 5 valores') for cont in range(0, 5): n = randint(0, 10) lista.append(n) print(f' {n} ', end='', flush=True) sleep(0.3) print('PRONTO!') def somapar(): soma = 0 for v in número: ...
StarcoderdataPython
11307550
from melodically.harmony import midi_to_std, get_root, harmonic_affinities, modes_dict class HarmonicState: """ This class allows to monitor and update an internal harmonic state, influenced by external notes inputs """ def __init__(self, buffer_size=16): # contains the input notes in std...
StarcoderdataPython
1975353
from itertools import* (n,), *d = [[*map(int, o.split())] for o in open(0)] S, T = zip(*d) a = [0] * -~max(T) for s in S: a[s] += 1 *a, = accumulate(a) for s, t in d: print(a[t] - a[s])
StarcoderdataPython
11312976
#!/usr/bin/env python # coding=utf-8 """ Copyright (C) 2010-2013, <NAME> <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later ...
StarcoderdataPython
3583193
<reponame>dmadea/Spectra-Manipulator<filename>spectramanipulator/dialogs/stylewidget_gui.py<gh_stars>1-10 # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'spectramanipulator/dialogs\stylewidget_gui.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to t...
StarcoderdataPython
3535813
<reponame>WangErFeiZi/Mei from flask_wtf import FlaskForm as Form from flask_login import current_user from ..models import User from wtforms import ValidationError, StringField, PasswordField, BooleanField, SubmitField from wtforms.validators import DataRequired, Length, Email, Regexp, EqualTo class LoginForm(Form):...
StarcoderdataPython
9720965
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from libtbx.program_template import ProgramTemplate from mmtbx.validation import rama_z from mmtbx.validation.ramalyze import ramalyze from mmtbx.validation.ramalyze import res_type_labels from cctbx.maptbx.box import shift_and_b...
StarcoderdataPython
3485588
<filename>appengine/findit/dto/flake_try_job_report.py # Copyright 2017 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. from dto.isolated_tests import IsolatedTests from dto.try_job_report import TryJobReport class Flake...
StarcoderdataPython
5080863
def solution(A): if len(A) == 0: return 0 else: # head = A[0] # tail = A[head] # beans_list.append(tail) # while head != tail: # tail = A[tail] # beans_list.append(tail) all_beans_list = [] for index in range(len(A)): b...
StarcoderdataPython
145952
<filename>old-code/move-sitelinks.py import csv from sys import * reader = csv.DictReader(open('genes-wikipedia.tab', 'r'), delimiter='\t') gqs = {} for item in reader: iturl = item.get('p') qit = iturl[iturl.rfind('/')+1:] lang = item.get('lang') lemma = item.get('lemma') d = gqs.get(qit) if d...
StarcoderdataPython
12824081
<gh_stars>0 import string import nltk class Preprocesar: def __init__(self, corpus): self.corpus = corpus def __call__(self, pad='<PAD>'): """ Realiza el preproceso del texto para obtener vectores a partir de tokens a partir del texto, eliminando puntuación y palabras comunes...
StarcoderdataPython
6602331
<gh_stars>1-10 #!/usr/bin/python import re from optparse import OptionParser import sys def fextract(text, start=None, end=None): """Return the text between regular expressions start and end.""" if type(text) is list: text = ''.join(text) if start is not None: text = re.split(start, text)[...
StarcoderdataPython
3457405
<reponame>MosyMosy/VDT from lab.tsne import plot # from lab.affines import plot # from lab.layers import plot # from lab.learning_curve import plot # from lab.tsne import plot # from lab.visual_domain import plot # from lab.autoencoder import transfer
StarcoderdataPython
9754602
import math import scipy.sparse as sp import torch import torch.nn as nn import torch.nn.functional as F import torch_sparse class SparseDropout(nn.Module): def __init__(self, p): super().__init__() self.p = p def forward(self, input): value_dropped = F.dropout(input.storage.value(), ...
StarcoderdataPython
8157755
<reponame>felix9064/PythonProject #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Topic: 让对象支持上下文管理器,即兼容 with 语句 Desc : 为了让一个对象兼容 with 语句,你需要实现 __enter__() 和 __exit__() 方法 下面的例子是自定义一个网络连接 """ from socket import socket, AF_INET, SOCK_STREAM from functools import partial class LazyConnection: """ 这个类的关键特点在于它...
StarcoderdataPython