text
string
size
int64
token_count
int64
# Copyright 2017 The Nuclio 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 applicable law or agreed to in wr...
1,323
440
import requests class KakaoMapClient: def __init__(self, kakao_auth_key): self.kakao_map_url = "https://dapi.kakao.com/v2/local/search/address.json" self.kakao_auth_key = kakao_auth_key def get_latitude_and_longitudes(self, pharmacies): searched_pharamacies = [] for pharmacy in ...
1,636
515
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Author : Alenx.Hai <alenx.hai@gmail.com> # created time: 2020/12/21-10:49 上午 import asyncio from src.mysql_elastic import MySQLElasticSearch @asyncio.coroutine def main(): elastic = MySQLElasticSearch() yield elastic.put_data() if __name__ == '__main__': l...
404
176
# Crie um módulo chamado moeda.py que tenha as funções incorporadas aumentar(), diminuir(), dobro() e metade(). Faça # também um programa que importe esse módulo e use algumas dessas funções. import moeda p = float(input('Digite o preço: ')) print(f'A metade do {p} é R${moeda.metade(p)}') print(f'O dobro de {p} é R${...
397
162
"""Class to hold all cover accessories.""" import logging from homeassistant.components.cover import ATTR_CURRENT_POSITION from homeassistant.helpers.event import async_track_state_change from . import TYPES from .accessories import HomeAccessory, add_preload_service from .const import ( SERV_WINDOW_COVERING, CHA...
3,024
888
import pandas as pd import numpy as np import datetime import pytz from pathlib import Path import warnings from io import IOBase from . import calpost_reader calpost_cat = calpost_reader.calpost_cat def hysplit_reader_long(f, tslice=slice(None, None), x=None, y=None, z=None, rdx_map=None): ...
5,888
2,278
import unittest from yapper import create_app, db from yapper.blueprints.user.models import User, Role class TestUserAddToDb(unittest.TestCase): def setUp(self): self.app = create_app('test') self.app_context = self.app.app_context() self.app_context.push() db.create_all() def...
1,094
364
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
2,880
915
import pyecharts.options as opts from pyecharts.charts import Line """ Gallery 使用 pyecharts 1.1.0 参考地址: https://echarts.baidu.com/examples/editor.html?c=line-aqi 目前无法实现的功能: 1、dataZoom 放大的时候无法固定 Y 轴的上下限 """ all_data = [ ["2000-06-05", 116], ["2000-06-06", 129], ["2000-06-07", 135], ["2000-06-08", 86]...
122,030
91,257
""" Stacking and Visualizing ------------------------ This script does the following: 1. Input LSST images, warp to sparse matrix, store as scidb arrays. This tests the warping of a single LSST exposure into a sparse matrix representation of a HEALPix grid. """ import os import sys import glob import matplotlib.pyplo...
1,416
580
import numpy as np sizes = list(map(int, input().split())) arr1 = list() arr2 = list() for _ in range(sizes[0]): arr1.append(list(map(int, input().split()))) for _ in range(sizes[1]): arr2.append(list(map(int, input().split()))) print(np.concatenate((np.array(arr1), np.array(arr2)), axis=0))
307
126
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from bibdeskparser.customization import InvalidName, splitname class TestSplitnameMethod(unittest.TestCase): def test_splitname_basic(self): """Basic tests of customization.splitname() """ # Empty input. result = splitname("")...
28,941
10,270
# schema for SQL database from data import app, db class HNuser(db.Model): """ SQL database class """ username = db.Column(db.String(100), primary_key=True) post_id = db.Column(db.Integer) salty_rank = db.Column(db.Float, nullable=False) salty_comments = db.Column(db.Integer, nullable=False) ...
1,349
436
import re import logging logger = logging.getLogger(__name__) def get_sorted_pair(a, b): # ensure citation pair is always in same order if a > b: return (a, b) else: return (b, a) def to_label(t, labels): if t in labels: return t else: return 'other' def normal...
2,608
798
from django.test import TestCase from django.utils import timezone from .models import Episode class PodCastsTests(TestCase): def setUp(self): self.episode = Episode.objects.create( title="My Awesome Podcast Episode", description="Look mom, I made it!", pub_date=timezon...
995
350
# 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...
4,114
1,273
# A 以上 B 以下の整数のうち、回文数となるものの個数を求めてください。 # ただし、回文数とは、先頭に 0 をつけない 10 進表記を文字列として見たとき、 # 前から読んでも後ろから読んでも同じ文字列となるような正の整数のことを指します。 # 文字列を逆順にして、同じ桁数の値をみる a, b = map(int, input().split()) cnt = 0 for i in range(a, b+1): s = str(i) s_r = s[::-1] n = int(len(str(s))/2) if s[: n] == s_r[:n]: cnt += 1 print(...
325
254
bl_info = { "name": "Import Fromsoft FLVER models", "description": "Import models from various Fromsoft games such as Dark Souls", "author": "Eliza Velasquez", "version": (0, 1, 0), "blender": (2, 80, 0), "category": "Import-Export", "location": "File > Import", "warning": "...
2,499
805
# -*- coding: utf-8 -*- # https://github.com/Kodi-vStream/venom-xbmc-addons from resources.lib.gui.contextElement import cContextElement from resources.lib.gui.guiElement import cGuiElement from resources.lib.db import cDb from resources.lib.handler.outputParameterHandler import cOutputParameterHandler from resources.l...
32,193
9,598
# Copyright (c) 2016-2019, Adam Karpierz # Licensed under the BSD license # http://opensource.org/licenses/BSD-3-Clause from ...jvm.lib.compat import * from ...jvm.lib import annotate from ...jvm.lib import public from ._typehandler import * # noqa @public class TypeManager(object): __slots__ = ('_state', '_h...
1,555
469
import os from django.conf import settings from django.core.exceptions import FieldDoesNotExist from hashids import Hashids import hashlib import string from datetime import datetime, date, timedelta from decimal import Decimal TWOPLACES = Decimal(10) ** -2 from django.db import models from django.apps import apps ge...
63,592
17,907
#!/usr/bin/env python3 __copyright__ = 'Copyright 2013-2016, http://radical.rutgers.edu' __license__ = 'MIT' import sys import radical.utils as ru import radical.pilot as rp rpu = rp.utils # ------------------------------------------------------------------------------ # if __name__ == '__main__': if len(sy...
803
281
try: from django.utils.deprecation import MiddlewareMixin except ImportError: # no-op class for Django < 1.10 class MiddlewareMixin(object): pass class BrokenRequestMiddleware(MiddlewareMixin): def process_request(self, request): raise ImportError('request') class BrokenResponseMiddl...
758
219
#!/usr/bin/env python3.6 from user import User from credential import Credential def createUser(userName,password): ''' Function to create a new user ''' newUser = User(userName,password) return newUser def saveUsers(user): ''' Function to save users ''' user.saveUser() def crea...
3,874
989
# constants used in more than one module # Some of them might find a better home later. from lib.nofloat import PRECISION MAIN_METASERVER_URL = open("cfg/metaserver.txt").read().strip() # old value used by some features (stats, ...) METASERVER_URL = "http://jlpo.free.fr/soundrts/metaserver/" # simulation VIRTUAL_T...
844
332
import tensorflow as tf import numpy as np ''' TF 2.0's basic attention layers(Attention and AdditiveAttention) calculate parallelly. TO USE MONOTONIC FUNCTION, ATTENTION MUST KNOW 'n-1 ALIGNMENT'. Thus, this parallel versions do not support the monotonic function. ''' class BahdanauAttention(tf.keras.layers.Layer): ...
9,104
3,109
import faiss import torch import logging import numpy as np from tqdm import tqdm from torch.utils.data import DataLoader from torch.utils.data.dataset import Subset def test_efficient_ram_usage(args, eval_ds, model, test_method="hard_resize"): """This function gives the same output as test(), but uses much less...
14,002
4,341
import random li=[] for i in range(10):#creating a random list using code from blackboard li=li+[random.randrange(0,50)] print(li) def insertionSort(li):#insertion sort function i=1 while(i < len(li)): j = i while (j>0) and (li[j-1] > li[j]): li[j], li[j-1] = li[j-1], li[j] j = j-1 i = i+1 return li pr...
355
170
import nose.tools from hyperopt import fmin, rand, tpe, hp, Trials, exceptions, space_eval def test_quadratic1_rand(): trials = Trials() argmin = fmin( fn=lambda x: (x - 3) ** 2, space=hp.uniform('x', -5, 5), algo=rand.suggest, max_evals=500, trial...
1,442
585
# -*- coding: utf-8 -*- import os from datetime import timedelta from flask import Flask, session default_timezone = 'Europe/Berlin' app = Flask(__name__, static_folder='../static', static_url_path='/static', template_folder="../templates/") app.permanent_session_lifetime = timedelta(minutes=60) app.config.update(...
737
268
#========================================================================== # # Copyright Insight Software Consortium # # 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 # # ...
1,528
499
import os import sys sys.path.append("../../../monk/"); import psutil from gluon_prototype import prototype gtf = prototype(verbose=1); gtf.Prototype("sample-project-1", "sample-experiment-1"); gtf.Default(dataset_path="../../../monk/system_check_tests/datasets/dataset_cats_dogs_train", model_name="resnet...
1,520
334
cache_root = '/home/ubuntu/ppa-mirror/cache/' mirror_root = '/home/ubuntu/ppa-mirror/repo' http_proxy = "188.112.194.222:8080"
126
62
import sys, getopt import sched import time import csv from pprint import pprint import urllib, urllib2 from random import randint import threading proxies_file = "" targets_file = "" proxies = [] targets = [] scheduler = sched.scheduler(time.time, time.sleep) def pick_random_proxy(): proxy_count = len(proxies...
3,031
1,118
import random from django.conf import settings from django.db.models import Prefetch from django.db.models.functions.math import Radians, Cos, ACos, Sin from ..models import Factory, ReportRecord, Image, Document def _sample(objs, k): list_of_objs = list(objs) random.shuffle(list_of_objs) return list_of...
1,799
616
from __future__ import absolute_import from __future__ import print_function import pytest import std_srvs.srv as std_srvs # public decorators from pyros_schemas.ros import with_service_schemas # # Testing with_service_schemas decorator # @with_service_schemas(std_srvs.Trigger) def service_callback(data, data_dict...
886
294
""" @param: A: A list of integers @param: elem: An integer @return: The new length after remove """ #倒序遍历list def removeElement(self, A, elem): # write your code here for i in range(len(A)-1,-1,-1): if A[i] == elem: A.pop(i) return len(A) ...
516
188
from setuptools import setup, find_packages import io from collections import OrderedDict with io.open('README.rst', 'rt', encoding='utf8') as f: readme = f.read() def get_version(): return '0.1.1' setup( name='Flask-Wired', version=get_version(), license='MIT', author='Karthikkannan Maruth...
2,057
696
from flask import jsonify def auth_login(http_status_code, message, token): view = jsonify({'status_code': http_status_code, 'message': message, '_token': token}) return view def auth_is_valid(http_status_code, message, token): view = jsonify({'status_code': http_status_code, 'message': message, '_toke...
510
163
# -*- coding: utf-8 -*- try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages REQUIRES = ['six', 'pecan', 'setuptools >= 1.1.6', 'cassandra-driver', 'pymongo'] setup( name='deuce', ...
604
216
import telepot import time import requests from bs4 import BeautifulSoup as bs import cPickle import csv RAHUL_ID = 931906767 # You can leave this bit out if you're using a paid PythonAnywhere account # proxy_url = "http://proxy.server:3128" # telepot.api._pools = { # 'default': urllib3.ProxyManager(proxy_url=pro...
6,580
2,693
""" Train ===== Defines functions which train models and write model artifacts to disk. """ from __future__ import print_function import os import tempfile import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from tensorflow_mnist import model, paths def train(path): """ Train...
1,607
468
# -*- coding: utf-8 -*- # Copyright 2020 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...
16,942
4,826
# Copyright (c) 2006-2010, Jesse Liesch # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditi...
4,841
1,805
import torch from torch.distributions import Gamma import torch.nn.functional as F import matplotlib.pyplot as plt from tqdm import tqdm from pyro.distributions import * import pyro from pyro.optim import Adam from pyro.infer import SVI, Trace_ELBO, Predictive assert pyro.__version__.startswith('1') pyro.enable_va...
5,913
2,334
from calplus.tests import base from calplus.v1 import utils class TestUtils(base.TestCase): """docstring for TestUtils""" def setUp(self): super(TestUtils, self).setUp() def test_get_all_driver(self): drivers = utils.get_all_driver() self.assertEqual([], drivers) def test_v...
539
161
# General imports import os, json, logging import click from pathlib import Path import yaml # From common from luna_core.common.custom_logger import init_logger from luna_core.common.DataStore import DataStore_v2 from luna_core.common.Node import Node from luna_core.common.config import C...
4,213
1,270
import numpy as np import cv2 from matplotlib import pyplot as plt image = cv2.imread('champaigneditedcompressed.png') kernel = np.ones((20, 20), np.float32) / 25 img = cv2.filter2D(image, -1, kernel) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) corners = cv2.goodFeaturesToTrack(gray,10,0.01,10) corners = np.int0(cor...
442
206
''' Created on 12 Jun, 2015 @author: artur.mrowca ''' from enum import Enum from PyQt5.Qt import QObject from PyQt5 import QtCore from tools.ecu_logging import ECULogger import copy class AbstractInputHandler(QObject): publish_infos_sig = QtCore.pyqtSignal(list) def __init__(self): ...
25,581
9,666
################################################################################ # Copyright: Tobias Weber 2019 # # Apache 2.0 License # # This file contains all code related to pid check objects # ################################################################################ import re import requests from breadp.c...
1,994
594
from unittest import TestCase from src.domain.holiday import Holiday import src.infrastructure.persistence.holiday_dynamo_repository as repository HOLIDAY = Holiday( date='2021-12-25', name='Natal', category='NATIONAL' ) class TestHolidayDynamoRepository(TestCase): def test_holiday_must_be_dict_when...
495
170
from config.defs import * import peewee db = peewee.SqliteDatabase(DATABASE_NAME) class BaseModel(peewee.Model): class Meta: database = db class Partida(BaseModel): id_time_casa = peewee.CharField() id_time_visitante = peewee.CharField() time_casa = peewee.CharField() time_visitante = peewee.CharField(...
3,136
1,267
class AnimationException(SystemException,ISerializable,_Exception): """ The exception that is thrown when an error occurs while animating a property. """ def add_SerializeObjectState(self,*args): """ add_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """ pass def remov...
1,386
426
r""" ======= quantnn ======= The quantnn package provides functionality for probabilistic modeling and prediction using deep neural networks. The two main features of the quantnn package are implemented by the :py:class:`~quantnn.qrnn.QRNN` and :py:class:`~quantnn.qrnn.DRNN` classes, which implement quantile regressi...
1,165
367
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import attr import magnum as mn import numpy as np @attr.s(auto_attribs=True, slots=True) class RobotTarget: """ ...
805
262
#!/usr/bin/env python #-*- coding: utf-8 -*- class ListNode(object): def __init__(self, x): self.val = x self.next = None class TwoNumbers(object): @staticmethod def builderListNode(nums): if nums is not None: head = ListNode(str(nums)[0]) a = head ...
1,314
442
import logging import tensorflow as tf import recsys.util.proto.config_pb2 as config def int64_feature(val): return tf.train.Feature(int64_list = tf.train.Int64List(value=[val])) def int64_list_feature(val_list): return tf.train.Feature(int64_list = tf.train.Int64List(value=val_list)) def bytes_feature(val):...
3,961
1,328
''' This module handles starring of modules. ''' import web from app import RENDER from components import model, session class StarModule(object): ''' Class handles starring and unstarring of modules. ''' def GET(self): ''' This function is called when /starModule is acce...
1,894
538
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 23 16:21:35 2021 @author: Paolo Cozzi <paolo.cozzi@ibba.cnr.it> """ import os import logging import pathlib import pycountry import mongoengine from enum import Enum from typing import Union from pymongo import database, ReturnDocument from doten...
27,362
8,100
#! /usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import torch from botorch.exceptions.errors import BotorchError, BotorchTensorDime...
6,143
1,969
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals import ast import sys import pytest from pyupgrade import _fix_dict_set from pyupgrade import _fix_escape_sequences from pyupgrade import _fix_format_literals from pyupgrade import _fix_fstrings from pyupgrade impo...
34,139
12,279
file_berita = open("berita.txt", "r") berita = file_berita.read() berita = berita.split() berita = [x.lower() for x in berita] berita = list(set(berita)) berita = sorted(berita) print (berita)
194
79
# Copyright 2016-present CERN – European Organization for Nuclear Research # # 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...
2,139
703
import pytest from responses import RequestsMock from tests import loader def test_parameter_cannot_be_parsed(responses: RequestsMock, tmpdir): responses.add( responses.GET, url="http://test/", json={ "swagger": "2.0", "paths": { "/test": { ...
2,771
660
"""Package for YooKassa Payout API Python Client Library."""
61
17
import toml from delfino.constants import ENTRY_POINT, PYPROJECT_TOML_FILENAME from delfino.models.pyproject_toml import PyprojectToml from tests.constants import PROJECT_ROOT class TestEntrypointConstant: @staticmethod def should_match_entrypoint_in_pyproject_toml(): file_path = PROJECT_ROOT / PYPRO...
467
162
from random import randint from typing import Callable, List, Optional class Coin: """Simulates a coin.""" def __init__(self) -> None: self.__head = False self.__toss_count = 0 self.__head_count = 0 def toss(self) -> None: """Toss a coin.""" r = randint(1, 2) ...
6,888
2,142
#!/bin/python
16
8
""" @Fire https://github.com/fire717 """ cfg = { ##### Global Setting 'GPU_ID': '0', "num_workers":8, "random_seed":42, "cfg_verbose":True, "save_dir": "output/", "num_classes": 17, "width_mult":1.0, "img_size": 192, ##### Train Setting 'img_path':"./data/croped/img...
1,285
593
from nmigen import * from nmigen.back.pysim import * # Function to calculate a clock divider which creates the # desired output frequency from a given input frequency. # Verifies that the divider is a positive integer, and that # the resulting signal doesn't deviate more than expected. def clock_divider( inf, outf, ma...
11,038
4,224
## @file # This file is used to define the FMMT dependent external tool management class. # # Copyright (c) 2021-, Intel Corporation. All rights reserved.<BR> # SPDX-License-Identifier: BSD-2-Clause-Patent ## import glob import logging import os import shutil import sys import tempfile import uuid from edk2basetools.FM...
5,853
1,957
from challenges.tree_intersection.tree_intersection import find_intersection from challenges.tree.tree import BinarySearchTree def test_find_intersection(): tree1 = BinarySearchTree() tree1.add(1) tree1.add(2) tree1.add(3) tree1.add(4) tree1.add(5) tree1.add(6) tree1.add(7) tree1.ad...
1,709
709
from setuptools import setup, find_packages setup( name = "imgdup", version = "1.3", packages = find_packages(), scripts = ['imgdup.py'], install_requires = ['pillow>=2.8.1'], # metadata for upload to PyPI author = "Radu Ioan Fericean", author_email = "radu@fericean.ro", description...
562
176
k = float(input("Digite uma distância em quilometros: ")) m = k / 1.61 print("A distância digitada é de {} quilometros, essa distância convertida é {:.2f} milhas" .format(k,m))
178
73
from django.conf.urls.defaults import * urlpatterns = patterns('rcs.wiki.views', url(r'^((?:[A-Z]+[a-z]+){2,})/$', 'page', {}, name="wiki_page"), url(r'^((?:[A-Z]+[a-z]+){2,})/edit/$', 'edit', {}, name="wiki_edit"), url(r'^((?:[A-Z]+[a-z]+){2,})/attachments/$', 'attachments', {}, name="wiki_attachments"), ...
660
300
import cv2 as cv import numpy as np import pandas as pd import heapq def sort_contours_horizontally(contours): dic = {} for contour in contours: x_points = contour[:, :, 0] dic[min(x_points)[0]] = contour dic = dict(sorted(dic.items())) return dic.values() def sort_contours(conto...
3,359
1,306
# 7. Write a program that estimates the average number of drawings it takes before the user’s # numbers are picked in a lottery that consists of correctly picking six different numbers that # are between 1 and 10. To do this, run a loop 1000 times that randomly generates a set of # user numbers and simulates drawings u...
704
228
from django.conf import settings from django.utils.importlib import import_module from humfrey.update.transform.base import Transform def get_transforms(): try: return get_transforms._cache except AttributeError: pass transforms = {'__builtins__': {}} for class_path in settings.UPDATE...
709
203
from .db_base import db, env class Device(db.Model): __tablename__ = 'device' id = db.Column(db.Integer, primary_key=True) if env == 'development': model = db.Column(db.String(16, 'utf8mb4_unicode_ci')) serial = db.Column(db.String(20, 'utf8mb4_unicode_ci')) company_id =...
2,448
834
from lib.remote.remote_util import RemoteMachineShellConnection from pytests.tuqquery.tuq import QueryTests class TokenTests(QueryTests): def setUp(self): if not self._testMethodName == 'suite_setUp': self.skip_buckets_handle = True super(TokenTests, self).setUp() self.n1ql_port...
18,542
5,920
# AutoTransform # Large scale, component based code modification library # # Licensed under the MIT License <http://opensource.org/licenses/MIT> # SPDX-License-Identifier: MIT # Copyright (c) 2022-present Nathan Rockenbach <http://github.com/nathro> # @black_format """The implementation for the DirectoryInput.""" fr...
1,074
311
""" tracker.py Copyright (c) 2013-2014 Snowplow Analytics Ltd. All rights reserved. This program is licensed to you under the Apache License Version 2.0, and you may not use this file except in compliance with the Apache License Version 2.0. You may obtain a copy of the Apache License Version 2.0 ...
27,790
7,758
import logging from http import cookiejar as http_cookiejar from http.cookiejar import http2time # type: ignore from typing import Any # noqa from typing import Dict # noqa from urllib.parse import parse_qs from urllib.parse import urlsplit from urllib.parse import urlunsplit from oic.exception import UnSupported f...
6,597
1,992
import sys import yaml import numpy import random import logging import argparse from os import path, makedirs from datetime import datetime from src.finger_proxy.proxy_agent import ProxyAgent from src.utilities.logging_config_manager import setup_logging from src.display.touchscreendevice import TouchScreenDevice fr...
5,890
1,721
#!/usr/bin/python # # Decoding a legacy chain ric # import pyrfa p = pyrfa.Pyrfa() p.createConfigDb("./pyrfa.cfg") p.acquireSession("Session1") p.createOMMConsumer() p.login() p.directoryRequest() p.dictionaryRequest() p.setInteractionType("snapshot") def snapshotRequest(chainRIC): p.marketPriceRequest(chainRIC) ...
1,854
736
#!/usr/bin/python # -*- coding: utf-8 -*- # launchctl unload /System/Library/LaunchDaemons/com.apple.syslogd.plist # launchctl load /System/Library/LaunchDaemons/com.apple.syslogd.plist from twisted.internet import reactor, stdio, defer from twisted.internet.protocol import Protocol, Factory from twisted.protocols.ba...
1,746
655
import requests as reqlib import os import re import random import time import pickle import abc import hashlib import threading from urllib.parse import urlparse from purifier import TEAgent from purifier.logb import getLogger from enum import IntEnum from typing import Tuple, List, Dict, Optional cl...
11,371
3,755
# CPU实时监控 # 作者:Charles # 公众号:Charles的皮卡丘 import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager import psutil as p POINTS = 300 fig, ax = plt.subplots() ax.set_ylim([0, 100]) ax.set_xlim([0, POINTS]) ax.set_autoscale_on(False) ax.set_xticks([]) ax.set_yticks(range(0, 101, 10)) ax.grid(True) # ...
1,554
763
import datetime from rest_framework import viewsets from rest_framework.response import Response from leaderboards import LEADERBOARD_MAX_PER_PAGE from leaderboards.models import LeaderboardEntry, Medal, LeaderboardSpan from leaderboards.serializers import (LeaderboardEntrySerializer, MedalSerializer, ...
8,128
2,272
from ... pyaz_utils import _call_az def show(name, resource_group): ''' Get the details for an instance pool. Required Parameters: - name -- Instance Pool Name - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` ''' r...
4,450
1,209
aluno = {} aluno['nome'] = str(input('Digite o nome do aluno: ')) aluno['media'] = float(input('Digite a média desse aluno: ')) if aluno['media'] >= 5: aluno['situação'] = '\033[32mAprovado\033[m' else: aluno['situação'] = '\033[31mReprovado\033[m' for k, v in aluno.items(): print(f'{k} do aluno é {v}')
316
147
# -*- coding: utf-8 -*- """ Created on Tue Aug 6 10:57:41 2019 Creates train and test splits at the IMAGE LEVEL to prep for thumbnail extraction in countr_cnn_1 @author: smcguire """ import pandas as pd import numpy as np import matplotlib.pyplot as plt ## read dataframe of unique images with annotati...
813
330
## @ingroup Attributes-Propellants # Aviation_Gasoline.py # # Created: Unk 2013, SUAVE TEAM # Modified: Apr 2015, SUAVE TEAM # ---------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------- from .Propellant import Propellant...
1,144
315
import os, glob, shutil class Write_grok(): def __init__(self, grok_name, grok_directory): ''' modify a given grok file''' self.grok_directory = grok_directory self.grok_path = os.path.join(grok_directory,grok_name) if not os.path.exists(self.grok_path): print("File not ...
4,108
1,162
import decimal import hashlib import json import requests import tempfile import uuid import os from tqdm import tqdm from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor def sha256_for_file(f, buf_size=65536): pos = f.tell() dgst = hashlib.sha256() while True: data = f.read(bu...
5,752
1,848
from __future__ import annotations import sys from skeema.intermediate.compiler.parser import Parser from skeema import ModelMeta from skeema import util def private(name): return f'_{name}' class ClassBuilder: """ ClassBuilder """ @staticmethod def set_class_module(klass, module_name: st...
1,824
504
""" From http://jimorlin.wordpress.com/2009/02/17/colored-letters-labeled-dice-a-logic-puzzle/ There are 13 words as follows: buoy, cave, celt, flub, fork, hemp, judy, junk, limn, quip, swag, visa. There are 24 different letters that appear in the 13 words. The question is: can one assign the 24 letters to 4 different ...
1,064
387
from JumpScale import j base = j.tools.cuisine._getBaseClass() class CuisineCockpit(base): def __init__(self, executor, cuisine): self._executor = executor self._cuisine = cuisine def configure(self): C = """ [mode] prod = false [oauth] client_secret...
4,220
1,443
""" Finetuning BERT using DeepSpeed's ZeRO-Offload """ import json import dataclasses from pathlib import Path from functools import partial import nlp import torch import typer import deepspeed import numpy as np from transformers import BertTokenizerFast from transformers import BertForSequenceClassification from sk...
7,103
2,321
# -*- coding: utf-8 -*- """ Auto Encoder Example. Using an auto encoder on MNIST handwritten digits. References: Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner. "Gradient-based learning applied to document recognition." Proceedings of the IEEE, 86(11):2278-2324, November 1998. Links: [MNIST Dataset]...
2,118
780