text
string
size
int64
token_count
int64
from django.shortcuts import render, redirect from django.shortcuts import HttpResponse from django.core.mail import EmailMessage import subprocess import os PROFILES_DIR = '/code/profiles' def index(request): return render(request, 'index.html') def profile_create(request): if request.method != 'POST': ...
1,516
479
import sys import os import cv2 import numpy as np from matplotlib import pyplot as plt import hed curdir = os.path.abspath(os.path.curdir) sys.path.append(os.path.join(os.path.dirname(curdir), 'tf_pose')) from pycocotools.coco import COCO dataset_path = '/home/artia/prj/datasets/coco' coco = COCO(os.path.join(dataset...
2,922
1,171
dict1 = {"a": 1, "b": 2} dict2 = {"b": 3, "c": 4, 3: 9} dict3 = {"a": 2} dict4 = {"d": 8, "e": 1} print("Result of merging dict 1-4:", {**dict1, **dict2, **dict3, **dict4})
174
97
import os import time import subprocess from DIRAC import gLogger class MergeFile(object): def __init__(self): self._directlyRead = False self._localValidation = True def merge(self, fileList, outputDir, mergeName, mergeExt, mergeMaxSize, mergeCallback): allFileSize = self.__getAllFileSize(fileList)...
1,742
563
# # findings from dojo.utils import Product_Tab from dojo.forms import DeleteFindingGroupForm from dojo.notifications.helper import create_notification from django.contrib import messages from django.contrib.admin.utils import NestedObjects from django.db.utils import DEFAULT_DB_ALIAS from django.http.response import ...
5,727
1,648
import os import tempfile from pathlib import Path from yt.data_objects.time_series import get_filenames_from_glob_pattern from yt.testing import assert_raises def test_pattern_expansion(): file_list = ["fake_data_file_{}".format(str(i).zfill(4)) for i in range(10)] with tempfile.TemporaryDirectory() as tmp...
899
301
from typing import Dict, Any, Callable, Optional import torch from decouple import Module from torch import nn from .events import ( ModelForwardStartEvent, ModelForwardEndEvent, ModelInitEvent) from ..loader import LoaderProcessBatchStartEvent from ..runner import RunnerStartEvent class InferManager(Module): ...
1,561
448
############################################################################## ## Project Banner: Sensor Data Logging ## Created: 07-11-2016 by Madeline McMillan and Nate Peirson ## Texas A&M University, Department of Aerospace Engineering ## High Altitude Balloon Club ## Sensor data points are taken by this script ...
1,757
611
# Send SMS message on WM6 phone from Python 2 # Silas S. Brown - public domain import ctypes import ctypes.wintypes as wintypes def send_SMS_message(number, unicode_text, confirm_delivery=True): print "Sending to "+number+"..." handle = wintypes.DWORD() ret = ctypes.cdll.sms.SmsOpen(u"Microsoft Text SMS Protocol...
1,064
418
#coding=utf-8 from __future__ import print_function try: import numpy as np except: pass try: from hyperopt import Trials, STATUS_OK, tpe except: pass try: from keras.datasets import mnist except: pass try: from keras.layers.core import Dense, Dropout, Activation except: pass try: ...
3,861
1,329
# # Example python script to generate a BOM from a KiCad generic netlist # # Example: Sorted and Grouped HTML BOM with advanced grouping # """ @package Generate a HTML BOM list. Components are sorted and grouped by value Fields are (if exist) Ref, Quantity, Value, Part, Footprint, Description, Vend...
4,313
1,374
import os from keras.models import * from keras.layers import * from keras.optimizers import Adam import tensorflow as tf import keras import itertools import numpy as np from keras.callbacks import Callback from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score import tensorflow as tf fr...
7,908
2,994
''' This package comes from https://github.com/xianghuzhao/paradag It can also be installed by "pip install paradag" ''' import random class DagVertexNotFoundError(Exception): pass class DagEdgeNotFoundError(Exception): pass class DagCycleError(Exception): pass class DagData(object): def __init__...
5,925
1,891
import numpy as np from tqdm import tqdm from pensa.features import * from pensa.statesinfo import * # -- Functions to calculate SSI statistics across paired ensembles -- def ssi_ensemble_analysis(features_a, features_b, all_data_a, all_data_b, torsions=None, pocket_occupancy=None, pbc=True, ...
33,547
10,498
import os import logging import time import unittest import urllib.parse import xml.etree.ElementTree as ElementTree from streamsx.topology.tester import Tester from streamsx.topology.context import ConfigParams, JobConfig from streamsx.build import BuildService from streamsx.rest_primitives import * logger = loggin...
16,582
4,912
import asyncio from .config import conf from .logger import main_logger from .web import HTTPRequest, http301, WebHandler log = main_logger.get_logger() target_port = conf.get("https", "port") class Redirect_Handler(WebHandler): async def get(self): if self.request.head.get("X-Local"): return ...
1,730
534
import time from datetime import timedelta import numpy as np from qflow.wavefunctions import ( JastrowPade, SimpleGaussian, WavefunctionProduct, Dnn, InputSorter, ) from qflow.wavefunctions.nn.layers import DenseLayer from qflow.wavefunctions.nn.activations import tanh, exponential from qflow.hami...
3,619
1,418
# CON_TC28_ManyArticle: Ismételt és sorozatos adatbevitel adatforrásból # a szükséges csomagok, modulok betöltése from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import time import csv def test_CON_TC28_ManyArticle(): # webdriver konfiguráció, tesztelt oldal megnyitása ...
2,721
916
from flask_discord_interactions import CommandOptionType, Context, Member def test_subcommand(discord, client): group = discord.command_group("group") @group.command() def sub_one(ctx): return "sub one" @group.command() def sub_two(ctx): return "sub two" assert client.run("g...
2,943
841
#-*- coding:utf-8 _*- """ @author:charlesXu @file: setup.py @desc: 设置 @time: 2019/05/23 """ from setuptools import setup setup( name="TimeConverter", version="1.1.0", keywords=("time", "nlp"), description="...", long_description="...", license="MIT Licence", url="http://test.com", auth...
783
277
class SudokuSolver: def __init__(self, query_string, rows = 'ABCDEFGHI', columns = '123456789'): """ Initializing the various variables required here """ self.query_string = query_string self.rows = rows # The Rows are labeled from A to Z self.colu...
6,963
1,966
import numpy as np import pytest from dnnv.verifiers.common.reductions.iopolytope import * from dnnv.verifiers.common.reductions.iopolytope import Variable def setup_function(): Variable._count = 0 def test_update_constraint_single_index(): v = Variable((1, 3, 2, 2)) hspoly = HyperRectangle(v) var...
4,599
1,912
# Copyright (c) 2022, Rabie Moses Santillan and contributors # For license information, please see license.txt import frappe from frappe.model.document import Document class PawnTicketJewelry(Document): def before_save(self): if frappe.db.exists('Pawn Ticket Jewelry', self.name) == None: settings = frappe.get_d...
615
229
import matplotlib.pyplot as plt # Example plot X = range(-5, 5) # Note the missing +5! Y = [pow(x, 2) for x in X] plt.plot(X, Y) plt.show() plt.xlabel('X', color='fuchsia', fontweight='bold') plt.ylabel('f(x)') plt.plot(X, Y, 'o-', label='squared') # other styles: '--', ':' plt.legend(loc="upper left") plt.savefig...
346
153
from .analyser import Analyser from project.bots.response.response_answer import ResponseAnswer from project.bots.response.response import BotResponse from project.bots.response.unknown_response import UnknownResponse from project.bots.documents import MessagesDocument from project.bots.models import Messages class E...
1,866
488
from pathlib import Path import json class Settings: def __init__(self): self.config = {} self.path_settings_file = Path.home().joinpath('.breefkase') self.breefkase_dir = None self.load() def load(self): f = self.path_settings_file try: with open(f...
1,258
344
# _*_ coding:utf-8 _*_ # 作者:hungryboy # @Time: 2021/1/28 # @File: class01.py print("欢迎来到hungryboy的python世界!") def test(): print("这是一个函数,在Demo类外面") class Demo: print("this is a demo") def demo(self): print("这是Demo类中的方法!")
244
128
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
4,751
1,511
import unittest from data_cube_utilities import dc_coastal_change class TestCoastalChange(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_compute_coastal_change(self): pass def test_mask_mosaic_with_coastlines(self): pass def test_m...
371
132
import argparse from joblib import Parallel, delayed from scripts.ssc.TopoAE_ext.config_libraries.swissroll import swissroll_run1 from src.models.WitnessComplexAE.train_engine import simulator_TopoAE_ext def parse_input(): parser = argparse.ArgumentParser() parser.add_argument("--threads", default=30, help=...
502
171
def problem363(): pass
27
11
# -*- coding: utf-8 -*- from nlplingo.common.utils import DEPREL_TO_ID # ==> from nlplingo.oregon.event_models.uoregon.models.pipeline._01.local_constants import * from fairseq.models.roberta import XLMRModel from nlplingo.oregon.event_models.uoregon.tools.utils import * from nlplingo.oregon.event_models.uoregon.layer...
41,666
19,538
# ref: https://www.tensorflow.org/guide/keras/rnn # ref: https://www.tensorflow.org/tutorials/structured_data/time_series from __future__ import absolute_import, division, print_function, unicode_literals import collections import matplotlib.pyplot as plt import numpy as np import pandas as pd import tensorflow as tf ...
3,203
1,307
import os import requests # export FASTAPI_ROOT="http://fastapi-micro-service:8000" FASTAPI_ROOT = os.environ.get("FASTAPI_ROOT") def test_hello_world(): endpoint_url = f"{FASTAPI_ROOT}/" response = requests.get(endpoint_url) assert response.status_code == 200 response_json = response.json() asse...
436
147
from cloudmesh.burn.image import Image import os i = Image() os.system("touch ~/.cloudmesh/cmburn/images/junk.img") os.system("touch ~/.cloudmesh/cmburn/images/junk.zip") r = i.ls() print (r) r = i.clear() print (r)
221
93
""" * Assignment: Sequence Slice Train/Test * Required: yes * Complexity: easy * Lines of code: 4 lines * Time: 8 min English: 1. Divide `data` into two lists: a. `train`: 60% - training data b. `test`: 40% - testing data 2. Calculate split point: a. `data` length multiplied by percent ...
2,963
1,297
from django.db import models from django.utils import timezone from dateutil import tz import pytz from datetime import date from django.core.validators import MinValueValidator from django.db import transaction from profil.models import KioskUser from django.db import connection from django.conf import settings from ...
26,869
11,089
import sqlite3 import re from sys import prefix conn = sqlite3.connect('orgdb.sqlite') cur = conn.cursor() cur.execute('DROP TABLE IF EXISTS Counts') cur.execute(''' CREATE TABLE Counts (org TEXT, count INTEGER)''') prefix='../file/' fname = input('Enter file name: ') if (len(fname) < 1): fname = 'mbox-short.tx...
910
350
from django.db import models from profiles.models import Profile # Create your models here. class Group(models.Model): users = models.ManyToManyField(Profile, blank=True, related_name='groups') owner = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name='+') name = models.CharField...
694
208
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import sys from torch.utils.data import DataLoader import argparse import copy sys.path.append("../utils/") import matplotlib.pyplot as plt import numpy as np from models import * from social_utils import * import yaml parse...
7,111
3,200
import copy import json def process_template(template, params): new_template = copy.deepcopy(template) status = 'success' for name, resource in template['Resources'].items(): if 'Count' in resource: #Get the number of times to multiply the resource count = new_template['Res...
3,386
814
MWZWSmMhtUsRrINuSTzFrxaxjBTBJqSWKuKnGWRXkqWQJqFZtHcGtyMgFWrExRGweSHLOCtzbXotCELvYZdsUDmsxKLYPEnCGzbpsNkLrKPigaoVayVePBGtbjfjhKyb=""" \x23\x20\x2d\x2a\x2d\x20\x63\x6f\x64\x69\x6e\x67\x3a\x20\x75\x74\x66\x2d\x38\x20\x2d\x2a\x2d\x0a \x69\x6d\x70\x6f\x72\x74\x20\x64\x61\x74\x65\x74\x69\x6d\x65\x0a \x53\x4b\x4f\x47\x5a\x7a\...
176,065
175,999
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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 requi...
8,745
2,873
# t210.py from machine import Pin from simp_py import tft count=0 def counting(v): global count, show, p5 if p5.value()==0: count+=1 else: count-=1 btnA= Pin(39,Pin.IN) a = Pin(5, Pin.IN,Pin.PULL_UP) b = Pin(2, Pin.IN,Pin.PULL_UP) a.irq(counting,trigger=Pin.IRQ_RISING| Pin.IRQ_FALLING) pcount=-1 while 1: ...
461
225
import datetime import logging import pytz from django.utils import timezone from django.utils.dateparse import parse_date, parse_datetime logger = logging.getLogger(__name__) Y2K = datetime.datetime(2000, 1, 1) def formated_timedelta(total_seconds): """ Format time delta as H:M:S\ :param total_secon...
2,876
988
"""Contains structure parsers.""" __all__ = [ "alarms", "device_parameters", "frame_versions", "lambda_", "mixer_parameters", "mixers", "modules", "output_flags", "outputs", "statuses", "temperatures", "thermostats", "uid", "var_string", ]
297
108
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # Licensed under the Apache License, Version 2.0 https://aws.amazon.com/apache-2-0/ from api.connector import AWSConnector import os import json import time import argparse try: client_config_file = os...
2,805
836
import random #setting variables ranwins = 0 conwins = 0 ties = 0 takes = 1000 for quiz in range (0, takes): rancorrect=0 ranincorrect=0 concorrect=0 conincorrect=0 revisions=1000 possible = 4 # the consistent variable remains constant through the entire sequence # and is compared to the same s...
1,745
561
import threading import time from typing import Callable, List, Dict class Scheduler(): def __init__(self, interval:int, function:Callable, *args, **kwargs) -> None: self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs ...
901
259
from ..base import BaseQuery from .attributes import DiscourseNode class DiscourseQuery(BaseQuery): """ Class for generating a Cypher query over discourses """ def __init__(self, corpus): to_find = DiscourseNode(corpus=corpus.corpus_name, hierarchy=corpus.hierarchy) super(DiscourseQue...
356
107
import pymysql as mdb import sys class App(object): def __init__(self, ip, user, passwd, db): # Menú de la interfaz de texto self.mainMenu='''\n Videoclub: ------------------ 0: Salir. 1: Dar de alta un socio. 2: Dar de baja un socio. 3: Cerrar un alquiler. 4: Consultar DVDs para una película. 5: Con...
5,166
1,805
import warnings import numpy as np try: import matplotlib.pyplot as plt except ImportError: # mpl is optional pass from .kdeplot import kdeplot def energyplot(trace, kind='kde', figsize=None, ax=None, legend=True, shade=0.35, bw=4.5, frame=True, kwargs_shade=None, **kwargs): """Plot energ...
2,533
768
from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms import StringField, PasswordField, SubmitField, BooleanField, FieldList, TextAreaField, IntegerField from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError from wtforms.fields.html5...
6,852
1,906
from imutils.object_detection import non_max_suppression from imutils import paths, resize import numpy as np import argparse import imutils import cv2 from math import cos, sin, atan import time def find_body_part(mask, ratio_y, ratio_x): bodyPartAverage = 0 bodyPart = np.zeros( (int(mask.shape[0] / ...
14,986
6,539
#!/bin/env python from __future__ import print_function import argparse import traceback import sys from . import io from . import utl def main(): parser = argparse.ArgumentParser(description="convert between zeke dump files and directory structures") parser.add_argument("-f", "--file", metavar="DUMP", he...
2,027
595
#!/usr/bin/env python3 import logging import os from pathlib import Path from typing import Optional import click from clin.clinfile import calculate_scope from clin.config import ConfigurationError, load_config from clin.nakadi import Nakadi, NakadiError from clin.processor import Processor, ProcessingError from cli...
5,470
1,723
"""-------------------------------------------------------------------- Copyright (c) 2017, Kinova Robotics inc. 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 mus...
13,668
4,304
# Copyright (c) 2021 EcoFOCIpy """Setup script for installing EcoFOCIpy.""" import sys from setuptools import setup if sys.version_info[0] < 3: error = """ EcoFOCIpy requires the Python 3.8 or above, but will install on all versions of python3. Python {py} detected. """.format(py='.'.join([str(v...
412
158
from nltk.corpus import stopwords # Remove stop words stop_words = set(stopwords.words("english")) def remove_stop_words(sentence): filtered_sentence = [] for w in sentence: if w not in stop_words: filtered_sentence.append(w) return filtered_sentence
288
91
import os import torch import random import numpy as np import math import torch.distributions as pyd import psutil import datetime class TanhTransform(pyd.transforms.Transform): domain = pyd.constraints.real codomain = pyd.constraints.interval(-1.0, 1.0) bijective = True sign = +1 def __init__(s...
3,781
1,292
def downloader(year, month, day, week): #downloads the data from Nordpool from download import download from jsonhandler import importJSON, writeJSON time = str("{:4d}-{:02d}-{:02d}".format(year, month,day)) data = importJSON("tasklists/tasklist.json") if time != data["downloader_time"]: ...
7,374
2,501
import base64 import json import random from unittest.mock import create_autospec import pytest from pytest import fixture from bai_kafka_utils.executors.descriptor import BenchmarkDescriptor, DescriptorError from transpiler.bai_knowledge import ( BaiKubernetesObjectBuilder, SingleRunBenchmarkKubernetesObject...
4,213
1,402
from CTFd.constants import RawEnum class FreezeTimes(str, RawEnum): NOT_STARTED = "2017-10-3" # Tuesday, October 3, 2017 STARTED = "2017-10-5" # Thursday, October 5, 2017 ENDED = "2017-10-7" # Saturday, October 7, 2017 START = "1507089600" # Wednesday, October 4, 2017 12:00:00 AM GMT-04:00 DST ...
393
221
from bootstrapvz.base import Task from bootstrapvz.common import phases import os class CheckAssetsPath(Task): description = 'Checking whether the assets path exist' phase = phases.preparation @classmethod def run(cls, info): from bootstrapvz.common.exceptions import TaskError assets = info.manifest.plugins[...
1,050
350
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-06-17 20:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('comms', '0011_auto_20170606_1731'), ('comms', '0011_auto_20170217_2039'), ] operations = [ ]
295
142
import resnet3 as net import numpy as np import cv2 img = cv2.imread('9_1.jpg') res1 = net.eval(img.reshape([-1,128,128,3])) img = cv2.imread('10_1.jpg') res2 = net.eval(img.reshape([-1,128,128,3])) res1 = res1/np.linalg.norm(res1) res2 = res2/np.linalg.norm(res2) cosres = res1*res2 cosres = cosres.sum() print(...
370
186
# Copyright 2015 Google Inc. 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 applicable law or ag...
2,988
779
import os import psycopg2 class PersistentStringSet: def __init__(self, name): self._table_name = f"persistent_set_{name}" def _conn(self): conn = psycopg2.connect(os.environ["DATABASE_URL"]) cursor = conn.cursor() cursor.execute( f""" CREATE TABLE IF N...
1,161
308
# -*- coding: utf-8 -*- class RateExceededError(Exception): pass
71
30
from online_net import OnlineNet import utils import printer import asyncio # 领取银瓜子 async def GetAward(): temp = await OnlineNet().req('get_time_about_silver') # print (temp['code']) #宝箱领完返回的code为-10017 if temp['code'] == -10017: printer.info(["# 今日宝箱领取完毕"]) else: time_start = temp[...
2,193
853
from keras import backend as K from skimage.transform import resize import tensorflow as tf K.set_image_data_format('channels_last') def true_pos(y_true, y_pred): return K.sum(y_true * K.round(y_pred)) def false_pos(y_true, y_pred): return K.sum(y_true * (1. - K.round(y_pred))) def false_neg(y_true, y_pred...
1,585
584
# Generated by Django 3.2.6 on 2021-08-06 23:57 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app', '0009_auto_20210806_2012'), ] operations = [ migrations.RemoveField( model_name='device',...
1,968
586
split_string = "This string has been \nsplit over\nseveral\nlines" print(split_string) tabbed_string = "1\t2\t3\t" print(tabbed_string) print('Hello what\'s the situation like. He\'s is not responding') print("Hello what's the situation like. He's is not responding") print("""Hello what's the situation like. He's is ...
537
189
from app.helpers.uuid_helper import is_valid_uuid from app.libs.utils import convert_tx_id def test_convert_tx_id(): tx_id_to_convert = "bc26d5ef-8475-4710-ac82-753a0a150708" assert is_valid_uuid(tx_id_to_convert) assert convert_tx_id(tx_id_to_convert) == "BC26 - D5EF - 8475 - 4710"
299
144
"""csi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based vie...
2,381
755
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-21 06:09 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('cryptographer', '0001_cryptographer_user'), ('challen...
1,179
366
import pdb import argparse from config.load_config import load_config load_config() class CommandOptions: dmcheckuserscreenname = None class Migration: def __init__(self): #tested self.cmd_options = CommandOptions() def read_command(self): #tested parser = argparse.Argumen...
1,219
353
#!/usr/bin/env python #-*- coding: utf-8 -*- from __future__ import unicode_literals import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from django.test.client import Client from django.utils import unittest from django.test import TestCase from django.test.utils import override_settings class J...
2,055
718
import os import subprocess import argparse import utils as ut import time """ A simple script for running prediction on a multiple sessions, fusing the resulting point clouds, and then uploading the results to sketchfab, as well as copying them to a more convenient location on the file system. """ def write_results...
4,034
1,231
print(f'{"CÁLCULO DE PROGRESSÃO ARITMÉTICA":=^60}') print() a1 = int(input('Digite o primeiro termo da PA: ')) r = int(input('Digite a razão da PA: ')) an = a1 + 10 * r # Cálculo termo geral da PA, para saber qual o último termo da PA, "10" são a quantidade de termos # da PA for c in range(a1, an, r): print(f"{c...
349
155
"""Portall's GeoDataFrame wrappers.""" from __future__ import annotations import geopandas as gpd from typing import Optional from pydantic.types import UUID4 from pydantic import BaseModel, Field from pyportall.api.engine.core import APIClient, ENDPOINT_DATAFRAMES from pyportall.api.models.geojson import FeatureColl...
7,176
2,638
import numpy as np class Configuration: """ A :any:`Configuration` describes a specific arrangement of objects in the vector space of possible positions. Objects are represented by integers, with indistinguishable objects denoted by identical integers. This class subclasses `numpy.matrix <https://docs....
6,778
1,728
from . import test_generators
29
8
from multiclass_model import MulticlassMultiLabelModel """ Classify a single image file from the filesystem. """ parser = ArgumentParser() parser.add_argument('--runname', '-n', dest='run_name', type=str, help='Name for this run, will otherwise not try to load model.') parser.a...
853
290
import numpy as np import cv2 img = cv2.imread("opencv-template-matching-python-tutorial[1].jpg") template = cv2.imread("opencv-template-for-matching[1].jpg",0) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) w,h = template.shape[::-1] #w=width h=height res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) ...
621
259
from enum import IntEnum from enum import Enum class Player: """Player Class""" name = "" MaxHP = 0 hp = 0 Strength = 0 Defense = 0 gold = 0 MaxExp = 100 exp = 0 lvl = 1 Pclass = "" uniqueId = 0 Inventory = dict() Equipment = dict() def __init__(self, playe...
1,958
725
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
2,311
523
import sys import time import threading from baseplatform import BasePlatform class DesktopPlatform(BasePlatform): def __init__(self, config): super(DesktopPlatform, self).__init__(config) self.__config = config self.__pconfig = config['platforms']['common'] self.__pconfig.update(config['platforms']['desk...
1,481
525
from tradedoubler_api_client import Tradedoubler import pprint if __name__ == '__main__': pp = pprint.PrettyPrinter(indent=4, compact=True, sort_dicts=False) td = Tradedoubler('credentials.json') report = td.reporting().get_transactions(fromDate='20210601', toDate='20210610') report.filter_sales() ...
425
158
""" Vorticity and tangential velocity for a 2D inviscid vortex patch See: [1] Chapter 33, p.402, Branlard - Wind turbine aerodynamics and vorticity based methods, Springer 2017 """ import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from vortilib.tools.colors import fColrs from vortilib.tool...
4,107
1,960
#!/usr/bin/python # # Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es) # # 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 ...
7,771
2,439
""" Test models with requiring a db connection """ import pytest from timelink.mhk.models import base # noqa from timelink.mhk.models.entity import Entity # noqa from timelink.mhk.models.pom_som_mapper import PomSomMapper from timelink.mhk.models.base_class import Base from timelink.mhk.models.db import TimelinkDB...
755
270
"""This problem was asked by Twitter. Given a list of numbers, create an algorithm that arranges them in order to form the largest possible integer. For example, given [10, 7, 76, 415], you should return 77641510."""
218
70
# generated from catkin/cmake/template/order_packages.context.py.in source_root_dir = "/home/engboustani/Documents/3d-printer-arm/catkin_ws/src" whitelisted_packages = "".split(';') if "" != "" else [] blacklisted_packages = "".split(';') if "" != "" else [] underlay_workspaces = "/home/engboustani/Documents/3d-printer...
533
210
# # LAMMPS.py # # Interface to LAMMPS (http://lammps.sandia.gov) # # Copyright (c) 2017 Terumasa Tadano # # This file is distributed under the terms of the MIT license. # Please see the file 'LICENCE.txt' in the root directory # or http://opensource.org/licenses/mit-license.php for information. # import numpy as np ...
11,188
3,611
# -*- coding: utf-8 -*- """ Created on Mon Sep 16 11:53:02 2019 @author: uqcleon4 """ import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm class WaveEquationFD: def __init__(self, N, D, Mx, My): self.N = N self.D = D self.M...
4,550
1,808
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class SpiritCommentConfig(AppConfig): name = 'spirit.comment' verbose_name = "Spirit Comment" label = 'spirit_comment'
234
78
""" Functions and classes for heif images to read. """ import builtins import pathlib from functools import partial from warnings import warn from _pillow_heif_cffi import ffi, lib from .constants import ( HeifFiletype, HeifColorProfileType, HeifChroma, HeifChannel, HeifColorspace, HeifBrand,...
11,443
4,008
import time from collections import OrderedDict import pickle import numpy as np import gym import os import tensorflow as tf from flow.controllers.imitation_learning.utils import * from flow.utils.registry import make_create_env from flow.controllers.imitation_learning.imitating_controller import ImitatingController f...
58,113
16,736
annual_salary = float(input("Enter your annual salary")) portion_saved = float(input("Enter the percent of your salary to save, as a decimal")) total_cost = float(input("Enter the cost of your dream home")) semi_annual_raise = float(input("Enter the semi­annual raise, as a decimal")) portion_down_payment = 0.25 * tota...
660
251