text
string
size
int64
token_count
int64
""" Lacework Run Reports API wrapper. """ import logging logger = logging.getLogger(__name__) class RunReportsAPI(object): """ Lacework RunReports API. """ def __init__(self, session): """ Initializes the RunReportsAPI object. :param session: An instance of the HttpSession ...
2,447
665
admin_username = "richard" admin_password = "richard666"
56
21
import json class ConfigObject(dict): def __init__(self, **kwargs): super().__init__(**kwargs) self.load_attributes(kwargs) def load_attributes(self, d): for k, v in d.items(): if isinstance(v, dict): self[k] = self.__class__(**v) elif isinstan...
888
254
import discord from discord.ext import commands import os from discord.ext import tasks from datetime import datetime bot = commands.Bot(command_prefix='&') token = os.environ['DISCORD_BOT_TOKEN'] guild = bot.get_guild(417245684656373766) #ステータス @bot.event async def on_ready(): activity = discord.Activity(name='...
2,523
1,152
#=========================================================================== # # Copyright (c) 2014, California Institute of Technology. # U.S. Government Sponsorship under NASA Contract NAS7-03001 is # acknowledged. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modific...
7,225
2,097
import math import pylab from app import StandardRobot, LeastDistanceRobot, RandomWalkRobot, runSimulation def timeNumberPlot(title, x_label, y_label, dim_length): """ Plots the relation between the number of robots and the average time taken by different robots to clean a portion of the room. """ ...
12,285
4,477
""" Ingest Package Config """ # The list of entities that will be loaded into the target service. These # should be class_name values of your target API config's target entity # classes. target_service_entities = [ "family", "participant", "diagnosis", "phenotype", "outcome", "biospecimen", ...
795
249
#!/usr/bin/env python """ Written by Anthony Nguyen 2015/06/20 """ import sqlite3 import sys #import smap_analytics as smap_analytics open_this_file = None if len(sys.argv) == 2: open_this_file = sys.argv[1] else: open_this_file = "config/smap_2015.csv" with sqlite3.connect('dashboard.db') as conn: c = c...
1,877
608
""" Script to perform RC sorting Wren Saylor July 5 2017 Copyright 2017 Harvard University, Wu Lab 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 ...
3,746
1,278
import sys import math # Auto-generated code below aims at helping you parse # the standard input according to the problem statement. n = int(input()) # the number of temperatures to analyse temps = input() # the n temperatures expressed as integers ranging from -273 to 5526 temps = temps.split() if n == 0: pr...
580
185
import numpy as np import cv2 import matplotlib.pyplot as plt from openvino.inference_engine import IECore import openvino_model_experiment_package as omep # Load an IR model model = 'intel/human-pose-estimation-0001/FP16/human-pose-estimation-0001' ie, net, exenet, inblobs, outblobs, inshapes, outshapes = omep.loa...
694
285
import large_image import urllib import pytest @pytest.mark.parametrize("item, output", [ ('590346ff8d777f16d01e054c', '/tmp/Huron.Image2_JPEG2K.tif') ]) def test_tiff_tile_source(item, output): """Check whether large_image can return a tile with tiff sources.""" test_url = 'https://data.kitware.com/api/v...
657
245
import os import sys import pickle import traceback from XSTAF.core.logger import LOGGER class ToolManager(object): def __init__(self): self.settings = {"ToolsLocation" : r"tools", "ToolsConfigureFile" : "config.pickle"} self.tool_name_list = [] ...
3,359
971
from django import forms from .models import Image, Profile, Comments class NewsLetterForm(forms.Form): your_name = forms.CharField(label='First Name', max_length=30) email = forms.EmailField(label='Email') class NewImageForm(forms.ModelForm): class Meta: model = Image exclude = ['prof...
1,200
347
string_input = "amazing" vowels = "aeiou" answer = [char for char in string_input if char not in vowels] print(answer)
120
47
""" Test serializer """ import unittest import glob import json try: from cStringIO import StringIO except ImportError: from io import StringIO from pyingest.parsers.iop import IOPJATSParser from pyingest.serializers.classic import Tagged from pyingest.serializers.refwriter import * class TestClassic(unittes...
3,404
1,020
#!/usr/bin/env python # Code Listing #4 """ Maximum subarray problem - final version """ from contextlib import contextmanager import random import time # 復習 @contextmanager def timer(): """ Measure real-time execution of a block of code """ try: start = time.time() yield finally: ...
1,473
513
""" One-time migration script from sqlalchemy models and sqlite database to custom ORM & PostgreSQL. Not designed to work as part of the regular alembic system, merely placed here for archive purposes. Should never need to run this again. 2021-05-03 """ from datetime import datetime, timedelta import sqlite3 from d...
4,012
1,292
# fname = raw_input("Enter file name: ") fname = "romeo.txt" fh = open(fname) lst = list() def add_to_list(words): for word in words: if word not in lst: lst.append(word) for line in fh: words = line.split() add_to_list(words) lst.sort() print lst
291
110
from datasets.dataset_setup import DatasetSetup from models import read_data_text class YahooSetup(DatasetSetup): def __init__(self): super().__init__() self.num_classes = 10 self.size_bottom_out = 10 def set_datasets_for_ssl(self, file_path, n_labeled, party_num): train_label...
1,376
453
from mfl_playoff_leagues import MFL def run(request): """Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using `make_response <http://flask.poco...
744
239
# Copyright 2014 PDFium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os path = os.path.abspath(os.path.split(__file__)[0]) execfile(os.path.join(path, 'gyp_pdfium'))
262
96
from pyObjective import Variable, Model import numpy as np """This example script is written to demonstrate the use of classes, and how more complicated models can be built, and still passed to the solver. As a rudimentary example, it has two cubes and a sphere, and we are trying to find the dimensions such that the...
1,508
507
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2018 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
3,005
934
import pygame as pg class Sheet: """ Represents tool for extracting sprites from spritesheet. """ def __init__(self, sheet_path): """ Constructor for the sheet tool. Loading the spritesheet. """ self.spritesheet = pg.image.load(sheet_path).convert_alpha() d...
835
253
# Analytical solutions for problems that can be solved with the two sine basis. ### # Problem one is # # -u`` = f in [0, pi] with u(0) = u(pi) = 0 for f which is # g on [0, pi/2) and h on [pi/2, pi] # ### # Problem two is # # u```` = f in [0, pi] with u(0) = u(pi) = 0, u`(0) = u`(pi) = 0 for f which is # g on [0, ...
5,398
2,517
# Copyright (c) 2020-2022 The PyUnity Team # This file is licensed under the MIT License. # See https://docs.pyunity.x10.bz/en/latest/license.html """Class to represent a rotation in 3D space.""" __all__ = ["Quaternion", "QuaternionDiff"] from . import Mathf from .vector import Vector3, conv from .other import Locke...
7,642
2,674
from config import secret from utils import getLogger DEBUG = getLogger() class MysqlConnection: def __init__(self, database, server_name): self.host = secret[server_name]['mysql']['host'] self.port = secret[server_name]['mysql']['port'] self.username = secret[server_name]['mysql']['username'] self...
402
112
#from selenium.webdriver.remote import webdriver from selenium import webdriver #from selenium.webdriver.chrome import options from page_objects import EntryPage, LoginPage, RedactionPage, ContactTracePage, AddNewRecordPage, AddDataToRecordPage, StageForPublishingPage, PublishDataPage, SettingsPage, Tools import unitte...
5,147
1,652
""" A small, very basic OutputCollector-derived class used to test handling of multiple OutputCollectors in inference_runner scenario """ from kenning.core.outputcollector import OutputCollector from kenning.datasets.open_images_dataset import DectObject from typing import Any, Union import numpy as np from pathlib imp...
2,532
718
from typing import Any from .. import util FORMAT = '''\ 🤔 {username} 发布了……一些东西 https://t.bilibili.com/{id} 目前机器人还不能理解这个qwq''' def handle(content: Any) -> str: return FORMAT.format( username=content["desc"]["user_profile"]["info"]["uname"], id=content["desc"]["dynamic_id_str"])
291
122
from collections import OrderedDict from geotrek.authent.tests.factories import StructureFactory from georiviere.tests import CommonRiverTest from georiviere.observations.models import Station, ParameterTracking from .factories import ( StationFactory, StationProfileFactory, ParameterFactory ) class StationView...
4,159
1,322
import requests from requests.auth import HTTPBasicAuth import json import pprint class Cloudflare_Enduser_API: def __init__(self, cf_token, cf_email): self.cf_token = cf_token self.cf_email = cf_email self.headers = { 'Content-Type': 'application/json', 'X-Auth-Key...
8,145
2,364
import unittest import os from subprocess import call import z5py import vigra from test_class import McLuigiTestCase class TestDataTasks(McLuigiTestCase): @classmethod def setUpClass(cls): super(TestDataTasks, cls).setUpClass() @classmethod def tearDownClass(cls): super(TestDataTa...
1,085
367
# Generated by Django 3.0.8 on 2020-07-13 19:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("images", "0003_image_creation_date"), ] operations = [ migrations.AddField( model_name="image",...
1,912
533
import numba import numpy as np from scipy.sparse import csr_matrix from .base import BasePointer, GraphBlasContainer from .context import handle_panic, return_error from .exceptions import GrB_Info class MatrixPtr(BasePointer): def set_matrix(self, matrix): self.instance = matrix class Matrix(GraphBlas...
4,733
1,645
from django.contrib import admin from imagekit.admin import AdminThumbnail from .models import Icon @admin.register(Icon) class IconAdmin(admin.ModelAdmin): list_display = ('name', 'icon_thumbnail') icon_thumbnail = AdminThumbnail(image_field='thumbnail')
266
77
def getSKLearnLogisticRegression(self, regParam, dim=1): from DLplatform.learning.batch.sklearnClassifiers import LogisticRegression learner = LogisticRegression(regParam = regParam, dim = dim) return learner
245
69
import json import os import shutil import tempfile from datetime import timedelta from unittest import mock from unittest import TestCase from pytuber.storage import Registry class RegistryTests(TestCase): def tearDown(self): Registry.clear() Registry._obj = {} def test_singleton(self): ...
2,933
1,039
""" Problem: You are given given a list of rectangles represented by min and max x- and y-coordinates. Compute whether or not a pair of rectangles overlap each other. If one rectangle completely covers another, it is considered overlapping. For example, given the following rectangles: { "top_left": (1, 4), "...
2,636
945
import asyncio from asynckafka import Producer, Consumer import config import utils loop = asyncio.get_event_loop() async def fill_topic_with_messages(): producer = Producer( brokers=config.KAFKA_URL, rdk_producer_config=config.RDK_PRODUCER_CONFIG, rdk_topic_config=config.RDK_TOPIC_CONF...
1,819
596
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) def my_callback(channel): print "falling edge detected on 18" def my_callback2(channel): print "falling edge detect...
744
349
# -*- coding: utf-8 -*- """ file: module_topology_distmat_test.py Unit tests for distance matrix computations """ import os from pandas import DataFrame from interact.md_system import System from tests.module.unittest_baseclass import UnittestPythonCompatibility class DistanceMatrixTests(UnittestPythonCompatibil...
2,465
757
import typing import bs4 import requests class ScrapeAllComicIds(): def __call__( self, ) -> typing.List[int]: self.__find() return self.__ids def __find( self, ) -> typing.NoReturn: self.__ids = [] for q in self.__query: self.__find_per_page(q) def __find_per_page( ...
1,010
392
""" Path Converter. pymdownx.pathconverter An extension for Python Markdown. An extension to covert tag paths to relative or absolute: Given an absolute base and a target relative path, this extension searches for file references that are relative and converts them to a path relative to the base path. -or- Given a...
6,241
1,919
import os, string oldWin = '''span { font-family: Verdana; background: #e0e0d0; font-size: 10pt; } </style> </head> <body bgcolor="#e0e0d0"> ''' oldLinux = '''span { font-family: Verdana; background: #e0e0d0; font-size: 13pt; } </style> </head> <body bgcolor="#e0e0d0"> ''' new = '''span { font-family: Verdana...
879
356
from typing import TYPE_CHECKING if TYPE_CHECKING: from .webapp import WebApp class StaticHeader: """Contains all relevant methods to a static header.""" id: int url: str name: str value: dict def __init__(self, resp: dict, webapp: 'WebApp') -> None: """ Initialize the cl...
1,191
365
class Nodo: elemento = None Siguiente = None def __init__(self, elemento, siguiente): self.elemento = elemento self.Siguiente = siguiente class Pila: tamano = 0 top = None def apilar(self, elemento): """ Agrega un elemento al tope de la pila :param e...
1,654
527
# Copyright (c) OpenMMLab. All rights reserved. import copy import logging from collections import defaultdict from itertools import chain from torch.nn.utils import clip_grad from mmcv.utils import TORCH_VERSION, _BatchNorm, digit_version # from ..dist_utils import allreduce_grads # from ..fp16_utils import LossScal...
3,354
928
import pytest from news.reporters import ReporterMeta from news.reporters.feed import AtomReporter, RSSReporter @pytest.fixture def rss_reporter(sa_schedule, sa_backend): meta = ReporterMeta(schedule=sa_schedule) return RSSReporter(meta=meta, backend=sa_backend) @pytest.fixture def atom_reporter(sa_schedule...
436
154
#!/usr/bin/env python import sys import os import ConfigParser import json import time import threading from distutils.core import setup import pika import boto import pusherclient from boto.sqs.message import RawMessage # set defaults channel = None global pusher config = ConfigParser.ConfigParser() class MQServer...
4,945
1,456
# -*- coding: utf-8 -*- from __future__ import absolute_import from .diffusion import create_mrtrix_dti_pipeline from .connectivity_mapping import create_connectivity_pipeline from .group_connectivity import (create_group_connectivity_pipeline)
245
75
import src.lex import src.parse import src.eval import src.tools import src.optimize import src.pre import re import sys def main(file, n=None, first=False): import os debug = False version = "Beta 2.5" l = src.tools.readSembleFile(file) #if first: # l += src.pre.importf("base.smb", l)[0] l, fname ...
1,528
688
#!/usr/bin/env python """ Data browser for When's My Transport, with caching and JSON/XML parsing """ import json import logging import os import urllib2 import time from xml.dom.minidom import parseString from xml.etree.ElementTree import fromstring from lib.exceptions import WhensMyTransportException # # API URLs ...
5,005
1,454
import colorsys import numpy as np # ----------------------------------------------------------------------------- # Utilities to generate a HSL colourmap from the magnetisation field data def convert_to_RGB(hls_color): return np.array(colorsys.hls_to_rgb(hls_color[0] / (2 * np.pi), ...
1,099
366
class Solution(object): def deleteDuplicates(self, head): initial = head while head: if head.next and head.val == head.next.val: head.next = head.next.next else: head = head.next head = initial return head
299
78
''' Created on Wed Sep 18 2019 @author XXX ''' import numpy as np import scipy.sparse as sps import time import sys import copy from tqdm import tqdm from enum import Enum from RecSysFramework.Utils import seconds_to_biggest_unit from RecSysFramework.Utils.compute_popularity import compute_popularity_user from RecSys...
9,165
2,720
import numpy as np class CellularAutomationModel: grid_width = 40 grid_height = 40 def __init__(self): self.grid = self._randomised_grid() def evolve(self): """ Evolve the current grid state using Conway's Game of Life algorithm. :returns dict: A dictiona...
3,233
1,009
from encoder import Encoder from decoder import Decoder from parser import Parser from baseline import * from language_model import LanguageModel from util import Reader import dynet as dy from misc import compute_eval_score, compute_perplexity import os initializers = {'glorot': dy.GlorotInitializer(), ...
21,365
6,285
import random def mutacion(indiv): alea_1=random.randint(0,len(indiv)-1) alea_2 = random.randint(0, len(indiv)-1) interc_1=indiv[alea_1] interc_2=indiv[alea_2] indiv[alea_1] = interc_2 indiv[alea_2] = interc_1 return indiv
254
122
#!/usr/bin/env python # Copyright (c) 2019 Riverbed Technology, Inc. # # This software is licensed under the terms and conditions of the MIT License # accompanying the software ("License"). This software is distributed "AS IS" # as set forth in the License. import csv import sys import string import optparse from co...
4,724
1,374
from clint.textui import * def Write(): i = 0 while True: i += 1 text = input(colored.cyan("%d: "%i)) if text == "q": sys.exit(0) def Print(): print(colored.cyan("-- Bug list --")) print(colored.cyan("-- ") + colored.red("<q:quit>") + colored.cyan(" --")) Write(...
330
121
from datasets.hscic.hscic_datasets import scrape as datasets_scrape from datasets.hscic.hscic_indicators import scrape as indicators_scrape def main(workspace): datasets_scrape(workspace) indicators_scrape(workspace)
229
84
import copy import json import requests import datetime from src.tests.behave.common.config import get_conflagration class APIClient(object): def __init__(self, base_url, request_kwargs=None, client_kwargs=None): self.cfg = get_conflagration() token = self.get_identity_token() timeout = ...
5,754
1,753
"""*********************************************************** *** Copyright Tektronix, Inc. *** *** See www.tek.com/sample-license for licensing terms. *** ***********************************************************""" import socket import struct import math import time import sys echo_cmd =...
10,556
2,996
import cv2 from dev_autopilot import autopilot from emulation import get_bindings, clear_input import threading import kthread from pynput import keyboard from programInfo import showInfo STATE = 0 def start_action(): stop_action() kthread.KThread(target = autopilot, name = "EDAutopilot").start() ...
1,143
359
""" Showcases correlated colour temperature computations. """ import colour from colour.utilities import message_box message_box("Correlated Colour Temperature Computations") cmfs = colour.MSDS_CMFS["CIE 1931 2 Degree Standard Observer"] illuminant = colour.SDS_ILLUMINANTS["D65"] xy = colour.XYZ_to_xy(colour.sd_to_X...
3,284
1,495
#!/usr/bin/env python import drmaa import shlex from optparse import OptionParser from sys import stderr, stdin, exit from datetime import datetime import traceback def Stop(pool, jt, info): '''Job failure function that stops synchronization.''' pool.shall_stop = True pool.all_done = False pool.failed...
9,940
2,886
import os import setuptools with open("README.md", "r") as fh: long_description = fh.read() here = os.path.dirname(os.path.abspath(__file__)) version_ns = {} with open(os.path.join(here, "jupyterlab_heroku", "_version.py")) as f: exec(f.read(), {}, version_ns) setuptools.setup( name="jupyterlab_heroku", ...
678
236
from rest_framework import serializers from .models import Placement class PlacementSerializer(serializers.ModelSerializer): class Meta: model = Placement fields = ("key", "placement_name", "company", "role", "description", "deadline")
258
68
# set random number generator np.random.seed(2020) # initialize step_end and v step_end = int(t_max / dt) v = el t = 0 with plt.xkcd(): # initialize the figure plt.figure() plt.title('$V_m$ with random I(t)') plt.xlabel('time (s)') plt.ylabel(r'$V_m$ (V)') # loop for step_end steps for step in range(s...
509
234
import sys from collections import defaultdict import torch from varclr.utils.infer import MockArgs from varclr.data.preprocessor import CodePreprocessor if __name__ == "__main__": ret = torch.load(sys.argv[2]) vars, embs = ret["vars"], ret["embs"] embs /= embs.norm(dim=1, keepdim=True) embs = embs.c...
1,509
517
import os import numpy as np from . import imtools, datprops from .datfile import DatFile from .chiptype import ChipType moduleDir = os.path.abspath( os.path.dirname( __file__ ) ) class FlowCorr: def __init__( self, chiptype, xblock=None, yblock=None, rootdir='.', method='' ): ''' Initialize a fl...
11,285
3,361
#!/usr/bin/env python import numpy as np def ini(): '''initialization Args: Returns: ''' pass def accuracy(Yte_predict, Yte): '''verification of the correct label with the predicted one Args: Yte_predict (list): predicted labels (by computer) Yte (list): true labels ...
688
219
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/models/models.dnn.ipynb (unless otherwise specified). __all__ = ['Multi_Layer_Perceptron', 'CollabFNet'] # Cell import torch import torch.nn as nn import torch.nn.functional as F # Cell class Multi_Layer_Perceptron(nn.Module): def __init__(self, args, num_users, nu...
2,354
855
import unittest import pandas as pd import numpy as np import src.features.outlier_correction as oc class TestFlagNormalOutliers(unittest.TestCase): def setUp(self): self.series = pd.Series(np.random.normal(0, 0.1, 1000)) self.series.loc[500] = -5 self.series.loc[42] = 5 def test...
477
175
import csv import operator if __name__ == "__main__": # We use try-except statements to properly handle errors, as in case the # input file does not exist in the directory. try: # We open the .csv file loading the filds separated by a ; delimiter: csv_archivo_locales = open("Locales.csv", e...
3,613
994
""" Copyright (c) College of Mechatronics and Control Engineering, Shenzhen University. All rights reserved. Description : Author:Team Li """ import glob, os, sys, time from threading import Thread import cv2 from carla_utils.world_ops import * from carla_utils.sensor_ops import * try: sys.path.append(glob.glo...
3,076
1,080
#!/usr/bin/env python import os if not os.path.isfile("/proc/sys/fs/binfmt_misc/WSLInterop"): # windows LOGFILE = os.environ['LOCALAPPDATA'] + "\\AGS\\New World\\Game.log" else: # wsl LOGFILE = os.popen('cmd.exe /c "echo %LocalAppData%"').read().strip() + "\\AGS\\New World\\Game.log" LOGFILE = os.popen("wslpath ...
2,792
938
#author SANKALP SAXENA def arrays(arr): arr.reverse() l = numpy.array(arr, float) return l
109
46
# -*- coding: utf-8 -*- import os import time import pytest from pip_services3_commons.config import ConfigParams from pip_services3_kafka.connect.KafkaConnection import KafkaConnection broker_host = os.environ.get('KAFKA_SERVICE_HOST') or 'localhost' broker_port = os.environ.get('KAFKA_SERVICE_PORT') or 9092 broke...
2,508
783
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
5,964
1,653
import itertools import numpy as np import torch import unittest from mogwai.data_loading import one_hot from mogwai.models import GremlinPseudolikelihood class TestGremlinPL(unittest.TestCase): def setUp(self): torch.manual_seed(0) N = 100 L = 20 A = 8 msa = torch.randin...
2,465
906
from . import cupy_wrapper as acp from .cupy_vjps import ( untake, balanced_eq, match_complex, replace_zero, dot_adjoint_0, dot_adjoint_1, tensordot_adjoint_0, tensordot_adjoint_1, nograd_functions, ) from autograd.extend import ( defjvp, defjvp_argnum, def_linear, vs...
10,233
4,775
# !/usr/bin/env python # -*- coding = utf-8 -*- # @Author:wanghui # @Time: # @File:getStartActivityConfig.py import configparser import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) class GetStartActivityConfig(object): def __init__(self): self.config = configparser.ConfigParser() s...
1,950
663
# MIT License # # Copyright (c) 2019 Daniel Brotsky # # Portions copyright (c) 2017 by Peter Norvig and Naoki Shibuya # (See https://towardsdatascience.com/peter-norvigs-sudoku-solver-25779bb349ce) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documen...
6,773
2,131
"""Decorators used for adding functionality to the library.""" from deserialize.exceptions import NoDefaultSpecifiedException def default(key_name, default_value): """A decorator function for mapping default values to key names.""" def store_defaults_map(class_reference): """Store the defaults map."...
1,442
418
from matplotlib import pyplot as plt import gpflow import tensorflow as tf import os import numpy as np import cProfile def outputGraph(model, dirName, fileName): model.compile() if not(os.path.isdir(dirName)): os.mkdir(dirName) fullFileName = os.path.join(dirName, fileName) if os.path.isfile(f...
3,608
1,443
import bpy import bmesh import base64 import math import mathutils import random import struct import zlib from array import array from itertools import islice from bpy.props import IntProperty, PointerProperty, StringProperty from bpy.types import Object, Operator, Panel, PropertyGroup from mathutils import Vector fr...
29,160
9,168
import configparser from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker config = configparser.ConfigParser() config.read('alembic.ini') connection_url = config['alembic']['sqlalchemy.url'] Engine = create_engine(connection_url, connect_args={'check_same_thread': False}) Session = sessionmaker...
335
101
# Copyright 2014-2016 ARM Limited # # 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 w...
4,682
1,606
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'variable_design.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow...
11,872
4,550
''' n-gram은 이와 같은 확률적 언어 모델의 대표적인 것으로서, n개 단어의 연쇄를 확률적으로 표현해 두면 실제로 발성된 문장의 기록을 계산할 수 있다. ''' # Step 1 : Bag of Words from nltk.corpus import reuters from collections import Counter, defaultdict counts = Counter(reuters.words()) total_count = len(reuters.words()) # 공통적으로 가장 많이 나타나는 20개의 단어 print(counts.most_commo...
2,597
1,288
#!/usr/bin/python import numpy class Color(object): lower_bound = 0 upper_bound = 255 def __init__(self, r, g, b, a): self.r = r self.g = g self.b = b self.a = a def __str__(self): return '(%s, %s, %s, %s)' % (self.r, self.g, self.b, self.a) def composite_pixels(src, dest): new_color = Color(0,0,0,0)...
1,977
1,071
import os import requests import urllib3.util.retry import logging import subprocess import re import pprint from datetime import datetime, timedelta import pygit2 from github import Github from github.GithubException import UnknownObjectException # Create logger with logging level set to all LOGGER = logging.getLogg...
10,139
3,053
from django.core.validators import MinLengthValidator from django.contrib.auth.models import User from django.contrib.auth.validators import UnicodeUsernameValidator from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.encoding import iri_to_u...
1,538
450
# Import external modules. from google.appengine.ext import ndb import logging # Import local modules. from configAutocomplete import const as conf from constants import Constants class Survey(ndb.Model): surveyId = ndb.StringProperty() # Primary key title = ndb.StringProperty() introduction = ndb.Str...
611
180
from flask import Flask from app.views import app
50
14
from wavenetlike.analyzers import DatasetAnalyzer from wavenetlike.datasetid import TorchAudioDataSetId def analyzer_example(): dataset = TorchAudioDataSetId("SPEECHCOMMANDS") data_analyzer = DatasetAnalyzer(dataset) data_analyzer.analyze_dataset() analysis_res = data_analyzer.get_analysis_result() ...
394
132
def get_ts_struct(ts): y=ts&0x3f ts=ts>>6 m=ts&0xf ts=ts>>4 d=ts&0x1f ts=ts>>5 hh=ts&0x1f ts=ts>>5 mm=ts&0x3f ts=ts>>6 ss=ts&0x3f ts=ts>>6 wd=ts&0x8 ts=ts>>3 yd=ts&0x1ff ts=ts>>9 ms=ts&0x3ff ts=ts>>10 pid=ts&0x3ff return y,m,d,hh,mm,ss,wd,yd,ms,pid
271
179