text
string
size
int64
token_count
int64
from mitmproxy import contentviews from . import base class ViewAuto(base.View): name = "Auto" def __call__(self, data, **metadata): # TODO: The auto view has little justification now that views implement render_priority, # but we keep it around for now to not touch more parts. priori...
654
184
from typing import List from processing.sl_filters import SynergyLogisticsFilters class Service(SynergyLogisticsFilters): """ Clase que contine servicios para el analisis de la tabla de Synergy Logistics. """ def get_routes_list(self, direction:str or None = None) -> List: """Genera una lista...
10,355
2,824
from sympy import init_printing, Rational from classes.BSpline import BSpline init_printing() # INPUT DATA HERE knots = [ 0, 0, 0, Rational(2, 5), Rational(1, 2), Rational(3, 5), 1, 1, 1, ] # fmt: off control_points = [ [2,2], [0,2], [0,0], [-2,0], [0,-2], [2,-2], ] # f...
467
228
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from recipe.models import Tag from recipe.serializers import TagSerializer from core.tests.utils import sample_tag, sample_user ...
2,765
887
from sfsidb import load as sload from sfsidb import toolkit from sfsidb import checking_tools as ct from sfsidb import sensor_file_reader as sfr from tests.conftest import TEST_DATA_DIR def test_get_depth_from_sensor_code(): sensor_ffp = TEST_DATA_DIR + "test-sensor-file.json" si = sfr.read_json_sensor_file(...
1,029
433
# Setup procedures -- WIP import os import re import arcpy arcpy.env.workspace = "in_memory" # TODO: out_gdb = "//cityfiles/DEVServices/WallyG/projects/NhoodProfiles/nhoods/data/NhoodAmenities.gdb/MtStatePlane" # DATA PROCESSING # Nhood_buffers: arcpy.Buffer_analysis("Nhoods", "nhood_buffers", ...
1,699
641
from ptrlib import * import re import time def create(name): sock.recvuntil("> ") sock.sendline("1") sock.sendline(name) def add(index, value): sock.recvuntil("> ") sock.sendline("2") sock.sendline(str(index)) sock.sendline(str(value)) def view(index, pos): sock.recvuntil("> ") so...
2,085
982
# coding: utf-8 """ PKS PKS API # noqa: E501 OpenAPI spec version: 1.1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import # python 2 and python 3 compatibility library import six from container_service_extension.lib.pksclient.api_cl...
43,142
12,185
import os import pytest import pandas as pd import numpy as np from shclassify.utils import (inverse_logit, choose_from_multinomial_probs, choose_from_binary_probs) def test_inverse_logit(): assert inverse_logit(0) == 0.5 def test_choose_from_multinomia...
2,334
807
import dataclasses from typing import Any, ClassVar, List, Optional, Sequence, Tuple, Type, Union from dbdaora.keys import FallbackKey from dbdaora.query import BaseQuery, Query, QueryMany from .repositories import HashData, HashEntity, HashRepository @dataclasses.dataclass(init=False) class HashQuery(Query[HashEnt...
2,111
619
"""Module used polling SNMP enabled targets.""" import sys # PIP3 imports import easysnmp from easysnmp import exceptions # Import Pattoo libraries from pattoo_shared import log from pattoo_shared.variables import DataPoint from pattoo_shared.constants import ( DATA_INT, DATA_COUNT64, DATA_COUNT, DATA_STRING, DA...
20,104
5,483
description = 'Resi instrument setup' group = 'basic' includes = ['base']
76
24
from __future__ import unicode_literals, division, absolute_import import logging from flexget.plugin import priority, register_plugin log = logging.getLogger('torrent_size') class TorrentSize(object): """ Provides file size information when dealing with torrents """ @priority(200) def on_task_m...
643
197
import re cmd = re.compile(r'^(\w+) (\w)?(?:, )?((?:\+|-)\d+)?$') with open('input23.txt') as f: # Subtract 1 from jump (offset) to enable ip++ for every instruction mem = [(i, r, j if j is None else int(j) - 1) for s in f for i, r, j in [cmd.match(s.strip()).groups()]] def run(a: int) -> int: reg = {'a':...
724
307
""" Ref: https://dacon.io/competitions/official/235673/talkboard/401911?page=1&dtype=recent """ import os import re import platform import itertools import collections import pkg_resources # pip install py-rouge from io import open if platform.system() == "Windows": try: from eunjeon import Mecab exc...
27,038
7,390
from django.contrib import admin from .. import models @admin.register(models.Contest) class ContestAdmin(admin.ModelAdmin): """ 대회관리 """ list_display = ['contest_name', 'start_time', 'end_time', 'message', 'host_email', 'after_open'] class Meta: model = models.Contest @admin.register(...
717
245
#!/usr/bin/env python3 import seaborn as sns import argparse import numpy as np import pandas as pd import matplotlib.pyplot as plt import pathlib import pathlib import kube_env import kube_util as util def graph(title, csv_path, output): old_to_new_names = {} df = pd.read_csv(csv_path) for col in df.colum...
3,566
1,078
import logging import predix.admin.cf.api import predix.admin.cf.orgs import predix.admin.cf.apps import predix.admin.cf.services class Space(object): """ Operations and data for Cloud Foundry Spaces. """ def __init__(self, *args, **kwargs): super(Space, self).__init__(*args, **kwargs) ...
4,920
1,412
import logging from fastapi import APIRouter from starlette import status from api.endpoints.dependencies.tenant_security import get_from_context from api.endpoints.models.v1.tenant import TenantGetResponse from api.services.v1 import tenant_service router = APIRouter() logger = logging.getLogger(__name__) @rou...
953
302
def quick_sort(array): ''' Prototypical quick sort algorithm using Python Time and Space Complexity: * Best: O(n * log(n)) time | O(log(n)) space * Avg: O(n * log(n)) time | O(log(n)) space * Worst: O(n^2) time | O(log(n)) space ''' return _quick_sort(array, 0, len(array)-1) def _quick_sort(arr...
1,573
649
def loops(): # String Array names = ["Apple", "Orange", "Pear"] # \n is a newline in a string print('\n---------------') print(' For Each Loop') print('---------------\n') # For Each Loop for i in names: print(i) print('\n---------------') print(' For Loop') prin...
1,618
468
import numpy as np from scipy import interpolate, signal from scipy.special import gamma import ndmath import warnings import pkg_resources class PlaningBoat(): """Prismatic planing craft Attributes: speed (float): Speed (m/s). It is an input to :class:`PlaningBoat`. weight (float): Weigh...
52,299
19,276
# -*- coding: utf-8 -*- """ Created on Tue Oct 6 09:54:17 2015 @author: jmilli """ import numpy as np from scipy.interpolate import interp1d def create2dMap(values,inputRadii=None,maxRadius=None): """ This function takes a 1D radial distribution in input and builds a 2map """ nbValues=len(values) ...
959
335
def solution(participant, completion): answer = '' # sort하면 시간절약이 가능 participant.sort() # [a, a, b] completion.sort() # [a, b] print(participant) print(completion) for i in range(len(completion)): if participant[i] != completion[i]: answer = participant[i] bre...
543
200
# -*- coding: utf-8 -*- """Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2020 Caleb Bell <Caleb.Andrew.Bell@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 ...
7,882
2,610
# Copyright 2018 The TensorFlow Authors. 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 required by applica...
4,604
1,401
import json from typing import Any, Optional import requests from django.core.exceptions import ValidationError from django.core.management import BaseCommand, CommandError from django.core.management.base import CommandParser from ....app.validators import AppURLValidator from ....core import JobStatus from ...insta...
2,102
565
# Copyright 2015 Google 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 required by applicable law or ag...
7,290
2,055
import argparse import glob import os, shutil import cv2 from YoloObjectDetector import YoloObjectDetector parser = argparse.ArgumentParser(description="Detect Objects in all images in the given folder.") parser.add_argument("-s", "--size", dest="size", default="320", type=str, help="Spatial Size (tiny, 320, 416, 60...
1,171
391
from rest_framework.routers import DefaultRouter from countries.api.views import CountryViewSet router = DefaultRouter() router.register('', CountryViewSet) urlpatterns = router.urls
186
50
class Node: def __init__(self, value, next_p=None): self.next = next_p self.value = value def __str__(self): return f'{self.value}' class InvalidOperationError(Exception): pass class Stack: def __init__(self): self.top = None def push(self, value): curren...
1,675
487
def main(): number = int(input("Enter number (Only positive integer is allowed)")) print(f'{number} square is {number ** 2}') # Press the green button in the gutter to run the script. if __name__ == '__main__': main()
232
73
import torch from torchvision import models from torch import nn class GoTurnRemix(nn.Module): """ Create a model based on GOTURN. The GOTURN architecture used a CaffeNet while GoTurnRemix uses AlexNet. The rest of the architecture is the similar to GOTURN. A PyTorch implementation of GOTURN can b...
1,869
599
#!/usr/bin/env python3 import faiss import numpy as np def main(outfile): d = 100 nlist = 100 k = 4 nb = 100000 np.random.seed(1234) xb = np.random.random((nb, d)).astype('float32') xb[:, 0] += np.arange(nb) / 1000. quantizer = faiss.IndexFlatL2(d) index = faiss.IndexIVFFlat(quan...
609
263
import os from getpass import getpass from pprint import pprint from netmiko import ConnectHandler # Code so automated tests will run properly password = os.getenv("NETMIKO_PASSWORD") if os.getenv("NETMIKO_PASSWORD") else getpass() arista1 = { "device_type": "arista_eos", "host": "arista1.lasthop.io", "us...
800
291
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Marshmallow loader for record deserialization. Use marshmallow schema to transfor...
2,891
846
from flask import jsonify from flask_restful import Resource class User(Resource): def get(self, id): data = {'name': 'nabin khadka'} return jsonify(data) def put(self, id): pass def patch(self, id): pass def delete(self, id): pass class UserList(Resource):...
475
157
import os import cv2 import glob import random import numpy as np import matplotlib.pyplot as plt def plot_image(img): plt.axis("off") plt.imshow(img, origin='upper') plt.show() def flip(img, dir_flag): # if flag: return cv2.flip(img, dir_flag) # else: # return img def brightness(i...
2,079
798
import os def left_join( hash , hash1): words = [] for value in hash.keys(): if value in hash1.keys(): words.append([value, hash [value],hash1[value] ]) else: words.append([value, hash [value],'NULL' ]) return words ...
703
240
# /usr/bin/env python # -*- encoding: utf-8 -*- from django.utils.text import capfirst from django.utils.translation import ugettext as _ from datable.core.serializers import BooleanSerializer from datable.core.serializers import DateSerializer from datable.core.serializers import DateTimeSerializer from datable.core...
2,583
710
from torch import nn import torch.nn.functional as F class FPNPredictor(nn.Module): def __init__(self, cfg): super().__init__() representation_size = cfg.MODEL.ROI_CAR_CLS_ROT_HEAD.MLP_HEAD_DIM num_car_classes = cfg.MODEL.ROI_CAR_CLS_ROT_HEAD.NUMBER_CARS num_rot = cfg.MODEL.ROI_CA...
1,233
525
# Generated by Django 2.0.6 on 2018-08-15 22:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('coderdojochi', '0020_mentor_shirt_size'), ] operations = [ migrations.AddField( model_name='mentor', name='home_addr...
771
250
import sys with open(sys.argv[1]) as handle: for new_line in handle: dest = new_line.split('/')[4] + '_' + new_line.split('/')[5] + '.zip' #print('curl -Ls -I -o /dev/null -w \'%{url_effective}\\n\' ' + new_line.strip()) print('curl -L --user ' + sys.argv[2] + ':' + sys.argv[3] + ' ' + new_...
350
140
from django.db import models from ..authentication.models import User class Follower(models.Model): """ Store data on following statistics for users. """ user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower') followed = models.ForeignKey(User, on_delete=models.CASCADE, ...
630
189
from dbt.adapters.doris.connections import DorisConnectionManager from dbt.adapters.doris.connections import DorisCredentials from dbt.adapters.doris.relation import DorisRelation from dbt.adapters.doris.column import DorisColumn from dbt.adapters.doris.impl import DorisAdapter from dbt.adapters.base import AdapterPlu...
477
154
from django.contrib.auth.decorators import login_required from django.conf.urls import url import views urlpatterns = [ url(r'public/$', views.RevelationModelListView.as_view(), name='revelation-list'), url(r'u/(?P<pk>\d+)/$', views.UserProfileView.as_view(), name='user-view')...
750
263
#!/usr/bin/env python # coding: utf-8 # vim: set ts=4 sw=4 expandtab sts=4: # Copyright (c) 2011-2013 Christian Geier & contributors # # 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 ...
6,395
2,061
import unittest from unittest.mock import Mock, patch from request import Request RESPONSE = { "status": "success", "message": "Processed" } class Response: def __init__(self): self.text = RESPONSE['message'] def json(self): return RESPONSE mock_response = Response() class Test...
2,483
774
import numpy as np import kirbytoolkit as ktk def test_jackknife_arr(): arr = [1, 2, 2, 3, 4] jkvar_true = 0.26 jkvar_code = ktk.jackknife_array(arr) np.testing.assert_almost_equal(jkvar_code, jkvar_true, decimal=7) # Test a longer array arr = np.loadtxt('randomdata.dat') jkvar_true = 0.0...
470
221
""" 使用装饰器限制函数的调用次数 """ import functools def call_limit(count): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): if decorator.calls >= count: raise AssertionError(f"单个程序最多允许调用此方法{count}次") decorator.calls += 1 return func(*ar...
530
213
s1 = {1} def sorted(s): l = list(s) l.sort() return repr(l) s1 = set() | set(range(3)) print sorted(s1) s2 = set(range(1, 5)) print sorted(s2) print repr(sorted(s1)), str(sorted(s1)) print sorted(s1 - s2) print sorted(s2 - s1) print sorted(s1 ^ s2) print sorted(s1 & s2) print sorted(s1 | s2) print len(...
1,691
795
import os import argparse import glob import pandas as pd from cpe775 import utils if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('data_dir', metavar='DIR') parser.add_argument('--out-dir', metavar='DIR') args = parser.parse_args() # Output to the data dir fil...
2,720
1,032
import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt import random from sympy import symbols, diff, N def fun(X, Y): return 2*(np.exp(-X**2 - Y**2))# - np.exp(-(X - 1)**2 - (Y - 1)**2)) def symfun(X, Y): return 2*(np.exp(1)**(-X**2 - Y**2))# - np.exp(1)**(-(X - 1)**2...
1,395
773
''' Selfiebooth Baas van Horst aan de Maas 2016 - CameraPuzzle =========================== This demonstrates using Scatter widgets with a live camera. You should see a shuffled grid of rectangles that make up the camera feed. You can drag the squares around to see the unscrambled camera feed or double click to scrambl...
639
205
#coding=utf-8 import requests,json headers = {'X-Rundeck-Auth-Token': '2EcW3xe0urFLrilqUOGCVYLXSbdByk2e','Accept': 'application/json'} headers['Content-type']='application/json' rundeck_host= 'http://10.1.16.26:4440' url = rundeck_host+'/api/16/project/fengyang/run/command' data={ 'project':'fengyang', 'exec...
521
237
import re from flask_restful import Resource, reqparse acceptedCreditCards = { "visa": r"/^4[0-9]{12}(?:[0-9]{3})?$/", "mastercard": r"/^5[1-5][0-9]{14}$|^2(?:2(?:2[1-9]|[3-9][0-9])|[3-6][0-9][0-9]|7(?:[01][0-9]|20))[0-9]{12}$/", "amex": r"/^3[47][0-9]{13}$/", "discover": r"/^65[4-9][0-9]{13}|64[4-9][0-9]{13}|...
2,984
1,253
import xmltodict import pytest from jmeter_api.configs.http_cache_manager.elements import HTTPCacheManager from jmeter_api.basics.utils import tag_wrapper class TestHTTPCacheManagerArgs: class TestClearCacheEachIteration: def test_check(self): with pytest.raises(TypeError): HT...
2,916
831
import configparser import mapping from main.helper.time_helper import get_token_time class TokenConfig: def __init__(self): self.config = configparser.ConfigParser() self.config_data = self.config['DEFAULT'] self.config.read(mapping.token_config) def read_token(self): self.co...
1,533
459
#!/usr/bin/env python # # Jiao Lin <jiao.lin@gmail.com> import os datadir = os.path.abspath(os.path.dirname(__file__)) def loadDOS(): f = os.path.join(datadir, 'V-dos.dat') from multiphonon.dos import io E, Z, error = io.fromascii(f) from multiphonon.dos.nice import nice_dos E,g = nice_dos(E, Z) ...
350
152
from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings import re import pymysql import geocoder import datetime import os class Weather: def __init__(self, host, user, passwd, db, port): settings_file_path = 'weather.weather.settings' # The path seen fr...
5,832
1,942
import asyncio import unittest from asyncio import ( gather, sleep, ) from unittest.mock import ( AsyncMock, call, ) from uuid import ( uuid4, ) import aiopg from minos.common import ( NotProvidedException, ) from minos.common.testing import ( PostgresAsyncTestCase, ) from minos.networks i...
7,578
2,242
import scrapy import datetime import re from datetime import timedelta from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class ItemNews(scrapy.Item): date = scrapy.Field() title = scrapy.Field() content = scrapy.Field() class SultraZonaSpider(scrapy.Spider): ...
4,489
1,534
import os.path as op import sys path = op.abspath(op.join(op.dirname(op.realpath(__file__)), "..", "src")) sys.path.append(path)
130
52
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class AccountMove(models.Model): _inherit = 'account.move' landed_costs_ids = fields.One2many('stock.landed.cost', 'vendor_bill_id', string='Landed Costs') landed_costs...
3,599
1,197
# -*- coding: utf-8 -*- """ Highcharts Demos Donut chart: http://www.highcharts.com/demo/pie-donut """ from highcharts import Highchart H = Highchart(width = 850, height = 400) data = [{ 'y': 55.11, 'color': 'Highcharts.getOptions().colors[0]', 'drilldown': { 'name'...
4,025
1,467
number_of_computers = int(input()) number_of_sales = 0 real_sales = 0 made_sales = 0 counter_sales = 0 total_ratings = 0 for i in range (number_of_computers): rating = int(input()) rating_scale = rating % 10 possible_sales = rating // 10 total_ratings += rating_scale if rating_scale == 2: r...
961
371
import discord import os import asyncio from discord.ext import commands from random import randint from cogs.libs import Settings from cogs.libs import Utils class Messages(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_message(self, message): ...
902
252
from features.move import Move class BestMove(Move): # TODO: replace this with an attribute which specifies columns @classmethod def from_row(cls, row): return cls(row.fen, row.best_move) def features(self, prefix=None): return super(BestMove, self).features(prefix="best_move")
315
94
import skimage.io import skimage.transform import numpy as np def load_image( path ): try: img = skimage.io.imread( path ).astype( float ) except: return None if img is None: return None if len(img.shape) < 2: return None if len(img.shape) == 4: return None if len(img.shape) ...
728
301
# -*- coding: utf-8 -*- __all__ = ["post_message"] import requests from . import config def post_message(message): secrets = config.SLACK_JSON r = requests.post(secrets["webhook_url"], json=dict(text=message)) r.raise_for_status()
248
91
import argparse import multiprocessing import random import time import torch.optim as optim from auto_LiRPA.eps_scheduler import LinearScheduler, AdaptiveScheduler, SmoothedScheduler, FixedScheduler from auto_LiRPA.perturbations import * from auto_LiRPA.utils import MultiAverageMeter from torch.nn import CrossEntropy...
10,054
3,328
from typing import Any, Callable, Dict, List, Optional, Type, TypeVar, Union import attr from ..models.client_applications_download_link import ClientApplicationsDownloadLink from ..types import UNSET, Unset from ..util.serialization import is_not_none T = TypeVar("T", bound="ClientApplication") @attr.s(auto_attri...
3,684
1,086
import FWCore.ParameterSet.Config as cms run2_GEM_2017 = cms.Modifier()
73
33
# !/usr/bin/env python # Copyright (c) 2019 Computer Vision Center (CVC) at the Universitat Autonoma de # Barcelona (UAB). # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. # # Modified by Rowan McAllister on 20 April 2020 import argparse import dat...
16,792
5,303
# -*- coding: utf-8 -*- """Gettext manipulation methods.""" from os import remove from os.path import exists from pathlib import Path from shutil import copyfile, copystat from typing import Sequence from filehash import FileHash from polib import MOFile, POFile, mofile from wren.change import Change def apply_cha...
2,386
845
from django.urls import path from . import views urlpatterns = [ path('language/', views.language), path('system/', views.system), path('ide/', views.ide), path('', views.nothing) ]
199
64
import streamlit as st import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set() from sklearn.datasets import load_boston from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.met...
5,908
2,246
# This file is part of the Reproducible and Reusable Data Analysis Workflow # Server (flowServ). # # Copyright (C) 2019-2021 NYU. # # flowServ is free software; you can redistribute it and/or modify it under the # terms of the MIT License; see LICENSE file for more details. """Unit tests for the worker factory.""" im...
4,585
1,375
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-06-11 05:18 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('announcements', '0001_initial'), ] operations = [ ...
640
216
"""Custom Sphinx extension to inject database documentation into a ReST document.""" from docutils import nodes from docutils.parsers.rst import Directive import sys import os import inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir)...
896
285
""" Created: 2001/08/05 Purpose: Turn PythonCard into a package __version__ = "$Revision: 1.1.1.1 $" __date__ = "$Date: 2001/08/06 19:53:11 $" """
149
82
import SpiceInterface import TestUtilities # create the test utility object test_utilities_obj = TestUtilities.TestUtilities() test_utilities_obj.netlist_generation('bandgap_opamp_test_op.sch', 'rundir') # create the spice interface spice_interface_obj = SpiceInterface.SpiceInterface(netlist_path="rundir/bandgap_opa...
764
302
# fa19-516-170 E.Cloudmesh.Common.2 from cloudmesh.common.dotdict import dotdict color = {"red": 255, "blue": 255, "green": 255, "alpha": 0} color = dotdict(color) print("A RGB color: ", color.red, color.blue, color.green, color.alpha)
238
104
#this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) #ok, the *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) #this just takes one argument def print_one(arg1):...
701
285
from enum import IntEnum import os import pygame import random import time import cmg import cmg.mathlib from cmg.application import * from cmg.graphics import * from cmg.input import * from study_tool.config import Config from study_tool.entities.entity import Entity class Menu(Entity): def __init__(self, option...
5,182
1,490
''' 对windows的注册表进行操作 _open_key: 返回key _read_key_value:读取key下一个value的值和类型 _save_key_value:以某种类型的方式,把值保存到某个key中 read_PATH_value:读取环境变量PATH的值 append_value_in_PATH:为PATH添加一个值 del_value_in_PATH:从PATH中删除一个值 check_key_value_exists(key,value_name):检查某个key小,value_name是否存在 create_value(key,value_name,value_type,value): 直接调用_sav...
3,677
1,542
import warnings from collections.abc import Iterable from collections import OrderedDict import torch import numpy as np from torch.utils.data import Dataset from deep_staple.utils.torch_utils import interpolate_sample, augmentNoise, spatial_augment, torch_manual_seeded, ensure_dense from deep_staple.utils.common_uti...
22,767
7,611
import sys import json import pandas as pd def main(): parquet_filename = sys.argv[1] json_filename = parquet_filename.replace(".parquet", ".json") print(json_filename) parquet_df = pd.read_parquet(parquet_filename) parquet_json = parquet_df.to_json() parquet_data = json.loads(parquet_json) ...
438
157
def main(): valid_passwords_by_range_policy = 0 valid_passwords_by_position_policy = 0 with open('input') as f: for line in f: policy_string, password = parse_line(line.strip()) policy = Policy.parse(policy_string) if policy.is_valid_by_range_policy(password): ...
1,720
516
#! /usr/bin/python3 # coding:utf-8 #pip install graphic-verification-code from captcha.image import ImageCaptcha import random,gvcode import numpy as np import tensorflow as tf number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n...
6,858
2,480
# PyEpoch Module Example File. import pyepoch # -- TODAY() -- # The today() function returns today's date. today = pyepoch.today() print("Today's date & time:") print(today) # -- TIMEZONE() -- # The timezone() function returns a date with a different timezone. # timezone() takes two(2) arguments: # - date = a da...
1,476
524
# -*- coding: UTF-8 -*- from base_plugin import SimpleCommandPlugin from plugins.core.player_manager_plugin import permissions, UserLevels from utility_functions import build_packet, move_ship_to_coords, extract_name from packets import ( Packets, WarpAliasType, WarpWorldType, WarpActionType, player...
9,615
2,764
# LTE using two pointers O(n**3) class Solution(object): def fourSumCount(self, A, B, C, D): # corner case: if len(A) == 0: return 0 A.sort() B.sort() C.sort() D.sort() count = 0 for i in range(len(A)): for j in range(len(B)...
1,735
562
from .handler import Handler from .pull_request_event import GetPullRequest, GetRepo format_message = ('We prefer that non-test backend code be written in Java or Kotlin, rather ' + 'than Groovy. The following files have been added and written in Groovy:\n\n' + '{}\n\n' + 'See our server-side ...
1,693
491
/home/runner/.cache/pip/pool/8f/3e/26/6ee86ef4171b7194b098a053f1e488bca8ba920931fd5f9fb809ad9a37
96
72
import json import os import boto3 topicArn = os.environ['TOPIC_ARN'] assumedRole = os.environ['ASSUMED_ROLE'] scpBoundary = os.environ['SCP_BOUNDARY_POLICY'] sns_client = boto3.client('sns') sts_client = boto3.client('sts') def lambda_handler(event, context): print(event) accountID = event['account'] ...
4,231
1,335
from requests import ConnectionError from ..exceptions import APIError from ..utils import check_status_code from .baseendpoint import BaseEndpoint class Navigation(BaseEndpoint): """ Navigation operations. """ def list_navigation(self, session=None): """ This Navigation Data for App...
1,200
295
import os from tqdm import tqdm from functools import reduce from typing import Dict, List, Callable, Tuple import numpy as np import pandas as pd from sklearn.preprocessing import OrdinalEncoder import torch from torch.utils.data import Dataset class FBPDataset(Dataset): def __init__( self, doc...
3,733
1,221
from django.urls import path from fl_user import views app_name = 'fl_user' urlpatterns = [ path('receive_data/',views.receive_data, name='receive_data'), path('doctorhome/', views.doctorhome, name='doctorhome'), path('fluhome/', views.fluhome, name='fluhome'), path('sluhome/', views.sluhome, name='s...
614
225
#!/usr/bin/env python # Copyright (c) 2018, 2019, 2020 Pure Storage, Inc. # # * Overview # # This short Nagios/Icinga plugin code shows how to build a simple plugin to monitor Pure Storage FlashArrays. # The Pure Storage Python REST Client is used to query the FlashArray. # # * Installation # # The script should be co...
4,350
1,298