text
string
size
int64
token_count
int64
# -*- coding: UTF-8 -*- import os import json import time import rsa import base64 import urllib import binascii import traceback import requests import pandas as pd from lxml import etree from datetime import datetime class NoResultException(Exception): def __init__(self): super().__init__() def __...
12,980
4,302
from spoty.commands.first_list_commands import \ count_command, \ export_command, \ print_command from spoty.commands.second_list_commands import \ filter_second_group, \ find_duplicates_second_command,\ find_deezer_second_group, \ find_spotify_second_group from spoty.commands import get_gro...
3,783
1,059
# encoding=utf8 import jenkins_job_wrecker.modules.base from jenkins_job_wrecker.helpers import get_bool, Mapper class Triggers(jenkins_job_wrecker.modules.base.Base): component = 'triggers' def gen_yml(self, yml_parent, data): triggers = [] for child in data: object_name = child...
19,804
5,228
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import re import regex import argparse # The variables below need to be adjusted for a language pair and dataset. # To add a new language, define the list of alpha characters in the dict below. MIN_LENGTH = 1 # minimum number of words in a sentence MAX_L...
4,097
2,034
from pathlib import Path from requests import post from random import randint from json import loads, dumps import random, datetime, rubika.encryption # because should be exist ! adminsAccess = { "pin":"PinMessages", "newAdmin":"SetAdmin", "editInfo":"ChangeInfo", "banMember":"BanMember", "changeLink":"SetJoinLin...
24,624
12,325
people = 30 cars = 40 buses = 15 if cars > people: print "We should take the cars." elif cars < people: print "we should not take the cars." else: print "we can't decide." if buses > cars: print " That's too many buses" elif buses < cars: print " Maybe we could take the bus." else: print "we stil can't decide."...
424
159
import logging import random import string from scrapy.http.request.form import _get_inputs as get_form_data logger = logging.getLogger(__name__) SEARCH_TERMS = list(string.ascii_lowercase) + list('123456789 *%.?') def search_form_requests(url, form, meta, search_terms=None, extra_search_terms=None): ...
3,001
900
import numpy as np import matplotlib.pyplot as plt pid_file = open("pid.txt", "w") x = np.linspace(0, 2 * np.pi, 100) print x pid_file.write(x) y1, y2 = np.sin(x), np.cos(x) plt.plot(x, y1, label='y = sin(x)') plt.plot(x, y2, label='y = cos(x)') plt.legend() plt.show()
277
140
# -*- coding: utf-8 -*- import info class subinfo(info.infoclass): def setTargets( self ): self.svnTargets['master'] = 'https://github.com/libssh2/libssh2.git||libssh2-1.8.0' self.targets['1.8.0'] = "https://www.libssh2.org/download/libssh2-1.8.0.tar.gz" self.targetInstSrc['1.8.0'] = "libss...
921
334
"""Test config_generator.py module""" from unittest import TestCase from projector_installer.config_generator import token_quote class ConfigGeneratorTest(TestCase): """Test config_generator.py module""" def test_token_quote(self) -> None: """The token_quote method must return the same token in quot...
396
112
import os import re import logging import zipfile logger = logging.getLogger(__name__) class MvnArtifact: """ Class representing a fully defined maven artifact (e.g., <groupId>:<artifactId>:<type>:<version>[:<dep_type>]) """ __elem_re = re.compile(r'^(.+?):(.+?):(.+?):(.+?)((:)(.+))?$') def __...
5,289
1,868
from ..schema.nexusphp import Attendance from ..schema.site_base import Work, SignState from ..utils.net_utils import NetUtils class MainClass(Attendance): URL = 'https://club.hares.top/' USER_CLASSES = { 'downloaded': [8796093022208], 'share_ratio': [5.5], 'days': [364] } def...
1,812
576
from garage.envs import GymEnv from garage.tf.algos.rl2 import RL2Worker from tests.fixtures import TfGraphTestCase from tests.fixtures.envs.dummy import DummyBoxEnv from tests.fixtures.policies import DummyPolicy class TestRL2Worker(TfGraphTestCase): def test_rl2_worker(self): env = GymEnv(DummyBoxEnv(...
716
240
#Uche Ogbuji exercises format-number on Brad Marshall's behalf from Xml.Xslt import test_harness sheet_1 = """\ <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match = "/"> <xsl:value-of select='format-number(10000000000.75 + 10000000000.50, "##.##"...
660
280
import typing as t import pytest as pt from fastapi_mailman import BadHeaderError, EmailMessage if t.TYPE_CHECKING: from fastapi_mailman import Mail @pt.mark.anyio async def test_send_message(mail: "Mail"): mail.backend = "locmem" msg = EmailMessage( subject="testing", to=["to@example.c...
2,697
870
# -*- coding: utf-8 -*- sayi1 = int(input("1. Sayı:")) sayi2 = int(input("2. Sayı:")) sayi3 = int(input("3. Sayı:")) if (sayi1>=sayi2) and (sayi1>=sayi3): enBuyuk = sayi1 elif(sayi2>=sayi1) and (sayi2>=sayi3): enBuyuk = sayi2 else: enBuyuk = sayi3 print("En Büyük Sayı:",enBuyuk)
294
152
with open('input.txt') as f: lines = f.readlines() counter = 0 for line in lines: right_part = line.split(" | ")[1] for segment in right_part.strip().split(" "): #print(segment, len(segment)) if len(segment) in [2,3,4,7]: counter += 1 #e...
399
127
import Tkinter import weighted_objects import tkFileDialog import time import ttk import numpy import sys while True: # Ask user for file dialog. Tkinter.Tk().withdraw() osu_file_path = tkFileDialog.askopenfilename(title="Select an osu file", filetypes=(("osu files", "*.osu"),)) # Calcula...
7,605
2,669
from .probe import ProbeTrainer # train using embeddings def train_embeddings(encoder, probe_type, num_epochs, lr, patience, wandb, save_dir, batch_size, tr_episodes, val_episodes, tr_labels, val_labels, test_episodes, test_labels, use_encoder=False, save_interval=100): if use_encoder: enc...
2,929
949
#!/usr/bin/env python """REL_DB blobstore implementation.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from grr_response_server import blob_store from grr_response_server import data_store class DbBlobStore(blob_store.BlobStore): """A REL_DB-bas...
1,310
439
#pragma out #pragma repy restrictions.loose def foo(ip,port,mess, ch): print ip,port,mess,ch stopcomm(ch) def noop(a,b,c,d): pass if callfunc == 'initialize': ip = getmyip() noopch = recvmess(ip,<messport>,noop) recvmess(ip,<messport1>,foo) sleep(.1) sendmess(ip,<messport1>,'hi',ip,<messport>) stop...
333
148
""" Startup checks """ import subprocess import pyzfscmds.system.agnostic as zfssys def is_root_on_zfs(): """Check if running root on ZFS""" system = zfssys.check_valid_system() if system is None: raise RuntimeError(f"System is not yet supported by pyzfscmds\n") root_dataset = None if z...
806
262
import sys def distinct_1(path): inFile = open(path, mode="r", encoding="utf8") char_set = set() all_unigram_count = 0 for line in inFile.readlines(): line = line.strip().split(" ") for word in line: char_set.add(word) all_unigram_count += len(line) distinct_unig...
2,015
746
""" Calculate PDFs for polar vortex response Notes ----- Author : Zachary Labe Date : 25 June 2019 """ ### Import modules import numpy as np import matplotlib.pyplot as plt import datetime import read_MonthlyData as MO import calc_Utilities as UT import cmocean import scipy.stats as sts ### Define director...
5,036
1,909
import pytest from airtunnel.operators.sql import sql_helpers TEST_SCRIPT = "ddl/test_schema/test_table.sql" @pytest.mark.parametrize( argnames=("sql_path",), argvalues=((TEST_SCRIPT,), ("/" + TEST_SCRIPT,), ((TEST_SCRIPT,),)), ) def test_load_sql_script(sql_path: str): # load with a single relative pat...
906
345
import numpy as np import matplotlib.pyplot as plt ## softmax: 0.1 600 ## perceptron: 0.05 550 def readData(csvname): data = np.loadtxt(csvname, delimiter=',') x = data[:-1, :] y = data[-1:, :] return x, y def softmaxCostFunc(x, y, w): cost = np.sum(np.log(1 + np.exp(-y*np.transpose(np.dot(np.t...
2,582
1,095
height = float(input("Enter height of the square: ")) width = float(input("Enter width of the Square: ")) perimeter = (2 * height) + (2 * width) area = height * height print("The perimeter of the square is", perimeter) print("The area of the square is", area) close = input("Press X to exit") #...
416
132
import numpy as np from common.util import im2col from collections import OrderedDict from common.layers import * from common.gradient import numerical_gradient ## 4차원 배열 ## x = np.random.rand(10, 1, 28, 28) # (m, c, h, w) print(x.shape) x[0].shape # data 1개 x[0, 0] # 첫 data의 channel 공간 x1 = np.random.rand(1, 3, 7, ...
6,492
2,834
import datetime import pytest import requests from datavault_api_client import crawler from datavault_api_client.data_structures import DiscoveredFileInfo class TestCleanRawFilename: @pytest.mark.parametrize( "datavault_assigned_name, expected_cleaned_filename", [ ("WATCHLIST_username_676_20...
17,136
5,890
#!/usr/bin/env python __author__ = 'Michael Meisinger' import gevent import random from pyon.datastore.datastore import DatastoreManager from pyon.public import IonObject import ooi.timer """ from prototype.couch.couch_concurrent import runcc runcc(dict(num_obj=100000, num_read=2000, num_thread=3)) """ class Couc...
2,976
1,087
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : 2020-04-06 23:45:54 # @Author : Racter Liu (racterub) (racterub@gmail.com) # @Link : https://racterub.me # @License : MIT from flask import Flask, render_template, request, url_for, redirect, session, send_from_directory, send_file, make_response app = F...
2,226
791
from sanic.response import json from sanic import Blueprint from service import ListService from injector import inject, singleton from logging import Logger from sanic import Sanic @singleton class ListController: @inject def __init__(self, logger: Logger, list_service : ListService): self.logger = l...
4,067
1,355
""" Author: Darren Date: 02/05/2021 Solving https://adventofcode.com/2015/day/24 We require three bags of equal weight. Bag 1 in the passenger compartment, needs to have fewest packages. Bags 2 and 3 to either side. Solution: Use subset sum function to work out which combinations of packages adds up to...
5,223
1,583
from .problem import Problem from .algorithm import Algorithm from .config import artap_root import time import numpy as np import os import sys sys.path.append(artap_root + os.sep + "lib" + os.sep) import bayesopt from multiprocessing import Process, Pipe, Queue, Manager # from multiprocessing.managers import Base...
8,946
2,800
def Short_Bubble_Sort(alist): ''' Sorting alist using Short Bubble Sort ''' passnum = len(alist) - 1 exchangesDone = True while passnum > 0 and exchangesDone: exchangesDone = False for i in range(passnum): if alist[i] > alist[i+1]: exchangesDone = True...
538
214
# This file was created by a source code generator: # genxml2wrap.py # Do not modify. Change the definition and # run the generator again! # # (c) 2010 Mathias Hoffmann, GFZ Potsdam # # import datetime class _TrackedObject(object): def __init__(self): self.__dict__['last_modified'] = datetime.datetime(1970, 1, 1, ...
5,997
2,102
# coding: utf-8 """ Mailchimp Marketing API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 3.0.74 Contact: apihelp@mailchimp.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import...
7,754
2,223
import time import sys class Loadingstatus: def __init__(self, barlength = 20): self.loading = 0 self.lastCall = self.getMilliSeconds() self.barlength = barlength def getMilliSeconds(self): return int(time.time() * 1000) def updatePending(self): newCall = self.getM...
1,118
359
import os from fastapi import FastAPI from fastapi_sqlalchemy import DBSessionMiddleware from fastapi_sqlalchemy import db from dotenv import load_dotenv from sqlalchemy import schema from db import models as db_model from schemas import models as schema load_dotenv() POSTGRES_USER = os.getenv('POSTGRES_USER') POSTG...
1,596
574
import bpy __all__ = [ "delete_all_data", ] def delete_all_data(): """Delete all collections, mesh and curve objects, meshes, curves, materials.""" for collection in bpy.data.collections: bpy.data.collections.remove(collection) for obj in bpy.data.objects: if obj.type == 'MESH': ...
866
260
############## # team_to_tsv script # Creates two tsv files for importing into domjudge # Team info gets stored inside teams.tsv in the following format # <team_id(int)> <external_id> <category_id> <team_name> # Account info gets stored inside acccounts.tsv in the following format # team <team-name> <use...
2,335
761
from __future__ import unicode_literals import frappe import filetype """ NEED IMPORT LOCAL LANG FROM FRAPPE """ def attach_print(doctype, name, file_name=None, print_format=None, style=None, html=None, doc=None, lang=None, encrypt=False, password=None, print_letterhead=True): from frappe.utils import scrub_urls ...
1,848
596
import hashlib import json import uuid import requests import aiohttp from .exceptions import ApiResponseError from .action import Action class BaseCleverApi(): def __init__(self, access_token, version="5.73"): self.access_token = access_token self.api_version = version self.device_id = ...
4,906
1,592
from datetime import datetime as dt from flask import render_template, redirect, request, url_for, abort from flask_login import login_user, logout_user, login_required, current_user, login_url from . import app, db, login_manager from .models import Post, Tag, Author, tags as Post_Tag from .forms import LoginForm, Pos...
5,350
1,717
import string import secrets def gen_objective_id(): return ''.join(secrets.choice(string.ascii_lowercase + string.digits) for _ in range(16)) def gen_scoreholder_id(): return ''.join(secrets.choice(string.ascii_lowercase + string.digits) for _ in range(16)) def gen_function_id(): return ''.join(secr...
509
196
from aiogram.dispatcher.filters.state import StatesGroup, State class Attack(StatesGroup): set_phone_call = State() class Mailing(StatesGroup): set_mailing_text_call = State()
185
59
from rest_framework.routers import DefaultRouter from apps.user.views import AuthViewSet, UserViewSet router = DefaultRouter() router.register("", AuthViewSet, basename="auth") router.register("", UserViewSet, basename="user") urlpatterns = router.urls
255
73
import collections import torch import pprint import string remove_whitespace = str.maketrans('', '', string.whitespace) def cfg_to_md(cfg, uuid): ''' Because tensorboard uses markdown''' return uuid + "\n\n " + pprint.pformat((cfg)).replace("\n", " \n").replace("\n \'", "\n \'") + "" def is_interac...
1,514
519
#!/usr/bin/python import unittest import time import usb.util from g13gui.observer.observer import ObserverTestCase from g13gui.model.prefs import Preferences from g13gui.g13.manager import DeviceManager from g13gui.g13.manager import LCD_BUFFER_SIZE class DeviceManagerTests(ObserverTestCase): def setUp(self): ...
1,652
618
import socket import logging log = logging.getLogger('mpikat.utils.unix_socket') class UDSClient(object): def __init__(self, socket_name): self._socket_name = socket_name self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: self._sock.connect(self._socket_name) ...
754
236
#1- Crie um programa que ler 3 números inteiros A, B, C e exibe a mensagem se o resultado R=(A+B)/C é maior que B ou não. A, B, C = int(input()), int(input()), int(input()) R = (A + B)/C def Maior(R, B): if (R > B): return 'R é maior que B.' else: return 'R não é maior que B.' print(Maior(R, B))
311
128
from django.core.files.storage import FileSystemStorage from django.conf import settings import os class OverwriteStorage(FileSystemStorage): def get_available_name(self, name, max_length=None): """ Returns a filename that's free on the target storage system, and available for new...
1,021
288
class RoomCalculationService: def __init__(self, room_id): self.room_id = room_id def calculate_results(self): pass
140
43
__author__ = 'sp' class Location: def __init__(self, x, y): self.x = x self.y = y class Location_ID: def __init__(self, id, direct, x, y, range): self.id = id self.direct = direct self.x = x self.y = y self.range = range class Products(): def __in...
624
231
#!venv/bin/python import os, re, json from flask import Flask, request from flask_restful import Resource, Api from json import dumps from flask_jsonpify import jsonify from flask import render_template from boxes import * app = Flask(__name__) api = Api(app) def get_logs(date, severity, box): DATESTAMP_RE...
2,400
917
#!/usr/bin/env python3 import boto.utils, json, requests def detect_ec2(): try: r = requests.get('http://169.254.169.254/latest/meta-data/ami-id') print(r) # probably should check for something in the response here. return True except: return False def gen_link(): ...
1,362
429
# # PySNMP MIB module FORCE10-MONITORING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FORCE10-MONITORING-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:14:24 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
58,839
24,719
import numpy as np from requests import session from .core import CPUClient, GPUClient, HybridClient from .temp import TempCPUWorker from .errors import * # Dump a client's attributes into a dictionary so that it can be used remotely. def dump(c): try: return { "_type": c.type, "u...
1,964
708
import os DB_LOCATION = os.getenv("DB_URI", "test.db") # Debug flag to output more verbose logging # - defaults to False DEBUG = os.getenv("DEBUG", False) # Configurable output directory for saving machine learning model pickles # - defaults to ../output OUTPUT_DIR = os.getenv("OUTPUT_DIR", "output") # Port to make...
1,921
696
class A(object): __slots__ = ['foo', 'bar'] a = A() a.ba<caret> class B(object): __slots__ = ['bar'] class C(B): pass C().ba<caret> class D(object): pass class E(D): __slots__ = ['bar'] E().ba<caret> class F: __slots__ = ['baz'] F().ba<caret>
278
132
""" Function : Title : Written by: Email : aarc.88@gmail.com Date : Last edit : Language : Python 3.8 or > Aeronautical Institute of Technology - Airbus Brazil Description: - Inputs: - Outputs: - TODO's: - """ # =========================================================================...
1,952
628
N = int(input()) X = list(map(int, input().split())) W = list(map(int, input().split())) def weighted_mean(X, W): numerator = sum([a * b for a, b in zip(X, W)]) denominator = sum(W) weighted_mean_value = numerator / denominator return round(weighted_mean_value, 1) print(weighted_mean(X, W))
317
126
# -*- coding: utf-8 -*- import os os_env = os.environ class Config(object): COMMON_PATH = os.path.abspath(os.path.dirname(__file__)) # This directory PROJECT_ROOT = os.path.abspath(os.path.join(COMMON_PATH, os.pardir)) DATABASE_URL = "postgresql://he:he@localhost:5432/jobbole" class CeleryConfig(obje...
2,274
933
import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Mock.ui' # # Created by: PyQt5 UI code generator 5.12.3 # # WARNING! All changes made in this file will be lost! import sys import subprocess import application_backend as ab from PyQt5 im...
8,834
2,808
from locust import HttpUser, task, between import re import random import json import os class OdooUser: if os.environ.get('HOST'): host = os.environ.get('HOST') wait_time = between(20, 40) def on_start(self): response = self.client.get("/web/login") assert response.status_code =...
10,935
3,057
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 13 18:03:27 2017 @author: paul """ from SimulatorTLKT import Boat from SimulatorTLKT import FIT_VELOCITY import numpy as np import matplotlib import matplotlib.pyplot as plt from math import pi matplotlib.rcParams.update({'font.size': 22}) pOfS=...
939
424
from pprint import pformat ds_obj_mcx_note = ('The MCX data returned back from \'dscl\' is a string nested in the attribute queried.\n' 'Settings can be filtered by using key filters.\n' 'Multiple values can be filtered for specific domains by comma seperating the values\n' ...
3,387
810
# DESCRIPTION # Run dns check and store the results in the db # monitor_source = host address # DEPENDENCIES # Install python # Install mysql.connector "python -m pip install mysql-connector-python" # Install dotenv "python -m pip install python-dotenv" # Install nslookup "python -m pip install nslookup" # HOW TO RUN...
2,622
836
import torch import cv2 #data dir with train i validation picture data_dir = '/home/pawel/Pulpit/picture_data' #source video stream camera_source = '/dev/video2' #flag, false, not used save = False #input picture size (px) input_size = (224,224) size_pict = input_size[0] #part of the data from the database intended f...
797
278
from .classifier import SpatialClassifier def get_field(config, num_classes, num_indicators, in_channels): if config.name == 'classifier': return SpatialClassifier( num_classes = num_classes, num_indicators = num_indicators, in_channels = in_channels, num_fi...
501
149
from datetime import datetime, timedelta import requests import pandas as pd def cleaner_data(data): columns = ['ESTACAO', 'LATITUDE', 'LONGITUDE', 'ALTITUDE', 'ANO', 'MES', 'DIA', 'HORA', 'TEMP', 'TMAX', 'TMIN', 'UR', 'URMAX', 'URMIN', 'TD', 'TDMAX', 'TDMIN', 'PRESSAONNM', 'PRESSAONNM_MAX', 'PRESS...
1,693
679
#%% # import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from datetime import datetime import os import time %matplotlib inline #%% import pymysql def Select(tableName, start, end) : sql_query = """ SELECT DataSavedTime, Item005 FROM """+tableName+""" WHERE DataSavedTime...
7,795
3,290
from pyconcepticon import Concepticon from pynorare.dataset import get_dataset_cls def add_datasets(parser): parser.add_argument( 'dataset', nargs='+', help='select your dataset', type=str) def iter_datasets(args): for dsid in args.dataset: cls = get_dataset_cls(args...
435
147
# Copyright 2012 Jonathan Paugh # See COPYING for license details ''' Functions that deal with lang files or rulesets ''' import ds import comp as cpl from .options import opt from .util import fwarn, do_re, gettype import os langdir = os.path.join(os.path.dirname(__file__), 'lang') if not os.path.isdir(langdir): ...
2,987
1,056
n,m=map(int,input().split()) mid=n//2 if n==1 and m==1: print("1") elif mid<m: print(m-1) else: print(m+1)
118
60
#!/usr/bin/env python #coding:utf-8 from toughlib import config as iconfig import os import requests class TestMixin: MANAGE_URL = 'http://127.0.0.1:18160' def sub_path(self,path): return "%s%s"%(TestMixin.MANAGE_URL,path) def init_rundir(self): try: os.mkdir("/tmp/toughradiu...
966
327
from game.data.components.TestComponent import *
48
12
from .challenges import Challenge from .solvers import Solver from .agents import random_agent from .exceptions import *
121
33
# recovery (and error) vs noise for all algorithms # recovery (and error) vs condB for all algorithms # recovery vs (k,d) for all algorithms (heatmap) # todo: also condD? # Questions: # - test two distributions for X: Gaussian, and decreasing # - to choose lambda(s), we fix according to average best one from a set o...
10,869
4,635
from . import bb def foo(): bb.bar()
42
19
import click import pytest from click.testing import CliRunner @pytest.yield_fixture def pb_api(mocker): from pushbullet_cli import app from tests.mock_pushbullet import MockPushBullet mock_pb = MockPushBullet() mocker.patch.object(app, "_get_pb", return_value=mock_pb) yield mock_pb @pytest.fix...
1,262
412
#!/usr/bin/env python3 -u # -*- coding: utf-8 -*- """Tests for hierarchical aggregator.""" # copyright: sktime developers, BSD-3-Clause License (see LICENSE file) __author__ = ["ciaran-g"] import pytest from sktime.transformations.hierarchical.aggregate import Aggregator from sktime.utils._testing.hierarchical impor...
2,478
829
from flask.testing import FlaskClient from doni.tests.unit import utils def test_list_availability_windows( mocker, user_auth_headers, client: "FlaskClient", database: "utils.DBFixtures" ): mock_authorize = mocker.patch("doni.api.availability_window.authorize") hw = database.add_hardware() res = clie...
563
192
""" serializers Created by: Martin Sicho On: 27-01-20, 17:00 """ from rest_framework import serializers from genui.utils.serializers import GenericModelSerializerMixIn from genui.compounds.serializers import MolSetSerializer from genui.projects.serializers import ProjectSerializer from . import models class Generato...
747
212
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine from datetime import datetime, timedelta from sqlalchemy import Table, Column, Integer, String, Date, ForeignKey, Boolean from sqlalchemy.orm import relationship, backref from sqlalchemy.orm import sessionmaker from re import s...
5,898
1,631
#!/usr/bin/python3 import math class Solution: @staticmethod def number_of_factor(self): count = 0 if self == 1: return 1 for i in range(1, math.ceil(math.sqrt(self))): if self % i == 0: count += 2 if math.ceil(math.sqrt(self)) == math....
848
307
import numpy as np import pylab as plt from scipy.integrate import simps def grid_interpolate_samples(x, y, bins=1000, return_norm=False): idx = np.argsort(x) x, y = x[idx], y[idx] x_grid = np.linspace(x[0], x[-1], bins) y_grid = np.interp(x_grid, x, y) norm = simps(y_grid, x_grid) y_grid_norm...
9,253
3,332
import os from tabulate import tabulate import requests def iniciar(): os.system('cls') while True: print('Seleccione una opción: ') print('\t1. Registrar movimiento') print('\t2. Ver todos los movimientos') print('\t3. Buscar un movimiento') print('\t4. Modificar un mo...
3,038
1,011
"""Depth-first traversing of a binary tree. Call a function _f on every node of binary tree _bt, in depth-first infix order Source: programming-idioms.org """ # Implementation author: TinyFawks # Created on 2016-02-18T08:50:27.130406Z # Last modified on 2016-02-18T09:16:52.625429Z # Version 2 # Recursive DFS. def...
409
185
# -*- coding: utf-8 -*- from .equipment import lt_equipment from .spell import lt_spell_lxy, lt_spell_zle, lt_spell_lyr, lt_spell_an from .monster import lt_monster from .zone import lt_zone doc_data = dict( lt_equipment=lt_equipment, lt_spell_lxy=lt_spell_lxy, lt_spell_zle=lt_spell_zle, lt_spell_lyr=...
412
210
import matplotlib.pyplot as plt import numpy.ma as ma import numpy as np import pyart.graph import tempfile import pyart.io import boto s3conn = boto.connect_s3("AKIAISFFH4JXWC2HYFSA","9Az+XWYP9cbL3Sh641z/tbMuC1CSpjPjQTFkHj8D") bucket = s3conn.get_bucket('noaa-nexrad-level2') s3key = bucket.get_key('2015/05/...
3,157
1,322
import unittest import requests import json import pytest BASE_URL = "https://api.serverest.dev" class Products(unittest.TestCase): def setUp(self): # Do authentication # Cart endpoint requires authentication full_url = BASE_URL + "/login" body = { "email": "fulano@qa...
3,746
1,114
# Generated by Django 2.1.5 on 2022-03-21 19:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('QuotePT109', '0001_initial'), ] operations = [ migrations.AddField( model_name='page', name='likes', fie...
372
130
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-11-24 13:57 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("message_sender", "0002_auto_20161124_1150")] operations = [ migrations.AlterField( ...
474
174
# -*- coding: utf-8 -*- """02-ppo.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1GXTVkhpJyQQsUWn6tGQAWPmstw9adAzj # PPO for transformer models > A Pytorch implementation of Proximal Policy Optimization for transfomer models. This follows the l...
15,639
4,850
"""Rock Paper Scisssors game using OOP""" import random from tempfile import mkstemp from shutil import move, copymode from os import fdopen, remove class RockPaperScissors: """initializing the 'global' atributtes""" def __init__(self): self.defeat = {"scissors": "rock", "paper" : "scissors"...
4,589
1,363
from faker import Faker from ..models import Client, UserProfile from django.contrib.auth import get_user_model from factory import django, SubFactory, fuzzy, Sequence, LazyAttribute fake = Faker() User = get_user_model() class ClientFactory(django.DjangoModelFactory): class Meta: model = Client ke...
807
241
"""Tests for Devcon."""
24
9
a = input() i = 0 while i != len(a): if a[i] in a[i+1:]: break print(str(i == len(a)).lower())
98
51
# -*- coding: utf-8 -*- # ******************************************************* # Copyright (c) VMware, Inc. 2020-2021. All Rights Reserved. # SPDX-License-Identifier: MIT # ******************************************************* # * # * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT # * WARRANTIES OR C...
2,813
1,011