text
string
size
int64
token_count
int64
from unittest import TestCase from utils import to_bytes, to_str class TestUtils(TestCase): def test_bytes(self): self.assertEqual(to_bytes(b'Should be bytes \xe3\x81\xa0\xe3\x82\x88'), b'Should be bytes \xe3\x81\xa0\xe3\x82\x88') self.assertEqual(to_bytes('Should be byt...
687
265
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.BatchRoyaltyDetail import BatchRoyaltyDetail class AlipayTradeBatchTransferQueryResponse(AlipayResponse): def __init__(self): super(AlipayTradeBatchTrans...
1,723
548
"""The views for the barcodes app.""" import json from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib import messages from django.contrib.messages.views import SuccessMessageMixin from django.db import transaction from django.db.models import ProtectedError from django.shortcuts import rever...
9,418
2,629
dollars = float(input("Enter amount to change in dollars :")) # 20 dollar notes num1 = dollars//20 # remainder after 20 num2 = dollars%20 # notes by 10 num3 = num2//10 # remainder after 10 num4 = num2%10 # notes by 5 dollar num5 = num4//5 # remainder after 5 dollars num6 = num4%5 # notes by 1 dollar num7 = num6//1 #rem...
857
380
from ula import Ula ula=Ula(4) A = [1,0,0,0,1,0,0,1] B = [1,0,0,0,1,0,0,1] C = [1,1,1,1,1,1,1,1] ula.setA(A) ula.setB(B) ula.setInstrucao([0,0,0,1]) ula.selecao() print(ula.getSaida()) ula.setInstrucao([0,0,1,0]) ula.selecao() print(ula.getSaida()) ula.setInstrucao([0,0,1,1]) ula.selecao() print(ula.getSaida()) ...
713
414
from django.conf.urls import url from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured, PermissionDenied from django.db import connections, transaction from django.db.models import F, Count from django.db.models.expressions import Case, Value, When from django.db.models.functions import Cast from d...
12,902
3,707
""" Copyright (C) 2022 Martin Ahrnbom Released under MIT License. See the file LICENSE for details. General script for training a CNN in PyTorch """ from typing import List import torch from torch import optim import numpy as np from datetime import datetime from plot import multi_plot from u...
4,875
1,597
# import paho.mqtt.client as mqtt import paho.mqtt.publish as publish import time HOST = "127.0.0.1" PORT = 8222 def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) client.subscribe("test") def on_message(client, userdata, msg): print(msg.topic + " " + msg.payloa...
1,179
449
class Solution: def isValid(self, s: str) -> bool: stack = [] d = {"]": "[", "}": "{", ")": "("} for char in s: # Opening if char in d.values(): stack.append(char) elif char in d.keys(): if stack == [] or d[char] != stack.po...
476
136
# -*- coding: utf-8 -*- """ @Time : 2020/3/4 13:58 @Author : 半纸梁 @File : urls.py """ from django.urls import path from course import views app_name = "course" urlpatterns = [ path("index/", views.CourseIndexView.as_view(), name="index"), path("<int:course_id>/", views.CourseDetailView.as_view(), name=...
339
143
# -*- coding: utf-8 -*- import os,sys,importlib import xml.etree.ElementTree as ET import xdrlib,xlrd # 防止中文乱码 importlib.reload(sys) #配置文件名 CONFIG_NAME = "config.ini" #保存文件类型 SAVE_FILE_TYPE = ".json" #保存映射类类型 SAVE_MAPPING_TYPE = ".cs" #分隔符 SPLIT_CAHR = ":" #表格路径 XLS_PATH = "" #解析路径 XML_PATH = "" #导出路径 OUT_PATH = ""...
10,932
4,129
from gateways.authorizenet import AuthorizeNet from creditcard import CreditCard from datetime import datetime LOGIN = '' PASSWORD = '' def setup_authorize(): options = { 'order_id': '1', 'description': 'Test of AUTH code', 'email': 'john@doe.com', 'customer': '947', 'ip': ...
3,318
1,174
n=int(input("Enter the number upto which you want the prime numbers => ")) print print ("The List of Prime Nubmber :-") def prime(n): for i in range (1,n): x=1 for j in range (2,i): n=i%j if n==0: x=0 break if x==1: ...
393
146
# Copyright 2019 Axis Communications AB. # # For a full list of individual contributors, please see the commit history. # # 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.apac...
3,117
906
from fabric.api import * from fabric.contrib.files import * import random import string import common.ConfigFile import common.Services import common.Utils import Revert @task def drush_fra_branches(config): # If a 'branches' option exists in the [Features] section in config.ini, proceed if config.has_option("Fea...
27,628
8,820
""" This module implements the N-vortex dynamics for the half plane. Insert code here as if it were inside a class definition statement """ import numpy as np def JGradG(self, z1, z2): """ JGradG(z1, z2) is the product of the 2d symplectic matrix J with the gradient with respect to the first variable of t...
1,012
380
# coding: utf-8 """ UltraCart Rest API V2 UltraCart REST API Version 2 # noqa: E501 OpenAPI spec version: 2.0.0 Contact: support@ultracart.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class EmailSegmentCustomersRes...
6,929
2,084
print('\033[1;35m#\033[m'*10, '\033[1;30;46mDESAFIO 03\033[m', '\033[1;35m#\033[m'*10) n1 = int(input('\033[1;33mPrimeiro numero:\033[m ')) n2 = int(input('\033[1;36mSegundo numero:\033[m ')) r = n1 + n2 print('A soma é', r)
225
149
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import TodoItem def todoView(request): # return HttpResponse("Hello! This is Todo View Page...") all_todo_items=TodoItem.objects.all() return render(request, 'todo.html', {'all_items':...
793
265
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.http import HttpResponse from .models import Game, Person from .forms import NewUserForm, NewGameForm from django.contrib.auth.models import User # Create your views here. # TO REQUI...
2,852
942
"""empty message Revision ID: 2c64078d1aff Revises: 635e91180d41 Create Date: 2021-03-04 20:03:25.441608 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '2c64078d1aff' down_revision = '635e91180d41' branch_labels = None depends_on = None def upgrade(): # ...
676
276
""" 时间:2020/6/13 作者:lurui 功能:根据提供的模版,生成haprocy对应的haproxy.cfg配置文件 时间:2020/6/16 作者:lurui 修改:读master.txt文件改为读config.ini 时间:2020/6/17 作者:lurui 修改:基路径 basedir = os.path.dirname(os.path.dirname(os.getcwd())),改为调用者路径 basedir = os.path.abspath('.') """ import os import configparser def start_haproxy_cfg(): basedir = o...
2,115
833
import motor.motor_asyncio from bson.objectid import ObjectId from decouple import config from outfit import Outfit, Logger, ConsulCon, VaultCon, merge_dict __confit_info__ = 'configs/config.yaml' # load config via python-outfit Outfit.setup(__confit_info__) vault = VaultCon().get_secret_kv() consul = ConsulCon()....
3,025
914
from socket import * serverName = "localhost" serverPort = 12000 clientSocket = socket(AF_INET, SOCK_DGRAM) message = bytes(input("Input lowercase sentence: "), encoding="UTF-8") clientSocket.sendto(message, (serverName, serverPort)) modifiedMessage, serverAddress = clientSocket.recvfrom(2048) print(modifiedMessage) c...
340
111
# from django.core.urlresolvers import reverse # from django.conf.urls import patterns, url # from rest_framework import serializers, generics # from rest_framework.test import APITestCase # from tests.models import NullableForeignKeySource # class NullableFKSourceSerializer(serializers.ModelSerializer): # class...
1,300
390
from k5test import * realm = K5Realm(start_kadmind=True) # Create a principal. Test -q option and keyboard entry of the admin # password and principal password. Verify creation with kadmin.local. realm.run([kadmin, '-q', 'addprinc princ/pw'], input=password('admin') + '\npw1\npw1\n') realm.run([kadminl, '...
2,745
1,017
import functools from .declarative import get_members from .dispatch import dispatch from .namespace import ( Namespace, setdefaults_path, ) # This is just a marker class for declaring shortcuts, and later for collecting them class Shortcut(Namespace): shortcut = True # decorator def shortcut(f): f...
3,332
924
import os # Detect availability of torch package here. # NOTE: this try/except is temporary until torch is required for ML-Agents. try: # This should be the only place that we import torch directly. # Everywhere else is caught by the banned-modules setting for flake8 import torch # noqa I201 torch.se...
1,032
345
"pyokagan's personal utilities collection"
43
13
from .progress import Progress
30
6
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'worldgen.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_WorldGenDialog(object): def setupUi(self, WorldGenDialog): Wo...
13,352
4,322
#!/usr/bin/env python # -*- coding: utf-8 -*- # # tests/server/database.py # # 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 li...
3,958
1,466
from datetime import time, datetime from django.db import models # Create your models here. class FoodAvailabilityTimings(models.Model): shift_name = models.CharField(max_length=255, unique=True, blank=False, null=False) start_time = models.TimeField(default=time(hour=0, minute=0)) end_time = models.Time...
1,645
543
""" Plot a geodesic on the sphere S2 """ import matplotlib.pyplot as plt import numpy as np import geomstats.visualization as visualization from geomstats.hypersphere import Hypersphere SPHERE2 = Hypersphere(dimension=2) METRIC = SPHERE2.metric def main(): initial_point = [1., 0., 0.] initial_tangent_vec ...
860
298
import argparse import datetime import os import boto3 import ffmpeg # ------------------------------------------------------------------------------ def collect_and_store(rtsp_url: str, start_seconds: int, duration_seconds: int, s3_bucket: str, ...
3,666
1,052
from lib.base import BaseJiraAction __all__ = [ 'UpdateFieldValue' ] class UpdateFieldValue(BaseJiraAction): def run(self, issue_key, field, value, notify): issue = self._client.issue(issue_key) issue.update(fields={field: value}, notify=notify) result = issue.fields.labels re...
332
100
import pytest from django.core.management import call_command @pytest.mark.django_db def test_frab_import_minimal(superuser): call_command('init')
153
51
# Python modules # 3rd party modules import wx # Our modules import vespa.common.menu as common_menu import vespa.common.util.config as util_common_config ######################################################################## # This is a collection of menu-related constants, functions and utilities. # The funct...
6,524
2,204
import os import PIL.Image import numpy import cv2 import threading import datetime import config import game_region as game_region_module class BoundingBoxInfo(object): def __init__(self, name, source_coords): self.name = name self.source_coords = source_coords class BoundingBox(object): ...
5,198
1,764
############################################################################### # # IBT: Isolated Build Tool # Copyright (C) 2016, Richard Cook. All rights reserved. # # Simple wrappers around Docker etc. for fully isolated build environments # ###########################################################################...
1,536
440
from tests.assertions import CustomAssertions import numpy as np import floq.systems.spins as spins def single_hf(controls, omega): a1 = controls[0] b1 = controls[1] a2 = controls[2] b2 = controls[3] return np.array([[[0, 0.25*(1j*a2 + b2)], [0.25*1j*(a2 + 1j*b2), 0]], ...
3,241
1,399
import json import pandas as pd from unittest import TestCase from pandas._testing import assert_frame_equal from helper.utils.utils import load_json_as_df, reformat_json class TestUtils(TestCase): def test_load_json_as_df(self): test_json_data = {'text1': 'translation1', 'text2': 'translation2'} ...
877
286
# description: guozhi # date: 2021/1/9 9:54 # author: objcat # version: 1.0 import requests from bs4 import BeautifulSoup from win32com.client import Dispatch import pathlib import os class Guozhi: FC_URL = "http://2018.emu618.net:6180/index.php?controller=site&action=pro_list&cat=23" SFC_URL = "http://2018...
1,954
754
from setuptools import setup import codecs import os here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): return codecs.open(os.path.join(here, *parts), 'r').read() long_description = read('README.md') setup( name='forif', version='0.0.1', py_modules=['forif'], url='https://git...
1,066
343
import cv2 import numpy as np def DCTConstant(u, v): if u == 0 and v == 0: return 1 / 2 elif u == 0 or v == 0: return 1 / np.sqrt(2) else: return 1 def DCT(img, block=8): Ver, Hor, Col = img.shape result = np.zeros((Ver, Hor, Col)).astype(np.float32) x = np.tile(np.a...
2,742
1,270
import argparse import os, time import torch import shutil import numpy as np import torch.nn as nn import torchvision.transforms as transforms import torchvision.datasets as datasets import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable import models import torch.backends.cud...
19,861
6,523
""" Contains the functions and class (SonataWriter) necessary for generating and saving the input spike rasters. """ import numpy as np import scipy.signal as ss import scipy import scipy.stats as st import matplotlib.pyplot as plt import h5py from bmtk.utils.reports.spike_trains import PoissonSpikeGenerator import pa...
6,200
2,006
from config import * from argparse import Namespace as Args from schemas import Schema import shlex import subprocess import signal class Task(object): def _check_empty_setting(self, s, title): if len(s) > 0: return raise TaskException("Expanded {} for task '{}' is empty".format(title,...
8,086
2,587
import os from conans import ConanFile, CMake, tools class TinyObjLoaderConan(ConanFile): name = "tinyobjloader" description = "Tiny but powerful single file wavefront obj loader" settings = "os", "arch", "build_type", "compiler" options = {"shared": [True, False], "fPIC": [True, False]} default_o...
1,853
614
from .gcp_secrets import GcpSecretsManager
42
15
""" day15-part2.py Created on 2020-12-15 Updated on 2020-12-20 Copyright © Ryan Kan """ # INPUT with open("input.txt", "r") as f: numbers = [int(number) for number in f.readline().split(",")] f.close() # COMPUTATION saidNumbers = {} # Process the first numbers for i, number in enumerate(numbers): print...
1,074
382
import unittest import timeframe import timeseries import datetime import frequency #from django.test import TestCase # Create your tests here. class Tests(unittest.TestCase): """ Class for tests """ def setUp(self): pass def test_timeframe(self): empty_timeframe = timeframe.Timefr...
1,309
408
""" experiment launcher using tmux panes """ import os import math import GPUtil import re available_gpu_devices = None class Options(): def __init__(self, *args, **kwargs): self.args = [] self.kvs = {"gpu_ids": "0"} self.set(*args, **kwargs) def set(self, *args, **kwargs): f...
7,488
2,450
def strategy(history, memory): """ Orannis's punitive detective: Cooperate but when the other player defects, cooperate one more turn to see if they defect again. If they do, defect for 10 turns. Cooperate twice more and if they defect the second time, defect forever. memory is a tu...
1,557
480
class WeightSensorException(Exception): pass class WeightSensor: async def reset(self) -> None: raise NotImplementedError() async def start(self, delay: float = 0) -> None: raise NotImplementedError() async def stop(self) -> None: raise NotImplementedError() async def reset(self) -> None: raise NotI...
948
366
# ******************************************************************************* # Copyright 2017 Dell 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/L...
2,438
749
""" # **************************************************************************** # # GOVERNMENT PURPOSE RIGHTS # # Contract Number: FA8750-15-2-0270 (Prime: William Marsh Rice University) # Contractor Name: GrammaTech, Inc. (Right Holder - subaward R18683) # Contractor Address: 531 Esty Street, Ithaca, NY 14850 # Ex...
4,743
1,247
"""Holds all feature types to be part of a FeatureSet.""" from butterfree.transform.features.feature import Feature from butterfree.transform.features.key_feature import KeyFeature from butterfree.transform.features.timestamp_feature import TimestampFeature __all__ = ["Feature", "KeyFeature", "TimestampFeature"]
316
83
from keystoneclient.session import Session as KeystoneSession from keystoneclient.auth.identity.v3 import Password as KeystonePassword from keystoneclient.v3 import Client as KeystoneClient #from novaclient import client as novaclient from designateclient.v2 import client as designateclient def get_keystone_session(pr...
971
305
from copy import copy from functools import total_ordering import numpy as np import scipy.stats as stats from cascade.core import getLoggers CODELOG, MATHLOG = getLoggers(__name__) # A description of how dismod interprets these distributions and their parameters can be found here: # https://bradbell.github.io/dismo...
17,679
5,503
from django.contrib.auth import get_user_model from graphene import relay from graphene_django.filter import DjangoFilterConnectionField from graphene_django.types import DjangoObjectType from .models import User, Category, Publisher, Subscription import graphene class UserType(DjangoObjectType): class Meta: ...
2,581
729
import idautils import idc import collections searchItems = {"mono_init_internal" : "Max native code in a domain", #req'd for iOS "mono_class_load_from_name" : "Runtime critical type %s.%s not found", # req'd for iOS "mono_assembly_request_open" : "Assembly Loader probing location: '%s'."...
4,057
1,272
# file where i test everything import pi_vex_393, screen # fix this import time motor = pi_vex_393.Motor() screen = screen.Screen() while True: screen.clearScreen() screen.drawIP() screen.drawSystemLoad() screen.drawDebugLine(motor.currentStatus()) try: motor.spin('left', 50) motor.spin('right', 50) ...
389
160
# -*- coding: utf-8 -*- import os import sys import time import re import logging import subprocess from watchdog.observers import Observer from watchdog.events import LoggingEventHandler from watchdog.events import FileSystemEventHandler class CIHandler(FileSystemEventHandler): def __init__(self, context): ...
2,193
663
import numpy from numpy import dot def gaussian_elimination(a, b): n = len(b) for k in range(0, n - 1): for i in range(k + 1, n): lam = a[i, k]/a[k, k] a[i, k:n] -= lam*a[k, k:n] b[i] -= lam*b[k] for k in range(n - 1, -1, -1): b[k] = (b[k] - dot(a[k, k + 1:n], b[k + 1:n]))/a[k, k] re...
558
289
import bz2 import io from strelka import strelka class ScanBzip2(strelka.Scanner): """Decompresses bzip2 files.""" def scan(self, data, file, options, expire_at): with io.BytesIO(data) as bzip2_io: with bz2.BZ2File(filename=bzip2_io) as bzip2_obj: try: ...
1,009
285
""" Backwards compatibility shim module (forever). """ from pyramid.asset import * # b/w compat resolve_resource_spec = resolve_asset_spec resource_spec_from_abspath = asset_spec_from_abspath abspath_from_resource_spec = abspath_from_asset_spec
245
80
from tg.configuration import milestones from tg.appwrappers.base import ApplicationWrapper from .evolver import Evolution from webob.exc import HTTPServiceUnavailable from threading import Thread __all__ = ['plugme', 'Evolution'] import logging log = logging.getLogger('tgext.evolve') def plugme(configurator, option...
2,985
877
#imports import matplotlib.pyplot as plt import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split #Loading the data from a csv dataset=pd.read_csv("Salary_Data.csv") #Data pre processing for salary vs experience x=dataset.iloc[:,:-1].values print(...
1,189
441
# # @lc app=leetcode id=1041 lang=python3 # # [1041] Robot Bounded In Circle # # https://leetcode.com/problems/robot-bounded-in-circle/description/ # # algorithms # Medium (54.22%) # Likes: 557 # Dislikes: 176 # Total Accepted: 39.9K # Total Submissions: 73.7K # Testcase Example: '"GGLLGG"' # # On an infinite pl...
2,235
830
# __all__ = ['linvpy_latest', 'toolboxutilities_latest', 'toolboxinverse_latest'] # in your __init__.py from regularizedtau import *
133
45
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod import datetime, time import sys, os, os.path import pymongo import cPickle as pickle import logging class PersistenceLayer(object): __metaclass__ = ABCMeta @abstractmethod def create(self, name, document): pass @abstractmethod de...
2,381
758
def manhatten_hex_dist(orig, dest): dist_x = dest[0] - orig[0] dist_y = dest[1] - orig[1] if dist_x > 0 == dist_y > 0: return abs(dist_x + dist_y) else: return max(abs(dist_x), abs(dist_y)) def next_loc(orig, direc): if direc == 'n': return (orig[0], orig[1]+1) elif di...
1,035
428
import os from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable, Union, Iterator, Iterable from PIL.PpmImagePlugin import PpmImageFile from misc_utils.cached_data import CachedData from misc_utils.dataclass_utils import _UNDEFINED, UNDEFINED from misc_utils.prefix_suffix im...
3,809
1,459
#! /usr/bin/env python # -*- coding: utf-8 -*- """ @version: 0.1 @author: quantpy @file: tools.py @time: 2018/4/11 16:25 """ import os from functools import partial import numpy as np import pandas as pd from .apply_parallel import df_group_apply_parallel def get_grouper(df: pd.DataFrame, by=None, axis=0, le...
1,654
629
import requests import pytest from metric_status_worker.worker import MetricsStatus def test_get_metric_index_in_table_row(): row = "metric |sTatuS|TestString" metric_status = MetricsStatus("api.github.com") result = metric_status.get_metric_index_in_table_row(row) print(result) assert result == (...
512
177
""" Automated tests for the ldls application. """ import json from datetime import datetime from django.utils import unittest from django.db import models from jsonserializermixin import JSONSerializerMixin from jsonencoderdelegator import JSONEncoderDelegator class TestModel(models.Model, JSONSerializerMixin): ...
3,563
976
#!/usr/bin/python # -*- coding: utf-8 -*- #pylint: disable=I0011,R0913,R0902,R0921 """View interface""" from builtins import object class View(object): """Class for views""" def hide(self): """on hide event""" raise NotImplementedError("hide not implemented") def show(self): """o...
609
188
"multi_replace" ########################################################################## # # multi_replace function # # By Xavier Defrang. # # From the Python cookbook: # # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 # # There's more cool related code at the above site... # #######################...
888
251
import pytest from pettingzoo.classic import hanabi_v4 def test_pettingzoo(): env = hanabi_v4.env() env.reset() for agent in env.agent_iter(): observation, reward, done, info = env.last() if done: return else: action = env.action_space(agent).sample() ...
344
109
#!/usr/bin/env python # -*- coding: utf-8 -*- # Filter used by doxygen to any fortran file to do: # 0 - no error, always return something # 1 - Add include file (recursive call) import re import sys #Include command re_include = re.compile('^[ ]*include.*?\n',re.MULTILINE+re.IGNORECASE) #Extract file of the include...
1,002
329
from cli import Command from cmd.status import Status from cmd.samba import Samba class RootCommand(Command): def __init__(self, name): super().__init__(name=name) # self.add_child(Test(parent=self, name='test')) self.add_child(Status(parent=self, name='status')) self.add_child(Samb...
965
287
"""The main module handling the simulation""" import copy import datetime import logging import os import pickle import queue import random import sys import threading import warnings from functools import lru_cache from pprint import pformat # TODO set some defaults for width/etc with partial? import numpy as np imp...
38,401
13,811
""" Application views/routes are based on Flask's MethodView. All primary views are combined into a Flask blueprint. """ __author__ = 'Ralph Seichter' import datetime from operator import attrgetter import flask_login from flask import Blueprint, flash, redirect, url_for from flask.templating import render_template f...
10,557
3,082
__author__ = "Otacilio Maia" __version__ = "1.0.0" from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer def main(): chatbot = ChatBot('Chat AI') trainer = ChatterBotCorpusTrainer(chatbot) trainer.train("chatterbot.corpus.portuguese") user_text = "" while(user_tex...
514
188
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import * class AlipayMarketingPassInstanceQueryModel(object): def __init__(self): self._page_num = None self._page_size = None self._pass_id = None self._serial_num...
3,290
1,097
from b import foo from c import bar1 foo() bar1() print "Goodbye, World!"
74
27
# -*- coding: utf-8 -*- from .municipality import Municipality from .government import Government from .environment import MunicipalityEnvironment
149
41
# -*- coding: utf-8 -*- """ :mod:`MCEq.misc` - other useful things ====================================== Some helper functions and plotting features are collected in this module. """ import numpy as np from mceq_config import dbg def normalize_hadronic_model_name(name): """Converts hadronic model name into st...
9,053
3,044
from aiida.backends.utils import load_dbenv, is_dbenv_loaded if not is_dbenv_loaded(): load_dbenv() from aiida_yambo.workflows.yamboconvergence import YamboConvergenceWorkflow try: from aiida.orm.data.base import Float, Str, NumericType, BaseType, List from aiida.work.run import run, submit except Impo...
5,103
1,695
# coding: utf-8 _USERS_STORAGE = { 'default_id': None, # current issue } def set_user_issues(user_id, issue=None): if not issue: issue = Issue('', '') _USERS_STORAGE[user_id] = issue return _USERS_STORAGE[user_id] def get_user_issue(user_id): return _USERS_STORAGE[user_id] class Issue(...
503
186
import os os.environ["CUDA_VISIBLE_DEVICES"] = "1" import models as M import numpy as np import scipy import matplotlib.pyplot as plt from sklearn.metrics import roc_curve from sklearn.metrics import roc_auc_score from sklearn.metrics import confusion_matrix from sklearn.metrics import precision_recall_curve from sklea...
4,936
1,997
# ****************************************************** ## Copyright 2019, PBL Netherlands Environmental Assessment Agency and Utrecht University. ## Reuse permitted under Gnu Public License, GPL v3. # ****************************************************** ''' imports mocsy module ''' try: import mocsy except Modul...
600
185
""" The stocks blueprint handles the user management for this application. Specifically, this blueprint allows for users to add, edit, and delete stock data from their portfolio. """ from flask import Blueprint stocks_blueprint = Blueprint('stocks', __name__, template_folder='templates') from . import routes
311
81
import unittest class OneAwayTest(unittest.TestCase): def test_oneaway_missing_letter1(self): actual = one_away("pale", "ple") self.assertTrue(actual) def test_oneaway_missing_letter2(self): actual = one_away("p", "") self.assertTrue(actual) def test_oneaway_same_letters(self): actual = on...
1,548
564
from typing import Union def atmospeheres_to_bars(atm: float, unit: str) -> Union[float, str]: """ This function converts atm to bar Wikipedia reference: https://en.wikipedia.org/wiki/Standard_atmosphere_(unit) Wikipedia reference: https://en.wikipedia.org/wiki/Bar_(unit) >>> atmospeheres_to_bars...
9,593
3,733
import sys MOD = 10 ** 9 + 7 n, m, *a = map(int, sys.stdin.read().split()) broken = set(a) def main(): res = [None] * (n + 1) res[0] = 1 res[1] = 0 if 1 in broken else 1 for i in range(2, n+1): if i in broken: res[i] = 0 else: res[i] = res[i-2]...
444
209
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function __metaclass__ = type # (c) 2017, Ansible by Red Hat, inc # # This file is part of Ansible by Red Hat # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Pu...
6,569
1,964
from collections import deque import sys import greenlet from . import event, hubs from .support import reraise __all__ = ['sleep', 'spawn', 'spawn_n', 'kill', 'spawn_after', 'GreenThread'] def sleep(seconds=0): """Yield control to the hub until at least `seconds` have elapsed :param float seconds: time to...
8,555
2,393
name = None x=0 while not name: x=x+1 if x<3: name = input("Enter your name: ") if x==3: name = input("Man enter your name : ") if x==4: name = input("Why are spamming mate: ") if x==5: name = input("For God sake: ") if x==6: name = input("Bro!........") ...
460
165