text
string
size
int64
token_count
int64
import urllib2 import json import base64 import time import ssl """ define our rubrik credentials """ RUBRIK_IP='rubrik.demo.com' RUBRIK_USER='admin' RUBRIK_PASS='mypassword123!' """ ignore self-signed certs """ ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # get the repo...
1,720
633
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
2,476
790
import numpy as np import pandas as pd from sklearn.metrics import silhouette_samples, silhouette_score from sklearn.metrics import confusion_matrix, accuracy_score, recall_score, precision_score, f1_score,roc_auc_score,roc_curve from sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score import ma...
18,341
6,768
import re from urlparse import urlparse from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from plone.app.layout.viewlets.common import ViewletBase ZOTERO_JSON_BASE = 'https://api.zotero.org{}?v=3&format=json' Z_MATCH = re.compile(r'^/(groups|users)/\d+/items/[A-Z1-9]+$') class PublicationZotero...
845
300
#!/usr/bin/env python import argparse import json import jinja2 import webbrowser import graph if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('groups', help='json file describing seed groups') args = parser.parse_args() # load group from file with open(args.gro...
1,079
350
"Actual (primitive) types instanitated in the type system." import sys from .typesys import * class np: # Dummy class ndarray: pass int32 = TCon("Int32") int64 = TCon("Int64") float32 = TCon("Float") double64 = TCon("Double") void = TCon("Void")
268
106
import sys from numbers import Real from hypothesis import given from cfractions import Fraction from tests.utils import (equivalence, is_fraction_valid, skip_reference_counter_test) from . import strategies @given(strategies.fractions) def test_basic(fraction: Frac...
2,735
898
# -*- coding: utf-8 -*- """ flag.parser ~~~~~~~~~~~ """ import argparse from . import registry def parse(): parser = argparse.ArgumentParser() for flag in registry.iter(): flag.add_to_parser(parser) args = vars(parser.parse_args()) for flag in registry.iter(): flag.update(a...
336
113
def format_number(number: float, precision: int) -> str: return f'{number:.{precision}f}'
93
32
import json import pandas as pd import numpy as np import random from Sqldatabasehandler import sqlhandler from datetime import datetime from sklearn.linear_model import SGDClassifier from sklearn.preprocessing import PolynomialFeatures import pickle import torch from torch import nn import torch.optim as optim from ...
14,375
4,814
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch from torch.nn import functional as F def crop_mask_within_box(mask, box, mask_size): """ Crop the mask content in the given box. The cropped mask is resized to (mask_size, mask_size). This function is used when genera...
2,227
739
from fastapi import APIRouter, Depends from fastapi_plus.schema.base import ListArgsSchema, RespListSchema, RespIdSchema, RespBaseSchema from fastapi_plus.utils.auth import get_auth_data from fastapi_plus.utils.custom_route import CustomRoute from ..schema.org import OrgInfoSchema, OrgRespDetailSchema from ..service.o...
1,727
665
#!/usr/bin/env python # coding=utf8 import os TOP = os.path.abspath('.') STATIC = os.path.join(os.path.abspath('.'), 'static', 'exe') ALLOWED_EXTENSIONS = set(['py']) def allowed(filename): return '.' in filename and filename.rsplit('.')[-1] in ALLOWED_EXTENSIONS def exepath(filename): filepath = os.path.joi...
652
238
import unittest from django.contrib.redirects.models import Redirect from django.contrib.sites.models import Site from django.db.utils import IntegrityError from django.test import TestCase class Redirects(TestCase): def test_redirect_from_existing_page(self): """`refarm-site.redirects` app should redir...
1,896
567
# flake8: noqa # FIXME: find sol for F403 error (caused by import *), most likely need to import everything by hand from .sg_module import * from super_gradients.training.models.classification_models.densenet import * from super_gradients.training.models.classification_models.dpn import * from super_gradients.training....
1,448
409
from selenium.common.exceptions import NoAlertPresentException import nerodia from .exception import UnknownObjectException from .wait.wait import Waitable, TimeoutError class Alert(Waitable): def __init__(self, browser): self.browser = browser self.alert = None @property def text(self):...
2,327
648
from finetwork.distance_calculator import _distance_metrics import pandas as pd class CalculateDistance: def __init__(self, data, method='pearson', scaled=False, sigma = 0.5): self.data = data self.method = method self.scaled = scaled self.sigma = sigma ...
1,448
427
#!/usr/bin/python3 # -*- encoding: utf-8 -*- __version__ = 1.2 from tkinter.ttk import * from tkinter.messagebox import * from tkinter.scrolledtext import * from tkinter import * from bs4 import BeautifulSoup from urllib.request import urlopen from mailcomposer import MailComposer from threading import Thread import ...
27,818
9,320
#!/usr/bin/env python """ Copyright 2015 Brocade Communications Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by appl...
5,480
1,466
''' 面试题51. 数组中的逆序对 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。 示例 1: 输入: [7,5,6,4] 输出: 5 限制: 0 <= 数组长度 <= 50000 https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/ 执行用时 :1564 ms, 在所有 Python3 提交中击败了85.67%的用户 内存消耗 :18.5 MB, 在所有 Python3 提交中击败了100.00%的用户 ''' # merge-sort # test cases: # 1...
1,929
787
# File: greynoise_connector.py # # Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) # Python 3 Compatibility imports from __future__ import print_function, unicode_literals # Phantom App imports import phantom.app as phantom from phantom.base_connector import BaseConnector from phantom.acti...
21,954
6,085
class MainLoopModule(object): def __init__(self, trainer): self.trainer = trainer self.train_loader = trainer.data_loaders["train"] self.config = trainer.config self.device = trainer.device self.seed = trainer.seed self.tracker = self.trainer.tracker self.crit...
1,044
317
import subprocess import sys def dump(url): try: return subprocess.Popen(['pg_dump', url], stdout=subprocess.PIPE) except OSError as err: print(f"Error: {err}") sys.exit(1) def dump_file_name(url, timestamp=None): db_name = url.split('/')[-1] db_name = db_name.split('?')[0] if timestamp: return f"{db_na...
373
155
numero_vogal = 0 espaço = 0 numero_consoante = 0 contador = 0 escrita = 0 arquivo = input('Digite o nome do seu arquivo (.txt): ') with open(arquivo, 'w', encoding='utf-8') as texto: while escrita != 'sair': escrita = input('Digite: ') texto.write(escrita) texto.write(...
1,190
555
# -*- coding: utf-8 -*- from base64 import b64encode, b64decode from unittest import mock from django.conf import settings from django.http import HttpResponseRedirect from django.test import TestCase, Client from django.urls import reverse from testutils import factories from urllib.parse import urlparse, parse_qs ...
7,249
2,226
"""ensembl interaction function""" import os import requests, sys import yaml import logging import gffutils from collections import defaultdict import mammoth.logger as mylog server = "http://rest.ensembl.org{ext}" ext = "/sequence/id/{id}?type=cds" prot = "/sequence/id/{id}?type=protein" sequence = "/sequence/reg...
2,843
922
# -*- coding: utf-8 -*- # 2013-03, Erik Svensson <erik.public@gmail.com> # Licensed under the MIT license. import unittest import transmissionrpc class TopTest(unittest.TestCase): def testConstants(self): self.assertTrue(isinstance(transmissionrpc.__author__, str)) self.assertTrue(isin...
906
296
# __init__.py from ._sgRNA_Library import _sgRNA_Library as Library # functions from ._gene_annotation_functions._merge_reduce_gene_regions import _merge_reduce_gene_regions as merge_reduce from ._guide_annotation_functions._annotate_biochemistry import _annotate_biochemistry as annotate_biochemistry, _annotate_GC_c...
389
127
__copyright__ = """ Copyright (c) 2021 HangYan. """ __license__ = 'MIT license' __version__ = '1.0' __author__ = 'topaz1668@gmail.com' from models import conn_db, UploadFiles from sqlalchemy import func, distinct, or_, and_ import datetime from datetime import timedelta import time import math def string_to_ts(str_t...
10,317
4,246
""" """ import datetime import unittest import numpy from math import pi import oyb from oyb import earth, anomaly class ClassTests(unittest.TestCase): def test_default(self): o = oyb.Orbit() def test_args(self): o = oyb.Orbit(a_m=1.064e7, e=0.42607, i_rad=39.687*pi/180, O_rad=130.32*...
4,490
2,376
#!/usr/bin/env python """ The actual jobArchiver algorithm """ import logging import os import os.path import shutil import tarfile import threading from Utils.IteratorTools import grouper from Utils.Timers import timeFunction from WMCore.DAOFactory import DAOFactory from WMCore.JobStateMachine.ChangeState import Chan...
11,656
3,180
#!/usr/bin/env python # coding: utf-8 import psycopg2 def executeScriptsFromFile(filename, cursor): '''Execute SQL create views''' fd = open(filename, 'r') sqlFile = fd.read() fd.close() sqlCommands = sqlFile.split(';') for command in sqlCommands: try: print(command) ...
1,795
511
from __future__ import print_function import argparse from math import ceil from random import Random from socket import socket import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR import...
5,127
1,719
# -*- codeing = utf-8 -*- # @Time : 2022/4/12 13:43 # @Author : linyaxuan # @File : one_scripts.py # @Software : PyCharm """ 将数据库数据导入es """ import pymysql import traceback from elasticsearch import Elasticsearch def get_db_data(): # 打开数据库连接(ip/数据库用户名/登录密码/数据库名) db = pymysql.connect(host="127.0.0.1:3306", use...
1,218
500
from django.test import TestCase from core.services.freckle import Freckle from datetime import datetime class TestServices(TestCase): """docstring for TestServices""" def setUp(self): self.client = Freckle('8zh8ny1wlym4ljyi68p0je410s1aj8b', 'andela') self.users = self.client.get_users() ...
1,048
365
#!/usr/bin/python # -*- coding: UTF-8 -*- # licensed under CC-Zero: https://creativecommons.org/publicdomain/zero/1.0 import pywikibot from pywikibot.data import api import re site = pywikibot.Site('wikidata', 'wikidata') site.login() repo = site.data_repository() def redirect(fromId, toId): # get...
1,343
467
class Solution: def XXX(self, digits: List[int]) -> List[int]: num = 0 ss = [] for i in range(len(digits)): num += digits[i]*(pow(10,len(digits)-i-1)) for i in str(num+1): ss.append(int(i)) return ss
271
97
from domanda1 import * import random import time class DPATrial: def __init__(self,m): self.numNodes = m self.nodeNumbers = list() for i in range(m): for _ in range(m): self.nodeNumbers.append(i) def runTrial(self,m): V = [] random.shuffle(s...
2,327
863
from typing import List class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: return permute_unique(nums) # https://leetcode.com/problems/permutations-ii/discuss/18602/9-line-python-solution-with-1-line-to-handle-duplication-beat-99-of-others-%3A-) def permute_unique(nums): r...
1,237
452
#MSO5x.py # Created on: 2020.11.18 # Author: ppudo # e-mail: ppudo@outlook.com # # Project: labtoys # Description: Class representing Tektronix MSO5 osciloscope series # # # Changelog: # -2021.11.18 version: 0.1.0 # - Initial class # #------------------------------------------------...
14,051
3,670
from pedurma.pecha import ProofreadNotePage from pedurma.utils import from_yaml def get_note_page_img_link(text_id, pg_num, repo_path): text_meta = from_yaml((repo_path / text_id / "meta.yml")) image_grp_id = text_meta.get("img_grp_id", "") img_link = f"https://iiif.bdrc.io/bdr:{image_grp_id}::{image_grp_...
1,543
604
import json from rest_framework import status, response from django.urls import reverse from .base import ArticlesBaseTest from .test_data import VALID_ARTICLE from authors.apps.authentication.tests.test_data import ( VALID_USER_DATA ) from rest_framework.test import APIClient, APITestCase from .base import BaseTes...
4,043
1,213
# -*- coding: utf-8 -*- """ Created on Wed Nov 3 04:38:07 2021 @author: User """ import sqlite3 connexion = sqlite3.connect("dbM2IQL.db") curseur = connexion.cursor() curseur.execute("""SELECT e.Nom, c.note FROM Etudiant as e INNER JOIN CF as c ON e.id = c.fk_etudiant ORDER BY c.note DESC LIMIT ...
353
157
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import utils import os import os.path import sys import subprocess import re import time filepath = os.path.dirname(os.path.realpath(__file__)) small_time_delay = 5 ##--> Use this to set up your small time delay. This time delay is in seconds. medium_time_delay = 20 ##--...
24,410
7,577
import numpy as np class Bandit: def __init__(self, k=10, mean=0): self.k = k self.q = np.random.randn(k) + mean self.old_q = [q_val for q_val in self.q] # copy def max_action(self): return np.argmax(self.q) def reward(self, action): return np.random.normal(self.q[action]) def reset(se...
349
144
#coding:utf-8 ######################### #Copyright(c) 2014 dtysky ######################### def EditFormat(US,UT): tmp={ 'sc':[ 0,('k'),{'k':'None'}, ('cp','sc'),{'cp':'None','sc':'None'} ], 'sw':[ 0,(),{}, ('s',),{'s':'None'} ], 'chrlast':[ 1,('l','t'),{'l':'None','t':'None'}...
1,765
1,045
from random import randint def ataque(): r = randint(1, 20) if r >= 18: print('DANO CRÍTICO!') elif r >= 8 or r < 18: print('DANO NORMAL!') elif r >= 3 or r < 8: print('DANO REDUZIDO!') else: print('ERRO!') ataque()
272
123
#!/usr/bin/env python3 """ Script to extract the gp bias features from microscopy images """ import sys import json import os import copy as cp import numpy as np import glob import matplotlib.pyplot as plt import matplotlib from numpy.polynomial import polynomial import offsets as GS from probability_dist import * imp...
6,850
2,600
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ A website monitor. """ import sys import traceback import requests import re import json import datetime DEFAULT_CONFIG_FILE = 'config.json' def check(): headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'...
2,448
863
#!/usr/bin/env python from __future__ import print_function import sys sys.path.insert(0, '.') from cloudmanager.board import MicropythonBoards for result in MicropythonBoards().execute("import os;print(os.uname())"): print(result.read().strip())
253
81
""" Name : c3_27_datadotworld_1.py Book : Hands-on Data Science with Anaconda) Publisher: Packt Publishing Ltd. Author : Yuxing Yan and James Yan Date : 1/15/2018 email : yany@canisius.edu paulyxy@hotmail.com """ import datadotworld as dw dataset = 'jonloyens/an-intro-to-dat...
412
155
import re import os import errno import string import subprocess import k3color listtype = (tuple, list) invisible_chars = ''.join(map(chr, list(range(0, 32)))) invisible_chars_re = re.compile('[%s]' % re.escape(invisible_chars)) def break_line(linestr, width): lines = linestr.splitlines() rst = [] spa...
15,964
5,189
import logging import math import numpy as np import pyglet import udSDK logger = logging.getLogger(__name__) class Camera(): """ Base camera class for Euclideon udSDK Python Sample This sets the default behaviour for a perspective camera Stores the state of the camera, and provides functions for modifyting ...
16,920
6,027
import sys class Menu(): @staticmethod def print_menu(): print (30 * "-" , "Text based adventure" , 30 * "-") print ("1. start adventure (intro)") print ("2. start adventure (no intro)") print ("3. help") print ("4. quit") print (67 * "-") print(" ")
316
99
""" Defines the parameter template for the specified data type. """ from .basicarray import BASICARRAY class ULONG64ARRAY(BASICARRAY): """ Defines the parameter template for the specified data type. """ pass def template(): """Factory method for this parameter template class""" return ULONG6...
337
102
# -*- coding: utf-8 -*- """Full Executer WordShop.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1kGSQWNtImJknauUN9L8ZRRwIzAdwbmo_ First, we load the pegasus paraphraser. """ # Commented out IPython magic to ensure Python compatibility. !git cl...
41,336
12,081
import torch import os from model.visualization import Visualization from panel.main import tensorboard_panel from torch.utils.data.dataset import Subset import random import numpy as np def write_on_tensorboard(epoch:int, loss:int, bleu:int, image, expected_captions, generated_captions): tensorboard_panel.add_senten...
4,831
1,796
from flask import jsonify from sqlalchemy import func from datetime import datetime, date from models.previsao import Previsao, db def configure(app): # /probabilidade - retorna a probabilidade total de chuva # - inicio (YYYY-MM-DD) # - fim (YYYY-MM-DD) @app.route('/probabilidade/<inicio>/<fim>', metho...
2,251
700
import sys,os import utils as cu params = cu.loadParams('fullList positivesList output') full = [x for x in open(params['fullList'])] positives = [x for x in open(params['positivesList'])] out = open(params['output'],'w') for r in full: if r not in positives: out.write(r) out.close()
293
105
import pytest from rollinghub.db import get_db def test_index(client, auth): response = client.get('/') assert b"Log In" in response.data assert b"Register" in response.data auth.login() response = client.get('/') assert b'Log Out' in response.data assert b'test title' in response.data ...
1,354
452
# -*- coding: utf-8 -*- """Load camera from FBX.""" from pathlib import Path import unreal from unreal import EditorAssetLibrary from unreal import EditorLevelLibrary from unreal import EditorLevelUtils from openpype.pipeline import ( AVALON_CONTAINER_ID, legacy_io, ) from openpype.hosts.unreal.api import plu...
19,672
5,404
#!/usr/bin/env python3 """ Main application file """ __author__ = "Armend Ukehaxhaj" __version__ = "1.0.0" __license__ = "MIT" from logzero import logger import numpy as np import pandas as pd import csv import pickle from word2vec import word2vec from preprocessor import preprocessor import json primary_data_filen...
2,862
926
"""Tests for ML models."""
27
9
from typing import Optional, List from pyspark.sql import Column, DataFrame from pyspark.sql.functions import coalesce, to_timestamp from spark_auto_mapper.data_types.column import AutoMapperDataTypeColumn from spark_auto_mapper.data_types.data_type_base import AutoMapperDataTypeBase from spark_auto_mapper.data_types...
2,378
636
# Generated by Django 3.2.9 on 2022-01-05 12:36 from django.db import migrations, models import django.db.models.manager class Migration(migrations.Migration): dependencies = [ ('registry', '0001_initial'), ] operations = [ migrations.AlterModelManagers( name='webfeatureserv...
1,425
390
# Python implementation of DBS PayLah! # By ttwj - 2017 import base64 import random import string #remember to install pycryptodome! import datetime from Crypto.Cipher import AES, PKCS1_v1_5 from Crypto.PublicKey import RSA import lxml.etree, json from lxml import html from pprint import pprint from io import String...
15,524
5,445
import streamlit as st import dill import pandas as pd import plotly.express as px from datetime import date import statsmodels with open('compiled-sentiment-history.pkd', 'rb') as f: df_compiled = dill.load(f) df_compiled.drop_duplicates(inplace=True) dates = list({idx[1] for idx in df_compiled.ind...
13,090
3,900
# Generated by Django 3.1.7 on 2021-03-01 20:26 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('hoofball', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fi...
745
225
from __future__ import absolute_import, unicode_literals import logging from time import sleep from datetime import datetime from .settings import PULSE_DURATION from .io import pull, release logger = logging.getLogger(__name__) def pulse(): logger.debug('Pulsing at {}'.format(datetime.now().time())) pull()...
627
207
some_number: int some_number = 'test'
38
15
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-04-02 13:58 from django.db import migrations def forwards_func(apps, schema_editor): """Grant permissions for TwitterAccount to admins and mods. Includes creating a new view permission. """ # We can't import the models directly as they may be...
2,513
793
class Solution: def generatePalindromes(self, s): cnt, n = collections.Counter(s), len(s) // 2 odd, s, q = [c for c in cnt if cnt[c] % 2], "".join(k * (cnt[k] // 2) for k in cnt), {"#" * n} if len(odd) > 1: return [] for c in s: new = set() for w in q: ...
544
208
#!/usr/bin/env python # -*- coding: utf-8 -*- # flake8: noqa """ Morlet Wavelet in time and Fourier domain ========================================= This example shows how to generate a wavelet filter-bank. """ import symjax import symjax.tensor as T import matplotlib.pyplot as plt import numpy as np J = 5 Q = 4 s...
909
370
from kfdata.manage import main main()
39
15
import sys #sys.stderr.write('Stderr text\n'); #sys.stderr.flush() #sys.stdout.write('Stdout text\n'); #print(sys.argv[1]) #if len(sys.argv)>1: # print(float(sys.argv[1])*5); def main(arg1): print(int(arg1)*4); main(sys.argv[1]);
240
110
# flake8: noqa from .form import FormHandler from .slash import SlashHandler from .manual import ManualHandler from .interactions import ActionHandler, MessageHandler
167
43
class PrimaryKeyNotFoundError(Exception): def __init__(self, *args): if args: self.message = args[0] else: self.message = None self.default_message = "Cannot find primary key in the data point. Every data point should at least have primary key" def __str__(self):...
779
205
#!/usr/bin/env python # encoding:utf-8 """ Author : Yuanqing Mei Date : 2021/4/8 Time: 15:42 File: RocMethod.py HomePage : http://github.com/yuanqingmei Email : dg1533019@smail.nju.edu.cn This script find out the cutoff of a metric value by maximizing the AUC value and ROC、BPP、MFM、GM methods. References: [1] Bender,...
13,902
5,257
from django.db import models from django.utils import timezone from django.contrib.auth.models import User class BaseModel(models.Model): date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class Meta: abstract = True class UserProfile(BaseMo...
1,372
424
"""empty message Revision ID: 3cbc86a0a9d7 Revises: 77894fcde804 Create Date: 2018-09-27 12:25:31.893545 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '3cbc86a0a9d7' down_revision = '77894fcde804' branch_labels = None depends_on = None def upgrade(): # ...
717
281
import random from .util import sign class AI: def __init__(self, entity): self.entity = entity self.queued_path = [] def think(self): if self.queued_path: x, y = self.queued_path.pop(0) self.move(x - self.entity.x, y - self.entity.y) def move(self, dx, dy...
2,685
900
from .material_generic import * __all__ = [] __all__ += material_generic.__all__
83
29
import os PROJECT_ROOT = os.path.dirname(__file__) # DEBUG # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = False # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug TEMPLATE_DEBUG = DEBUG # END DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS...
7,657
2,635
import re import sys from music21.interval import Interval from music21.key import Key def findKeysInRomanTextString(rntxt): """Get all the keys in a RomanText string. Receive a string with valid RomanText content. Output a list of all the key changes that happen throughout the content. """ ...
2,661
828
import json import pytest import uuid from mock import AsyncMock, patch from db.errors import EntityDoesNotExist from models.domain.resource import Status from models.domain.workspace import Workspace from models.domain.resource import Deployment from resources import strings from service_bus.deployment_status_update...
4,847
1,555
import os import time import logging as log import numpy as np from scikit-learn.preprocessing import normalize # local modules import config def process(encoding): normalized_encoding = get_quantized_features(encoding) return normalized_encoding def get_median_values_for_bins(bins): median_values = {}...
1,384
444
from datetime import date, datetime, timedelta import pytest from pydantic.error_wrappers import ValidationError from infobip_channels.sms.models.body.reschedule_sms_messages import ( RescheduleSMSMessagesMessageBody, ) from infobip_channels.sms.models.query_parameters.reschedule_messages import ( RescheduleS...
1,587
520
# 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...
8,349
2,701
# ------------------------------------------------------------------------------ # Module Import # ------------------------------------------------------------------------------ import nuke, nukescripts import platform from Qt import QtWidgets, QtGui, QtCore #------------------------------------------------...
5,578
2,053
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-11-10 21:35 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0002_auto_20161103_0100'), ] operations = [ migrations.AlterModel...
897
300
import requests import os class Imgur(): client_id = None remCredits = None def __init__(self, clientID): self.client_id = clientID def uploadImage(self, file, title, description): file.save(file.filename) with open(file.filename, 'rb') as f: data = f.read() ...
780
224
#!/usr/bin/python # Copyright (c) 2018 Red Hat # # This module 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 3 of the License, or # (at your option) any later version. # # This software is di...
4,489
1,442
""" authenticators: the server instance accepts an authenticator object, which is basically any callable (i.e., a function) that takes the newly connected socket and "authenticates" it. the authenticator should return a socket-like object with its associated credentials (a tuple), or raise AuthenticationError if it ...
4,199
1,292
# Generated by Django 3.0.5 on 2020-09-21 06:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.CreateModel( name='Confi...
1,156
342
# Generated by Django 2.0.3 on 2018-03-24 23:35 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('events', '0001_initial'), ] operations = [ migrations.CreateModel( ...
2,823
791
# 使用情绪分析流水线 import torch from transformers import BertTokenizer, BertForSequenceClassification torch.manual_seed(0) tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") model = BertForSequenceClassification.from_pretrained("bert-base-uncased", problem_type="multi_label_classification", num_labels=2) inputs ...
574
200
import time import numpy from amuse.lab import Huayno from amuse.lab import Hermite from amuse.lab import nbody_system from amuse.lab import new_king_model from matplotlib import pyplot def gravity_minimal(bodies, t_end, nproc): gravity = Hermite(number_of_workers=nproc) gravity.particles.add_particles(bodies...
1,293
506
import requests import json def random_cat_pic(): try: url = 'http://aws.random.cat/meow' response = requests.get(url) response_json = json.loads(response.text) return "Here's a super cute cat pic: " + response_json.get('file') except: return "Error meow"
311
98
#装饰器的结构 import time def timer(func): def wrapper(*args,**kwargs):#args 用来接收元祖 kwargs用来接收字典 start_time = time.time() func(*args,**kwargs) end_time = time.time() print("the function run time is %s" %(end_time-start_time)) return wrapper; @timer def test(): time.sleep(1) p...
407
156
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
3,255
946