id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
106610
<reponame>OpenTelekomCloud/ansible_collections #!/usr/bin/python # 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 applic...
StarcoderdataPython
3261011
from django.db.models import QuerySet class ActiveQuerySet(QuerySet): """Active query set for models with is_active boolean field.""" def actives(self) -> QuerySet: """Filter only actives queryset.""" return self.filter(is_active=True)
StarcoderdataPython
143480
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayTradeRepaybillModifyModel(object): def __init__(self): self._amount = None self._bill_no = None self._bill_status = None self._operation_type = None ...
StarcoderdataPython
3223135
<reponame>bielrv/cs50w-HarvardX<filename>project1/import.py import os from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker import csv from datetime import datetime engine = create_engine('postgres://ficpljxencvllu:<EMAIL>@ec2-54-247-79-32.eu-west-1.compute.<EMAIL>.com:5432/dftm1...
StarcoderdataPython
96674
#!/usr/bin/python3 import sqlite3 import filecmp import os import subprocess os.system("python3 manage.py makemigrations CarSalon_App") os.system("python3 manage.py migrate CarSalon_App") os.system("python3 manage.py makemigrations") os.system("python3 manage.py migrate") os.system("python3 manage.py loaddata data") o...
StarcoderdataPython
1794782
#!/usr/bin/python3 # -*- coding: utf-8 -*- """Example Google style docstrings. """ from password import GMAIL_PASSWORD_KEY ALTERNATIVE = "alternative" ASSET = "asset" ASSET_IDX = 0 BALANCE = "balance" BINANCE = "Binance" BOTH = "BOTH" BNB = "BNB" BNBUSDT = "BNBUSDT" BTC = "BTC" BTCUSDT = "BTCUSDT" BUY = "BUY" BYB...
StarcoderdataPython
1704155
# -*- coding: UTF-8 -*- # # Given a linked list, remove the nth node from the end of list and return its head. # # For example, # # Given linked list: 1->2->3->4->5, and n = 2. # # After removing the second node from the end, the linked list becomes 1->2->3->5. # Note: # Given n will always be valid. # Try to do this i...
StarcoderdataPython
4837452
def rec_list_dir(path, rec=True): from os.path import isdir, isfile, exists from imghdr import what rst = [] if exists(path): if isdir(path) and rec: from os import listdir from os.path import join for f in listdir(path): rst += rec_list_dir(join(path, f)) elif isfile(path) and...
StarcoderdataPython
3254264
#!/usr/bin/env python3 import gzip import io import pickle import os import sys from argparse import ArgumentParser try: from .version import SalmID_version except ImportError: SalmID_version = "version unknown" def reverse_complement(sequence): """return the reverse complement of a nucleotide (includi...
StarcoderdataPython
147089
class WebOperationCollection: def __init__(self): self.id = None self.opt_type = None self.opt_name = None self.opt_trans = None self.opt_element = None self.opt_data = None self.opt_code = None @staticmethod def __parse(ui_data: dict, name): ...
StarcoderdataPython
124868
<reponame>jpotter/angel import os import re import sys import time from devops.generic_service import GenericService from angel.util.pidfile import is_pid_in_pidfile_running from angel.util.checksum import get_md5_of_path_contents from devops.simple_cache import simple_cache_get, simple_cache_set from angel.stats.disk...
StarcoderdataPython
3367882
# Generated with SMOP 0.41 from libsmop import * # MatInv.m @function def MatInv(matrixSize=None,mX=None,mY=None,*args,**kwargs): varargin = MatInv.varargin nargin = MatInv.nargin mY=dot(mX.T,mX) # MatInv.m:3 mA=inv(mY) # MatInv.m:5 mB=pinv(mX) # MatInv.m:6 mA=mA + mB # MatInv.m:8 re...
StarcoderdataPython
78659
<reponame>rakhi2001/ecom7 __________________________________________________________________________________________________ sample 476 ms submission class Solution: def countTriplets(self, A: List[int]) -> int: n=len(A) tmp=[bin(a)[2:].zfill(16) for a in A] one={} for i,a in enumera...
StarcoderdataPython
1790874
<gh_stars>100-1000 import time from breakout_bmp280 import BreakoutBMP280 from pimoroni_i2c import PimoroniI2C PINS_BREAKOUT_GARDEN = {"sda": 4, "scl": 5} PINS_PICO_EXPLORER = {"sda": 20, "scl": 21} i2c = PimoroniI2C(**PINS_BREAKOUT_GARDEN) bmp = BreakoutBMP280(i2c) while True: reading = bmp.read() print(rea...
StarcoderdataPython
3217641
<reponame>kaysen820/PyHuTool # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function __version__ = "0.1.1" __author__ = "kaysen"
StarcoderdataPython
3208474
<gh_stars>10-100 # pylint: disable=missing-docstring import re from esperanto_analyzer.speech import Numeral from esperanto_analyzer.analyzers.morphological import BaseMorphologicalAnalyzer class NumeralMorphologicalAnalyzer(BaseMorphologicalAnalyzer): # These are the basics numbers names in Esperanto BASIC_N...
StarcoderdataPython
3384738
<reponame>huangbuhuan/qqbot # -*- coding: utf-8 -*- import requests import schedule import time from datetime import datetime import threading def startJob(): while True: schedule.run_pending() time.sleep(1) t = threading.Thread(target=startJob, name='LoopThread') t.start() url = 'http://api.shu...
StarcoderdataPython
3386386
import discord, aiohttp, asyncio from .webhookhandler import WebhookHandler class Client: def __init__(self): self._webhook_handler = WebhookHandler() self._loop = asyncio.get_event_loop() self._session = aiohttp.ClientSession(loop=self._loop) def send_event(self, coro): se...
StarcoderdataPython
1783573
from openpyxl import load_workbook from openpyxl.styles import PatternFill from pyecharts.charts import Bar, Pie from pyecharts import options as opts from pyecharts.options import InitOpts, TitleOpts, ToolboxOpts from pyecharts.globals import ThemeType import sys WARNING_STRING = """ -> 请确保请假考勤按以下格式填写,如: -> 事假: 事8 ->...
StarcoderdataPython
3207083
<filename>Lesson17_FunctionArguments/10-PositionalArgUnpacking.py from os.path import join def shout_strings(*args): for argument in args: print(argument.upper()) shout_strings("hi", "what do we have here", "cool, thanks!") # Prints out: # "HI" # "WHAT DO WE HAVE HERE" # "COOL, THANKS!" def truncate_sentence...
StarcoderdataPython
1714045
from .tasks import SetupTask from .tasks import InvokeTask from .tasks import MakeZipTask from .tasks import AWSLambdaGetConfigTask from .tasks import AWSLambdaInvokeTask from .tasks import AWSLambdaUpdateCodeTask
StarcoderdataPython
1642378
<gh_stars>0 import os ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # This is your Project Root MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) # This is the module Root
StarcoderdataPython
1623809
# -*- encoding: utf-8 -*- from .. import log_cis, pformat print log_cis.info(">>> reading settings.app_settings.py ") ### vars for name application / metas app_metas = { "title" : u"carrefour des innovations sociales", ### dataioio.com | coralcommons.com/io | tadata.io | coraless.io | solidata.io "subtitle" ...
StarcoderdataPython
3277636
# coding: utf-8 """ Wavefront Python SDK <p>This is a Wavefront Python SDK</p> # noqa: E501 """ from setuptools import setup, find_packages # noqa: H301 NAME = "wavefront-sdk-python" VERSION = "1.0.0" # To install the library, run the following # # python setup.py install # # prerequisite: setuptools # htt...
StarcoderdataPython
1609932
"""Tests for scripts/interwikidata.py.""" # # (C) Pywikibot team, 2015-2021 # # Distributed under the terms of the MIT license. # import unittest from contextlib import suppress import pywikibot from pywikibot import Link from scripts import interwikidata from tests.aspects import SiteAttributeTestCase from tests....
StarcoderdataPython
3230681
<filename>src/app/views/network.py from app import app from flask import request from flask import jsonify from app.utils.myencrypt import create_key, verify_key from app.main.network import NetWork from app.main.service import Service from app import work_log @app.route("/api/v2/network", methods=["GET", "POST"]) def...
StarcoderdataPython
20728
# $Filename$ # $Authors$ # Last Changed: $Date$ $Committer$ $Revision-Id$ # # Copyright (c) 2003-2011, German Aerospace Center (DLR) # # All rights reserved. #Redistribution and use in source and binary forms, with or without #modification, are permitted provided that the following conditions are # #met: # ...
StarcoderdataPython
30265
#!/usr/bin/env ipython import numpy as np #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ class gral(): def __init__(self): self.name = '' sh, mc = gral(), gral() cr = gral() cr.sh, cr.mc = gral(), gral() vlo, vhi = 550.0, 3000.0 #550., 3000. #100.0, 450.0 #...
StarcoderdataPython
17500
<reponame>vrevelas/awx<filename>awxkit/test/cli/test_client.py<gh_stars>0 from io import StringIO import pytest from requests.exceptions import ConnectionError from awxkit.cli import run, CLI class MockedCLI(CLI): def fetch_version_root(self): pass @property def v2(self): return Mocked...
StarcoderdataPython
138245
import ca3 as ca g = 19 h = 24717 Fp = 48611 res = ca.pollard_rho(g, h, Fp) assert(res == 37869)
StarcoderdataPython
33673
<reponame>josivantarcio/Desafios-em-Python<gh_stars>0 frase = str(input('Digite a frase: ')).strip().upper() palavras = frase.split() juntarPalavras = ''.join(palavras) trocar = juntarPalavras[::-1] print(trocar)
StarcoderdataPython
3280870
import numpy as np def knn_finder(x_train, y_train, x_test): sim = np.matmul(x_train, x_test.T) max_index = np.argmax(sim) return y_train[max_index] def predict_image_label(): x_train = np.load('x_train.npy') y_train = np.load('y_train.npy') x_test = np.load('x_test.npy') y_pred = np.ze...
StarcoderdataPython
3306860
<reponame>varunvarma/panoptes<gh_stars>0 """ Copyright 2018, Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE file in project root for terms. This module implements Heartbeat EnrichmentGroup defined with schema validator """ from yahoo_panoptes.framework.enrichment import \ PanoptesEnrich...
StarcoderdataPython
4807151
# https://stats.stackexchange.com/questions/89484/how-to-compute-the-standard-errors-of-a-logistic-regressions-coefficients # The standard errors of the model coefficients are the square roots of the diagonal entries of the covariance matrix. # Consider the following: # Design matrix: # X = ⎡1 x_1,1 ... x_1,p⎤ # ...
StarcoderdataPython
1629627
<filename>tests/__init__.py """Unit test package for validate_cnpj."""
StarcoderdataPython
1616
<gh_stars>1-10 """ 读取PDF文件 Version: 0.1 Author: BDFD Date: 2018-03-26 """ from PyPDF2 import PdfFileReader with open('./res/Python课程大纲.pdf', 'rb') as f: reader = PdfFileReader(f, strict=False) print(reader.numPages) if reader.isEncrypted: reader.decrypt('') current_page = reader.getPage(5) ...
StarcoderdataPython
3279498
<reponame>btozer/gmt-python<filename>gmt/clib/session.py """ Defines the Session class to create and destroy a GMT API session and provides access to the API functions. Uses ctypes to wrap most of the core functions from the C API. """ import sys import ctypes as ctp from contextlib import contextmanager from packagin...
StarcoderdataPython
190097
import os from .settings_dev import * ######### # Setup # ######### FIXTURE_DIRS = ( PROJECT_ROOT, ) ############# # Overrides # ############# RUN_TASKS_ASYNC = False # avoid sending celery tasks to queue -- just run inline SUBDOMAIN_URLCONFS = {} DEBUG = False TESTING = True ADMINS = ( ("<NAME>", '<E...
StarcoderdataPython
4804183
#! /usr/bin/jython # -*- coding: utf-8 -*- # # berkeley_delete.py # # Aug/23/2010 import sys #import json from bsddb import db import string # sys.path.append ('/var/www/uchida/data_base/common/python_common') from text_manipulate import hash_update_proc #from dbm_manipulate import dbm_disp_proc,dbm_delete_proc # -...
StarcoderdataPython
71037
<gh_stars>1-10 import os import shutil import subprocess import sys import tempfile ## Fixture # Creates a temporary directory to hold bossfiles. oldcwd = os.getcwd() tempdir = None def run_bossy(*args): p = subprocess.Popen( ['python', '-m', 'bossy.main'] + list(args), executable=sys.executabl...
StarcoderdataPython
3203232
# plot g(r) import pandas as pd import numpy as np import matplotlib.pyplot as plt kap = 10 lam = [11] for j in lam: fname = 'rdfdata.csv' data=pd.read_csv(fname, header=None) print(data) plt.scatter(data[0],data[1],label=('$\lambda=$'+str(j))) plt.legend() plt.show()
StarcoderdataPython
1695268
<reponame>ronikobrosly/causal-curve<filename>causal_curve/__init__.py """causal_curve module""" import warnings from statsmodels.genmod.generalized_linear_model import DomainWarning from causal_curve.gps_classifier import GPS_Classifier from causal_curve.gps_regressor import GPS_Regressor from causal_curve.tmle_reg...
StarcoderdataPython
54811
<reponame>nel215/lightgbm-mean-teacher from chainer import reporter as reporter_module from chainer.dataset import convert from chainer.training.extensions import Evaluator from chainer.backends import cuda from sklearn.metrics import roc_auc_score class AUCEvaluator(Evaluator): def evaluate(self): itera...
StarcoderdataPython
1671769
<reponame>notwarp/armory<filename>blender/arm/logicnode/native/LN_script.py import bpy from arm.logicnode.arm_nodes import * class ScriptNode(ArmLogicTreeNode): """Executes the given script.""" bl_idname = 'LNScriptNode' bl_label = 'Script' arm_section = 'haxe' arm_version = 1 @property ...
StarcoderdataPython
140588
#!/usr/bin/env python # Copyright (c) 2014 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Make sure safeseh setting is extracted properly. """ import TestGyp import sys if sys.platform == 'win32': test = TestGyp.TestGyp()...
StarcoderdataPython
1626617
# Author: StevenChaoo # -*- coding=UTF-8 -*- import argparse import torch import torch.distributed as dist from data_loader import load_and_cache_examples from trainer import Trainer from utils import init_logger, load_tokenizer, set_seed def main(args): # Initialize logger configurations in...
StarcoderdataPython
96427
<reponame>sionab/simmate # -*- coding: utf-8 -*- import os def set_default_executor(dask_scheduler_address): """ If you want to start a Prefect Agent that uses a specific Dask Cluster for all workflow runs, you can run this function before starting your Prefect Agent. What it does is set two env...
StarcoderdataPython
1775577
from manimlib.imports import * class Levy(VMobject): def __init__(self, start, end, it, **kwargs): self.start = start self.end = end self.it = it VMobject.__init__(self, **kwargs) def get_point(self, p1, p2): v = (p2 - p1) / 2 [x, y] = v[0:2] rv = y * R...
StarcoderdataPython
50962
import hashlib import io import sys from typing import Optional from PIL import Image, ImageOps from django.core import checks from django.core.files.uploadedfile import InMemoryUploadedFile from django.db.models import ImageField class ResizedHashNameImageField(ImageField): """A custom ImageField class that wil...
StarcoderdataPython
1674744
#!/usr/bin/python3 import shasta import GetConfig # Read the config file. config = GetConfig.getConfig() # Initialize the assembler and access what we need. a = shasta.Assembler() a.accessMarkers() a.accessAlignmentData() a.accessCompressedAlignments() a.accessMarkerGraphVertices(readWriteAccess = True) a.accessMark...
StarcoderdataPython
154144
<gh_stars>1-10 from zope.interface import implementer from sqlalchemy import ( Column, Unicode, Integer, ForeignKey, UniqueConstraint, or_, and_, ) from sqlalchemy.orm import relationship, aliased, joinedload, backref from clld import interfaces from clld.db.meta import Base, CustomModelMix...
StarcoderdataPython
3336331
<reponame>fpiantini/jokettt_demo<gh_stars>0 #!/usr/bin/env python3 # """Play tic-tac-toe games between a learner players and another AI player (minimax, random or another learner). At the end of the training save the 'learned' data""" from argparse import ArgumentParser, ArgumentTypeError import os import sys i...
StarcoderdataPython
3282800
<filename>tests/server/test_env.py # Tests of server/env.py import os import random import pytest from server.env import Env, NetIdentity import lib.coins as lib_coins BASE_DAEMON_URL = 'http://username:password@hostname:7574/' BASE_DB_DIR = '/some/dir' base_environ = { 'DB_DIRECTORY': BASE_DB_DIR, 'DAEM...
StarcoderdataPython
122626
<gh_stars>0 # coding: utf-8 from django import forms from .models import Doctor, Reception from django.contrib.admin import widgets import datetime class ReceptionForm(forms.ModelForm): class Meta: model = Reception fields = ['date','time','patient_name','patient_info'] def __init__(self, *arg...
StarcoderdataPython
4805470
import sys import os import string import collections import codecs import re import json import traceback import getopt from string import Template TypeMapping = { "INT" : "int", "STRING" : "string", "BOOL" : "bool", "FLOAT" : "float", "STRING_ID" : "StringID", "RES_PATH" : "Resourc...
StarcoderdataPython
99879
<gh_stars>10-100 from collections.abc import Sequence from itertools import chain import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dense from tensorflow.python.framework.smart_cond import smart_cond from .set_utils import ( build_dense_dropout_model, PaddedToSegments, SegmentAggregat...
StarcoderdataPython
126059
from __future__ import annotations import dataclasses from pathlib import Path from textwrap import dedent from typing import List from typing import Union OFFSET = ' ' * 4 @dataclasses.dataclass class File: path: Path def read_content(self) -> str: return self.path.read_text() @dataclasses.datac...
StarcoderdataPython
179219
<gh_stars>0 from maltego_trx.entities import Phrase from maltego_trx.transform import DiscoverableTransform from maltego_trx.maltego import UIM_PARTIAL import requests class LookUpTorExit(DiscoverableTransform): """ Check if an IP is a Tor Exit Node and Returns a Phrase """ @classmethod ...
StarcoderdataPython
1722626
""" batch mode """ # TODO look into Mesa's BatchRunner class... import json import time import pandas as pd import argparse from collections import Counter # suppress deprecation warning we can't do anything about import warnings warnings.filterwarnings(action='ignore', category=FutureWarning, module=r'.*pyproj' ) ...
StarcoderdataPython
1653572
# Display the following using the range() function and a for-loop # i) the table for numbers from 1 to 10; with a total at the end of all the cubes # ii) the table for values from 0 to 100 in steps of 10, with a total at the end of all the cubes # Your program should display the number then its cube (the number multipl...
StarcoderdataPython
3275437
import queue import threading import time import unittest from typing import Union from blatann.event_args import PasskeyDisplayEventArgs, PasskeyEntryEventArgs from blatann.gap import SecurityStatus, SecurityLevel, IoCapabilities, PairingPolicy, SecurityParameters from blatann.peer import Client, Peripheral...
StarcoderdataPython
61038
import subprocess import os """ Much of the generated code is based on code internal to quickjs with minor changes. Generated IDL files are header files that provide basic declarations and wrappers. The normal function signature for quickjs is... JSValue js_std_gc(JSContext *ctx, JSValueConst this_val, int argc, JS...
StarcoderdataPython
35894
<reponame>cdc08x/automated-flight-diversion-detection import logging predictLogger = logging.getLogger(__name__) def predictDiversion(trajectory, classification, decfunout, threshold): severities = computeSeverities(trajectory, decfunout, threshold) (diversionDetections, firstDetectionIndex) = catchDive...
StarcoderdataPython
3314715
# Import required packages import requests import json from spatialite_database import SpatialiteDatabase import sqlite3 import csv import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def get_report(data_url_path): """ Reads the data from the url and converts to text. Additionally, i...
StarcoderdataPython
1624898
<filename>settings.py from sys import platform NGINX_PATH={} LOG_PATH={} if platform == "darwin": DEVICE="mac" NGINX_PATH[DEVICE] = "/usr/local/etc/nginx" LOG_PATH[DEVICE] = "/usr/local/var/log/nginx" elif platform == "linux": DEVICE="ubuntu" NGINX_PATH[DEVICE] = "/etc/nginx" LOG_PATH[DEVICE] = ...
StarcoderdataPython
45111
from __future__ import absolute_import from unittest import TestCase from plotly import exceptions from plotly.graph_objs import Bar, Frames class FramesTest(TestCase): def test_instantiation(self): native_frames = [ {}, {'data': []}, 'foo', {'data': [],...
StarcoderdataPython
141632
<reponame>nextflow/ucloud-sdk-python3 import typing import logging import json as json_mod from ucloud.core import exc from ucloud.core.transport import utils from ucloud.core.utils.compat import str logger = logging.getLogger(__name__) class Request: def __init__( self, url: str, method...
StarcoderdataPython
3354300
import logging from upbit.utils import Version __all__ = ['client', 'websocket'] __module_name__ = 'upbit-client' __version__ = '1.1.6.29' __released_version__ = Version.get_versions(__module_name__) __latest_version__ = __released_version__[0] if __latest_version__ != __version__: logging.bas...
StarcoderdataPython
1782246
<reponame>qnomon/Python-Studies v = float(input('Digite o valor do produto ')) cond = int(input('Digite [1] para pagamento a vista com dinheiro ou cheque;\nDigite [2] para pagamento a vista no cartão\nDigite [3] para pagamento de 2x no cartão\nDigite [4] para pagamento 3x ou mais no cartão: ')) if cond == 1 : print...
StarcoderdataPython
3275222
# Cálculo de IMC com condições aninhadas print() peso = float(input('Informe seu peso: ')) print() altura = float(input('Informe sua altura em metros: ')) print() imc = peso / altura ** 2 if(imc < 18.5): print('Abaixo do peso.') elif(imc >= 18.5 and imc <= 25): print('Peso ideal.') elif(imc > 25 and imc <= 30):...
StarcoderdataPython
176794
<reponame>shiyuechengineer/adventure-lab import meraki from chatbot import * SWITCH_SERIAL = 'Q2AB-1234-CDEF' SWITCH_PORT = 8 # Disable port's PoE to trigger webhook alert def disable_port(session, headers, payload, api_key): response = meraki.getswitchportdetail(api_key, SWITCH_SERIAL, SWITCH_PORT) if not ...
StarcoderdataPython
3200957
from collections import Counter import unittest from solutions.CHK import checkout_solution class TestLoadPrices(unittest.TestCase): def test_load_prices(self): prices, deals = checkout_solution.load_prices() self.assertEqual(len(prices), 26) self.assertEqual(len(deals), 15) class TestP...
StarcoderdataPython
3186
<filename>test/unittest_base.py # Copyright 2018 Tensorforce Team. 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 # # ...
StarcoderdataPython
87399
<reponame>cmu-lib/campi # Generated by Django 3.0.6 on 2020-05-29 14:14 import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('photograph', '0001_initial'), ] o...
StarcoderdataPython
3398533
<reponame>LazeMSS/OctoPrint-Printoid from io import BytesIO ## for Python 2 & 3 import requests from PIL import Image from .alerts import Alerts class JobNotifications: _lastPrinterState = None def __init__(self, logger): self._logger = logger self._alerts = Alerts(self._logger) def set_progress_mode(self...
StarcoderdataPython
1607162
# Generated by Django 2.2.24 on 2021-08-18 06:14 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('content_libraries', '0005_contentlibraryblockimporttask'), ('content_libraries', '0006_auto_20210615_1916'), ] operations = [ ]
StarcoderdataPython
1750774
<reponame>osso73/contabilidad<filename>conta/main/views.py import datetime from django.shortcuts import render from django.views import View from django.http import HttpResponseRedirect from django.urls import reverse from django.db.models.deletion import ProtectedError from django.contrib.auth.decorators import login...
StarcoderdataPython
1691001
from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, antecedents, out_attributes, user_options, num_cores, outfile): import subprocess from Betsy import module_utils from genomi...
StarcoderdataPython
134974
#!/usr/bin/env python2.7 import sys def notify_mayhem(): import os os.kill(os.getpid(),11) #exec'()'*7**6 def my_sqrt(x): """Computes the square root of x, using the Newton-Raphson method""" approx = None guess = x / 2 while approx != guess: approx = guess guess = (appr...
StarcoderdataPython
189155
<gh_stars>1-10 def swap_case(s): t="" for i in s: if i.isalpha(): if i.isupper(): t=t+i.lower() else: t=t+i.upper() else: t=t+i return (t)
StarcoderdataPython
1665874
from django.db import models from django.contrib.auth.models import AbstractUser from django.core.validators import RegexValidator, MinValueValidator, MaxValueValidator from .managers import UserManager from customer.models import VehicleTypeChoices, Vehicle from django.utils import timezone class UserTypeChoices(model...
StarcoderdataPython
1689640
# -*- coding: utf-8 -*- from pip_services3_expressions.io.IScanner import IScanner from pip_services3_expressions.tokenizers.ITokenizer import ITokenizer from pip_services3_expressions.tokenizers.Token import Token from pip_services3_expressions.tokenizers.TokenType import TokenType from pip_services3_expressions.toke...
StarcoderdataPython
1659400
''' Copyright (c) 2020 Fractus IT d.o.o. <http://fractus.io> ''' import keras import numpy as np from keras.applications import vgg16, resnet50, mobilenet, inception_v3 from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array from keras.applications.imagenet_utils...
StarcoderdataPython
1656827
import gym from gym import spaces import numpy as np import os from collections import defaultdict import matplotlib; matplotlib.use('Agg') import matplotlib.pyplot as plt class DiscretizedObservationWapper(gym.ObservationWrapper) : def __init__(self, env, n_bins = 10, low = None, high = None) : super()._...
StarcoderdataPython
1630686
<reponame>youngershen/kungfucms # PROJECT : kungfucms # TIME : 2019/11/18 17:36 # AUTHOR : <NAME> # EMAIL : <EMAIL> # CELL : 13811754531 # WECHAT : 13811754531 # https://github.com/youngershen/ from django.urls import path from kungfucms.apps.account.api import sign_in urlpatterns = [ path('sign-in', sign_in, na...
StarcoderdataPython
4830044
<gh_stars>0 import torch import torch.nn as nn kl_loss = nn.KLDivLoss(reduction='batchmean').cuda() def knowledge_distill_loss(outputs, outputs_student): T = 3.0 P = nn.functional.softmax(outputs_student / T, dim=1) Q = nn.functional.softmax(outputs / T, dim=1) M = 0.5 * (P + Q) P = torch.clamp(P...
StarcoderdataPython
4841729
<reponame>KeerthanaPravallika/OpenOctober<filename>EthicalHacking/Cryptography/Server/Server.py import socket, os import onetimepad as otp from tkinter import * from tkinter import messagebox s = socket.socket() s.bind(('127.0.0.1',8888)) s.listen(1) c,addr = s.accept() def Encrypt_Window(): master = Tk() maste...
StarcoderdataPython
8926
import sys sys.path = ['', '..'] + sys.path[1:] import daemon from assistance_bot import core from functionality.voice_processing import speaking, listening from functionality.commands import * if __name__ == '__main__': speaking.setup_assistant_voice(core.ttsEngine, core.assistant) while True: # st...
StarcoderdataPython
3396552
<filename>admin/admin.py from flask import Blueprint, request, jsonify, session, render_template from flask_login import login_required admin = Blueprint('admin', __name__) @login_required @admin.route('/welcome', methods=['GET']) def admin_on_boarding(): pass @login_required @admin.route('/dashboard', methods...
StarcoderdataPython
1694379
""" Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more...
StarcoderdataPython
3344258
<reponame>reloadware/reloadium from typing import TYPE_CHECKING, Any, Callable, List, Optional from reloadium.vendored.envium.exceptions import EnviumError if TYPE_CHECKING: pass from reloadium.vendored.envium.vars import ComputedMixin, Var, VarGroup, VarType __all__ = ["ctx_var", "Ctx", "computed_ctx_var", "Ct...
StarcoderdataPython
48814
<filename>tests/xpath_first_test.py import unittest import lxml.etree import webracer.utils class AbsolutizeUrlTest(webracer.WebTestCase): def setUp(self): xml = '<root><el><child><grandchild>text</grandchild></child></el></root>' self.doc = lxml.etree.XML(xml) def test_xpath_first_found(s...
StarcoderdataPython
194193
<reponame>stefanv/scikits.gpu<filename>scikits/gpu/tests/test_texture.py<gh_stars>1-10 from nose.tools import * from scikits.gpu.texture import * import pyglet.gl as gl def test_creation(): Texture(20, 20) Texture(20, 25) #def test_texture_target(): # assert_equal(texture_target(16, 16), gl.GL_TEXTURE_2D)...
StarcoderdataPython
1679395
""" By <NAME> (DTAI lab KU Leuven, 2019) A script to evaluate and create a mean squared sampled error (MSSE) plot for each epoch in the learning process. The mean squared sampled error is obtained by sampling from the correct model and comparing the utility of the sample with the utility according to the found_utiliti...
StarcoderdataPython
3381100
<gh_stars>1-10 def sumNaturalNumbers(n: int) -> int: return n * (n + 1) // 2 rows = int(input()) # upper triangle number = 1 for i in range(rows): for j in range(i + 1): print(number if j == i else f'{number}*', end='') number += 1 print() # lower triangle for i in range(rows): numbe...
StarcoderdataPython
3335508
import os import glob import json from numba import njit import xml.dom.minidom from xml.dom import minidom path = "F:\\0903modeldata\\labels\\" img_list = glob.glob(path + "*.json") width = 0 height = 0 # 自行填写当前文件夹,假如文件路径分割数组长度为1 folder = "" def get_annotation(labels): res = [] for i in ran...
StarcoderdataPython
3304632
import logging import bcrypt from .model import User from tangled.util import constant_time_compare log = logging.getLogger(__name__) def user_id_validator(request, user_id): """Ensure user (still) exists and return canonical ID. This is called by the registered Authenticator. ``user_id`` *must* be ...
StarcoderdataPython
1695528
# A context has all information necessary to generate schedules # Basically with a Node and a context, we can generate new Nodes # Each node is an assignment of a schedule # A schedule assignment is made by concantenating schedules from # root to leaf node from treelib import Node, Tree class ScheduleNode: """ A...
StarcoderdataPython
3321289
"""View suite.""" from django.shortcuts import render, get_object_or_404 # Create your views here. from django.http import HttpResponseRedirect # from django.template import loader from django.urls import reverse from django.views import generic from django.utils import timezone from .models import Question, Choice ...
StarcoderdataPython
154323
<gh_stars>10-100 #!/usr/bin/env python2.7 # -*- coding: utf8 -*- # import pip # pip.main(['-q', 'install', 'cymruwhois']) # pip.main(['-q', 'install', 'dpkt']) # pip.main(['-q', 'install', 'simplejson']) try: import dpkt except: print "Download dpkt" try: import cymruwhois except: print "Download ...
StarcoderdataPython