text
string
size
int64
token_count
int64
#Copyright 2020 DB Engineering #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, softwa...
12,973
5,131
# # This is the library part of Anita, the Automated NetBSD Installation # and Test Application. # import os import pexpect import re import string import subprocess import sys import time import urllib import urlparse __version__='1.40' # Your preferred NetBSD FTP mirror site. # This is used only by the obsolete co...
59,491
20,286
# Copyright (c) 2019, Solitude Developers # # This source code is licensed under the BSD-3-Clause license found in the # COPYING file in the root directory of this source tree from typing import Mapping, Union, Optional # noqa import os import shutil import tempfile from functools import wraps from collections import...
5,356
1,549
from abc import ABC, abstractmethod from datetime import datetime from typing import TYPE_CHECKING, Dict, Any, List, Optional if TYPE_CHECKING: from openwater.core import OpenWater class ZoneRun: def __init__(self, id: int, zone_id: int, start: datetime, duration: int): self.id = id self.zone...
2,883
912
#!/usr/bin/env python import struct from elftools.elf.elffile import ELFFile def elf_get_preinit(elffile): preinit_offset = None preinit_funcs = tuple() for sec in elffile.iter_sections(): if sec.name == '.preinit_array': sz = sec['sh_size'] preinit_offset = sec['sh_offset...
2,339
755
from .attribute import process_attribute
41
9
import hashlib from django.test import TestCase from django.urls import reverse from shortener.models import Url class RedirectViewTestCase(TestCase): def setUp(self): self.redirect = "https://pennlabs.org" self.url, _ = Url.objects.get_or_create(long_url=self.redirect) def test_exists(self...
855
274
import torch import torch.nn as nn from timm.loss import LabelSmoothingCrossEntropy from pytorch_metric_learning import losses class create_class_loss(nn.Module): """ 常规分类 - 损失函数入口 """ def __init__(self, name): super(create_class_loss, self).__init__() assert name in ["cross_entropy",...
1,758
587
from rdflib import URIRef from rdflib.namespace import DC, RDF, OWL, RDFS from geontology import GeoOntology ont = GeoOntology("geo_ontology.ttl", frmt='n3') # print ont.serialize() graph = ont.graph print "InfoColumns" for s, p, o in graph.triples( (None, RDFS.subClassOf, URIRef('http://move.ugent.be/geod...
1,195
499
import os import os.path as osp import argparse import random parser = argparse.ArgumentParser(description='Emotiw dataset list producer') args = parser.parse_args() train = "/home/quxiaoye/disk/FR/Emotiw2018/data/Train_AFEW_all/Emotiw-faces" test = "/home/quxiaoye/disk/FR/Emotiw2018/data/Val_AFEW/Emotiw-faces" tr...
1,397
544
IMG_DIR = "/path/to/pictures" IMG_POLL_RATE = 1 # minute DWELL_TIME = 5 # seconds FADE_TIME = 1 # seconds REFRESH_RATE = 10 # milliseconds
141
66
####################################################################### ## ## Zed64 MetroComputer ## ## Unless a module otherwise marked, ## Copyright 2014, Michael T. Mayers (michael@tweakoz.com ## Provided under the Creative Commons Attribution License 3.0 ## Please see https://creativecommons.org/licenses/by/3.0/us/...
5,050
1,690
# https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/ # Return the lexicographically smallest subsequence of s that contains all the # distinct characters of s exactly once. # Note: This question is the same as 316: https://leetcode.com/problems/remove- # duplicate-letters/ ###################...
1,127
296
import boto3 import re import datetime import time ec = boto3.client('ec2') iam = boto3.client('iam') """ This function looks at *all* snapshots that have the tags "Type:Automated" and "DeleteOn" containing the current day formatted as YYYY-MM-DD. The function will delete the if the todays date is > than the "DeleteO...
2,207
662
'''OpenGL extension NV.fragment_program This module customises the behaviour of the OpenGL.raw.GL.NV.fragment_program to provide a more Python-friendly API ''' from OpenGL import platform, constants, constant, arrays from OpenGL import extensions, wrapper from OpenGL.GL import glget import ctypes from OpenGL.raw.GL....
378
107
from appr.commands.push import PushCmd as ApprPushCmd from kpm.manifest_jsonnet import ManifestJsonnet class PushCmd(ApprPushCmd): default_media_type = 'kpm' def _kpm(self): self.filter_files = True self.manifest = ManifestJsonnet() ns, name = self.manifest.package['name'].split("/")...
675
202
""" Define the errors which may occur """ langMismatchWarning = "Classical language {} does not match output language {}" langNotDefWarning = "Language {0} translation not found, check QASMToQuEST/langs/{0}.py exists" noLangSpecWarning = "No language specified for screen print" noSpecWarning = "Neither language nor out...
360
97
from common.matrix import Matrix def distinct_powers(n): m = Matrix(n + 2, n + 2) for i in range(2, n + 1): m[i][2] = i ** 2 for j in range(3, n + 1): m[i][j] = m[i][j - 1] * i distinct_values = set() for i in range(2, n + 1): for j in range(2, n + 1): ...
383
159
# exercism exercise "transpose" def transpose(lines: str) -> str: input_list = lines.split('\n') # or splitlines input_height = len(input_list) input_width = get_input_width(input_list) output_list = [] for colnum in range(input_width): output = '' for rownum in range(input_height)...
1,436
496
import h5py def create_file(filename, datapath, labels, live, timestamps, spectra): # Creating sample dataset f = h5py.File(filename, "w") # data structure for MUSE files dset1 = f.create_dataset(datapath + labels['live'], (1000,)) dset2 = f.create_dataset(datapath + labels['timestamps'], (100...
548
201
from django.db import models from django.utils.timezone import now from django.core.validators import FileExtensionValidator from django.contrib.auth import get_user_model from django.contrib.postgres.fields import ArrayField from django.db.models import (Func, Value, CharField, IntegerField) from .shortcuts import up...
4,318
1,223
import OnePy as op instrument = "000001" ktype = "D" start = "2017-01-01" end = None test = op.Tushare_to_MongoDB(database=instrument, collection=ktype) test.data_to_db(code=instrument, start=start, end=end, ktype=ktype, autype="qfq", index=False)
250
111
from __future__ import print_function import h5py as h5f import numpy as np import six import os from .npy_generator import NpzGeneratorDataset from .image import * class H5fGeneratorDataset(NpzGeneratorDataset): ''' Placeholder class for use with the ctp training tool. This one generates samples from an...
1,836
526
import Distances as d import pandas as pd import numpy as np class CBSmot: nano_to_seconds = 1000000000 def count_neighbors(self, traj, position, max_dist): neighbors = 0 yet = True j = position + 1 while j < len(traj.index) and yet: if d.Distances.calculate_two_poi...
5,821
1,914
from django.contrib import admin from .models import TipoDeGasto, PresupuestoDeGasto admin.site.register(TipoDeGasto) admin.site.register(PresupuestoDeGasto)
164
57
#!/usr/bin/env python # encoding: utf-8 """ Validate a JavaScript file using eslint. Author: Nate Silva Copyright 2014 Nate Silva License: MIT """ from __future__ import print_function import sys import os import re import time import json import subprocess import tempfile import hashlib import shutil def find_up_...
13,838
4,323
# y = f(X) # y = 2*x -10 # x>0 # y = 0# x=0 # y = 2 * abs(x) -1 # x<0 print("Введіть число") x = float(input()) y = 0 if x > 0: y = 2*x -10 elif x == 0: y = 0 else: #x<0 y = 2 * abs(x) -1 print ("y: ",y)
240
151
import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torch.nn.functional as F from torch.nn import init class attention(nn.Module): def __init__(self, input_channels, map_size): super(attention, self).__init__() ...
8,745
2,970
import setuptools exec(open('histoprep/_version.py').read()) with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="histoprep", version=__version__, author="jopo666", scripts=['HistoPrep'], author_email="jopo@birdlover.com", description="...
1,349
487
import platform from setuptools import Extension, setup target = platform.system().lower() extra_compile_args = [] if target.startswith('linux'): extra_compile_args.append('-std=c++11') ext = Extension( name='depth_sort', sources=['depth_sort.cpp'], extra_compile_args=extra_compile_args, ) setup( ...
389
136
## @package Training_app # Training code developed with Tensorflow Keras. Content: Unet, Unet++ and FCN # # @version 1 # # Pontificia Universidad Javeriana # # Electronic Enginnering # # Developed by: # - Andrea Juliana Ruiz Gomez # Mail: <andrea_ruiz@javeriana.edu.co> # GitHub: andrearuizg # - Pedro E...
15,260
6,787
#!/usr/bin/env python # -*- coding: utf-8 -*- import tensorflow as tf import copy from tf_image_segmentation.models.fcn_8s import FCN_8s from tf_image_segmentation.utils.tf_records import read_tfrecord_and_decode_into_image_annotation_pair_tensors from tf_image_segmentation.utils.training import get_valid_logits_and_l...
12,133
3,631
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' try: from PyQt4.QtCore import QSettings except: from PyQt5.QtCore import QSettings if __name__ == '__main__': config = QSettings('config.ini', QSettings.IniFormat) counter = int(config.value('counter', 0)) config.setValue('...
379
141
#!/usr/bin/env python __version__ = '0.9.6'
46
23
""" Main test """ import unittest import uuid from api import APP from flask import json from api.models.user import User from api.models.business import Business from api.helpers import get_token class MainTests(unittest.TestCase): """ Main test """ url_prefix = '/api/v1/' def setUp(self...
3,410
968
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ Topic: print分隔符和结尾符 Desc : """ def print_sepend(): print('ACME', 50, 91.5) print('ACME', 50, 91.5, sep=',') print('ACME', 50, 91.5, sep=',', end='!!\n') for i in range(5): print(i) for i in range(5): print(i, end=' ') print() ...
423
205
import yaml def read_config(): file_stream = open("config/config.yaml", "r") return yaml.safe_load(file_stream)
122
44
from django.db import models from game.models import Game class Character(models.Model): name = models.CharField(max_length=250) game = models.ManyToManyField(Game, related_name='characters') def __unicode__(self): return "{0}".format(self.name) def __str__(self): return "{0}".format...
331
105
import math import matplotlib.pyplot as plt from simpy import model ax1 = plt.subplot(121) ax2 = plt.subplot(122) model_sin = model.TimedFunctionModel(math.sin) model_cos = model.TimedFunctionModel(math.cos) scope = model.ScopeModel(ax1, ax2) def run(): scope(model_sin(), model_cos())
296
112
bs=input("Enter basic salary:") days=input("Enter no. of working days:") ovrti=input("Enter no. of overtime working hrs:") deduct=0 if days<6: deduct=3500 salary=calci(bs,days,ovrti,deduct) elif days>=6 and days<=12: deduct=1000 salary= calci(bs,days,ovrti,deduct) elif days>=13 and days<=18: deduct=800 ...
655
312
# class Song: # Song is name of Class, start with Capital letter # def __init__(self, title="", author="", lyrics=tuple()): # constructor method called upon creation of object # self.title = title # self.author = author # self.lyrics = lyrics # # print(f"New Song made by Author: {s...
2,760
930
""" Modules to configure Django's settings """
51
16
from constants import STYLE_NORMAL, STYLE_BOLD, STYLE_ITALIC from prefabs.text import write_autoline from widgets.widget import WidgetByRect from base_node import get_surface from prefabs.surface import blit from shape import Rect import pygame class Text(WidgetByRect): def __init__( self, ...
1,956
612
''' Source codes for Python Machine Learning By Example 2nd Edition (Packt Publishing) Chapter 5: Classifying Newsgroup Topic with Support Vector Machine Author: Yuxi (Hayden) Liu ''' from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.datasets import fetch_20newsgroups from nltk.corpus import nam...
5,350
1,940
#------------------------------------------------------------------------------- # # Written by: David C. Morrill # # Date: 05/20/2005 # # (c) Copyright 2005 by Enthought, Inc. # # Classes defined: KeyBinding, KeyBindings # #------------------------------------------------------------------------------- """ Defines...
9,076
1,993
#!/usr/bin/env python3 # -*-coding:utf-8 -* import cocos from cocos.text import HTMLLabel from cocos.director import director class TestLayer(cocos.layer.Layer): def __init__(self): super(TestLayer, self).__init__() x, y = director.get_window_size() self.text = HTMLLabel("""<center><font...
639
229
# from nltk.tokenize import word_tokenize from xml.dom import minidom import progressbar from time import sleep input_file = 'data/dataset_output.txt' num_lines = sum(1 for line in open(input_file)) read_file = open(input_file, 'r') write_output_file = open('data/dataset_output_no_pronouns.txt', 'w') pronouns = ['h...
4,284
1,256
""" Python3 Module Summary: User Input Manipulation """ import re from string import ascii_lowercase def bool_assignment(arg, patterns=None): """ Summary: Enforces correct bool argment assignment Arg: :arg (*): arg which must be interpreted as either bool True or False Returns: ...
2,794
769
import duckdb from datetime import date from dateutil.relativedelta import relativedelta import os import shutil con = duckdb.connect(database='ldbc.duckdb', read_only=False) # batches are selected from the [network_start_date, network_end_date) interval, # each batch denotes a [batch_start_date, batch_end_date) wher...
17,008
5,300
try: a=int(input("Please enter a number:")) if 9<a<100: a = str(a) print(a[0]) print(a[1]) else: print("no correct") except: print("no correct")
193
75
""" Contains all the logic for running the game (game clock, per-frame logic, game state update generation, and so on) """
122
32
import hypothesis import torch from hypothesis.nn.util import list_modules_with_type def allocate_neuromodulated_activation(activation, allocator): class LambdaNeuromodulatedActivation(BaseNeuromodulatedModule): def __init__(self): super(LambdaNeuromodulatedActivation, self).__init__( ...
1,131
336
#!/usr/bin/python3 """ Good morning! Here's your coding interview problem for today. This problem was asked by Uber. Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input...
1,151
392
from django.core.management.base import NoArgsCommand, CommandError; from ldap_login.ldapUtils import ldapManager; from ldap_login.models import user,group,Role; from datetime import datetime; import traceback; class Command(NoArgsCommand): """Import LDAP users from Active Directory. Uses the ldapUtils back...
3,685
947
from rocketchat_API.APISections.base import RocketChatBase class RocketChatSubscriptions(RocketChatBase): def subscriptions_get(self, **kwargs): """Get all subscriptions.""" return self.call_api_get("subscriptions.get", kwargs=kwargs) def subscriptions_get_one(self, room_id, **kwargs): ...
822
260
from django.db import models from django.contrib.auth.models import User from instances.models import Instance class UserInstance(models.Model): user = models.ForeignKey(User) instance = models.ForeignKey(Instance) is_change = models.BooleanField(default=False) is_delete = models.BooleanField(default=...
1,081
338
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from typing import Union from . import utilities, tables class CustomS...
8,744
2,415
#Задачи на циклы и оператор условия------ #---------------------------------------- ''' # Задача 1 Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. ''' print ('Задача1') x = 0 for x in range (1,6,): print (x,0) ''' Задача 2 Пользователь в цикле вводит 10 цифр. Найти к...
1,804
805
"""Configuration loader class.""" import ast import logging import os import types from operator import attrgetter import pkg_resources logger = logging.getLogger(__name__) class Config(object): """Configuration loader, it's like a normal dictionary with super-powers. It will load configuration in the fol...
5,062
1,311
import abc from typing import AbstractSet class BaseStorage(abc.ABC): """Abstract base class for storing invite link tokens""" def insert(self, token: str, *, payload: dict, max_uses=1): """Insert token to storage. Shoud call super().insert(...)""" if type(payload) != dict: raise...
1,616
467
#! /usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import os import pandas as pd import testmodel import imageio if __name__ == "__main__": #################### 不可修改区域开始 ###################### testpath = '/home/data/' #测试集路径。包含验证码图片文件 result_folder_path = '/code/result/submission.csv' ...
874
423
from flask import Blueprint from app.api.v1 import user, book, client, token def create_blueprint(): bp_v1 = Blueprint('v1', __name__) user.api.register(bp_v1, url_prefix='/client') user.api.register(bp_v1, url_prefix='/user') book.api.register(bp_v1, url_prefix='/book') book.api.register(bp_v1, ...
359
140
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Christian Heider Nielsen" __doc__ = r""" Created on 26-01-2021 """ from enum import Enum from typing import Tuple import numpy from matplotlib import patheffects, pyplot __all__ = ["plot_median_labels", "show_values_on_bars"] from ...
3,125
1,041
class Platforms: @property def win(self): return 'win' @property def linux(self): return 'linux' @property def macos(self): return 'macos' @property def win_32(self): return 'win32' @property def win_64(self): return 'win64' @prop...
523
183
from dash import dash, dcc, html from dash.dependencies import Input, Output import plotly.graph_objs as go import pandas as pd url = 'csv/covidtesting.csv' df = pd.read_csv(url) app = dash.Dash() # list = df.columns[1:] # filter_options = [] # for option in list: # filter_options.append({'label': str(option), ...
1,061
368
############################################################################################### from keras.models import Model, load_model from PIL import Image import numpy as np import time import cv2 import os import logging import pymongo #import dlib import requests import appconfig import json cascade = cv2.Cas...
4,288
1,492
"""Object detection pipeline.""" import multiprocessing import datetime import time import sys import cv2 import numpy as np import socket import sharedmem import mpipe import coils import util DEVICE = int(sys.argv[1]) WIDTH = int(sys.argv[2]) HEIGHT = int(sys.argv[3]) DURATION = float(sys.argv[4]) # In se...
5,488
1,706
# 1から10までの整数を表示する for num in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: print(num)
78
63
#!/usr/bin/python L = [1, 3, 6, 77, 34, 45, 26, 81] result = "" for number in L: result = result + str(number) print(result)
132
68
import maya.cmds as cmds class blendShapeEditor(object): def __init__(self): self.blendshape_node = blendshape_node = [] self.target_nodes = target_nodes = [] def prepareOrginialGeo(self,*args): sel = cmds.ls(sl=True)[0] if '_org' in sel: blendshape_base_geo = cmds...
2,743
980
""" Basic test, just raises a TestWarning """ import support raise support.TestWarning('A test of TestWarning. It is not an error')
134
40
import numpy as np import tensorflow as tf def normalized_columns_initializer(std=1.0): def _initializer(shape, dtype=None, partition_info=None): out = np.random.randn(*shape).astype(np.float32) out *= std / np.sqrt(np.square(out).sum(axis=0, keepdims=True)) return tf.constant(out) ret...
5,511
1,896
from collections import deque n, q = map(int, input().split()) graph = [[] for _ in range(n + 1)] for i in range(n - 1): a, b = map(int, input().split()) graph[a].append(b) graph[b].append(a) CD = [] for i in range(q): e, f = map(int, input().split()) CD.append([e, f]) dist = [-1] * (n + 1) dis...
632
274
# Copyright (c) 2010 Twilio Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distri...
265,414
97,610
import copy import logging import math import sys from collections import defaultdict from functools import reduce from typing import ( Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union, ) import tabulate from ortools.sat.python import cp_model from ..model impo...
49,047
13,235
import pytest from restclientaio._util import * class TestFullName: @pytest.mark.parametrize('args,expected', [ ((str,), 'builtins.str'), ((str, 'lower'), 'builtins.str.lower'), ]) def test_full_name(self, args, expected): assert full_name(*args) == expected class TestFormatRe...
806
292
# pylint: disable=redefined-outer-name """Test Experiments. This test runs all problems and hyperparameter pairs for 100 time steps. It only guarantees correct API compatiblity and not the problem performance metrics. """ import pytest from torchrl import registry from torchrl.cli.commands.run import do_run proble...
1,112
381
import json import time import bs4 import numpy as np import pandas as pd import requests as rqs url_apiV2 = r'https://api.guildwars2.com/v2' working_dir = r'/home/ubuntu/' def gw2_request(request_type, item_nums, retries = 25): item_num_str = ','.join([str(num) for num in item_nums]) req...
3,289
1,152
from flask import Flask from flask_sqlalchemy import SQLAlchemy from config import Config app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(128), ind...
2,055
793
# exercise 3.1.4 import numpy as np from sklearn.feature_extraction.text import CountVectorizer # Load the textDocs.txt as a long string into raw_file: with open('../Data/textDocs.txt', 'r') as f: raw_file = f.read() # raw_file contains sentences seperated by newline characters, # so we split by '\n': corpus = ra...
1,954
594
from turtle import * def l(y,x): lt(y) fd(x) def r(y,x): rt(y) fd(x) def gt(x,y): pu() goto(x,y) pd() bgcolor("lime") color("black","white") shape("circle") ht() speed(1) width(15) gt(-365,-380) begin_fill() seth(90) fd(20) r(5,20) r(4,60) r(5,100) r(5,120) l(85,50) r(10,25) r(15,10) r(15,40) r(15,50) r(1...
797
607
from django import forms from django.core.validators import RegexValidator from django.core.exceptions import ValidationError from django_otp import user_has_device, devices_for_user from magicauth import settings as magicauth_settings class OTPForm(forms.Form): OTP_NUM_DIGITS = magicauth_settings.OTP_NUM_DIGIT...
1,316
425
from pydantic import BaseModel class UserUpdate(BaseModel): fullname: str class ChangePassword(BaseModel): current_password: str new_password: str confirm_password: str
186
53
from unittest import TestCase, main from unittest.mock import patch, MagicMock, call from monolith_filemanager.adapters.s3_processes import S3ProcessesAdapter, S3ProcessesAdapterError class TestS3ProcessesAdapter(TestCase): @patch("monolith_filemanager.adapters.s3_processes.S3ProcessesAdapter.__init__") def ...
19,428
6,357
from sklearn import tree #[height, weight, shoe size] X = [[181,80,44], [177,70, 43],[160, 60,38],[154, 54, 37], [166,65,40], [190, 90, 47], [175, 64, 39], [177, 70, 40],[159, 55, 45],[171, 75, 42], [181, 85, 43] ] Y = ['male', 'female', 'female', 'female', 'male','male', 'male', 'female', 'male', 'female', 'male'] ...
459
267
#!/usr/bin/env python from Asap.Setup.Lattice.FCCOrtho import * from Asap.Setup.Dislocation import Dislocation from ASE.ChemicalElements import Element from Asap import * from Asap.Trajectories import NetCDFTrajectory from ASE.Visualization.PrimiPlotter import * from Numeric import * splitting = 5 size = (25, 35, 10)...
1,921
770
import time from collections import defaultdict from .. import exceptions, utils class Memory(object): """Cache directly in memory. This is by far the fastest solution, but the cache cannot be shared outside the current process. This is not completely thread safe, but care has been taken to avoid...
7,450
2,105
from utils import read_cfg from falling_objects_env import FallingObjects, PLAYER_KEYS, ACTIONS from argparse import ArgumentParser from demo_agent import DemoAgent from dqn_agent import DDQNAgent import importlib import numpy as np import cv2 as cv2 BATCH_SIZE = 32 if __name__ == "__main__": arg_parser = Argumen...
2,541
878
""" The Self-Taught Programmer - Chapter 4 Challenges Author: Dante Valentine Date: 22 May, 2021 """ """ CHALLENGE 1 """ to_square = 12 def square_func(x): # Returns the square of x. return x*x resp = square_func(to_square) #print("The square of", to_square, "is", str(resp) + ".") """ CHAL...
1,505
629
import cv2 import numpy as np import argparse def unpurple(params): img = cv2.imread(params.input).astype(np.float64) img_b = img[..., 0] img_b = np.maximum(0, img_b - params.m * 255) img_b *= params.i / (1 - params.m) width = (params.r << 1) + 1 bl = cv2.blur(img_b, (width, width)) i...
2,874
940
from .bit_arr import * from .ecc import * from .int import *
61
22
#!/usr/bin/env python3 import numpy as np # from rrc_example_package.code.training_env import make_training_env from rrc_example_package.code.training_env.env import ActionType import rrc_example_package.move_cube import rrc_example_package.cube_env # env = make_training_env(visualization=False, **eval_config) # env....
1,588
554
import random def QFT(first: int, last: int) -> str: res = "// Begin QFT\n" for a in range(first, last+1): res += f"h q[{a}];\n" for b in range(a+1,last+1): res += f"crz({1/(2**(b-a+1))}) q[{a}], q[{b}];\n" return res def QFT_inv(first: int, last: int) -> str: res = "// Beg...
1,253
551
import pygame from . import assets from .vector import * global registered_sprites registered_sprites = {} def register_sprite(name, definition): registered_sprites[name] = definition class Sprite: texture = "none.png" rect = pygame.Rect(0, 0, 0, 0) def __init__(self, name, pos, z): self.nam...
1,458
525
########################### # 6.00.2x Problem Set 1: Space Cows from ps1_partition import get_partitions import time #================================ # Part A: Transporting Space Cows #================================ def load_cows(filename): """ Read the contents of the given file. Assumes th...
5,873
1,827
# Copyright (c) 2020 - for information on the respective copyright owner # see the NOTICE file and/or the repository https://github.com/boschresearch/blackboxopt # # SPDX-License-Identifier: Apache-2.0 import logging import time from typing import Callable, List, Set, Union try: import dask.distributed as dd exce...
6,080
1,696
#! /usr/bin/env casarun # # # you can either use the "import" method from within casapy # or use the casarun shortcut to run this from a unix shell # with the argument being the casa image file to be processed # # Typical test usage: # ./test_ingest.py test123.fits [dummy] # This will produce admit....
2,997
1,084
""" Authors: Fernando (UPDATE HIS INFO) License: GPL 3.0 Description: This file contains functions that allows the user to change the pitch of a .wav Comments: None. """ import subprocess import os from sys import platform as _platform from lib import pydub def changeDuration(filename,percent): """ Input: file...
2,156
732
from Queue import Empty, Queue import collections import ipaddress import netifaces import pwd import signal import socket from subprocess import Popen from threading import Thread ################################################################################ #### String utils def newline( *args ): class Single...
12,711
3,602
# DBPLoadController.py # 1) Run Validate on the files to process # 2) Move any Fileset that is accepted to uploading # 3) Perform upload # 4) Move any fully uploaded fileset to database # 5) Update fileset related tables # 6) Move updated fileset to complete import os from Config import * from RunStatus import * fro...
8,824
3,679