text
string
size
int64
token_count
int64
from typing import Callable import kge from kge.core import events from kge.core.eventlib import EventMixin from kge.core.events import Event class BaseComponent(EventMixin): """ A component represents an element that can be added to an entity to add a functionality """ def __fire_...
1,903
547
class Solution: def advantageCount(self, A: List[int], B: List[int]) -> List[int]: n=len(A) A.sort() B_sorted_idxs = sorted(list(range(0,n)), key = lambda x: B[x]) permuted_A = [-1]*n j = 0 #for A -index remainingA = [] for idx in B_sorted_idxs: w...
766
251
from pathlib import Path import numpy as np import pickle as pk from itertools import chain, product from collections import OrderedDict from structure import Struct MONKEYS = ['M', 'N'] REGIONS = ['OFC', 'ACC'] TASKVARS = ['value', 'type'] SUBSPACES = [True, False] EVT_WINS = OrderedDict((('cues ON', (-500, 1500)), ...
11,162
3,657
import setuptools with open('README.rst', 'r') as f: readme = f.read() with open('version', 'r') as f: version = f.read() if __name__ == '__main__': setuptools.setup( name='ohmlr', version=version, description='One-hot multinomial logisitc regression', long_description=re...
634
214
from commands2 import CommandBase, ParallelCommandGroup from subsystems.climbers.leftclimbersubsystem import LeftClimber from subsystems.climbers.rightclimbersubsystem import RightClimber class HoldLeftClimberPosition(CommandBase): def __init__(self, climber: LeftClimber) -> None: CommandBase.__init__(sel...
1,301
417
import os from flask import Flask import practicer_flask.auth import practicer_flask.exercises import practicer_flask.dashboard import practicer_flask.topic import practicer_flask.model_viewer def create_app(test_config=None): app = Flask(__name__) app.config.from_mapping(SECRET_KEY=os.environ.get("SECRET_...
668
258
from models.models import Topic, TopicInTopic import json def visual(vis, params): model = vis.model group_by = params[1] # year,month,week,day topics = Topic.objects.filter( model=model, layer=model.layers_count).order_by("spectrum_index") topics = [topic.title for topic in topics] ...
737
254
# SPDX-FileCopyrightText: 2021 Genome Research Ltd. # # SPDX-License-Identifier: MIT from .base import Base, db class SubmissionsManifest(Base): __tablename__ = "manifest" manifest_id = db.Column(db.Integer, primary_key=True) samples = db.relationship('SubmissionsSample', back_populates="manifest", ...
3,596
1,098
#!/usr/bin/env python3 # # Copyright (c) 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. ...
6,411
1,990
import numpy as np import os # Data manipulate class dm: def __init__(self): pass def saveNp(self, a, name, path='.'): np.save(os.path.join(path,name), a) def saveTxt(self, a, name, path='.'): np.savetxt(os.path.join(path,name)+'.txt', a) def saveArrows(self, a1, a2, n...
408
169
class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: if k <= 1: return 0 ans = 0 prod = 1 j = 0 for i, num in enumerate(nums): prod *= num while prod >= k: prod /= nums[j] j += 1 ans += i - j + 1 return ans
310
123
# Generated by Django 3.0.10 on 2021-02-15 15:09 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('users', '0006_auto_20210209_0849'), ('session', '0001_initial'), ] operations = [ migr...
2,832
802
""" File-Name: [app]/serializers.py File-Desc: Rest API serializers for las_util App-Name: las_util Project-Name: Las-Util-Django Copyright: Copyright (c) 2019, DC Slagel License-Identifier: BSD-3-Clause """ from rest_framework import serializers from las_util.models import SectionInfo class DocSerializer(serializers....
880
253
#!/usr/bin/env python # Display a runtext with double-buffering. from samplebase import SampleBase from rgbmatrix import graphics import time import requests import transitfeed import datetime import arrow import schedule today = datetime.date.today() starttime = time.time() schedule = transitfeed.Schedule() url = "ht...
3,965
1,493
from django.apps import AppConfig class BaseUserConfig(AppConfig): name = 'base_user'
92
29
from random import sample from tile import Tile from utils import neighbours class BoardGenerator: def __init__(self, size, numMines): self.numMines = numMines self.size = size self.board = [] self.generate_board() def generate_board(self): # Generate a board for Mines...
1,188
376
import smart_imports smart_imports.all() class BattleRequest: __slots__ = ('id', 'initiator_id', 'matchmaker_type', 'created_at', 'updated_at') def __init__(self, id, initiator_id, matchmaker_type, created_at, updated_at): self.id = id self.initiator_id = initiator_id self.matchmake...
1,054
347
import numpy as np import math p = np.poly1d([ +0.1429511242e-53, +0.1561712123e-44, -0.2259472298e-35, -0.2669710222e-26, +0.9784247973e-18, +0.1655572013e-8, +0.3991098106e+0, ]) def sigmoid(x): return 1 / (1 + math.exp(-x)) for i in range(1000): k = float(i) / 100 print(sigmoid(k), p(k))
300
214
import psycopg2 import psycopg2.extras import discord from models.BotMention import BotMention from models.UpdatedMessage import UpdatedMessage from forever.Steam import Steam_API, Dota_Match, Dota_Match_Player from forever.Utilities import run_in_executor, log from forever.Warframe import CetusMessage, FissureM...
19,035
8,121
import keras from keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape model = Sequential() model.add(Reshape((3, 32, 32), input_shape=(3*32*32,) )) model.add(Conv2D(filters=32, kernel_size=(3,3), padding='same', activation="relu", data_format='channels_first')) model.add(MaxPool2D()) model.add(Conv2D(filt...
822
321
# Dicionarios pessoas = {'nome': 'Igor', 'sexo': 'M', 'idade': 20} print(f'O {pessoas["nome"]} tem {pessoas["idade"]} anos.') print(pessoas.keys()) #chaves do dicionario print(pessoas.values())#valores das chaves print(pessoas.items())#mostra os itens do dicionario print() for k in pessoas.keys(): print(k) for v in...
1,111
454
""" polyanalyst6api.api ~~~~~~~~~~~~~~~~~~~ This module contains functionality for access to PolyAnalyst API. """ import configparser import contextlib import pathlib import warnings from typing import Any, Dict, List, Tuple, Union, Optional from urllib.parse import urljoin, urlparse import requests import urllib3 f...
9,697
2,751
from django.contrib import admin from django.http import HttpResponse from django.utils.translation import ugettext as _ from froide.publicbody.models import (PublicBody, FoiLaw, PublicBodyTopic, Jurisdiction) class PublicBodyAdmin(admin.ModelAdmin): prepopulated_fields = { "slug": ("name",), ...
1,998
605
n = int(input()) # @return [0]:約数の個数 [1]:約数リスト def divisor(num): ret=[] L=[] for i in range(1,num+1): if (num%i==0): L.append(i) ret.append(len(L)) ret.append(L) return ret L=[] ans=0 for i in range(1,n+1): if(i%2==0): continue else: for j in range...
462
215
import serial def setup(): ser = serial.Serial('/dev/ttyUSB0', timeout=2) ser.setRTS(True) ser.setRTS(False) if ser.isOpen(): ser.close() ser.open() ser.isOpen() print "USB connection established" def read(): rawString = ser.readline() print rawString return (str(rawString)) def write(string...
3,931
2,259
"""ORM models for multinet."""
31
10
import bs4 import os import re from typing import Iterable from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait # for implicit and explict waits from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.common.by import By from dataPipelines.gc_crawler...
6,296
1,915
import re from django.db.models.signals import m2m_changed, post_save, pre_delete from django.dispatch import receiver from django.urls import reverse from .models import Entry, Notification, User @receiver(post_save, sender=Entry) def entry_notification(sender, instance, created, **kwargs): """ Signal used...
3,938
1,009
from unittest.mock import mock_open from unittest.mock import patch import flow.utils.commons as commons def test_extract_story_id_with_empty_list(): story_list = commons.extract_story_id_from_commit_messages([]) assert len(story_list) == 0 commit_example = [ "223342f Adding ability to specify artifactory u...
2,532
1,009
# coding: utf-8 """ finAPI RESTful Services finAPI RESTful Services # noqa: E501 OpenAPI spec version: v1.42.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class ClientConfiguration(object): """NOTE: This class is...
28,482
7,820
from functools import wraps from flask_jwt_extended import verify_jwt_in_request, get_jwt_claims, exceptions from jwt import exceptions as jwt_exception from utils.custom_response import bad_request def admin_required(fn): @wraps(fn) def wrapper(*args, **kwargs): try: verify_jwt_in_request...
912
289
#!/usr/bin/env python """S/MIME demo. Copyright (c) 2000 Ng Pheng Siong. All rights reserved.""" from M2Crypto import BIO, Rand, SMIME, X509 import sys def decrypt_verify(p7file, recip_key, signer_cert, ca_cert): s = SMIME.SMIME() # Load decryption private key. s.load_key(recip_key) # Extract PKCS...
1,254
515
#!/usr/bin/env python """A model for the sky brightness """ from functools import partial from math import pi, cos, acos, sin, sqrt, log10 from datetime import datetime, tzinfo, timedelta from time import strptime from calendar import timegm from copy import deepcopy from sys import argv from collections import namedtu...
14,867
5,950
# -*- coding: utf-8 -*- import unittest import arima import os import pandas as pd class Arima_Test(unittest.TestCase): def set_data_dir(self): print("set_data_dir") self.dir = "E:/code/python/MachineLearning/data/test_data/" self.error = 0.001 self.num_percent = 0.9 def t...
1,675
562
# -*- coding:utf-8 -*- """ This file is part of OpenSesame. OpenSesame is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenSesame is distr...
8,004
2,471
#!/usr/bin/env python __author__ = 'Roger Unwin' import socket import time from time import gmtime, strftime import datetime import string import sys import random import asyncore import thread import getopt import select import os ### default values defined below (b/c class is not yet defined) #default_port = 4001 ...
42,563
13,882
import matplotlib.pyplot as plt import numpy as np import pandas as pd data = pd.read_csv('results.csv') labels = [1,2,3,4] width = 0.75 x = np.arange(len(labels)) # the label locations fig = plt.figure(figsize=(9,6)) # Number people waiting ax1 = fig.add_subplot(121) y1 = data['av_waiting'].values.flatten() w...
976
404
# -*- coding: utf-8 -*- """ Spyder Editor Amritha Subburayan code for STOUT DDA FULL STACK CASE STUDIES """ import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from sklearn import preprocessing import sklearn.metrics as sm data = pd.r...
10,360
4,106
""" Datastore is a generic layer of abstraction for data store and database access. It is a **simple** API with the aim to enable application development in a datastore-agnostic way, allowing datastores to be swapped seamlessly without changing application code. Thus, one can leverage different datastores with differen...
1,373
414
# -*- coding: utf-8 -*- from __future__ import division import random from otree.common import Currency as c, currency_range from . import views from ._builtin import Bot from .models import Constants class PlayerBot(Bot): """Bot that plays one round""" def play_round(self): self.submit(views.MyPa...
402
129
class Solution: def XXX(self, intervals: List[List[int]]) -> List[List[int]]: if len(intervals) == 1: return intervals intervals.sort() result = [intervals[0]] for i in range(1, len(intervals)): # 总共三种情况需要考虑,比较两个区间,另两个区间中的元素值依次为a,b,c,d。 temp = res...
709
279
#!/usr/bin/env python # -*- coding:utf8 -*- # Copyright 2017, Schuberg Philis BV # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership...
2,531
735
from os import name from django.db import models from django.contrib.auth.models import User from PIL import Image #Model classes are tables objects in a database. #each variable is a column and its datatype. #__str__ method defines the name of a object (row) in a database table #profile model is meant to be used as ...
1,340
403
#!/usr/bin/env python import RPi.GPIO as GPIO GPIO.setwarnings(False) led_color_gpio = { 'yellow': 0, 'orange': 2, 'red': 3, 'green': 4, 'blue': 5, 'white': 6 } buttons_gpio = { 'red': 28, 'blue': 29, } gpio_to_bcm = { 0: 17, 1: 18, 2: 27, 3: 22, 4: 23, 5:...
1,446
673
#!/usr/bin/env python ########################################################################### # # Written in 2009 by Ian Katz <ijk5@mit.edu> # Terms: WTFPL (http://sam.zoy.org/wtfpl/) # See COPYING and WARRANTY files included in this distribution # #####################################...
5,551
1,794
from unittest import TestCase from unittest.mock import patch from word_vectorizer.constants import Constants from word_vectorizer.model_downloading.gensim_model_downloader import \ GensimModelDownloader class TestGensimModelDownloader(TestCase): NAME_MODEL = "name_model" URL = "gensim" PATH_WHERE_G...
1,172
407
#!/usr/bin/python3 # # Copyright 2018, The Android Open Source Project # # 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 b...
26,840
9,695
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: Ampel-ZTF/ampel/ztf/dev/DevSkyPortalClient.py # Author: Jakob van Santen <jakob.van.santen@desy.de> # Date: 16.09.2020 # Last Modified Date: 16.09.2020 # Last Modified By: Jakob van Santen <jakob.van.santen@desy.de> im...
6,975
2,215
""" Reads in a tsv file with pre-trained bottom up attention features and stores it in HDF5 format. Also store {image_id: feature_idx} as a pickle file. Hierarchy of HDF5 file: { 'image_features': num_images x num_boxes x 2048 array of features 'image_bb': num_images x num_boxes x 4 array of bounding boxes } """ ...
3,806
1,363
from . import views from django.urls import path urlpatterns = [ path('', views.profile, name='profile'), path('sign-up', views.sign_up, name='show_sign_up_form') ]
176
61
from tkinter.font import BOLD from PIL import ImageTk from tkinter import* from PIL import Image from tkinter import messagebox from Tools.log_db import* class Sign: def __init__(self, root): self.root = root ## Init frame and button Frame_sign = Frame(self.root, bg="#120b26") Fr...
3,720
1,248
from functools import partial from typing import Optional, List, Tuple import numpy from numpy.typing import ArrayLike from skimage.restoration import denoise_bilateral as skimage_denoise_bilateral from aydin.it.classic_denoisers import _defaults from aydin.util.crop.rep_crop import representative_crop from aydin.uti...
6,301
1,920
import logging import time from .exceptions import HostEntryNotValid from .check import CheckFactory from .alert import AlertFactory from .host import Host from .logging import logger class PyMon: def __init__(self, host_list, check_list, alert_list, daemonize=False): self.hosts = {} self.checks =...
1,889
541
import logging import time from django.test import Client from django.conf import settings from django.urls import reverse from django.db import IntegrityError from django.utils import timezone from rest_framework.parsers import JSONParser from rest_framework import serializers from io import BytesIO import json fr...
52,397
16,495
import os from bot.TextInput import TextInput from bot.prompt import color_msg def PythonCommands(file, name, category, description, slash): here = os.getcwd() # Writing a new import line cogs = file['config']['commands'] = [] cogs.append(name) with open(here + "/main.py", "r") as f : ...
2,484
738
from methods.AbstactMethod import AbstractMethod class Addition(AbstractMethod): name = 'Addition' def apply(self, args: dict) -> dict: return { 'res': args.get('x') + args.get('y') }
223
70
# imports from decouple import config import pandas as pd import praw import psycopg2 import schedule from sqlalchemy import create_engine import time def job(): current_day = time.strftime("%m/%d/%Y") print(f"Performing job on {current_day}") startTime = time.time() # connecting to reddit API re...
3,914
1,129
#!/bin/python #Frame processing and distance estimation for #goal #------------------------------------------------------------------------------- # IMPORTS #------------------------------------------------------------------------------- import cv2 import math import numpy i...
9,139
3,123
i=1 while i<=4: j=16 while j>=i: print(i,end="") j=j-1 print() i=i+1
100
50
import logging import weakref from threading import Event from threading import Thread try: from Queue import Queue except ImportError: from queue import Queue try: import gevent from gevent import Greenlet as GThread from gevent.event import Event as GEvent from gevent.queue import Queue as GQ...
8,539
2,401
#!/usr/bin/python3 from Common.Straw import Straw import pymongo from pymongo import MongoClient from bson.objectid import ObjectId import os class Db(Straw): # 任务 _taskFields = { 'videoIds': 'string', #待操作的 视频 'setId': 'objectid', #待操作的视频集 id 'fromDevice': 'string', 'toDevice':...
9,056
3,339
from django.template import Context from django.template import Template from .test_base import LDAPGroupAuthTestBase from django.contrib.auth.models import AnonymousUser class CanUserPerformActionTagTest(LDAPGroupAuthTestBase): BASIC_TEMPLATE = Template( "{% load baya_tags %}" "{% can_user_pe...
1,251
374
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from torch.nn import functional as F # In EGG, the game designer must implement the core functionality of t...
2,611
777
import os import shutil import random def copy_random_k_files(src_dir, k, dst_dir): file_list = os.listdir(src_dir) if k == -1: k=len(file_list) for i in range(k): random_file=random.choice(file_list) print(random_file) src1 = os.path.join(src_dir, random_file) dst...
2,757
1,076
# generated bbox ground truth from pixel-wise segmentation # it currently only generate one bbox from __future__ import print_function import numpy as np import h5py import os import pdb mask_path = '../data/acce' f = h5py.File(os.path.join(mask_path, "resized_label_ac_2d.h5"), 'r') bbox_path = '../data/acce/bbox' if...
1,285
479
# some codes refer to Holoclean evaluation function # https://github.com/HoloClean/holoclean import pandas as pd import numpy as np import logging import random import argparse parser = argparse.ArgumentParser(description='Predict on many examples') parser.add_argument("--dataset", type=str, help="dataset path") pars...
8,510
2,528
import numpy as arr n,m=map(int,input().split()) ar=([list(map(int,input().split()))for _ in range(n)]) arr1=arr.min(ar,axis=1) print(max(arr1))
145
63
import os import glob from astropy.io import fits #/home/student/Desktop/Images/iTelescope/20180716-California-T24-GOOD # Yo Neal. When you use this program, you have to change a few things between iTelescope and LFOP # FIRST, remember to change the file path or you'll be a dummy. Also for LFOP -13 and -12 while ...
918
340
from fastai.vision.all import * from PIL import Image import streamlit as st import numpy as np from io import BytesIO from .config import imgWidth, imgHeight st.title("CleanvsMessy") st.markdown(''' ## Upload the image''',True) st.set_option('deprecation.showfileUploaderEncoding', False) file = st.file_uploader(" ") ...
959
322
import pickle import matplotlib.pyplot as plt import pandas as pd trials = pickle.load(open("trials.p", "rb")) print("Set breakpoint here") #for item in trials.trials: # args = item["vals"] # res = item["result"]["loss"] #itemtuples = [(item["misc"]["vals"]["dilation_group"], item["misc"]["vals"]["use_ref_po...
1,030
405
import logging import logging.config import os import subprocess from datetime import datetime, timedelta from botocore.credentials import CredentialProvider, RefreshableCredentials from dateutil.tz import tzlocal from common.E3 import e3 class AtlassianAwsSecurity(CredentialProvider): """ This class is onl...
3,151
918
''' Stuff you need to update for this to work ''' 'Enter your username here' user = '' 'Enter your password here' passwd = '' image1 = '2d83af05944d49c69fa9565fb238a91b.jpg' image2 = '49b2788b672e4088a25eb0a9eff35c17.jpg' image3 = '355c2c7e87f0489bb5f0308cdec108f6.jpg' " ^ You need to change EACH of these to whateve...
3,506
1,189
#import roslib; roslib.load_manifest('rcommander_core') import graph.style as gs import graph import graph.layout as gl import tool_utils as tu import graph_model as gm import numpy as np import time import copy def copy_style(astyle, bstyle): bstyle.background = astyle.background bstyle.fill = as...
14,121
4,691
# -*- coding: utf-8 -*- from django.urls import reverse from rest_framework.response import Response from rest_framework import status from ...collection import BaseAPICollector, BaseAPISpecification from ... import models from . import serializers class RestFrameworkSpecification(BaseAPISpecification): content...
3,264
868
#!/usr/bin/env python3 """ This module defines functions for depth-first-search in a graph with a given adjacency list """ def dfs_visit(node_list, adj_list, root_node, parent): """ Takes the graph node list, its adj list, and a node s, and visits all the nodes reachable from s recursively. """ fo...
770
243
# uncompyle6 version 3.2.0 # Python bytecode 2.4 (62061) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] # Embedded file name: pirates.quest.QuestHolderBase class QuestHolderBase: __module__ = __name__ def __init__(self): self._rewardCollectors...
791
299
from setuptools import setup, find_packages VERSION = "0.1.1" setup( name="hhsh", version=VERSION, description="能不能好好说话? cli", long_description="能不能好好说话? cli", keywords="python hhsh cli terminal", author="itorr,yihong0618", author_email="zouzou0208@gmail.com", url="https://github.com/y...
933
312
import datetime import hashlib import os import pathlib from typing import Optional import yaml def key(name): return hashlib.sha1(name.encode()).hexdigest() def path(name): return pathlib.Path(os.environ['CACHE_AWS_MNT']) / key(name) def aws_get(name) -> Optional[dict]: try: with path(name)...
937
296
from collections import Counter import pytest from datasets import load_dataset from lassl.blender import DatasetBlender def test_blending(): try: from langid import classify except ImportError as _: raise ImportError( "To test dataset blending, you need to install langid. " ...
1,118
381
# -*- coding: utf-8 -*- """ After the introduction of version 6.2, all wisp data and hst-3d are now on MAST 3D-HST has not added any new data nor changed their directory structure, but that's not the case for WISP Aim: parse new directories to make them compatible with v5.0 """ import os import glob from ..utils...
4,542
1,937
import storage import pytest class TestTransaction: @pytest.fixture(autouse=True) def transact(self): yield storage.conn.rollback()
158
49
# -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2017-12-06 13:50 from __future__ import unicode_literals import aldryn_redirects.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'),...
2,451
713
""" .. Copyright (c) 2015 Marshall Farrier license http://opensource.org/licenses/MIT Constants ========= """ UPVEL_COL = 'Up Vel' DOWNVEL_COL = 'Down Vel'
161
65
#! /usr/bin/env python3 import rospy from geometry_msgs.msg import Twist from sensor_msgs.msg import LaserScan import numpy as np import math from std_msgs.msg import String def callback(data): laser_arr_f = np.array(data.ranges[0:10]) laser_arr_l= np.array(data.ranges[85:95]) laser_arr_r = np.array(d...
3,284
1,266
""" Registry for tracking providers dynamically in OpenNSA. Keeping track of providers in a dynamical way in an NSI implementation is a huge pain in the ass. This is a combination of things, such as seperate identities and endpoints, callbacks, and the combination of local providers. The class ProviderRegistry tries ...
2,622
760
from test_utils import TempDirectoryContext from shedclient import task_tracker def test_task_tracker(): with TempDirectoryContext() as context: config = dict( task_tracking_directory=context.temp_directory ) tracker = task_tracker.build_task_tracker(config) assert len...
997
330
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.13.0) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x04\x1a\ \x00\ \x01\x08\x3e\x78\x9c\xed\x9c\x4d\x6e\xd3\x50\x14\x85\x1d\x65\x10\ \x66\x61\xc4\x...
5,825
4,946
n = int(input()) # names = {input() for _ in range(n)} names = [] for _ in range(n): names.append(input()) unique_names = list(set(names)) [print(name) for name in sorted(unique_names, key=names.index)]
213
80
from optparse import OptionParser class CmdParser(OptionParser): def error(self, msg): print('Error!提示信息如下:') self.print_help() self.exit(0) def exit(self, status=0, msg=None): exit(status)
233
80
# Generated by Django 3.0.6 on 2020-05-22 04:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('posts', '0002_auto_20200520_0536'), ] operations = [ migrations.AddField( model_name='post', name='subtitle', ...
587
199
from django.db import models class TimeStamp(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True
191
63
import logging import pytest from loguru import logger @pytest.fixture(name='caplog', autouse=True) def loguru_caplog(caplog): class PropogateHandler(logging.Handler): def emit(self, record): logging.getLogger(record.name).handle(record) logger.remove() handler_id = logger.add(Prop...
439
139
# Create a plotter without any lights and then enable the # default light kit. # import pyvista pl = pyvista.Plotter(lighting=None) pl.enable_lightkit() actor = pl.add_mesh(pyvista.Cube(), show_edges=True) pl.show()
216
80
# -*- coding: utf-8 -*- """ sphinx.environment.managers ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Manager components for sphinx.environment. :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ if False: # For type annotation from typing import An...
1,353
426
import getopt import sys import os import re import string import xml.etree.ElementTree as ET input_filename = "" expansion_filename = "" output_type = "combine" exclude = set(string.punctuation) options, remainder = getopt.getopt(sys.argv[1:], 'i:e:t:', ['inputfile=', 'expansionfile=', 'type=']) for opt, arg in op...
3,692
1,214
import cartopy.crs as ccrs import cartopy.feature as cf from matplotlib import pyplot as plt from matplotlib import image as img def createMap(): fig = plt.figure() ax = plt.axes(projection=ccrs.PlateCarree()) ax.coastlines(linewidth=1) ax.add_feature(cf.BORDERS,linestyle='-',linewidth=1) fig.savefig('globalMap.p...
370
138
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import subprocess import unittest import filecmp import gdal import otbApplication as otb from abc import ABC from decloud.core.system import get_env_var, pathify, basename class DecloudTest(ABC, unittest.TestCase): DECLOUD_DATA_DIR = get_env_var("DECLOUD_...
2,124
700
from sclblonnx import add_output, add_input, add_node, node, empty_graph, add_constant, display, merge, run import numpy as np def test_merge(): # Subgraph 1 sg1 = empty_graph("Graph 1") n1 = node('Add', inputs=['x1', 'x2'], outputs=['sum']) sg1 = add_node(sg1, n1) sg1 = add_input(sg1, 'x1', "FLO...
1,327
549
import glob import cv2 import numpy as np class CameraCalibrator: ''' Class for correcting the distortion of the pictures taken from the camera. ''' def __init__(self, calibration_pictures_path_pattern='../camera_cal/calibration*.jpg'): ''' :param calibration_pictures_path_pattern: F...
2,609
768
description = 'Instrument shutter' prefix = "IOC" devices = dict( beam_monitor_1=device( 'nicos_ess.devices.epics.motor.EpicsMotor', description="Beam monitor continuous position feedback", motorpv=f'{prefix}:m8', abslimits=(-10, 10), unit='mm', speed=5., ), ...
591
205