text
string
size
int64
token_count
int64
#!/usr/bin/env python import re class LocalData: """ Data class containing data structures and methods to interact with them """ # ('ipv4', 'ipv6', 'port') super_friends = list() # {'pktid' : (ip, port)} received_packets = dict() # 'pktid' sent_supe_packet = str() # 'pktid' sent_menu_quer_packet = str()...
8,025
3,159
from msc.args import parse_args, prompt_string_arg_if_none from msc.pool_cmds import pool_list, pool_create, pool_delete, pool_exec, pool_shell from msc.digitalocean import DigitalOceanPoolProvider def main(): providers = [DigitalOceanPoolProvider()] args = parse_args() if args.sub_cmd == "pool": ...
951
303
import setuptools setuptools.setup( name="vive_ros2_server", version="0.0.1", author="Michael Equi", author_email="michaelequi@berkeley.edu", description="Package for running the pure python server", long_description="", long_description_content_type="text/markdown", url="https://github...
590
190
from contextlib import ExitStack import contextlib @contextlib.contextmanager def first(): print('First') yield @contextlib.contextmanager def second(): print('Second') yield for n in range(5): with ExitStack() as stack: stack.enter_context(first()) if n % 2 == 0: stac...
384
115
def combined_linear_cong(n=10000): r = [0.0] * n m1 = 2147483563 a1 = 40014 y1 = 1 m2 = 2147483399 a2 = 40692 y2 = 1 for i in range(n): y1 = a1 * y1 % m1 y2 = a2 * y2 % m2 x = (y1 - y2) % (m1 - 1) if x > 0: r[i] = (x / m1) else: ...
398
215
#!/usr/bin/env python3 import inkex import math import string from lxml import etree from inkex.transforms import Transform # Function for calculating a point from the origin when you know the distance # and the angle def calculate_point(angle, distance): if (angle < 0 or angle > 360): return None els...
18,997
5,425
from typing import Iterable, Mapping, Sequence, Callable from urllib.parse import quote from facebookads import FacebookAdsApi from facebookads.adobjects.ad import Ad from facebookads.adobjects.adaccount import AdAccount from facebookads.adobjects.adcreative import AdCreative from facebookads.adobjects.adset import Ad...
1,756
548
from flask import Flask, Blueprint, request, session from flask_httpauth import HTTPTokenAuth from sqlalchemy import desc from auth import verify_token, generate_token, token_exists, hash_multiple, remove_token from database import * from models.user import User from models.mood import Mood from models.notes import No...
8,106
2,919
import os import uuid from osipkd.tools import row2dict, xls_reader from datetime import datetime from sqlalchemy import not_, func from sqlalchemy.sql.expression import and_ from ziggurat_foundations.models import groupfinder from pyramid.view import ( view_config, ) from pyramid.httpexceptions import ( HT...
11,228
3,235
#!/usr/bin/env python3 def parse_garbage(stream): stream = iter(stream) while True: try: c = next(stream) except StopIteration: return else: if c == '!': next(stream) elif c == '>': return else:...
3,518
1,262
import sys from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad def encrypt(data, password): """Enrcrypt data and return content in binary""" try: cipher = AES.new(password.encode(), AES.MODE_CBC) cypher_text_bytes = cipher.encrypt(pad(data.encode(), AES.block_size)) ...
908
301
import requests import pandas as pd from util.api_util import AV_API_KEY def query_av(function, symbol, datatype): url = f"https://www.alphavantage.co/query?function={function}&symbol={symbol}&apikey={AV_API_KEY}" r = requests.get(url) req = r.json() symbol = req["symbol"] data = req[datatype] ...
1,812
618
import pygame, sys, math, random from Meme import * from Bossmeme import * from Wall import * from Level import * from Player import * from Memefinity import * pygame.init() #Hello b0ss, this file shall be the final game, or a script, kinda, whatever. #Reading the file top to bottom should be the game from start to fi...
502
150
# 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 warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
10,876
3,383
from dataclasses import dataclass from typing import Any, Callable, Generic, Iterable, Optional, TypeVar from .strings import StringPosition, StringPositions, to_string __all__ = [ 'Match', 'Matcher', 'MatchOption', ] T = TypeVar('T') @dataclass(frozen=True) class MatchOption(Generic[T]): data: T ...
2,943
847
import configparser import logging import multiprocessing as mp import os.path from contextlib import contextmanager from datetime import datetime from enum import Enum from parser.parser import Parser, ParserConfig from queue import Empty from typing import Any, Dict from monitor.config import DaemonConfig STATE_FIL...
4,311
1,287
import unittest import numpy from xminds.ds.scaling import linearscaling class LinearToolsTestCase(unittest.TestCase): def test_linearscaling_scalar(self): assert numpy.isclose(linearscaling(0, 0, 10, 0, 1), 0) assert numpy.isclose(linearscaling(1, 0, 10, 0, 1), 10) assert numpy.isclose(...
1,569
664
#based on code by : Camilo Olarte|colarte@telesat.com.co|Sept.2003 import sys import string import calendar import Tkinter as tk import time import datetime from dateutil.parser import parse from dateutil.relativedelta import relativedelta from tk_simple_dialog import Dialog from ..core.status import Status class ...
12,912
4,018
import pytest from flaskr import db def test_index_shows_auth_links_when_not_logged(client, app): response = client.get('/') assert b'Log In' in response.data assert b'Register' in response.data def test_index_shows_content_when_logged(client, auth): auth.login() response = client.get('/') a...
3,929
1,330
#!/usr/bin/env python # # A simple script to save NUM lines from the huge dataset into a smaller file for simple tests # # Usage: build_test_data.py [outfile] from __future__ import print_function import argparse import random import sys __author__ = 'marco' FILE_NAME = 'data/OPPR_ALL_DTL_GNRL_12192014.csv' NUM = 10...
1,946
574
import unittest class DummyTestCase(unittest.TestCase): def setUp(self): self.AN_ITEM = "item" def test_givenAnEmpyArray_whenAnItemIsAdded_thenArraySizeIncreases(self): array = [] array_size_expected = 1 array.append(self.AN_ITEM) self.assertEquals(array_size_expecte...
335
116
''' Some python helper functions. Tested on Python 3.8 ''' # https://learning.oreilly.com/library/view/effective-python-90/9780134854717/ch01.xhtml#ch1 def to_str(bytes_or_str): if isinstance(bytes_or_str, bytes): value = bytes_or_str.decode('utf-8') else: value = bytes_or_str return value ...
528
197
from .MemoryReference import MemoryReference from .SymbolTable import SymbolTable class DirectMemoryReference(MemoryReference): def __init__(self,val): self._value = val def value(self): return self._value def collect_statistics(self,stats): self._value.collect_statistics(stats) ...
893
259
import heapq def dijkstrasAlgorithm(start, edges): dist = [float('inf') for _ in range(len(edges))] dist[start] = 0 queue = [(dist[start], start)] while queue: current_best_dist, current_node = heapq.heappop(queue) if current_best_dist != dist[current_node]: continue ...
635
209
from __future__ import annotations from spinta.components import Model from spinta.components import Property from spinta.core.ufuncs import Env class ChangeModelBase(Env): model: Model prop: Property
213
60
#!/usr/bin/env python # -*- coding: utf-8 -*- """ The Filter test suite. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from future.builtins import * # NOQA import gzip import os import unittest import warnings import numpy as np import scipy.signal a...
11,723
3,808
import unittest import random_greetings class RandomGreetings(unittest.TestCase): # abrir_csv def test_abrir_csv_com_sucesso_validando_numero_linhas(self): arquivo_csv = random_greetings.abrir_csv("test/lista_correta.csv") numero_linhas = sum(1 for linha in arquivo_csv) self.assert...
2,421
934
from finrl.config import config from finrl.preprocessing.preprocessors import FeatureEngineer import pandas as pd import numpy as np def preprocess_btc(df): df = df.rename(columns={'time':'date'}) df.insert(loc=1, column='tic',value='BTC/USDT') df = df[['date','tic','open','high','low','close','volume']] ...
762
248
#!/usr/bin/python3 fh = open('lines.txt') for line in fh.readlines(): print(line)
86
35
from tests.testcase import TestCase from edmunds.globals import session from flask.sessions import SecureCookieSession from werkzeug.local import LocalProxy class TestSessionCookie(TestCase): """ Test the SessionCookie """ def test_session_cookie(self): """ Test the file """ ...
1,807
528
#!/bin/env python ## tle file for r2cloud SDK # @author Lukáš Plevač <lukasplevac@gmail.com> # @date 9.9.2020 import time class auth: ## init function # @param object self - instance of class # @param dict auth_dict - dict of auth def __init__(self, auth_dict): sel...
837
270
#!/usr/bin/env python # _*_ coding: utf-8 _*_ import argparse from pymatflow.base.xyz import base_xyz from pymatflow.structure.crystal import crystal """ usage: xyz-build-supercell.py -i input.xyz -o output.xyz -n n1 n2 n3 n1, n2, n3 are the three repeated number in the three direct of three ...
1,097
399
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://pytest.org/latest/plugins.html """ from __future__ import print_function, absolute_import, division # import pytest
179
64
import numpy as np import cv2 as cv from matplotlib import pyplot as plt imgL = cv.imread('tsukuba_l.png', 0) imgR = cv.imread('tsukuba_r.png', 0) stereo = cv.StereoBM_create(numDisparities=16, blockSize=15) disparity = stereo.compute(imgL, imgR) plt.imshow(disparity, 'gray') plt.show()
288
126
#-*- coding =utf-8 -*- import bpy from bpy.props import * from bpy.types import Menu,Panel,AddonPreferences from .Ops_Light import getlight # shift a menu def add_cam_menu(self, context): # add menu if context.mode == 'OBJECT': self.layout.operator("object.add_view_camera",icon='VIEW_CAMERA',text = "A...
18,268
6,446
# Load a library that allows drawing and images. import cv2 # Save image in set directory # Read RGB image # download image from cleanpng.com img = cv2.imread('1-pets.jpg') # Output img with window name as 'image' cv2.imshow('image', img) # Maintain output window util user presses a key cv2.waitKey(0) ...
391
130
from pgmpy.factors.discrete import TabularCPD from pgmpy.inference import VariableElimination from pgmpy.models import BayesianModel """ CREATE NEW MODEL THEN INFER AFTER WE WILL MODIFY THE MODEL AND INFER AGAIN I'm simply creating the same network used here in this tutorial, except that I'm creating the network part...
2,438
863
#!/usr/bin/env python """ Homogeneous Transformation Matrices """ import math import numpy as np # Local modules import baldor as br def are_equal(T1, T2, rtol=1e-5, atol=1e-8): """ Returns True if two homogeneous transformation are equal within a tolerance. Parameters ---------- T1: array_like First i...
10,025
4,211
import os import logging from django.conf import settings # noqa from celery import signals from celery.task.control import inspect def copy_dict(ds): return {k: v for k, v in ds.iteritems()} @signals.celeryd_after_setup.connect def configure_task_logging(instance=None, **kwargs): tasks = inst...
1,423
468
import os import sys import cv2 import numpy as np import torch try: sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from data.util import imresize_np from utils import util except ImportError: pass def generate_mod_LR_bic(): # set parameters up_scale = 4 mod_...
4,419
1,727
# coding: utf-8 import django from sqlalchemy import types, ForeignKey def simple(typ): return lambda field: typ() def varchar(field): return types.String(length=field.max_length) def foreign_key(field): if django.VERSION < (1, 8): parent_model = field.related.parent_model elif django.VER...
602
195
import os import re from linters.markdown_linter import MarkdownLinter from general_tools.file_utils import read_file from app_settings.app_settings import AppSettings class LexiconLinter(MarkdownLinter): def lint(self): """ Checks for issues with OBS Use self.log.warning("message") to l...
1,543
467
import nltk import random EXPLICIT_WORDS = ['shit', 'fuck', 'nigg', 'masturb', 'bitch'] def is_explicit(line): for word in line: for e in EXPLICIT_WORDS: if e in word.lower(): return True return False def get_random_line(corpus, last_line = None): if os.path.isfile('ly...
1,812
593
#!/usr/bin/python3 # -*- encoding="UTF-8" -*- #Import Package import sys sys.path.append("..") import re from tkinter.messagebox import * import parameters #Dont use from parameters import NetlistPath, it Will be import ealier than Changed from parameters import regExpExtend from parameters import regExpCommandEnd ...
1,596
551
''' Description: Functional file that initializes our app ''' import os from flask import Flask, flash, request, redirect, url_for from config import Config from flask_sqlalchemy import SQLAlchemy from werkzeug.utils import secure_filename from flask_login import LoginManager app = Flask(__name__) app.config.from_objec...
451
137
from django.http.response import HttpResponse from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, JsonResponse from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from main.functions import get_authenticated_user, get_new...
12,043
3,613
class Anonymizer: def __init__(self, context, dataframe): restructed = self.restructure(dataframe) self._anonymized = self.anonymize(restructed) def restructure(self, dataframe): """ Applies the restructuring Spark transformations :param dataframe: The original Spark d...
754
193
""" To plot this, you need to provide the experiment directory plus an output stem. I use this for InvertedPendulum: python plot.py outputs/InvertedPendulum-v1 --envname InvertedPendulum-v1 \ --out figures/InvertedPendulum-v1 (c) May 2017 by Daniel Seita """ import argparse import matplotlib matplotl...
4,221
1,444
# coding=utf-8 # Copyright 2022 The Balloon Learning Environment Authors. # # 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 require...
2,810
948
#!/usr/bin/python3 # # generate ISR table # vect_fmt = '''\ # vector {0} .weak _vector_{0}_fn, _vector_{0}_j _vector_{0}_fn = _default_isr_fn _vector_{0}_context = _isr_context .section .vector_{0}, "ax" .ent _vector_{0} _vector_{0}: la k0,_vector_{0}_fn j _vector_{0}_context nop .end _vect...
386
168
import collections import time from functools import wraps from typing import Any, Callable, Tuple, Union, List class StateMachine(object): """ 'Design a representation of the finite state machine using decorators to specify state machine handlers.' """ def __init__(self, T: int, HALT: int...
6,518
2,003
VERSION = (0, 0, 4) default_app_config = 'iitgauth.apps.IitgauthConfig'
73
37
from typing import Type, Union from dj_hybrid.types import SupportsPython from .registry import registry from .types import TypeWrapperOrProxy, Wrapable def wrap(expression: Wrapable) -> SupportsPython: """Wrap an expression so we can control how each one works within python Django essentially builds a cha...
932
239
#!/usr/bin/python # ----------------------------------------------------------------- # Canary deployment of Tileserver # ----------------------------------------------------------------- import time import subprocess from datetime import date import urllib2 import socket import time PG_VOLUME_NAME = 'mtb-tileserver-...
3,470
1,321
import frappe from frappe.utils import get_request_session import json def send_notification(auth_key,data): try: s = get_request_session() url = "https://fcm.googleapis.com/fcm/send" header = {"Authorization": "key={}".format(auth_key),"Content-Type": "application/json"} content = { "to":"/topics/all", ...
1,369
563
''' Test Cases for Metadata Class for Word Cloud Project Daniel Klein Computer-Based Honors Program The University of Alabama 9.12.2013 ''' import unittest from src.core.python.Metadata import Metadata class MetadataTest(unittest.TestCase): def setUp(self): self.test_metadata = Metadata() def tea...
1,183
359
import numpy as np class Graph: def __init__(self, size: int): self.size = size self.matrix = np.zeros((size, size), dtype=np.uint8) def add_edge(self, node1: int, node2: int) -> None: self.matrix[node1][node2] = 1 self.matrix[node2][node1] = 1 def remove_edge(self, nod...
426
161
import ifaint class FakeGrid: anchor = 0, 0 color = 255, 255, 255 dashed = False enabled = False spacing = 40 class Pimage: """Experimental Image implementation in Python. If this works out, I'll rename it as Image, and remove the C++-implementation py-image.cpp. "...
3,467
1,218
from __future__ import absolute_import, unicode_literals import sys import hashlib from threading import local import django.core.cache from django.conf import settings from django.core import signals as core_signals from django.core.cache import DEFAULT_CACHE_ALIAS from django.db.models import signals as model_signal...
5,514
1,619
#Inconsistent MRO class X(object): pass class Y(X): pass class Z(X, Y): pass class O: pass #This is OK in Python 2 class N(object, O): pass
172
70
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Utilities to compute J-factor maps """ from __future__ import absolute_import, division, print_function, unicode_literals from ...cube import make_separation_map from ...maps import WcsNDMap import astropy.units as u import numpy as np import copy __...
4,265
1,421
import discord from config import log from config import config import Webhook.log_send as ch_log from Moderating.Perms import role as perms def message_events(bot): @bot.event async def on_ready(): log.ready(bot) await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.w...
2,427
762
import os class AppLogger: def __init__(self, name, save_file=True, clear=False): self.file_name = name self.save_file = save_file if self.save_file and clear: if os.path.exists(name): os.remove(name) def write_line(self, obj): # text = None ...
740
238
from rest_framework.permissions import BasePermission class AllocateApplicationsPermissions(BasePermission): authenticated_users_only = True def has_permission(self, request, view): request_judge_id = int(request.parser_context['kwargs']['judge_id']) if request.user.id == request_judge_id: ...
395
108
# if gunicorn is used from run import app if __name__ == "__main__": app.run()
84
32
# # 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. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
3,162
1,061
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Factory method for easily getting imdbs by name.""" from pascal_voc...
2,969
1,054
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # An object that stores information about project in Gitlab. It uses API v4. from configparser import ConfigParser import json import requests import shutil import sys import urllib.parse import zipfile class GitlabProjectMeta(): def __init__(self, *args, **kwargs)...
4,668
1,302
# -*- coding: utf-8 -*- """ price calculations ~~~~~~~~~ WARNING: This is specific to US income data. If this needs to be changed, you will need to update the BINS values and some of the regex expressions. :copyright: (c) 2015 by Joe Hand, Santa Fe Institute. :license: MIT """ import numpy...
2,367
1,074
#!/usr/bin/python3 import array import datetime import functools import io import sys class Guard(): def __init__(self, id): self.id = id self.shifts = [] self.sleepIntervals = [] def registerShift(self, shift): self.shifts += [shift.date] self.sle...
5,945
1,802
from googleapiclient.errors import HttpError from httplib2 import Response def create_http_response(status, reason): resp = Response({"status": status}) resp.reason = reason return resp def create_http_error(status, reason, error): return HttpError( resp=create_http_response(status, reason),...
408
122
# coding: utf-8 import logging from typing import Optional from authlib.jose import jwt, errors as jwterrors from starlette.responses import RedirectResponse # NOQA from starlette.authentication import requires, has_required_scope # NOQA from fastapi import Query, HTTPException, Depends, Request from helpdesk impo...
10,492
3,249
from flask_assets import Bundle common_css = Bundle( # bootstrap Bundle('css/vendor/bootstrap.css', 'css/vendor/bootstrap-theme.css'), 'css/vendor/typelate.css', 'css/vendor/helper.css', 'css/main.css', filters='cssmin', output='public/css/common.css' ) common_js = Bundle( 'js/...
512
190
import requests import json,os import base64 from Crypto.Cipher import AES import codecs import binascii from lxml import etree musicUrl = ['http://music.163.com/discover/toplist?id=3779629'] basicUrl = 'http://music.163.com' def getMusic(): return get_html(musicUrl[0]) def get_html(url): headers = { ...
3,785
1,624
import argparse from datetime import datetime, timedelta from pathlib import Path from typing import NamedTuple import dask import numpy as np from snobedo.lib import ModisGeoTiff from snobedo.lib.command_line_helpers import add_dask_options, \ add_water_year_option from snobedo.lib.dask_utils import run_with_cli...
2,891
962
from leapp.actors import Actor from leapp.models import SSSDConfig8to9 from leapp import reporting from leapp.reporting import Report, create_report from leapp.tags import IPUWorkflowTag, ChecksPhaseTag COMMON_REPORT_TAGS = [reporting.Tags.AUTHENTICATION, reporting.Tags.SECURITY] related = [ reporting.RelatedRes...
2,114
572
# 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 # d...
11,308
3,211
''' Created on Sep 20, 2013 @author: nshearer ''' from ConsoleSimpleQuestion import ConsoleSimpleQuestion from ConsoleSimpleQuestion import UserAnswerValidationError class ConsoleCurrencyQuestion(ConsoleSimpleQuestion): def __init__(self, question): super(ConsoleCurrencyQuestion, self)._...
1,640
490
# -*- coding: utf-8 -*- """ Created on Mon Dec 19 14:48:39 2016 @author: Krounet e-mail : krounet@gmail.com """ __version__="0.0.1" from rasplivestation.livestreamerLaunching import livestreamerLaunching from rasplivestation.clienttoRasp import clienttoRasp
269
118
import logging import struct import socket import select import time from hashlib import sha256 import protocol import cryptoconfig USER_AGENT='/Satoshi:0.10.0/' #BIP 14 TCP_RECV_PACKET_SIZE=4096 SOCKET_BLOCK_SECONDS=0 # None means blocking calls, 0 means non blocking calls ADDRESS_TO_GET_IP='google.com' #connect t...
21,113
6,662
import torch import torch.nn as nn from .env import multienv class TextCNN(nn.Module): def __init__(self, kernel_num, kernel_sizes, configs): super(TextCNN, self).__init__() WN, WD = configs['embedding_matrix'].shape KN = kernel_num KS = kernel_sizes C = configs['num_cla...
2,330
785
from flask import Blueprint, render_template, abort from jinja2 import TemplateNotFound from app.auth import require_role import config page = Blueprint('index', __name__, template_folder='templates') @page.route('/') @require_role('user') def show(*args, **kwargs): '''Render Homepage''' user = kwargs['user']...
493
153
from abc import ABC, abstractmethod from dataclasses import dataclass, field from eopf.product.core import EOVariable, EOGroup, EOProduct, MetaData from typing import Any, Optional, Union import xarray as xr import numpy as np from utils import create_data class Builder(ABC): @abstractmethod def compute(sel...
2,534
838
# python3 # pylint: disable=g-bad-file-header # Copyright 2019 DeepMind Technologies Limited. 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...
12,026
3,998
from abc import ABC, abstractmethod class __LinearModel(ABC): @abstractmethod def _sample_split(self): pass @abstractmethod def _fit(self): pass @abstractmethod def _predict(self): pass @abstractmethod def _metrics(self): pass ...
1,041
296
# coding=utf8 from __future__ import unicode_literals, absolute_import, division, print_function """A way to track users""" import sopel from sopel.tools import Identifier from .Database import db as botdb from .Tools import is_number, inlist, similar, array_arrangesort, bot_privs, channel_privs from sopel_modules.s...
22,430
6,630
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 8 13:48:29 2017 @author: dhingratul Input: Filename, columnName Output : Unique number of a column of data """ import pandas as pd def uniqueOut(filename, columnName): file = pd.read_csv(filename) return len(file[columnName].unique()) fi...
444
163
#!/usr/bin/python import sys from lib import openstack from keystoneclient.v3.client import Client ostack = openstack.OpenStack('config.yaml') sess = ostack.getSession() client = Client(session=sess) print(ostack.run(client, sys.argv))
241
83
grooming_categories = [ 'Beauty & Spas', 'Barbers', 'Hair Salons', 'Skin Care', 'Hair Extensions', 'Medical Spas', 'Waxing', 'Nail Salons', 'Eyelash Service', 'Hair Removal', 'Blow Dry/Out Services', 'Hair Stylists', 'Day Spas', 'Massage', 'Massage Therapy', 'Eyebrow Services', 'Tattoo Removal', 'Kids Hair Salons', 'Sa...
567
247
import platform import struct import requests from .compat import to_bytes from .exceptions import RequestError from .exceptions import SelectOperationFailed from .exceptions import SelectOperationClientError from .exceptions import InconsistentError from . import utils import logging logger = logging.getLogger(__nam...
10,063
3,116
import os import cv2 import imutils import random from skimage.transform import rotate #3 next ones used for the skewing from skimage.transform import warp from skimage import data from skimage.transform import ProjectiveTransform import numpy as np #this class will rotate, translate, crop, add noise, skew, flip verti...
10,622
3,994
# Author: Taoz # Date : 8/29/2018 # Time : 3:08 PM # FileName: config.py import time import sys import configparser import os def load_conf(conf_file): # 获取当前文件路径 current_path = os.path.abspath(__file__) # config.ini文件路径,获取当前目录的父目录的父目录与congig.ini拼接 default_conf_file = os.path.join(os.path.abspath(...
3,381
1,569
from Kaspa.modules.abstract_modules.abstractBriefingSubmodule import AbstractBriefingSubmodule class TimeModuleDe(AbstractBriefingSubmodule): module_name = "Time" language = "de" key_regexes = dict() def __init__(self): self.key_regexes = {'(?i).*?(?=wieviel)+.+?(?=uhr)+.': self.action} ...
523
176
from django.shortcuts import render, redirect from django.http import HttpResponse from app.forms import PersonForm # Create your views here. def home(request): return render(request, 'index.html') def cadastrados(request): return render(request, 'cadastrados.html') def form(request): data = {} data[...
659
193
# -*- coding: utf-8 -*- # @Time : 2019/10/4 18:22 # @Author : floatsliang # @File : sql.py from typing import Union import re from copy import deepcopy from .epool import POOL from .compiler import QueryCompiler from .field import Expr, Field, OP_DICT, OP from .utils import result_wrapper, SearchResu...
9,657
3,206
import re from klgists.common.exceptions import ExternalCommandFailed, ParsingFailedException from klgists.common import abcd @abcd.dataclass(frozen=True) class GitDescription: text: str tag: str commits: str hash: str is_dirty: bool is_broken: bool @staticmethod def parse(text: str): pat = re.compile('''(...
1,512
595
#!/usr/bin/env python import rospy from std_msgs.msg import String def main(): rospy.init_node('service_client')
118
43
from reader import read_stl_verticies from utils import split_triangles, push2d, top_wider, push3d from writer import Binary_STL_Writer if __name__ == '__main__': faces = [] triangles = read_stl_verticies("./input.stl") more_triangles = split_triangles(triangles,5) for triangle in more_triangles: ...
702
238
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question # Create your tests here. class QuestionMethodTest(TestCase): def test_was_published_recently_with_future...
3,511
1,030
#!/usr/bin/python import griddb_python as griddb import sys import pandas factory = griddb.StoreFactory.get_instance() argv = sys.argv blob = bytearray([65, 66, 67, 68, 69, 70, 71, 72, 73, 74]) update = False containerName = "SamplePython_PutRows" try: # Get GridStore object gridstore = factory.get_store(h...
1,227
431