text
string
size
int64
token_count
int64
from pathlib import Path import os from PIL import Image, ImageFont, ImageDraw import numpy as np import pandas as pd from math import * p = Path("resources/graphics/Pokemon/Icons") df = pd.read_csv(Path("resources/PBS/compressed/pokemon.csv"), index_col=0) width = 64 height = ceil(len(df) / 64) canvas = Image.new(...
1,001
396
from django.contrib import admin from django.http import HttpResponse from django.urls import path from django.shortcuts import render, HttpResponse, redirect from django import forms import os import csv from io import TextIOWrapper, StringIO from .models import Player, Team, Usage, XgLookup class CsvImportForm(for...
4,237
1,231
# @Created Date: 2019-11-24 09:07:07 pm # @Filename: __init__.py # @Email: 1730416009@stu.suda.edu.cn # @Author: ZeFeng Zhu # @Last Modified: 2019-12-23 04:23:51 pm # @Copyright (c) 2019 MinghuiGroup, Soochow University
221
124
# -*- coding: utf-8 -*- # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See ful...
3,217
926
from toontown.safezone.DistributedETreasureAI import DistributedETreasureAI from toontown.safezone.RegenTreasurePlannerAI import RegenTreasurePlannerAI class ETreasurePlannerAI(RegenTreasurePlannerAI): def __init__(self, zoneId): self.healAmount = 2 self.spawnPoints = [] RegenTreasurePlan...
1,450
542
from sdk.color_print import c_print from user_roles import role_translate_id from tqdm import tqdm def add_roles(session, old_session, roles, logger): added = 0 tenant_name = session.tenant if roles: logger.info(f'Adding User Roles to tenant: \'{tenant_name}\'') #Translate Acc Grp IDs ...
2,204
666
# File: ds_base_service.py # # Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) # import json import time import base64 from functools import wraps from ..config import ds_api_host, ds_api_base from .ds_abstract_service import DSAbstractService class DSBaseService(DSAbstractService): ...
6,641
1,671
# Imports para o Carla import glob import os import sys try: sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % ( sys.version_info.major, sys.version_info.minor, 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0]) except IndexError: pass import carla try: sys.path...
4,216
1,399
import json import requests post_url = "http://127.0.0.1:5000/api/" # ---------- general web interfacing ---------------------- def post(endpoint, payload, uri="http://127.0.0.1:5000/api/"): """ Posts to the flask web server. Args: endpoint: The endpoint of the API payload: Payload accor...
5,705
1,917
from genes.gene_matching import tokenize_gene_symbols, GeneSymbolMatcher from genes.models import GeneList from snpdb.models import ImportStatus from upload.models import UploadedGeneList from upload.tasks.import_task import ImportTask from variantgrid.celery import app def create_gene_list(user, category, name, gene...
1,845
608
"""Loads the config.json file and store key value pairs into variables""" import json with open('config.json', 'r', encoding='utf-8') as f: config = json.load(f) config_location_type = config['location_type'] config_location = config['location'] country = config['country'] config_covid_terms = config['...
467
159
"""Maintains current version of package""" __version__ = "6.1.2"
65
24
import glob, os import numpy as np import tensorflow as tf import tensorflow.contrib.graph_editor as ge class Flownet2: def __init__(self, bilinear_warping_module): self.weights = dict() for key, shape in self.all_variables(): self.weights[key] = tf.get_variable(key, shape=shape) ...
51,350
22,650
""" """ import sys import uuid import base64 import fileinput import datetime from django.utils import timezone from django.conf import settings from django.shortcuts import get_object_or_404 from urlparse import urlparse, parse_qs from APNSWrapper import * from mdm.models import MDMDevice, DeviceCommand def replac...
874
264
import math import itertools from operator import itemgetter import json import os import random from .geom import hflip_pattern, vflip_pattern, rot_pattern from .patterns import ( get_pattern_size, get_pattern_livecount, get_grid_empty, get_grid_pattern, segment_pattern, methuselah_quadrants_pa...
34,207
11,527
#!/usr/bin/python2 import tempfile import sys import datetime mit_license = ("""\ /* MIT License Copyright (c) 2016 Paul Kramme 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 restrictio...
2,962
942
''' Created on Jun 21, 2020 @author: ballance ''' import vsc from vsc_test_case import VscTestCase from vsc.visitors.model_pretty_printer import ModelPrettyPrinter class TestListScalar(VscTestCase): @vsc.randobj class my_item_c(object): def __init__(self): self.fixed = vsc.ra...
4,048
1,390
import json from configserver import ConfigServer, get_postgres_db from configserver.errors import InvalidRouteUUIDError from flask.testing import FlaskClient import pytest from peewee import SqliteDatabase import logging from uuid import uuid4 import functools from typing import Iterable @pytest.fixture(autouse=True...
5,344
1,862
import os from PyPDF2 import PdfFileReader, PdfFileWriter #Solution based in two functions: #1.pdf remove : Remove existed pdf documents(result for your last split operation) #2.pdf splitter : Split your main pdf document into group of documents. def pdf_remove (length): for i in range(length): os.remove("...
1,318
437
from __future__ import absolute_import # import apis into api package from .contact_api import ContactApi
107
29
from typing import Callable import numpy as np from constants.constants import IndicatorType from strategy.base import BaseStrategy class OverReactStrategy(BaseStrategy): def trade_by_indicator( self, indicator_type: IndicatorType) -> Callable[[], np.ndarray]: """ Get trading strategy functi...
3,915
1,054
# coding=utf-8 # Copyright (C) 2020 - TODAY, Marcel Savegnago - Escodoo from __future__ import division from __future__ import print_function from __future__ import unicode_literals import xml.etree.ElementTree as ET from datetime import datetime from erpbrasil.base import misc from erpbrasil.edoc.nfse import NFSe ...
12,746
4,336
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 7 14:40:40 2021 @author: victorsellemi """ import numpy as np def filter_MA(Y,q = 2): """ DESCRIPTION: Decompose a time series into a trend and stationary component using the moving average (MA) filter (i.e., low pass fi...
1,647
647
import xml.etree.ElementTree as etree import xml.dom.minidom import subprocess import os import imageio import h5py import numpy as np def createXMLstring(filename,scaleVal,cameraPosX,cameraPosY): scene = etree.Element("scene",version="0.5.0") sensor = etree.SubElement(scene, "sensor", type="perspective") sensor_...
3,480
1,405
import datafile from collections import defaultdict def check_versions(df): result = [] if len(df.types[0]) < 1: result.append('no version') return result if len(df.types[0]) > 1: result.append('multiple versions') try: version = df.types[0][0] except IndexError: result.append('version id not 1') ret...
3,001
1,154
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_rotate_3dmarkers ---------------------------------- Tests for `rotate_3dmarkers` module. """ import sys import unittest import os.path import tempfile import shutil import logging from etspecutil.marker import MarkersList from etspecutil.marker import MarkersFr...
5,414
1,671
import sys import pytest import aiohttp_mako from aiohttp import web @pytest.fixture def app(): app = web.Application() lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) tplt...
431
143
from npc import * import math from pyglet import image from pyglet.graphics import TextureGroup import os import json class Enemy(Npc): def __init__(self, world, position, health, dy=0, walkSpeed=5, flying=False, flySpeed=10, height=1, jumpHeight=1.0): super(Enemy, self).__init__(world, position, health, ...
3,583
1,294
from typing import List from .model import StudioModel from ....source_shared.base import Base from ....utilities.byte_io_mdl import ByteIO class StudioBodypart(Base): def __init__(self): self.name = '' self.model_count = 0 self.base = 0 self.model_offset = 0 self.models: ...
754
229
from fastapi import Depends from fastapi.exceptions import HTTPException from fastapi.security import OAuth2PasswordBearer from app.models.users import User, UserRepository get_token = OAuth2PasswordBearer(tokenUrl="/login") async def get_user( token: str = Depends(get_token), users: UserRepository = Depends() ...
511
150
#!/usr/bin/env python # # Author: Fred C. # Email: # from __future__ import print_function from collections import defaultdict import sys import DNS import re RE_PARSE = re.compile(r'(ip4|ip6|include|redirect)[:=](.*)', re.IGNORECASE) MAX_RECURSION = 5 def dns_txt(domain): try: resp = DNS.dnslookup(domain, 'TX...
1,449
522
def cc_resources(name, data): out_inc = name + ".inc" cmd = ('echo "static const struct FileToc kPackedFiles[] = {" > $(@); \n' + "for j in $(SRCS); do\n" + ' echo "{\\"$$(basename "$${j}")\\"," >> $(@);\n' + ' echo "R\\"filecontent($$(< $${j}))filecontent\\"" >> $(@);\n' + ...
895
315
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 19 18:08:01 2020 @author: Felipe A. C. Pereira Implementação do ajuste do modelo SEIIHURD com separação de grupos. Necessita de mais verificações e funções para simplificar o input. Baseado nas classes disponíveis no modelos.py """ import numpy as...
32,249
20,487
import numpy as np import os from sklearn.neighbors import KNeighborsClassifier from .base_generator import BaseGenerator class KNNCodeGenerator(BaseGenerator): skeleton_path = "skeletons/knn_skeleton.txt" def __init__(self, clf: KNeighborsClassifier): self.clf = clf @staticmethod def gene...
2,447
792
# -*- coding: utf-8 -*- import os import sys from gluon import current from gluon.storage import Storage __all__ = ("PluginLoader", ) # Name of the plugin directory in modules PLUGINS = "plugins" # Module names to ignore when scanning for plugins IGNORE = ("skeleton", "__init__") # Name of the setup fu...
8,719
2,040
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ccm.ui' # # Created by: PyQt5 UI code generator 5.13.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_CCMTask(object): def setupUi(self, CCMTask): CCMTask.setObjec...
15,105
5,051
# 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, software # distributed under t...
11,758
3,547
# !/usr/bin/python import numpy as np import math as m def buildMesh(Mp,l,ppc): # Mesh built by giving : # 1-Number of elements in x-direction # 2-Length of meshed domain # 3-Number of particle per cell nex = Mp/ppc nnx=nex+1 lmp=l/(Mp-1) dx = ppc*l/nex xn = np.linspace(-lmp/2,l+lmp/2,nex+1) c...
1,107
555
import random import numpy as np import tensorflow as tf from collections import deque class PrioritizedReplayBuffer(): """ Class implements Prioritized Experience Replay (PER) """ def __init__(self, maxlen): """ PER constructor Args: maxlen (int): buffer length """ ...
3,202
869
#!/usr/bin/python3 # coding=utf-8 # 环境准备:pip install opencv_contrib_python # 输入话题:tianbot_mini/image_raw/compressed # 输出话题:roi import sys import os import rospy import sensor_msgs.msg from cv_bridge import CvBridge import cv2 import numpy as np from sensor_msgs.msg import RegionOfInterest as ROI from sensor_msgs.msg ...
5,722
2,191
# -*- coding:utf-8 -*- # @Author: ZhaoWen <withzhaowen@126.com> # @Date: 2021/1/2 # @GiteePath: https://gitee.com/openeuler2020/team-1186152014 from method_analysis_utils.scanner import get_scanner,token_type import os import logging.config from method_analysis_utils.complier import get_complier # 配置日志 logging.conf...
4,236
1,791
#-- GAUDI jobOptions generated on Mon Jul 20 10:20:49 2015 #-- Contains event types : #-- 11134011 - 42 files - 900254 events - 251.92 GBytes #-- Extra information about the data processing phases: #-- Processing Pass Step-125836 #-- StepId : 125836 #-- StepName : Stripping20-NoPrescalingFlagged for Sim08...
4,905
3,360
""" # Pyqtree Pyqtree is a pure Python spatial index for GIS or rendering usage. It stores and quickly retrieves items from a 2x2 rectangular grid area, and grows in depth and detail as more items are added. The actual quad tree implementation is adapted from [Matt Rasmussen's compbio library](https://github.com/mdras...
12,257
3,783
from logo import logo def add(n1, n2): return n1 + n2 def multiply(n1, n2): return n1 * n2 def subtract(n1, n2): return n1 - n2 def divide(n1, n2): return n1 / n2 symbols = ['+', '-', '/', '*'] operations = {'+': add, '-': subtract, '*': multiply, '/': divide} def Calci(): ...
1,136
370
# coding=utf-8 # Copyright 2020 Google LLC. # # 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 ...
6,089
1,648
try: from setuptools import setup except ImportError: from distutils.core import setup 'description': 'P4rmyKnife - The Swiss Army Knife for P4', 'author': 'Assembla, Inc.', 'url': 'https://assembla.com/' 'author_email': 'louis@assembla.com', 'version': '0.1', 'install_requires': [], ...
670
254
from configparser import RawConfigParser config = RawConfigParser() config.read("configuration/config.ini") class ReadConfig(): @staticmethod def getApplicationURL(): url = (config.get('common info', 'baseURL')) return url @staticmethod def getUserName(): username = (config.get('common info', 'username'))...
446
135
# -*- coding: utf-8 -*- from tinyq.app import Application # noqa __version__ = '0.3.0' __author__ = 'mozillazg' __license__ = 'MIT' __copyright__ = 'Copyright (c) 2017 mozillazg'
181
81
from .test_lightcurves import * from .test_statistics import * from .test_models import * from .test_fitting import * from .test_tools import * from .test_photometry import * from .test_tpf import * from .test_imaging import * from .test_photometry import *
258
83
class Person: def __init__(self, name, age): self.name = name self.age = age def say_hello(self): print('Hello, my name is {} and I am {} years old'.format(self.name, self.age)) if __name__ == '__main__': person = Person('David', 34) print('Age: {}'.format(person.age)) ...
340
120
import RPi.GPIO as GPIO from time import sleep import sys #setup GPIO.setmode(GPIO.BOARD) openRelay=11 closeRelay=13 GPIO.setup(openRelay, GPIO.OUT) GPIO.setup(closeRelay, GPIO.OUT) #get cmd args duration = float(sys.argv[1]) opening = sys.argv[2] in ['true', 'True', '1', 'TRUE'] relay = openRelay if opening else cl...
614
241
# AUTO GENERATED FILE - DO NOT EDIT from dash.development.base_component import Component, _explicitize_args class Popover(Component): """A Popover component. Keyword arguments: - children (a list of or a singular dash component, string or number; optional): The children of this component - id (string; optiona...
3,725
1,043
from asynctest import TestCase as AsyncTestCase import json from ...storage.error import StorageNotFoundError from ..util import bytes_to_b58 from ..key_type import KeyType from ...core.in_memory import InMemoryProfile from ...storage.in_memory import InMemoryStorage from ..key_pair import KeyPairStorageManager, KEY_...
3,954
1,311
from __future__ import print_function import warnings import numpy as np C4 = 261.6 # Hz piano_max = 4186.01 # Hz piano_min = 27.5000 # Hz - not audible __all__ = ['cent_per_value','get_f_min','get_f_max','FrequencyScale'] def cent_per_value(f_min, f_max, v_min, v_max): """ This function takes in a freque...
6,191
1,941
from apscheduler.schedulers.background import BackgroundScheduler from des.ccd import start_pipeline def download_queue(): start_pipeline() scheduler = BackgroundScheduler() scheduler.add_job( download_queue, 'interval', # minutes=1 seconds=20, max_instances=1, id='des_download_ccd' ) ...
338
116
from common.input import input_int, input_float def get_operand(): return input_float("Please enter an operand: ") def get_command(): return input("Enter a command: ") def get_history_entry_id(): return input_int("Please enter a history entry id: ") def get_history_file_name(): return input("Ent...
440
133
#!/usr/bin/env python import os import sys import re import math import random import matplotlib.pyplot as plt import numpy as np from google.protobuf import text_format sys.path.append(os.path.dirname(os.path.realpath(__file__))+"/../../build") import gsbn_pb2 if len(sys.argv) < 1: print("Arguments wrong! Please r...
1,872
963
#!/usr/bin/env python3 from geopy.geocoders import Nominatim locator = Nominatim(user_agent="getcity") loc = locator.geocode("Munich") print(loc.latitude, loc.longitude)
174
70
# repl/repl.py # # A REPL interface to a micro:bit or similar device running MicroPython # This is written on top of pyserial, however the dependency on pyserial # is soft (as the serial instance is passed in as a constructor parameter # and the detection of the need to bytes-encode strings is dynamic). # Thus you can ...
6,448
1,853
class RequestException(Exception): pass
44
11
from django.contrib.auth.models import User from django.db import models from markdownx.models import MarkdownxField class Category(models.Model): """ Represents a COCO category """ coco_id = models.IntegerField(unique=True, db_index=True) name = models.CharField(max_length=50) supercategory =...
3,172
1,071
#!/usr/bin/python import code import ctypes import os import random import select import socket import struct import subprocess import sys import threading has_windll = hasattr(ctypes, 'windll') # # Constants # PACKET_TYPE_REQUEST = 0 PACKET_TYPE_RESPONSE = 1 PACKET_TYPE_PLAIN_REQUEST = 10 PACKET_TYPE_PLAIN_RESPONSE ...
13,866
6,028
from sklearn.preprocessing import MinMaxScaler from sklearn.pipeline import Pipeline from scipy.stats import chi2_contingency from sklearn.compose import ColumnTransformer from boruta import BorutaPy from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import OrdinalEncoder from sklearn.impute...
8,599
2,528
""" User challenge API endpoints - list user's challenges & issue new ones """ import datetime import flask import sqlalchemy from .. import model, util from . import match as match_api from . import util as api_util from .blueprint import web_api def make_challenge_record(challenge, participants): result = { ...
6,293
1,928
from django.conf import settings from django.contrib import admin from django.urls import path, include urlpatterns = [ path('txt-jokes-administratus/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('pages.urls')), ]
264
82
import json from newsservice.models import News from flask import (Blueprint, request) bp = Blueprint('request', __name__) @bp.route('/requestnews', methods=['GET', 'POST']) def requestdb(): """ This Method receives filter values as a JSON and uses these to make queries at the database. It creates a Lis...
1,909
521
import re import unittest from rexlex import Lexer from rexlex.lexer.itemclass import get_itemclass class TestableLexer(Lexer): """Test tuple state transitions including #pop.""" LOGLEVEL = None re_skip = re.compile('\s+') tokendefs = { 'root': [ ('Root', 'a', 'bar'), ...
943
329
import unittest import numpy as np import utils.imageutils as imgutils import utils.numpyutils as nputils from algorithms.neuralnetwork.convolutional.conv_net import ConvNet from datahandler.numerical.NumericalDataSet import NumericalDataSet import utils.serialization as srlztn def gen_vertical_bars(num): bars ...
7,134
2,944
import requests from requests.auth import HTTPBasicAuth import sys import os from string import rfind import base64 class XdbException(Exception): '''Exist db connector exception''' class Connector: def __init__(self, url, user, password): self.url = url self.auth = HTTPBasicAuth(user, passwo...
2,747
834
# -*- coding: utf-8 -*- """ Created on Tue May 30 16:43:10 2017 ☜☜☜☜☜☜★☆★☆★☆★☆ provided code ★☆★☆★☆★☆☞☞☞☞☞☞ @author: Minsooyeo """ import os import matplotlib.image as mpimg import matplotlib.pyplot as plt from PIL import Image as im import numpy as np import utills as ut import tensorflow as tf sess = tf.InteractiveS...
5,736
2,463
import numpy as np from common import projection_back EPS = 1e-9 def ilrma(mix, n_iter, n_basis=2, proj_back=True): """Implementation of ILRMA (Independent Low-Rank Matrix Analysis). This algorithm is called ILRMA1 in http://d-kitamura.net/pdf/misc/AlgorithmsForIndependentLowRankMatrixAnalysis.pdf It on...
3,176
1,242
import pytest def test_index(client): res = client.get('/') assert res.status_code == 200 def test_about(client): res = client.get('/about') assert res.status_code == 200 def test_preferences(client): res = client.get('/preferences') assert res.status_code == 200 def test_signin(client): res = client....
367
136
num= int (input("enter number of rows=")) for i in range (1,num+1): for j in range(1,num-i+1): print (" ",end="") for j in range(2 and 9): print("2","9") for i in range(1, 6): for j in range(1, 10): if i==5 or i+j==5 or j-i==4: print("*", end...
412
150
import random import math from functools import reduce import torch import torch.nn as nn def random_z_v(z_dim, z_num): # ret = np.random.normal(0.01, 1.0, z_dim * z_num) return torch.distributions.normal.Normal(torch.zeros([z_num, z_dim]), 0.1).sample() class HyperNN(nn.Module): def __init__(self, obs_...
4,819
1,593
from functools import reduce from bokeh.plotting import figure, output_file, show from bokeh.io import output_notebook from CONSTANTS import * from utilities import * from bokeh.plotting import figure, output_file, show import pandas as pd, numpy as np ENVIRON = C.LOCAL def mmap(*args): return list(map(*args)) c...
8,351
2,891
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # [0,0] = TN # [1,1] = TP # [0,1] = FP # [1,0] = FN # cm is a confusion matrix # Accuracy: (TP + TN) / Total def accuracy(cm: pd.DataFrame) -> float: return (cm[0,0] + cm[1,1]) / cm.sum() # Precision: TP / (TP + FP) de...
6,790
2,582
''' Problem:- Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. ''' class Solution: def longestPalindrome(self, s: str) -> str: res = "" resL...
957
320
# import the necessary packages from .agegenderhelper import AgeGenderHelper from .imagenethelper import ImageNetHelper
119
30
from .. import lib from ..exceptions import * from .. import _libressl from .cipher import BaseCipher from .auth import BaseCipherAuth from .auth import GOST89_HMAC_Streebog512, AES256_GCM ffi, clib = _libressl.ffi, _libressl.lib class OnionCipher(object): """Onion ciphering.""" @classmethod def new(cls, ...
2,965
900
import os import numpy as np import matplotlib.pyplot as plt from ambiance import Atmosphere, CONST HERE = os.path.abspath(os.path.dirname(__file__)) FILE_NAME = os.path.basename(__file__).replace('.py', '.png') PATH_OUT = os.path.join(HERE, FILE_NAME) def density_estimate(h): return 10**((h - 2.33e3)/-16.3e3) ...
1,149
505
from __future__ import print_function import numba.unittest_support as unittest from numba.utils import PYVERSION from .support import TestCase, enable_pyobj_flags def build_set_usecase(*args): ns = {} src = """if 1: def build_set(): return {%s} """ % ', '.join(repr(arg) for arg in args) ...
1,277
453
from pep272_encryption import PEP272Cipher, MODE_ECB block_size = 1 key_size = 0 def new(*args, **kwargs): return RC4Cipher(*args, **kwargs) class RC4Cipher(PEP272Cipher): block_size = 1 key_size = 0 def __init__(self, key, mode=MODE_ECB, **kwargs): if mode != MODE_ECB: raise V...
1,188
534
""" color_scheme_matcher. Licensed under MIT. Copyright (C) 2012 Andrew Gibson <agibsonsw@gmail.com> 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 limit...
12,316
3,447
import re class Node: def __init__(self, id, ip, hostname, type): self.id = id self.ip = ip self.hostname = hostname self.type = type self.validate() def validate(self): self.illegal = False if re.match("^(\d{1,3}\.){3}\d{1,3}$", self.ip): ...
820
304
from random import * l = [] for i in range(50): l.append(randint(1, 100)) print(l) for i in range(len(l)): l[i] **= 2 print(l)
134
64
import math def radix_sort(arr): if arr != []: bucket_size = 10 maxLength = False temp = -1 placement = 1 while not maxLength: maxLength = True buckets = [list() for i in range( bucket_size )] #empty the arr for i in arr: ...
827
223
import os import random import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader import torch.optim.lr_scheduler as lr_scheduler from torch.utils.data.sampler import SubsetRandomSampler from torchvision.datasets import CIFAR100, CIFAR10 from tqdm import tqdm from config...
4,232
1,395
import sys from nexentaedge.utils import get_sid from nexentaedge.nedgeConfigurator import NedgeMgmtConfigurator from utils import get_iface_name_by_mac_from_list from utils import get_deployment_config def main(): # check nedge already installed and ready if get_sid(): return cfg = g...
1,284
438
from django.conf.urls import url from django.contrib.auth import views as auth_views from django.contrib.auth import views from . import views urlpatterns = [ #Custom login view # url(r'^login/$', views.user_login, name='login'), #Builtin login view url(r'^login/$', auth_views.login, name='login'), ...
1,234
422
#!/usr/bin/env python # Copyright (c) 2009 Six Apart Ltd. # 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 must retain the above copyright notice, # this lis...
10,195
3,266
#!/usr/bin/env python # -*- coding: utf-8 -*- # # droxi # Copyright (c) 2014, Andrew Robbins, All rights reserved. # # This library ("it") is free software; it is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; you can redistribute it and/or modify it under the terms of the # GNU Lesser Gen...
1,119
388
# Copyright 2021 Hathor Labs # # 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, s...
5,224
1,712
from .save_views import save_3d_views from .panels import plot_panels from ._default_params import ( params_inflatedless_lateral_medial_ventral, params_flatmap_lateral_medial, params_occipital_triple_view, params_inflated_dorsal_lateral_medial_ventral, ) __all__ = [ "save_3d_views", "plot_panel...
502
198
# -*- coding: utf-8 -*- from pyfr.mpiutil import get_comm_rank_root from pyfr.plugins.base import BasePlugin, init_csv class DtStatsPlugin(BasePlugin): name = 'dtstats' systems = ['*'] formulations = ['std'] def __init__(self, intg, cfgsect, prefix): super().__init__(intg, cfgsect, prefix) ...
1,456
475
# The source of this script is from: # https://github.com/TejasNaikk/Image-Alignment-and-Panoramas/blob/master/main.py import cv2 import numpy as np import math ''' Warp an image from cartesian coordinates (x, y) into cylindrical coordinates (theta, h) Returns: (image, mask) Mask is [0,255], and has 255s wherever the...
1,989
843
import math import random import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from fmt.pythonfmt.doubleintegrator import filter_reachable, gen_trajectory, show_trajectory from fmt.pythonfmt.world import World def dist2(p, q): return math.sqrt((p[1] - q[1]) ** 2 + (p[2] - q[2]) ** 2) # FM...
7,490
2,832
# import unittest import logging from timeit import timeit logging.basicConfig(level=logging.INFO) def memoize(function): cache = {} def memo(*args): if args not in cache: cache[args] = function(*args) return cache[args] return memo @memoize def edit_distance_recursive(sou...
2,338
740
# VMware vCloud Python SDK # Copyright (c) 2014 VMware, 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...
2,365
698
from debug_utils import * def run(node_l, cmd_l): popens = {} for i, n in enumerate(node_l): popens[n] = n.popen(cmd_l[i]) log(DEBUG, "Started {}".format(n)) def run_masters(m_l): run(m_l, ['./run.sh m {}'.format(i) for i in range(len(m_l))]) log(DEBUG, "done") def run_workers(w_l): run(w_l, ['./run.sh w {}...
607
280
import random options = { "year": { "start": 1946, "end": 2020 }, "body": ["Sedan", "Wagon", "Hatchback", "Coupe", "SUV", "Utility", "MPV", "Convertible", "Van"], "engine_location": ["front", "mid", "rear"], "engine_mounting": ["transverse", "longitudinal"], "drive": ["FWD",...
2,086
691