text
string
size
int64
token_count
int64
import json from tests.factories import (NOWSubmissionFactory, MineFactory, NOWClientFactory, NOWApplicationIdentityFactory) class TestGetApplicationResource: """GET /now-submissions/applications/{application_guid}""" def test_get_now_submission_by_guid_success(self, test_client,...
12,510
3,683
from output.models.nist_data.list_pkg.non_positive_integer.schema_instance.nistschema_sv_iv_list_non_positive_integer_enumeration_2_xsd.nistschema_sv_iv_list_non_positive_integer_enumeration_2 import ( NistschemaSvIvListNonPositiveIntegerEnumeration2, NistschemaSvIvListNonPositiveIntegerEnumeration2Type, ) __a...
447
167
import time def compute(a, b): time.sleep(2) return a + b cache = {} def cache_compute(a, b): if (a, b) in cache.keys(): return cache[a, b] else: new = compute(a, b) cache[a, b] = new return new print(cache_compute(1, 2)) print(cache_compute(3, 5)) print(cache_com...
386
158
from datetime import datetime import jwt from src import ConfigManager secret = ConfigManager.get_config("DL_COOKIE_SECRET_KEY") secure = ConfigManager.get_config("APP_SECURE") def validate_user_jwt(token, username): token = jwt.decode(token, secret, "HS256") expire = token['exp'] if username != token[...
675
224
# Copyright 2020 by Roman Khuramshin <mr.linqu@gmail.com>. # All rights reserved. # This file is part of the Intsa Term Client - X2Go terminal client for Windows, # and is released under the "MIT License Agreement". Please see the LICENSE # file that should have been included as part of this package. import logging i...
2,403
777
import unittest import sys sys.path.append(".") sys.path.insert(0, '..\\') from calculator.simplecalculator import Calculator class TestSimpleCalc(unittest.TestCase): @classmethod def setUpClass(cls): print ("In setupclass() method") cls.cal = Calculator(4, 3) @classmethod def tearDow...
1,264
450
#!/usr/bin/python3 # -*- coding: utf-8 -*- import datetime import sys import subprocess import os from playsound import playsound # ****************************************************************** # Definitionen # ****************************************************************** filename = 'countdown.txt' audiof...
2,683
958
# -*- coding: utf-8 -*- ## Author: Aziz Khan ## License: GPL v3 ## Copyright © 2017 Aziz Khan <azez.khan__AT__gmail.com> from rest_framework import serializers from portal.models import Matrix, MatrixAnnotation from django.http import HttpRequest class MatrixAnnotationSerializer(serializers.HyperlinkedModelSerializ...
1,392
473
import torch import torch.nn as nn from generator_model import G1, G2 from helper_functions.Blocks import downBlock, Block3x3_leakRelu from helper_functions.ret_image import Interpolate, condAugmentation from helper_functions.initial_weights import weights_init from helper_functions.losses import KLloss, custom_loss fr...
5,043
2,044
import numpy as np def NDVI(nir,red): ''' # https://eos.com/make-an-analysis/ndvi/ Inputs: nxm numpy arrays NIR – reflection in the near-infrared spectrum RED – reflection in the red range of the spectrum ''' num = nir-red dom = nir+red ndvi = np.divide(num,dom) ndvi[...
382
142
from starlette.applications import Starlette from starlette.responses import JSONResponse from api import workflow import oyaml as yaml app = Starlette(debug=True) def generateWorkflow(steps, nested=False): generatedWorkflow = workflow.initWorkflow(); generatedWorkflowInputs = {}; generatedSteps = []; if (n...
3,805
1,060
class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ res = [] tmp = [] # tmp[0] always save the current windows max for i in xrange(len(nums)): if i < k-1: # first k-1 num...
840
247
# -*- coding: utf-8 -*- DESC = "tsf-2018-03-26" INFO = { "DeletePublicConfig": { "params": [ { "name": "ConfigId", "desc": "配置项ID" } ], "desc": "删除公共配置项" }, "DescribeSimpleGroups": { "params": [ { "name": "GroupIdList", "desc": "部署组ID列表,不填写时查询全量" ...
29,151
13,379
import onnx from pathlib import Path import subprocess import sys def run_lfs_install(): result = subprocess.run(['git', 'lfs', 'install'], cwd=cwd_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print("Git LFS install completed with return code=" + str(result.returncode)) def pull_lfs_file(file_name): re...
1,729
588
from .utils import Config
25
6
import glob import pandas as pd from tqdm import tqdm from classifier import config class Dataset: """Create dataset class""" def __init__(self): # Get all txt files self.paths = sorted(glob.glob("data/*/*/*.txt")) self.dataframe = None def load_data(self): dfs = [] # i...
1,374
390
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="urdu_digit", version="0.0.17", keywords=["urdu", "numeric", "digit", "converter"], description="English to Urdu numeric digit converter.", long_description=open('README.md').read(), project_urls={ 'Homepag...
642
228
import collections Interval = collections.namedtuple("Interval", "start, end") class AugmentedTree: """ An augmented tree for querying intervals. The nodes are ordered by the start interval. The high attribute is the maximum end interval of the node and any of its children. This tree could become im...
1,682
445
import numpy as np import matplotlib.pyplot as plt def show_anomalies(patch_array): num_figs = len(patch_array) fig = plt.figure(figsize=(num_figs * 30, 30)) plt.tight_layout() for i in range(len(patch_array)): plt.subplot(num_figs, 1, i + 1) plt.imshow(patch_array[i]) plt.axis...
4,874
1,919
# ! /usr/bin/python # -*- coding: utf-8 -*- # ============================================================================= # Copyright 2020 NVIDIA. 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 obta...
18,223
4,904
import logging import signal from PySide2 import QtCore import vstreamer_utils class VideoStreamerServerApplication(QtCore.QCoreApplication): def __init__(self, argv): super().__init__(argv) self.setApplicationName("video_streamer_server") self.logger = vstreamer_utils.make_logger() ...
420
121
#Define environment variable FABRIC_UTILS_PATH and provide path to fabric_utils before running import time import os from contrail_fixtures import * import testtools from tcutils.commands import * from fabric.context_managers import settings from tcutils.wrappers import preposttest_wrapper from tcutils.util import * fr...
2,345
663
from server.services.wiki.pages.templates import OverviewPageTemplates from server.services.wiki.pages.page_service import PageService from server.services.wiki.mediawiki_service import MediaWikiService from server.services.wiki.wiki_text_service import WikiTextService from server.services.wiki.wiki_table_service impor...
15,382
3,953
# Generated by Django 4.0 on 2022-03-06 02:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('App', '0010_remove_user_percentage_preferences_user_preferences'), ] operations = [ migrations.AddField( model_name='playlist', ...
414
137
import imp import os.path from app import db from migrate.versioning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO def db_create(): # This creates the new database. db.create_all() # If no repo existed, the creation will prepare for the first migration....
2,779
982
from xmuda.models.SSC2d_proj3d2d import SSC2dProj3d2d from xmuda.data.NYU.nyu_dm import NYUDataModule from xmuda.data.semantic_kitti.kitti_dm import KittiDataModule from xmuda.common.utils.sscMetrics import SSCMetrics from xmuda.data.NYU.params import class_relation_freqs as NYU_class_relation_freqs, class_freq_1_4 as ...
5,253
2,246
# Author: penhe@microsoft.com # Date: 05/30/2019 # """ Data parallel module """ from collections import OrderedDict import numpy as np import torch from torch.cuda.comm import broadcast_coalesced from torch.cuda.comm import reduce_add_coalesced from torch.nn.parallel import parallel_apply from torch.nn.parallel.scatte...
9,695
3,410
from rest_framework import serializers from .models import User from .models import Product from django.contrib.auth import get_user_model class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password', 'balance') class ProductSerializer(serial...
1,190
350
''' Author: geekli Date: 2020-12-27 10:38:46 LastEditTime: 2020-12-27 10:40:44 LastEditors: your name Description: FilePath: \pythonQT\ch02\multiSinal_button.py ''' import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton class Demo(QWidget): def __init__(self): super(Demo, self).__init_...
811
302
from __main__ import * hm_df = functs_df[~((functs_df.head_type == 'prep') & (functs_df.suffix))].copy()
105
49
from autodc.components.hpo_optimizer.smac_optimizer import SMACOptimizer from autodc.components.hpo_optimizer.mfse_optimizer import MfseOptimizer from autodc.components.hpo_optimizer.bohb_optimizer import BohbOptimizer from autodc.components.hpo_optimizer.tpe_optimizer import TPEOptimizer def build_hpo_optimizer(eval...
1,123
373
# -*- coding: utf-8 -*- import sys, select, termios,tty import os def getKey(): fd = sys.stdin.fileno() old = termios.tcgetattr(fd) new = termios.tcgetattr(fd) new[3] &= ~termios.ICANON new[3] &= ~termios.ECHO try: termios.tcsetattr(fd, termios.TCSANOW, new) ch = sys.stdin.read(1) finally: ...
835
334
#!/usr/bin/python3 # Copyright (c) 2019 Bart Massey # [This program is licensed under the "MIT License"] # Please see the file LICENSE in the source # distribution of this software for license terms. # Find maximum and minimum sample in an audio file. import sys import wave as wav # Get the signal file. wavfile = wa...
1,516
470
''' A very simple test application to exercise a round trip of messages through the thywill system. This also illustrates the bare, bare minimum implementation of the 'thywill_interface.py' module - all it does is echo back incoming messages to the client who sent them. '''
275
65
from tests import app @app.route("/error-assert-variable") def error_assert_variable(): return ''
104
32
import typing from jk_cachefunccalls import cacheCalls from jk_cmdoutputparsinghelper import ValueParser_ByteWithUnit from .parsing_utils import * from .invoke_utils import run #import jk_json _parserColonKVP = ParseAtFirstDelimiter(delimiter=":", valueCanBeWrappedInDoubleQuotes=False, keysReplaceSpacesWithUnders...
6,979
3,360
''' This module provides the Telegram. ''' class Telegram: ''' Telegram encapsulates the pieces and parts of a telegram. ''' def __init__(self, sender, recipient, message): ''' Constructs a Telegram instance. :param sender: The sender of the telegram :param recipi...
900
240
from testing_framework.report import report from typing import Tuple import html def test_report(): result = report(("test_report", "second line")) expected_result = f""" <!DOCTYPE html> <html> <body> <div>test_report</div><div>second line</div> </body> </html> """ assert html.escape(expected_resul...
345
112
while(True): inp = [int(x) for x in input().split()] if inp[0] == 0 and inp[1] == 0: break print(inp[0]//inp[1], inp[0]%inp[1], "/", inp[1])
160
80
#!/usr/bin/env python import sys import time import rospy import subprocess import actionlib from std_msgs.msg import Float32 from sensor_msgs.msg import Joy from geometry_msgs.msg import Twist, PoseWithCovarianceStamped from actionlib_msgs.msg import GoalStatus, GoalStatusArray from move_base_msgs.msg import MoveBase...
4,480
1,551
from backend.domain.contracts import NewClient, NewOrder, NewOrderItem from .new_product import NewProduct
108
30
from uuid import UUID import json from ..mappings import * def add_doc_audit_entry(session, doc_id, status, data): """"Add an audit entry, requires that a commit be run on the session afterwards """ if not isinstance(doc_id, UUID): raise ValueError("Expecting UUID") if not isinstanc...
508
163
# versions of libraries used import sys import tweepy import numpy as np import pymongo import emoji import nltk.tokenize import requests print("Python version:{}".format(sys.version)) print("tweepy version:{}".format(tweepy.__version__)) print("pymongo version:{}".format(pymongo.__version__)) print("emoji...
523
180
def count_ones(num): binary = str(bin(num))[2:] print(binary) return binary count_ones(20)
94
40
#!/usr/bin/python # -*- coding: utf-8 -*- import dbm from sklearn.datasets import load_iris from classifer.base import BaseClassifier from classifer.decision_tree import DecisionTreeClassifier import numpy as np class AbsAdaBoostClassifier(BaseClassifier): def __init__(self, num_rounds): super(AbsAdaB...
6,968
2,317
import numpy as np from bioinfo.assembly.errors import InvalidPair from bioinfo.molecules.sequence import Sequence class LargestOverlapFinder: def __init__(self): pass # Get indices a, b, c, d of longest substrings first, # such that substring == first[a: b] == second[c: d]. # Also returns le...
4,942
1,488
from __future__ import annotations from . import _base class Operations(_base.Model): swagger_types: dict[str, str] = {'operations': 'list[Operation]'} attribute_map: dict[str, str] = {'operations': 'operations'} def __init__(self, operations=None): self._operations = None self.discrimi...
857
240
import pytest @pytest.fixture def fixture1(): return 1 @pytest.fixture def fixture2(fixture1): return fixture1 + 1 def test_with_fixture(fixture2): assert fixture2 == 2
187
77
def remoteImagesList(images): response = [] aliasesProcessed = [] aliases = [alias[20:] for alias in images['metadata']] for alias in aliases: strippedAlias = alias.replace('/default','') if strippedAlias not in aliasesProcessed: aliasesDetails = alias.split('/') ...
827
235
from searcher import CLIPSearcher from utils import get_args if __name__ == "__main__": args = get_args() cs = CLIPSearcher(device=args.device, store_path=args.store_path) cs.load_dir(args.dir, save_every=args.save_every, recursive=args.recursive, load_new=(not args.dont_load_new)) cs.search(texts=args...
390
140
"""For entities that have a property template.""" from gemd.entity.link_by_uid import LinkByUID from gemd.entity.setters import validate_list from gemd.entity.template.base_template import BaseTemplate from gemd.entity.template.property_template import PropertyTemplate from gemd.entity.bounds.base_bounds import BaseBou...
2,049
475
from app.models import Subscriber from flask_wtf import FlaskForm from wtforms import TextAreaField, StringField, IntegerField, EmailField from wtforms.validators import InputRequired, ValidationError from flask import flash class BlogForm(FlaskForm): title = StringField('Title', validators=[InputRequired()]) ...
1,547
409
import toml def read_config(_config_path=None): if _config_path is None: _config_path = './config.toml' # script_dir = os.path.dirname(__file__) # file_path = os.path.join(script_dir, config_path) _config = toml.load(_config_path) return _config
278
100
""" Retrieve GoDaddy DNS settings via their developer API See also: https://developer.godaddy.com/doc/endpoint/domains#/ """ import os import time from pprint import pprint from typing import List import requests import credential_loaders BASE_URL = "https://api.godaddy.com" # You can easily replace these with...
3,214
1,180
import cv2 import numpy as np class preprocessing: def process_image(self,image, rescale, recolor): if rescale['req']: image= self.rescale(image,rescale['width'], rescale['height']) if recolor['req']: image = self.rgb2gray(image) return image def rescale (self,image,wid...
1,184
443
# -*- coding: utf-8 -*- from .tables.pronto_soccorsi import table class ProntoSoccorso: _table = table def __init__(self, ps_dict): # entity dict self.e_d = ps_dict def to_dict(self): return self.e_d
214
96
# -*- coding: utf-8 -*- # @Author : Administrator # @DateTime : 2021/10/17 20:40 # @FileName : __init__.py # @SoftWare : PyCharm
132
65
import requests from datetime import date, timedelta today = date.today() yesterday = today - timedelta(days=1) country = "Russia" endpoint = f"https://api.covid19api.com/country/{country}/status/confirmed" params = {"from": str(yesterday), "to": str(today)} response = requests.get(endpoint, params=params).json() tot...
497
170
# import models from torchvision from torchvision.models import * # import models from efficientnet from .efficientnet import b0, b1, b2, b3, b4, b5, b6, b7
157
54
#This file plots the results from the MPI timing runs import sys import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import matplotlib.markers as mkr plt_style='ggplot' plt.rcParams['font.size'] = 11 plt.rcParams['font.family'] = 'serif' plt.rcParams['axes.labelsize'] = 11 plt.rc...
2,834
1,263
from typing import Iterator from entitykb import Span, interfaces, Doc class KeepExactNameOnly(interfaces.IFilterer): """ Only keep spans that are an exact match. """ def is_keep(self, span: Span): return span.name == span.text class RemoveInexactSynonyms(interfaces.IFilterer): """ Remove if n...
1,809
573
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # import pytest from click.testing import CliRunner from octavia_cli import entrypoint def test_octavia(): runner = CliRunner() result = runner.invoke(entrypoint.octavia) assert result.exit_code == 0 assert result.output.startswith("Usage: oc...
716
231
import json import logging import random from datetime import datetime from typing import Optional from paho.mqtt.client import MQTTMessage from enocean.protocol.constants import PACKET from enocean.protocol.packet import RadioPacket from src.command.switch_command import SwitchCommand from src.common.json_attributes...
5,261
1,554
import numpy as np import neuroml import neuroml.arraymorph as am class Benchmark: def __init__(self, num_segments): self.num_segments = num_segments def set_up(self): num_segments = int(1e4) # Per cell num_vertices = num_segments + 1 x = np.linspace(0, 10, num_vertices) ...
1,960
703
#!/usr/bin/env python # Extracts examples of given strings with context in a TAB-separated # field format from given text documents. from __future__ import with_statement import sys import re from os import path options = None def argparser(): import argparse ap=argparse.ArgumentParser(description="Extract...
5,840
1,714
#======================================================================= # verilog_bug_test.py #======================================================================= import pytest from pymtl import * from exceptions import VerilatorCompileError pytestmark = requires_verilator #-------------------------------...
2,813
813
import os # Get the list of all files with a specific extension # In this example, we will take a path of a directory and try to # list all the files, with a specific extension .py here, # in the directory and its sub-directories recursively. path = r'C:\Users\10900225\Documents\Witch\BTX\Workspaces\Library' for r...
436
148
#-*- coding: utf-8-*- from odoo import api, fields, models, _ # Wizard class class CreateAppointmentWizard(models.TransientModel): _name = "create.appointment.wizard" _description = "Create Appointment Wizard" date_appointment = fields.Date(string='Date', required=False) patient_id = fields.Many2one('hospital.pa...
1,509
616
#!/bin/env python3 import re from typing import List import numpy as np import matplotlib.pyplot as plt filtered_users = ["join-backup", "join-slave", "ucs-sso"] filtered_groups = ["computers", "dc backup hosts", "dc slave hosts"] class LDAPUser: name: str def __init__(self, name): self.name = name ...
4,731
1,531
from sqlalchemy import create_engine, Column, Integer, BigInteger, String, Boolean, MetaData, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy.types import DateTime, Date, Interval from sqlalchemy.pool import NullPool from .conf imp...
107,098
34,955
import Image from ImageColor import getrgb from reportlab.pdfgen import canvas from reportlab.lib.units import mm from reportlab.lib.pagesizes import A4 import uuid BEAD_RADIUS = 1.75*mm BEAD_THICKNESS = 1*mm BOARD_SPACING = 4.85*mm BOARD_BORDER = 4*mm #A4 60x43 = 2580 #A3 86x60 = 5160 #A2 86x120 = 10,320 #MARQUEE A4...
3,154
1,314
""" ----------------------------------------------------------------------------------------------------------- Package: AequilibraE Name: Report dialog Purpose: Dialog for showing the report from algorithm runs Original Author: Pedro Camargo (c@margo.co) Contributors: Last edited by: Pedro Camarg...
1,836
568
import os import sys sys.path.append('.') sys.path.append('..') import warnings warnings.filterwarnings("ignore") from datetime import datetime import matplotlib matplotlib.use("TkAgg") import matplotlib.lines as lines import matplotlib.image as mpimg from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg f...
21,580
6,654
#!/usr/bin/env python # -*- coding: utf-8 -*- lengths = "187,254,0,81,169,219,1,190,19,102,255,56,46,32,2,216" suffix = [17, 31, 73, 47, 23] num_rounds = 64 def puzzle1(): knot = range(256) skip_size = 0 idx1 = 0 for l in [int(a) for a in lengths.split(",")]: idx2 = idx1 + l k = [] ...
1,780
743
# -*- coding: utf-8 -*- """ @author:XuMing(xuming624@qq.com) @description: """ import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.layers as layers # 超参 num_words = 2000 num_tags = 12 num_departments = 4 # 输入 body_input = keras.Input(shape=(None,), name='body') title_input = keras.Input(...
1,914
786
expected_output = { 'vrf': {'default': {'address_family': {'ipv4': {'instance': {'1': {'areas': {'0.0.0.0': {'area_id': '0.0.0.0', ...
3,937
852
#!/usr/bin/env python # -*- coding:utf-8 -*- import json import platform import time from getdevinfo import getdevinfo import psutil from rain.common import rain_log from rain.common import utils from rain.common.utils import async_call logger = rain_log.logg(__name__) class SystemInfo(object): """system info...
4,566
1,397
"""Model Definations for trpo.""" import gym import numpy as np import torch import time import scipy.optimize import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from distributions import DiagonalGaussian from helpers import get_flat_params, set_flat_params, get_flat_grads #from ...
7,517
2,535
from django.contrib import admin from sample_1.models import * # Register your models here. admin.site.register(Author) admin.site.register(Book)
148
44
class DynamicalSystem: def __init__(self): """ Base virtual dynamical systems class. Any dynamics as an input to the system must inherit from this class. TODO(terry-suh): Consider using ABC? """ self.h = 0 self.dim_x = 0 self.dim_u = 0 def dynam...
2,217
680
from django.db import models import uuid # Create your models here. class Uuid(models.Model): uuids = models.CharField(max_length=225) created = models.DateTimeField(auto_now_add=True)
196
66
import os from shutil import move, rmtree from itertools import chain from genres import genre_of, DOWNLOAD_DIR, DST_DIRS, VIDEO_EXTENSIONS print(genre_of) print(f'moving files from {DOWNLOAD_DIR}: \n' # f'with keywords: {COMEDY_TAGS} \n' # f'with extensions: {VIDEO_EXTENSIONS} \n' ) files_moved =...
1,660
577
"""Handlers for project-related APIs.""" from __future__ import annotations from typing import Dict, Tuple from flask import request from flask_accept import accept_fallback from keeper.auth import token_auth from keeper.logutils import log_route from keeper.models import Organization, Product, db from keeper.servi...
3,572
1,089
# -*- coding: utf-8 -*- """ Allow server-side KaTeX rendering for Markdown through node.js The markdown extension adds regex patterns for `$` and `$$` in the source `.md` file, and applies KaTeX to the intermediate text with a `python-bond` call to node.js requires * node * npm * katex (npm install katex) * python-b...
2,237
716
# числата от N до 1 в обратен ред # Да се напише програма, която отпечатва числата от n до 1 в обратен ред (стъпка -1). # Например, ако n = 100, то резултатът ще е: 100, 99, 98, …, 3, 2, 1. n = int(input()) for i in range(n, 0, -1): print(i)
247
126
"""simpleclassroom URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') C...
1,490
513
#!usr/bin/env python import sys, logging import re import mechanize logger = logging.getLogger('mechanize') logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.DEBUG) br = mechanize.Browser() br.set_debug_http(True) br.set_debug_responses(True) br.set_debug_redirects(True) br.open("https://...
714
256
# \file DataWriter.py # \brief Class to read data # # \author Michael Ebner (michael.ebner.14@ucl.ac.uk) # \date June 2018 import os import sys import numpy as np import nibabel as nib import SimpleITK as sitk import pysitk.python_helper as ph import pysitk.simple_itk_helper as sitkh from simplereg.definitions i...
4,939
1,459
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Softwa...
3,881
1,253
from django.contrib.auth import get_user_model from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase, APIClient from rest_framework.views import status from voluntario.models import Voluntario class BaseViewTest(APITestCase): de...
2,952
1,003
# -*- coding:utf-8 -*- """ @Time:2022/05/05 12:57 @Author:KI @File:main.py @Motto:Hungry And Humble """ from data_process import clients_wind from server import Scaffold def main(): K, C, E, B, r = 10, 0.5, 30, 50, 10 input_dim = 28 lr = 0.08 options = {'K': K, 'C': C, 'E': E, 'B': B, 'r': r, 'clients...
508
240
#!/usr/bin/env python import pycassa sys = pycassa.SystemManager("cassandra.service.consul:9160") if "reddit" not in sys.list_keyspaces(): print "creating keyspace 'reddit'" sys.create_keyspace("reddit", "SimpleStrategy", {"replication_factor": "3"}) print "done" if "permacache" not in sys.get_keyspace_c...
464
162
## 1. Data Structures ## import pandas as pd fandango = pd.read_csv('fandango_score_comparison.csv') print(fandango.head(2)) ## 2. Integer Indexes ## fandango = pd.read_csv('fandango_score_comparison.csv') series_film = fandango['FILM'] series_rt = fandango['RottenTomatoes'] print(series_film[:5]) print(series_rt[:5...
1,472
549
n=int(input()) link=[[100]*n for i in range(n)] for i in range(n): x=input() for j in range(n): if x[j]=='Y': link[i][j]=1 for i in range(n): for j in range(n): for k in range(n): if link[j][i]+link[i][k]<link[j][k]: link[j][k]=link[j][i]+link[i][k] link[k][j]=link[j][k] ans=0 for ...
425
208
import pytest import os,sys import warnings try: from exceptions import Exception, TypeError, ImportError except: pass from runipy.notebook_runner import NotebookRunner wrapped_stdin = sys.stdin sys.stdin = sys.__stdin__ sys.stdin = wrapped_stdin try: from Queue import Empty except: from queue import ...
4,894
1,456
items = {"a": True, "b": False} b = [v for k, v in items.items() if v == True] print(b)
90
40
#! /usr/bin/env python # DESCRIPTION = "ztflc: Force photometry lc fitter" LONG_DESCRIPTION = """ Force photometry lc fitter""" DISTNAME = "ztflc" AUTHOR = "Mickael Rigault" MAINTAINER = "Mickael Rigault" MAINTAINER_EMAIL = "m.rigault@ipnl.in2p3.fr" URL = "https://github.com/MickaelRigault/ztflc/" LICENSE = "BSD (3-c...
2,258
734
#!/usr/bin/python __author__ = 'thovo' import sys def ibm1(): #Check for arguments args_length = len(sys.argv) print "The number of arguments: "+str(args_length) i = 0 while i < args_length: print "The argument number " + str(i) + " is " + str(sys.argv[i]) i += 1 ibm1()
311
115
import random from .utils import filler from .array import RawWordFindArray, WordArray class RawWordFind(RawWordFindArray): def __init__(self, size, wordbank): super().__init__(size, wordbank) for word in wordbank.words: if not self.valid_word_length(word): raise ValueE...
1,927
590
# ****************************************************************************** # Copyright 2017-2018 Intel Corporation # # 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.apa...
2,969
861