id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3269098
<reponame>uk-gov-mirror/ministryofjustice.cla_backend import re from cla_provider.models import Provider import os from datetime import timedelta, time, datetime, date from django import forms from django.db.transaction import atomic from django.utils import timezone from django.contrib.admin import widgets from lega...
StarcoderdataPython
139921
<filename>Scripts/python/scripts mundo 1/Desafios/Desafio012.py<gh_stars>0 p=float(input('\033[32mqual o preço do produto ? R$\033[m')) d=(p*5)/100 v=p-d print('\033[34mO desconto em 5 porcento do produto será de \033[31mR${}\033[34m'.format(d)) print('O valor do produto com 5 porcento de desconto é de \033[31mR${}'.fo...
StarcoderdataPython
1713517
<reponame>ckw017/showdown.py<filename>showdown/__init__.py # -*- coding: utf-8 -*- __title__ = "showdown" __author__ = "chriskw" __license__ = "MIT" __version__ = "1.0.0" from .client import Client # noqa: F401 from .user import User # noqa: F401 from .server import Server # noqa: F401 from .message import ChatMes...
StarcoderdataPython
162119
<reponame>oat431/HomeworkCollection<gh_stars>1-10 class Queue: qu = [] size = 0 front = 0 rear = 0 def __init__(self, size): self.size = size def en_queue(self, data): self.qu.append(data) self.size = self.size + 1 self.rear = self.rear + 1 def de_queue(sel...
StarcoderdataPython
1688495
<filename>apps/accounts/migrations/0003_auto_20200106_1846.py<gh_stars>0 # Generated by Django 3.0.1 on 2020-01-06 18:46 from django.db import migrations class Migration(migrations.Migration): def corrigir_username(apps, schema_editor): Account = apps.get_model('accounts', 'Account') for account...
StarcoderdataPython
3306313
""" How Many Vowels? Create a function that takes a string and returns the number (count) of vowels contained within it. Examples: print(count_vowels("Celebration")) ➞ 5 print(count_vowels("Palm")) ➞ 1 print(count_vowels("Prediction")) ➞ 4 NOTES: - The following characters are considered "vowels": a, e, i, o, u (n...
StarcoderdataPython
76567
<filename>l3py/utilities.py # Copyright (c) 2018 <NAME> # See LICENSE for copyright/license details. """ Auxiliary functions. """ import numpy as np def legendre_functions(nmax, colat): """ Associated fully normalized Legendre functions (1st kind). Parameters ---------- nmax : int maxim...
StarcoderdataPython
148968
# -*- coding: utf-8 -*- # Author: <NAME> <<EMAIL>> import pickle import os import pytest import numpy as np from renormalizer.model import MolList, MolList2, ModelTranslator, Mol, Phonon from renormalizer.mps import Mpo, Mps from renormalizer.tests.parameter import mol_list, ph_phys_dim, omega_quantities from renorm...
StarcoderdataPython
4842903
import re import datetime import os # Image File Upload Utilities def set_filename_format(now, instance, filename): return "{username}-{date}-{microsecond}{extension}" \ .format(username=instance.user_no, date=str(now.date()), microsecond=now.microsecond, ex...
StarcoderdataPython
22487
from .client import Client from .consts import * class FutureAPI(Client): def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) # query position def get_position(self): ...
StarcoderdataPython
1724603
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unittests for chrome stages.""" import os import sys sys.path.insert(0, os.path.abspath('%s/../../..' % os.path.dirname(__file_...
StarcoderdataPython
3225208
# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
StarcoderdataPython
3240266
from setuptools import setup setup(name='embeddingsviz', version='0.1', description='Visualize Embeddings of a Vocabulary in TensorBoard, Including the Neighbors', classifiers=[ 'Programming Language :: Python :: 3.5', 'Topic :: Text Processing :: Linguistic', ], url='http...
StarcoderdataPython
4820979
from .core import AvroModelContainer, avro_schema __all__ = ["AvroModelContainer", "avro_schema"]
StarcoderdataPython
1612049
<reponame>brouwa/CNNs-on-FPSPs<gh_stars>1-10 #!/usr/bin/env python from __future__ import print_function import rospy from geometry_msgs.msg import Twist import datetime import sys import time FORWARD_TIME = 0.8 RIGHT_FORWARD_TIME = 0.8 RIGHT_TURN_TIME = 0.8 LEFT_FORWARD_TIME = 0.8 LEFT_TURN_TIME = 0.8 msg = """ R...
StarcoderdataPython
51658
<gh_stars>0 from IPython.display import display from dutil.transform import ht def dht(arr, n: int = 2) -> None: """Display first and last (top and bottom) entries""" display(ht(arr, n))
StarcoderdataPython
1619945
#desafio 8: conversor de medidas m = float(input('Digite um valor em metros: ')) km = m / 1000 hm = m / 100 dam = m / 10 dm = m * 10 cm = m * 100 mm = m * 1000 print(f'A medida de {m}m corresponde a: \n {km:.5}km \n {hm}hm \n {dam}dam \n {dm}dm \n {cm:.0f}cm \n {mm:.0f}mm')
StarcoderdataPython
125891
<filename>pm08-multimax/multimax.py def multimax(iterable): if iterable is None: return [] maxvars = [] max = iterable[0] for item in iterable: if item > max: max = item for item in iterable: if item == max: maxvars.append(item) return maxvars ...
StarcoderdataPython
1610645
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from mjt.mjt.report.accounts_receivable_mjt.accounts_receivable_mjt import ReceivablePayableReportMJT def execute(filters=None): args = ...
StarcoderdataPython
1711489
<reponame>rmoskal/e-springpad import uuid from google.appengine.api import memcache class CollectionCache: def __init__(self, timeout=480, hash=None): self.contents = []; if hash: self.contents = memcache.get(hash) self.timeout = timeout def add(self, item): hash ...
StarcoderdataPython
1703726
#!usr/bin/env python # -*- coding:utf-8 -*- import os import random import logging import argparse import importlib import platform from pprint import pformat import numpy as np import torch from agents.utils import * # torch.backends.cudnn.enabled = True # torch.backends.cudnn.benchmark = True logging.basicConfig(...
StarcoderdataPython
4826039
<reponame>ebot1234/the-blue-alliance<gh_stars>0 import json import logging from google.appengine.api import taskqueue from helpers.cache_clearer import CacheClearer from helpers.manipulator_base import ManipulatorBase from helpers.notification_helper import NotificationHelper from helpers.tbans_helper import TBANSHel...
StarcoderdataPython
3342698
from selenium import webdriver import time import math try: link = "http://suninjuly.github.io/math.html" browser = webdriver.Chrome() browser.get(link) # Вычисление требуемое на странице link def calc(x): return str(math.log(abs(12 * math.sin(int(x))))) x_element = browser.find_ele...
StarcoderdataPython
120853
<gh_stars>100-1000 import tensorflow as tf sess = tf.Session() from keras import backend as K K.set_session(sess) # 분류 DNN 모델 구현 ######################## from keras.models import Sequential, Model from keras.layers import Dense, Dropout from keras.metrics import categorical_accuracy, categorical_crossentropy class D...
StarcoderdataPython
3380795
<filename>hanse.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 4 22:12:56 2018 @author: <EMAIL> """ from datetime import date, timedelta from hanse.city import get_city_list print("╔══════════════════╗") print("║ Start Hanse Game ║") print("╚══════════════════╝") today=date(1500,1,1) citie...
StarcoderdataPython
1647263
#!/usr/bin/env python ################################################################################################## ## receive.py ## ## Expects post or get with parameters: ## ## imei : string ## momsn : string ## transmit_time : string ## iridium_latitude : string ## iridium_longitude : string ## iridium_cep : s...
StarcoderdataPython
1707732
#!/usr/bin/python # -*- coding: utf-8 -*- from os import environ from ..util.url import urlsoup, soup_filter def _urlsoup(url, data=None, **kargs): environ['disable_fetchurl'] = 1 soup = urlsoup(url, data, **kargs) environ['disable_fetchurl'] = 0 return soup class Jandan(object): baseUrl = "ht...
StarcoderdataPython
3244670
<reponame>Ahleroy/deeplodocus import weakref from typing import Union from typing import List class Connection(object): """ AUTHORS: -------- :author: <NAME> DESCRIPTION: ------------ Connection class allowing to gather information for a connection in the Thalamus. Contains a weak r...
StarcoderdataPython
151847
src = Split(''' aos/soc_impl.c hal/uart.c hal/flash.c main.c ''') deps = Split(''' kernel/rhino platform/arch/arm/armv7m platform/mcu/wm_w600/ kernel/vcall kernel/init ''') global_macro = Split(''' STDIO_UART=0 CONFIG_NO_TCPIP ...
StarcoderdataPython
1786417
from collections import defaultdict def constant_factory(value): return lambda: value d = defaultdict(constant_factory('<missing>')) d.update(name='John', action='ran') print('%(name)s %(action)s to %(object)s' % d)
StarcoderdataPython
1627549
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
StarcoderdataPython
63557
<filename>CGI/simple-server-with-different-languages/cgi-bin/download.py #!/usr/bin/env python import os import sys fullpath = 'images/normal.png' filename = 'hello_world.png' # headers print 'Content-Type: application/octet-stream; name="%s"' % filename print 'Content-Disposition: attachment; filename="%s"' % filen...
StarcoderdataPython
3243176
# Generated by Django 2.0.3 on 2019-07-10 09:07 import api.helpers from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MOD...
StarcoderdataPython
36548
#!/usr/bin/env python3 """Initialize. Turn full names into initials. Source: https://edabit.com/challenge/ANsubgd5zPGxov3u8 """ def __initialize(name: str, period: bool=False) -> str: """Turn full name string into a initials string. Private function used by initialize. Arguments: name {[str]}...
StarcoderdataPython
3295991
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2019 <NAME> <<EMAIL>> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
StarcoderdataPython
60630
# Generated by Django 3.2.9 on 2021-12-28 03:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ...
StarcoderdataPython
182583
#!/usr/bin/env python #-*- encoding=utf-8 -*- import sys def readmap(filename): graph={} with open(filename,'r') as mapfile: line=mapfile.readline() directed=int(line[:-1]) line=mapfile.readline() nodes=line[:-1].split(' ') for node in nodes: graph[int(node)]=[] for line in mapfile: node1,node2=lin...
StarcoderdataPython
1672572
<reponame>Nailim/shuttler # for new opencv #import os,sys #os.chdir(os.path.expanduser('~/opencv-2.4.6.1/lib')) #sys.path.append(os.path.expanduser('~/opencv-2.4.6.1/lib/python2.7/dist-packages')) # before starting #export PYTHONPATH=~/opencv-2.4.6.1/lib/python2.7/dist-packages import os #import cv import cv2 import ...
StarcoderdataPython
181742
"""Dimensionality reduction through dimensionality selection.""" import logging import random import functools import multiprocessing import numpy as np import entropix.core.evaluator as evaluator __all__ = ('sample_seq', 'sample_limit') logger = logging.getLogger(__name__) def _init_eval_metric(metric): if m...
StarcoderdataPython
1671598
<filename>recipes/Python/576717_PDF_Directory_Images_using/recipe-576717.py import os from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from reportlab.lib.units import cm, mm, inch, pica def pdfDirectory(imageDirectory, outputPDFName): dirim = str(imageDirectory) output = str(outpu...
StarcoderdataPython
177669
from PIL import Image import json import os import re import sys # Getting palette # /absolute/path/to/Pxls convertpath = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')) # /absolute/path/to/Pxls/pxls.conf configpath = convertpath + '\\pxls.conf' configfile = open(configpath, 'r+') co...
StarcoderdataPython
1632548
<filename>src/DCGMM/layer/Linear_Classifier_Layer.py # 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
6241
<filename>pyConTextNLP/__init__.py<gh_stars>1-10 #Copyright 2010 <NAME> # #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 ap...
StarcoderdataPython
3226153
import pandas as pd from sklearn import model_selection from sklearn.tree import DecisionTreeClassifier def predict(home_team, away_team, city, toss_winner, toss_decision): matches_cleaned_data = pd.read_csv('./Dataset/matches_cleaned.csv') matches_df = matches_cleaned_data[['team1', 'team2', 'city', '...
StarcoderdataPython
1705055
<filename>packet.py from bson import BSON as bson import cryptoManager import os import io import struct class Packet: def __init__(self, PacketID=0, StatusCode=0, PacketName="", BodyType=0, Body=b""): self.PacketID = PacketID self.StatusCode = StatusCode self.PacketName = PacketName ...
StarcoderdataPython
93538
<reponame>mchiuminatto/MVA_Crossover from SignalLib.Signal import Signal def test_instantiation(): _sig = Signal()
StarcoderdataPython
1772469
<gh_stars>10-100 #------------------------------------------------------------------------------ # Copyright (c) 2011, Enthought, Inc. # All rights reserved. #------------------------------------------------------------------------------ from .enaml_test_case import EnamlTestCase, required_method class SelectionTes...
StarcoderdataPython
1664074
<filename>tests/setpoint.py from Compass import Compass cc = Compass.connect('localhost', 'admin', 'newpoint') Compass.setpoint(cc, "demodev1", "fi1", 2) exit(0)
StarcoderdataPython
66938
import torch from . import networks from os.path import join from util.util import seg_accuracy, print_network import pdb class ClassifierModel: """ Class for training Model weights :args opt: structure containing configuration params e.g., --dataset_mode -> classification / segmentation) --arch -...
StarcoderdataPython
66175
<filename>common.py<gh_stars>10-100 from spacy.matcher import Matcher def create_versioned(name): return [ [{'LOWER': name}], [{'LOWER': {'REGEX': f'({name}\d+\.?\d*.?\d*)'}}], [{'LOWER': name}, {'TEXT': {'REGEX': '(\d+\.?\d*.?\d*)'}}], ] def create_patterns(): versioned_languag...
StarcoderdataPython
167449
<reponame>anayakoti/FirstSample<filename>ForLoopPractice2.py letter="Sai Teja"; for i in letter: print(i);
StarcoderdataPython
3397049
import numpy as np import healpy as hp from astropy.utils.data import get_pkg_data_filename try: # PySM >= 3.2.1 import pysm3.units as u except ImportError: import pysm.units as u from .. import PrecomputedAlms from astropy.tests.helper import assert_quantity_allclose def test_precomputed_alms(): alms_...
StarcoderdataPython
1787756
import numpy as np import matplotlib.pyplot as plt import matplotlib.pylab as pl from mpl_toolkits.mplot3d import Axes3D from matplotlib import rc from matplotlib import cm rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']}) rc('text', usetex=True) class graph_defaults: def __init__(self, x, t, ...
StarcoderdataPython
1648152
class Result: def __init__(self, user_query, nodes, keywords): self.user_query = user_query self.nodes = nodes self.keywords = keywords def __len__(self): return len(self.nodes) def get_node(self, index): return self.nodes[index] # noinspection PyMethodMayBeSt...
StarcoderdataPython
3351855
<reponame>tyrylu/feel-the-streets<gh_stars>1-10 import os import datetime import logging from PySide2.QtCore import QThread, Signal from osm_db import AreaDatabase, CHANGE_REMOVE, CHANGE_REDOWNLOAD_DATABASE from .semantic_changelog_generator import get_change_description log = logging.getLogger(__name__) c...
StarcoderdataPython
1798340
# Generated by Django 3.2.12 on 2022-03-01 12:27 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0003_auto_20220301_1750'), ] operations = [ migrations.AlterField( model_name='user', name...
StarcoderdataPython
1650855
<filename>python/name2taxid.py #!/usr/bin/env python3 from taxadb.names import SciName import fileinput names = SciName() for line in fileinput.input(): print(names.taxid(line.rstrip()))
StarcoderdataPython
4805494
<filename>tracker/migrations/0005_device_descriptions.py # Generated by Django 3.2.7 on 2021-10-05 11:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tracker', '0004_device_cellnumber'), ] operations = [ migrations.AddField( ...
StarcoderdataPython
1752406
import asyncio import discord import random import itertools from typing import Iterator from async_timeout import timeout from discord.ext.commands import Context from discord import Guild, TextChannel from app.ext.performance import run_in_threadpool from .YTDLSource import YTDLSource from app.controlle...
StarcoderdataPython
13001
"""Wrapper for pygame, which exports the PSP Python API on non-PSP systems.""" __author__ = "<NAME>, <<EMAIL>>" import pygame pygame.init() _vol_music = 255 _vol_sound = 255 def setMusicVolume(vol): global _vol_music if vol >= 0 and vol <= 255: _vol_music = vol pygame.mixer.music.set_vol...
StarcoderdataPython
110489
<filename>aiokinesis/utils.py<gh_stars>1-10 import asyncio from heapq import heappush from time import time def rate_limit_per_rolling_second(requests_per_rolling_second): def outer_wrapper(f): async def inner_wrapper(self, *args, **kwargs): assert isinstance(self, object), """ ...
StarcoderdataPython
3218697
<filename>archive/do_InFoV_scan2.py import numpy as np import os from astropy.table import Table from astropy.io import fits from numba import jit, njit, prange from scipy import interpolate from math import erf import healpy as hp import pandas as pd import argparse import logging, traceback from copy import copy, dee...
StarcoderdataPython
1650814
import json from jupyter_server.base.handlers import APIHandler from jupyter_server.utils import url_path_join import tornado from os import listdir, environ, makedirs, removedirs, getcwd from os.path import isfile, isdir, join basedir = getcwd() def save_file(path, content): content_bytes = bytearray(content) ...
StarcoderdataPython
4832257
<reponame>fax001/tink # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
StarcoderdataPython
3253933
# (C) Copyright 2005-2021 Enthought, Inc., Austin, TX # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in LICENSE.txt and may be redistributed only under # the conditions described in the aforementioned license. The license # is also available online at...
StarcoderdataPython
27335
<gh_stars>0 from pyns.protocols import create_basestation, create_node, ProtocolType from pyns.engine import Simulator, SimArg, TraceFormatter, TransmissionMedium from pyns.phy import PHYLayer import logging import numpy import sys import random import os import json class ConstantSimulator(Simulator): def __init...
StarcoderdataPython
1636693
<gh_stars>1-10 from django.contrib import admin from .models import Diary # Register your models here. class DiaryAdmin(admin.ModelAdmin): list_display = ('id', 'email', 'title', 'content', 'emotion', 'write_date', 'rewrite_date') admin.site.register(Diary, DiaryAdmin)
StarcoderdataPython
169050
import numpy as np def run_optimizer(opt, cost_f, iterations, *args, **kwargs): errors = [cost_f.eval(cost_f.x_start, cost_f.y_start)] xs,ys= [cost_f.x_start],[cost_f.y_start] for epochs in range(iterations): x, y= opt.step(*args, **kwargs) xs.append(x) ys.append(y) errors....
StarcoderdataPython
1785231
<filename>src/app.py<gh_stars>0 from flask import Flask, render_template from hackernews_tidal import * from twitter_tidal import * import tweepy app = Flask(__name__) # sample dashboard constants to get this working before I try using an actual database dashboard = 'Trendy Software Developer' widgets = [] hn_user =...
StarcoderdataPython
1647899
# -*- coding: utf-8 -*- """Generate the Resilient customizations required for fn_hibp""" from __future__ import print_function from resilient_circuits.util import * def codegen_reload_data(): """Parameters to codegen used to generate the fn_hibp package""" reload_params = {"package": u"fn_hibp", ...
StarcoderdataPython
3278161
<reponame>BlueWhaleMain/cipher-manager import pyDes from Crypto.Cipher import AES from PyQt5 import QtWidgets, QtGui from cm.crypto.aes.file import CipherAesFile from cm.crypto.des.file import CipherDesFile from cm.crypto.file import SimpleCipherFile, PPCipherFile from cm.crypto.rsa.file import CipherRSAFile from cm.f...
StarcoderdataPython
70982
<reponame>mijo2/Eye-In_The_Sky import math import numpy as np import logging import sys logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s') # logging.disable(sys.maxsize) def rowslice(image, gtimage, ptsz): n = math.floor(image.shape[1]/(ptsz//2)) w ...
StarcoderdataPython
3363097
import datetime import time class Timer: def __init__(self): self.start() pass def start(self,totalCount = None): self.startTime = datetime.datetime.now() self.totalCount = totalCount def stop(self,text=""): now = datetime.datetime.now() delta = (now-self.sta...
StarcoderdataPython
1774017
<gh_stars>1-10 from django.apps import AppConfig class CitiesLocalConfig(AppConfig): name = 'cities_local'
StarcoderdataPython
3208722
<filename>src/envs/starcraft2/maps/mt_maps.py from __future__ import absolute_import from __future__ import division from __future__ import print_function from pysc2.maps import lib from functools import partial from itertools import combinations_with_replacement, product class SMACMap(lib.Map): directory = "SM...
StarcoderdataPython
81443
<gh_stars>10-100 import os from django.conf import settings from pyplan.pyplan.common.baseService import BaseService from pyplan.pyplan.usercompanies.models import UserCompany from .models import Activity, ActivityType class ActivityService(BaseService): def registerOpenModel(self, file_path): norm_fi...
StarcoderdataPython
3344119
<reponame>SAKERZ/Adafruit_Learning_System_Guides<filename>pi_radio/radio_lorawan.py """ Example for using the RFM9x Radio with Raspberry Pi and LoRaWAN Learn Guide: https://learn.adafruit.com/lora-and-lorawan-for-raspberry-pi Author: <NAME> for Adafruit Industries """ import threading import time import subprocess imp...
StarcoderdataPython
3380942
<reponame>30ideas-Software-Factory/readIT #!/usr/bin/python3 """Create a Super Class called BaseModel with attributes and methods that other classes will inherit.""" import models from uuid import uuid4 from sqlalchemy import Column, String from sqlalchemy.ext.declarative import declarative_base # import engine # from ...
StarcoderdataPython
1729937
# -*- coding: utf-8 -*- import argparse import nltk from nltk.corpus import wordnet from nltk.stem import WordNetLemmatizer from tqdm import tqdm def lemmatize(words): lemmatizer = WordNetLemmatizer() maps = {"J": wordnet.ADJ, "N": wordnet.NOUN, "V": wordnet.VERB, "R": wordnet.ADV} return [lemmatizer.le...
StarcoderdataPython
1695970
# Copyright 2018 Diamond Light Source Ltd. # # 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 t...
StarcoderdataPython
3306314
<filename>bowtie/_compat.py # -*- coding: utf-8 -*- """ python 2/3 compatability """ import inspect import sys from os import makedirs IS_PY2 = sys.version_info < (3, 0) if IS_PY2: # pylint: disable=invalid-name makedirs_lib = makedirs # pylint: disable=function-redefined,missing-docstring def makedi...
StarcoderdataPython
165858
import torch # tempo imports from . import compute_cell_posterior from . import utils from . import cell_posterior from . import objective_functions class ClockGenePosterior(torch.nn.Module): def __init__(self,gene_param_dict,gene_prior_dict,num_grid_points,clock_indices,use_nb=False,log_mean_log_disp_coef=No...
StarcoderdataPython
4801683
<gh_stars>0 import transformice import discord_bot import asyncio # from signal import signal, SIGPIPE, SIG_DFL # signal(SIGPIPE,SIG_DFL) if __name__ == '__main__': loop = asyncio.get_event_loop() discord = discord_bot.setup(loop) mapper = transformice.setup(loop) mapper.discord = discord discord.mapper = mapp...
StarcoderdataPython
14020
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
StarcoderdataPython
115711
# -*- coding: utf-8 -*- # Hikari Examples - A collection of examples for Hikari. # # To the extent possible under law, the author(s) have dedicated all copyright # and related and neighboring rights to this software to the public domain worldwide. # This software is distributed without any warranty. # # You should have...
StarcoderdataPython
82371
<reponame>truthiswill/intellij-community class MyType(type): def __instancecheck__(self, instance): <selection>return super(MyType, self).__instancecheck__(instance)</selection>
StarcoderdataPython
170299
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime def time_in_range(start, end, x): """ Return true if x is in the range [start, end] """ if start <= end: return start <= x <= end else: return start <= x or x <= end def formated_date(timestamp): return datetime.d...
StarcoderdataPython
3292080
<filename>arl/skycomponent/operations.py """Function to manage skycomponents. """ import numpy from typing import Union, List import collections from astropy.coordinates import SkyCoord from astropy.wcs.utils import skycoord_to_pixel, pixel_to_skycoord from arl.data.data_models import Image, Skycomponent, assert_sa...
StarcoderdataPython
1638815
<filename>day2/homework/q3_b.py a=int(input('Enter value of a: ')) b=int(input('Enter value of b: ')) a=a+b b=a-b a=a-b print("After swapping the values are: a = {} b = {} ".format(a,b))
StarcoderdataPython
1741135
<reponame>ttppss/simple-faster-rcnn-pytorch<filename>data/coco_generator.py<gh_stars>0 def coco_generator(image_path): images = [] for im_path in image_path: im = imageio.imread(im_path) # image_nbr = re.findall(r"[0-9]+", im_path) im_path = str(im_path) image_nbr = im_path[(im_p...
StarcoderdataPython
4821139
<gh_stars>1000+ """ Mini commands - Provides a template for writing quick command classes in Python using the subprocess module. Author: <NAME> <<EMAIL>> """ import os import time from subprocess import * class CmdProcessor(object): """ Class providing useful functions to execute system commands using subpr...
StarcoderdataPython
1629941
import argparse import googlemaps import carpool_data as cd import numpy as np if __name__ == '__main__': parser = argparse.ArgumentParser(description="Get Distance Matrix from Coordinates") parser.add_argument('--api_key', default='') parser.add_argument('--coords_file', default='map_data/carpo...
StarcoderdataPython
1708810
# Custom template context processors from publisher.config import SITE_CONFIG def site_config_processor(request): """Context processor to make SITE_CONFIG available to all templates.""" return {'SITE_CONFIG': SITE_CONFIG}
StarcoderdataPython
48588
import socket import xmlrpc.client """ referemce: https://stackoverflow.com/a/14397619 """ class ServerProxy: def __init__(self, url, timeout=10): self.__url = url self.__timeout = timeout self.__prevDefaultTimeout = None def __enter__(self): try: if self.__timeou...
StarcoderdataPython
178347
# Generated by Django 3.0.6 on 2020-05-07 11:56 import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUT...
StarcoderdataPython
1620706
from ._client import SlackClient
StarcoderdataPython
1606513
from django.urls import path from movie_api import views app_name = 'api' urlpatterns = [ path('movies/', views.MovieApiView.as_view(), name='movies'), path('movies/<int:pk>/', views.MovieApiView.as_view()), path('comments/', views.CommentList.as_view(), name='comments'), path('comments/<int:pk>/', ...
StarcoderdataPython
143486
import random from random import randint import networkx as nx import math import matplotlib.pyplot as plt import Evaluation as eval #This is local search heuristic Simulated Annealing. def anneal_DS(old_solution, allocated_network_topology): #This is algortihm 9 - Optimize DDS placement #print('----------SA-----...
StarcoderdataPython
138103
from stacker.context import Context from stacker.config import Config from stacker.variables import Variable from stacker_blueprints.network import Network from stacker.blueprints.testutil import BlueprintTestCase class TestNetwork(BlueprintTestCase): def setUp(self): self.ctx = Context(config=Config({'na...
StarcoderdataPython
3288172
# -*- coding: utf-8 -*- from datetime import datetime from functools import wraps def cache_result(): """ 缓存结果 :return: """ def decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): if hasattr(func, "__result"): return func.__dict__['__re...
StarcoderdataPython