text
string
size
int64
token_count
int64
# Copyright (c) OpenMMLab. All rights reserved. import ctypes import glob import logging import os def get_ops_path() -> str: """Get path of the TensorRT plugin library. Returns: str: A path of the TensorRT plugin library. """ wildcard = os.path.abspath( os.path.join( os.p...
1,054
326
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging import os import random import unittest from typing import Optional import numpy as np import pytorch_lightning as pl import torch import torch.nn as nn from parameterized import parameterized from reagent.co...
16,800
5,725
# MINLP written by GAMS Convert at 01/15/21 11:37:33 # # Equation counts # Total E G L N X C B # 1486 571 111 804 0 0 0 0 # # Variable counts # x b i s1s s2s sc ...
142,160
86,424
import unittest from flask import json from tests.base_test import BaseTest from app import db, elastic_index from app.model.resource import Resource from app.model.resource_category import ResourceCategory from app.model.resource_change_log import ResourceChangeLog from app.model.user import Role class TestResourc...
15,695
4,988
import json import logging import math import re from contextlib import contextmanager from django.core.management import call_command from django.core.management.base import CommandError from morango.models import Filter from morango.models import InstanceIDModel from morango.models import ScopeDefinition from morang...
18,432
4,946
import math import imageio import cv2 as cv import numpy as np import transformer def fix_rotation(img): img_copy = img.copy() img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) rows, cols = img.shape img = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY_INV, 15, 9) kernel = cv.g...
5,787
2,384
#!/usr/bin/env python3 """ A tool to grab a single BOSS image and pull a few items from its header. It is used in bin/sloan_log.py, but it could be used directly as well. """ import argparse from pathlib import Path from astropy.time import Time import fitsio class BOSSRaw: """A class to parse raw data from APOG...
2,318
751
# Altere o Programa 8.20 de forma que o usuário tenha três chances de acertar o número # O programa termina se o usuário acertar ou errar três vezes # Programa 8.20 do livro, página 184 # Programa 8.20 - Adivinhando o número # # import random # # n = random.randint(1, 10) # x = int(input('Escolha um número entre 1 e 1...
955
362
# -*- coding: utf-8 -*- """This sub module provides a global variable to check for checking if the non-interactive argument was set Exported variable: interactive -- False, if the main the non-interactive argument was set, True, if it was not set """ global interactive interactive = True;
293
82
import setuptools # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setuptools.setup( name="atm76", version="0.1.0", author="Steven H. Berg...
894
307
import logging import asyncio from agent.check_plugins import AbstractCheckPlugin # Do khong biet dung thu vien asyncio ntn ca nen em dung thu vien request # python import requests import sys import time from datetime import datetime logger = logging.getLogger(__name__) class Download(AbstractCheckPlugin): @as...
4,065
1,170
from django.urls import path from . import views app_name = "main" urlpatterns = [ path("",views.homepage,name="homepage") ]
130
45
""" Utility used by the Network class to actually train. Based on: https://github.com/fchollet/keras/blob/master/examples/mnist_mlp.py """ from keras.datasets import mnist, cifar10 from keras.models import Sequential from keras.layers import Dense, Dropout from keras.utils.np_utils import to_categorical from kera...
5,846
2,218
from openslides.agenda.models import Item from openslides.core.models import CustomSlide from openslides.utils.test import TestCase class TestItemManager(TestCase): def test_get_root_and_children_db_queries(self): """ Test that get_root_and_children needs only one db query. """ for...
491
148
import weakref import os import requests import ssl from ssl import SSLContext import logging from ssl_context_builder.builder.builder import SslContextBuilder from ssl_context_builder.http_impl.requests_wrapper.ssl_adapter import SslAdapter class RequestsSecureSession: def __init__(self, ssl_context: SSLContex...
3,272
920
''' Selected cifar-10. The .csv file format: class_index,data_index 3,0 8,1 8,2 ... ''' import pickle import pandas as pd file = 'E:\pycharm\LEARN\data\cifar-10\cifar-10-batches-py\\test_batch' with open(file, 'rb') as f: dict = pickle.load(f, encoding='bytes') dict.keys() batch_label = dict[b'batch_label'] ...
621
255
# Ghetto Fixtures from codebox import app from codebox.apps.auth.models import User from codebox.apps.snippets.models import Snippet from codebox.apps.organizations.models import Organization, OrganizationMember from flask import g client = app.test_client() _ctx = app.test_request_context() _ctx.push() app.preproces...
940
331
from unittest.mock import Mock, patch from django.test import SimpleTestCase from corehq.apps.domain.exceptions import DomainDoesNotExist from corehq.apps.linked_domain.exceptions import ( DomainLinkAlreadyExists, DomainLinkError, DomainLinkNotAllowed, ) from corehq.apps.linked_domain.views import link_do...
3,062
953
import function_exercise_01 as st st.sandwich_toppings('meatballs', 'salad')
79
34
#!/usr/bin/python # # from __future__ import absolute_import import json import re import logging from .datacite import DataCiteParser class WrongPublisherException(Exception): pass class ZenodoParser(DataCiteParser): def get_references(self, r): # as of version 3.1 of datacite schema, "References...
2,207
689
import json import time from functools import lru_cache from multiprocessing import Pool, Process from threading import Thread, Timer from typing import Any, Dict, List from datetime import datetime import hashlib import inspect import requests import waitress from bottle import BaseTemplate, Bottle, request, response,...
25,223
8,382
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow.python.framework import ops from collections import OrderedDict import warnings, logging from deepexplain.tf.v1_x import constants from deepexplain.tf.v1_x.baseClasses i...
5,914
1,773
""" Get the memory usage of a Keras model. From https://stackoverflow.com/a/46216013. """ def get_model_memory_usage(batch_size, model): """ Get the memory usage of a Keras model in GB. From https://stackoverflow.com/a/46216013. """ import numpy as np try: from keras import backend a...
1,457
496
import abc class DistortionABC(metaclass=abc.ABCMeta): maptype = None @abc.abstractmethod def apply(self, xy_in): """Apply distortion mapping""" pass @abc.abstractmethod def apply_inverse(self, xy_in): """Apply inverse distortion mapping""" pass
303
102
import io import os from setuptools import setup def read(file_name): """Read a text file and return the content as a string.""" with io.open(os.path.join(os.path.dirname(__file__), file_name), encoding='utf-8') as f: return f.read() setup( name='recmetrics', url='https://gi...
799
258
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
10,829
3,165
import sqlite3 import os import psycopg2 from dotenv import load_dotenv load_dotenv() DB_NAME2 = os.getenv("DB_NAME3") DB_USER2 = os.getenv("DB_USER3") DB_PASS2 = os.getenv("DB_PASS3") DB_HOST2 = os.getenv("DB_HOST3") conn = psycopg2.connect(dbname=DB_NAME2, user=DB_USER2, ...
1,174
408
import battlefy_data import battlefy_wiki_linkings from datetime import datetime from operator import itemgetter from pathlib import Path import calcup_roster_tracking def create_sidebar(data, wiki_name): sidebar = '{{Infobox league' + '\n' sidebar += '|liquipediatier=' + '\n' sidebar += '|name=' + data[...
24,232
8,268
import pygame class Texto: def __init__(self, screen, text, x, y, text_size = 20, fuente = 'Calibri', italic = False, bold= False, subrayado= False, color = (250, 240, 230), bg = [] ): self.screen = screen fg = color self.coord = x, y #load font, prepare values f...
3,169
1,086
# This is the code to train the xgboost model with cross-validation for each unique room in the dataset. # Models are dumped into ./models and results are dumped into two csv files in the current work directory. import argparse import json import math import os import pickle import warnings from typing import Tuple i...
11,662
3,862
import os from setuptools import setup # Read the version g = {} with open(os.path.join("editorconfig", "version.py"), "rt") as fp: exec(fp.read(), g) v = g['VERSION'] version = ".".join(str(x) for x in v[:3]) if v[3] != "final": version += "-" + v[3] setup( name='EditorConfig', versio...
1,293
381
import numpy as np import matplotlib.pyplot as plt t = np.arange(0,375,6.5) # MEM_1 = [0.031, 0.034, 0.034, 0.034, 0.031, 0.034, 0.034, 0.034, 0.031, 0.033, 0.035, 0.034, 0.031, 0.033, 0.034, 0.034, 0.031, 0.033, 0.034, 0.034, 0.031, 0.033, 0.034, 0.034, 0.031, 0.033, 0.034, 0.034, 0.031, 0.031, 0.031, 0.031, 0.031, 0...
6,035
5,184
import re import munge def parse_interval(val): """ converts a string to float of seconds .5 = 500ms 90 = 1m30s **Arguments** - val (`str`) """ re_intv = re.compile(r"([\d\.]+)([a-zA-Z]+)") val = val.strip() total = 0.0 for match in re_intv.findall(val): ...
1,042
352
# -*- coding: utf-8 -*- """Tests for sktime annotators.""" import pandas as pd import pytest from sktime.registry import all_estimators from sktime.utils._testing.estimator_checks import _make_args ALL_ANNOTATORS = all_estimators(estimator_types="series-annotator", return_names=False) @pytest.mark.parametrize("Est...
654
235
picamera import PiCamera from time import sleep import boto3 import os.path import subprocess s3 = boto3.client('s3') bucket = 'cambucket21' camera = PiCamera() #camera.resolution(1920,1080) x = 0 camerafile = x while True: if (x == 6): x = 1 else: x = x + 1 camera.start_preview() camera.start_recording('/home/pi/' ...
569
248
from datetime import datetime def run_example(): moment_in_time = datetime.fromordinal(256) print(moment_in_time) print(moment_in_time.toordinal()) print(moment_in_time.weekday()) print(moment_in_time.isoweekday()) other_moment = datetime.fromtimestamp(16_000_000) print(other_moment) ...
437
164
#!/usr/bin/env python from __future__ import print_function from kaldi.segmentation import NnetSAD, SegmentationProcessor from kaldi.nnet3 import NnetSimpleComputationOptions from kaldi.util.table import SequentialMatrixReader # Construct SAD model = NnetSAD.read_model("final.raw") post = NnetSAD.read_average_poster...
1,333
479
from cProfile import label from matplotlib.pyplot import text import pandas as pd import numpy as np from tokenizers import Tokenizer import torch from torch.utils.data import Dataset, DataLoader from typing import Dict, Any, Tuple from datasets import load_dataset class DataFrameDataset(Dataset): def __init__(se...
4,911
1,489
#!/usr/bin/python # mp4museum.org by julius schmiedel 2019 import os import sys import glob from subprocess import Popen, PIPE import RPi.GPIO as GPIO FNULL = open(os.devnull, "w") # setup GPIO pin GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(13, GPIO.IN, pull_up_down = ...
987
422
""" Comparison between the efficiency of the Boyer-Moore algorithm and the naive substring search algorithm. The runtimes for both algorithms are plotted on the same axes. """ import matplotlib.pyplot as plt import numpy as np import string import time import random from bm_alg import boyer_moore_match, naive_match #...
4,549
1,461
ans = dict() pairs = dict() def create_tree(p): if p in ans: return ans[p] else: try: res = 0 if p in pairs: for ch in pairs[p]: res += create_tree(ch) + 1 ans[p] = res return res except: pass...
616
200
def italicize(s): b = False res = '' for e in s: if e == '"': if b: res += '{\\i}' + e else: res += e + '{i}' b=not b else: res += e return res def main(): F=open('test_in.txt','r') X=F.read() F...
404
145
import json from typing import Type, TYPE_CHECKING from django.core.exceptions import ObjectDoesNotExist from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from rest_framework import viewsets, filters from rest_framework.exceptions import NotFound from rest_framew...
3,036
850
from magma import _BitType, BitType, BitsType, UIntType, SIntType class MantleImportError(RuntimeError): pass class UndefinedOperatorError(RuntimeError): pass def raise_mantle_import_error_unary(self): raise MantleImportError( "Operators are not defined until mantle has been imported") def r...
2,937
936
import subprocess import sys import time import traceback from queue import Queue from sultan.core import Base from sultan.echo import Echo from threading import Thread class Result(Base): """ Class that encompasses the result of a POpen command. """ def __init__(self, process, commands, context, st...
7,993
2,231
import os import click from .util import cli_message from great_expectations.render import DefaultJinjaPageView from great_expectations.version import __version__ as __version__ def add_datasource(context): cli_message( """ ========== Datasources ========== See <blue>https://docs.greatexpectations.io/en...
10,991
3,138
# -*- coding: utf-8 -*- """ Provide download function by request """ from datetime import datetime import logging import time import urllib.parse import requests from bs4 import BeautifulSoup class Throttle(object): """Throttle downloading by sleeping between requests to same domain.""" de...
4,105
1,179
#!/usr/bin/python class Solution(object): def reverseWords(self, s): if s == '': return s res = [] i = len(s) - 2 while i >= -1: if s[i] == ' ' or i == -1: word = '' j = i + 1 while j < len(s) and s[j] != ' ': ...
536
173
# -*- coding: utf-8 -*- # # The MIT License (MIT) # # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com> # # 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, in...
7,327
2,065
#!venv/bin/python3 cs = [int(c) for c in open("inputs/23.in", "r").readline().strip()] def f(cs, ts): p,cc = {n: cs[(i+1)%len(cs)] for i,n in enumerate(cs)},cs[-1] for _ in range(ts): cc,dc = p[cc],p[cc]-1 if p[cc]-1 > 0 else max(p.keys()) hc,p[cc] = [p[cc], p[p[cc]], p[p[p[cc]]]],p[p[p[p[cc]]...
700
351
# Import the application from device_registry import app # Run the application in debug mode app.run(host='0.0.0.0', port=int(app.config['PORT']), debug=True)
160
53
import yaml from ruamel.yaml import YAML from ruamel.yaml.error import YAMLError try: from yaml import CSafeLoader as SafeLoader except ImportError: from yaml import SafeLoader from dvc.exceptions import StageFileCorruptedError from dvc.utils.compat import open def load_stage_file(path): with open(path,...
1,263
403
entrada = input("palabra") listaDeLetras = [] for i in entrada: listaDeLetras.append(i)
93
37
import numpy as np from pyad.nn import NeuralNet from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split np.random.seed(0) data = load_breast_cancer() X_train, X_test, y_train, y_test = train_test_split( data.data, data.target, train_size=0.8, random_state=0 ) nn = Ne...
659
270
from microbit import * I2CADR = 0x0E DIE_TEMP = 0x0F while True: i2c.write(I2CADR, bytearray([DIE_TEMP])) d = i2c.read(I2CADR, 1) x = d[0] if x >=128: x -= 256 x += 10 print(x) sleep(500)
226
125
import ssl import nltk from textblob import TextBlob from nltk.corpus import stopwords # set SSL try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: pass else: ssl._create_default_https_context = _create_unverified_https_context # download noun data (if required...
793
256
from django_celery_beat.models import PeriodicTask, IntervalSchedule from django.core.management.base import BaseCommand from django.db import IntegrityError class Command(BaseCommand): def handle(self, *args, **options): try: schedule_channel, created = IntervalSchedule.objects.get_or_create...
1,418
344
# Copyright (c) 2021 PaddlePaddle 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 appli...
3,284
1,023
# required modules import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib import cm from matplotlib.colors import Normalize from mpl_toolkits.mplot3d import Axes3D from matplotlib.animation import FuncAnimation # two-dimesional version def plot_mse_loss_surface_2d(fi...
11,121
4,963
# Copyright 2019 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 agreed to in writing,...
7,435
3,255
from typing import Optional, List, TypeVar, Generic, Callable import discord.ui from .item import Item from .select_option import SelectOption from .custom import CustomSelect def _default_check(_: discord.Interaction) -> bool: return True C = TypeVar("C", bound=discord.ui.Select) class Select(Item, Generic...
2,356
690
"""This module contains the general information for StorageScsiLunRef ManagedObject.""" from ...ucscmo import ManagedObject from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta from ...ucscmeta import VersionMeta class StorageScsiLunRefConsts(): pass class StorageScsiLunRef(ManagedObject): """Th...
2,834
1,050
from __future__ import print_function, absolute_import, division from sys import stdout as _stdout from time import time as _time import numpy as np try: import pyfftw pyfftw.interfaces.cache.enable() pyfftw.interfaces.cache.set_keepalive_time(10) rfftn = pyfftw.interfaces.numpy_fft.rfftn irfftn =...
16,697
6,245
#!/usr/bin/env python3 import os import sys import time sys.path.append(os.getcwd()+'/lib') import random from dataclasses import dataclass, field from ObsInfo import ObsInfo def generate_random_obs(num_obs: int, size_list: list, config_data): """ config_file_name = "config.json" json_file = open(config_f...
985
361
# TG-UserBot - A modular Telegram UserBot script for Python. # Copyright (C) 2019 Kandarp <https://github.com/kandnub> # # TG-UserBot 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 t...
6,934
2,362
import numpy as np def get_n_from_txt(filepath, points=None, lambda_min=400, lambda_max=700, complex_n=True): ntxt = np.loadtxt(filepath) if np.min(np.abs(ntxt[:, 0] - lambda_min)) > 25 or np.min(np.abs(ntxt[:, 0] - lambda_max)) > 25: print('No measurement data for refractive indicies are available wit...
1,421
545
__package_name__ = "pyrocco" __version__ = "0.1.0" __author__ = "João Palmeiro" __author_email__ = "jm.palmeiro@campus.fct.unl.pt" __description__ = "A Python CLI to add the Party Parrot to a custom background image." __url__ = "https://github.com/joaopalmeiro/pyrocco"
270
106
class Machine(): def __init__(self): self.pointer = 0 self.accum = 0 self.visited = [] def run(self,program): salir = False while (salir == False): if (self.pointer in self.visited): return False if (self.pointer >= len(progr...
850
241
# coding: utf-8 # 2019/8/23 @ tongshiwei
41
25
""" Round a number -------------- Input (float) A floating point number (int) Number of decimals Default value is: 0 Output (float) Rounded number (int) Whether using the default decimals value, the return number will be the nearest ...
1,286
410
#!/usr/bin/env python3 import RPi.GPIO as GPIO from mfrc522 import SimpleMFRC522 import play import time class TagPlayer(object): def __init__(self): self._current = None self.reader = SimpleMFRC522() self._failed = 0 def step(self): id, text = self.reader.read_no_block() ...
992
306
import os MYPY = False if MYPY: from typing_extensions import Final PYTHON2_VERSION = (2, 7) # type: Final PYTHON3_VERSION = (3, 6) # type: Final PYTHON3_VERSION_MIN = (3, 4) # type: Final CACHE_DIR = '.mypy_cache' # type: Final CONFIG_FILE = 'mypy.ini' # type: Final SHARED_CONFIG_FILES = ['setup.cfg', ] # ...
1,118
385
#!/usr/bin/env python # -*- coding: utf-8 -*- # License: BSD-3 (https://tldrlegal.com/license/bsd-3-clause-license-(revised)) # Copyright (c) 2016-2021, Cabral, Juan; Luczywo, Nadia # All rights reserved. # ============================================================================= # DOCS # =========================...
3,558
1,057
# -*- coding: utf-8 -*- # # This class was auto-generated from the API references found at # https://support.direct.ingenico.com/documentation/api/reference/ # from ingenico.direct.sdk.data_object import DataObject from ingenico.direct.sdk.domain.address import Address from ingenico.direct.sdk.domain.company_informatio...
3,451
832
import time import pykeyboard # TODO: Replace following two lines with the code that activate the application. print('Activate the application 3 seconds.') time.sleep(3) k = pykeyboard.PyKeyboard() k.press_key(k.left_key) time.sleep(1) # Hold down left key for 1 second. k.release_key(k.left_key)
301
103
import os import tarfile from abc import ABC, abstractmethod from glob import glob import shutil import random import zstandard """ This registry is for automatically downloading and extracting datasets. To register a class you need to inherit the DataDownloader class, provide name, filetype and url attributes, and (...
4,819
1,652
from logging import getLogger logger = getLogger(__name__) class QLearning: """ Q-Learning用のクラス Attributes ---------- alpha : float 学習率α gamma : float 割引率γ data : dict Q-Learningでの学習結果の保存用辞書 init_value : float dataの初期値 """ def __init__(self, alpha: float, gamma: float, data: dict ...
1,575
696
#!/usr/bin/env python import os import json import sys import unittest import urllib2 from flexmock import flexmock sys.path.append(os.path.join(os.path.dirname(__file__), "../../")) import solr_interface import search_exceptions class FakeSolrDoc(): def __init__(self): self.fields = [] class FakeDocument():...
6,748
2,346
class PayabbhiError(Exception): def __init__(self, description=None, http_status=None, field=None): self.description = description self.http_status = http_status self.field = field self._message = self.error_message() super(PayabbhiError, self).__init__(self...
899
268
# coding=utf-8 # Copyright (c) 2019, NVIDIA CORPORATION. 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 re...
1,923
539
# -*- coding: utf-8 -*- import os from django.db import models from django.db.models.signals import post_delete from django.dispatch import receiver from .base import Pessoa from djangosige.apps.login.models import Usuario from djangosige.configs.settings import MEDIA_ROOT def logo_directory_path(inst...
2,141
752
import os from nltk.translate.bleu_score import corpus_bleu from nltk.translate.bleu_score import SmoothingFunction import json from tqdm import tqdm, trange from random import sample import numpy as np import pickle import argparse import bert_eval_acc import svm_eval_acc smooth = SmoothingFunction() def eval_bleu...
5,858
2,211
"""Constants for the UniFi component.""" import logging LOGGER = logging.getLogger(__package__) DOMAIN = "unifi" CONTROLLER_ID = "{host}-{site}" CONF_CONTROLLER = "controller" CONF_SITE_ID = "site" UNIFI_WIRELESS_CLIENTS = "unifi_wireless_clients" CONF_ALLOW_BANDWIDTH_SENSORS = "allow_bandwidth_sensors" CONF_BLOCK...
804
350
class OrderedStream: def __init__(self, n: int): self.data = [None]*n self.ptr = 0 def insert(self, id: int, value: str) -> List[str]: id -= 1 self.data[id] = value if id > self.ptr: return [] while self.ptr < len(self.data) and self.data[self.ptr]: ...
503
175
import numpy as np from treelas import post_order, TreeInstance def test_demo_3x7_postord(): parent = np.array([0, 4, 5, 0, 3, 4, 7, 8, 5, 6, 7, 8, 9, 14, 17, 12, 15, 16, 19, 16, 17]) po = post_order(parent, include_root=True) expect = np.array([12, 11, 19, 20, 21, 14, 15, 18, 17, 1...
1,091
591
import xmlrpc.client def main(): s = xmlrpc.client.ServerProxy('http://localhost:9991') nome = input("Nome: ") cargo = input("Cargo (programador, operador): ") salario = float(input("Salário: ")) print("\n\n{}".format(s.atualiza_salario(nome, cargo, salario))) if __name__ == '__main__': m...
326
123
# Generated by Django 3.0.7 on 2020-07-27 19:23 import build.models from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AutoCompleteRecord', fields=[ ...
846
244
import argparse import os import torch import yaml DEFAULT_DEVICE = 'cuda:0' def load_config(): parser = argparse.ArgumentParser(description='UNet3D training') parser.add_argument('--config', type=str, help='Path to the YAML config file', required=True) args = parser.parse_args() config = _load_conf...
636
208
from webdnn.backend.webgl.optimize_rules.simplify_channel_mode_conversion.simplify_nonsense_channel_mode_conversion import \ SimplifyNonsenseChannelModeConversion from webdnn.backend.webgl.optimize_rules.simplify_channel_mode_conversion.simplify_redundant_channel_mode_conversion import \ SimplifyRedundantChanne...
654
202
""" The constants used in FLV files and their meanings. """ # Tag type (TAG_TYPE_AUDIO, TAG_TYPE_VIDEO, TAG_TYPE_SCRIPT) = (8, 9, 18) # Sound format (SOUND_FORMAT_PCM_PLATFORM_ENDIAN, SOUND_FORMAT_ADPCM, SOUND_FORMAT_MP3, SOUND_FORMAT_PCM_LITTLE_ENDIAN, SOUND_FORMAT_NELLYMOSER_16KHZ, SOUND_FORMAT_NELLYMOSER_8KH...
3,998
2,041
from nltk.corpus import semcor class semcor_chunk: def __init__(self, chunk): self.chunk = chunk #returns the synset if applicable, otherwise returns None def get_syn_set(self): try: synset = self.chunk.label().synset() return synset except AttributeError: try: synset = wn.synset(self.chunk.lab...
738
309
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from load_cora import load_cora from baseline_model import create_ffn from utils import run_experiment from utils import display_learning_curves # Graph convolution layer class GraphConvLayer(layers.Layer): def __init__( ...
8,318
2,710
"""Discover Samsung Smart TV services.""" from . import SSDPDiscoverable from ..const import ATTR_NAME # For some models, Samsung forces a [TV] prefix to the user-specified name. FORCED_NAME_PREFIX = '[TV]' class Discoverable(SSDPDiscoverable): """Add support for discovering Samsung Smart TV services.""" de...
868
266
"""Package for reverse-engineering.""" from .rpa import *
59
19
# Generated by Django 3.2.5 on 2021-12-21 19:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('employees', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='employee', name='phone_alt', ), ...
324
113
class EmoteFetchError(Exception): '''Exception stating that there was a problem while fetching emotes from a source.'''
124
30
""" This is the most simple scenario with a basic topology, some users and a set of apps with only one service. @author: Isaac Lera """ import os import time import json import random import logging.config import networkx as nx import numpy as np from pathlib import Path from yafs.core import Sim from yafs.a...
5,098
1,768
from db import db class RisklayerPrognosis(db.Model): __tablename__ = 'risklayer_prognosis' datenbestand = db.Column(db.TIMESTAMP, primary_key=True, nullable=False) prognosis = db.Column(db.Float, nullable=False) # class RisklayerPrognosisSchema(SQLAlchemyAutoSchema): # class Meta: # strict ...
476
165
import os import unittest os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' import django if django.VERSION >= (1, 7): django.setup() from django import forms from django.db import models from django.forms.forms import NON_FIELD_ERRORS from django_secureform.forms import SecureForm def get_form_sname(form, name...
2,520
849
import cv2 as cv import numpy as np cap = cv.VideoCapture(1) print(cap.get(cv.CAP_PROP_FRAME_WIDTH)) print(cap.get(cv.CAP_PROP_FRAME_HEIGHT)) cap.set(3,3000) cap.set(4,3000) print(cap.get(cv.CAP_PROP_FRAME_WIDTH)) print(cap.get(cv.CAP_PROP_FRAME_HEIGHT)) while (cap.isOpened()): ret , frame = cap.read() if...
495
224