text
string
size
int64
token_count
int64
#!python """ Copyright (C) 2004-2017 Pivotal Software, Inc. All rights reserved. This program and the accompanying materials are made available under the terms of the 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 Li...
13,767
4,023
""" Unit tests for kinematics calculations. """ from __future__ import print_function, division import unittest import numpy as np from kinematic_math import math_toolbox class TruismsTestCase(unittest.TestCase): def setUp(self): print("In test '{}'...".format(self._testMethodName)) def test_false...
7,964
3,063
# coding: utf-8 import pprint import six from enum import Enum class RefundCreate: swagger_types = { 'amount': 'float', 'completion': 'int', 'external_id': 'str', 'merchant_reference': 'str', 'reductions': 'list[LineItemReductionCreate]', 'transaction': 'int'...
7,096
1,955
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 required by ...
4,025
1,234
from itertools import islice from django.core import mail from django.contrib.auth import get_user_model from django.contrib.gis.geos import Polygon, Point from djmoney.money import Money from rest_framework.test import APITestCase from api.models import Contact, Pricing, Product, PricingGeometry, Order, OrderItem, Ord...
13,270
4,387
from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib import auth @login_required def index(request): username = request.session.get('username') ctx = {"username": username} # return render(request, '...
1,080
296
# searchtweet.py import json from requests_oauthlib import OAuth1Session from . import tweetdata # const TWITTER_API_URL_PREFIX = "https://api.twitter.com/1.1/" # SearchTweet class class SearchTweet: def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret): self._twitter_oa...
2,442
711
# 27 Body mass Index #Asking for height and weight of user h = float(input("Enter the height = ")) m = float(input("Enter the mass = ")) print("Body Mass Index = ",m / (h * h))
183
67
# Scrapy settings for xueshu project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware....
4,221
2,005
""" GraphQL module used to create `get` and/or `aggregate` GraphQL requests from Weaviate. """ __all__ = ['Query'] from .query import Query
143
48
import core.utils as cu import core.manager as cm import core.cmd_line as cc def parse_args(ctx): class Args: def __init__(self): args = ctx['args'] self.realm = args[0] ctx['args'] = args[1:] self.config, self.pkgs = cc.parse_pkgs(ctx) return Args() ...
1,329
480
from typing import List class Solution: def findWords(self, words: List[str]) -> List[str]: set1 = set('qwertyuiop') set2 = set('asdfghjkl') set3 = set('zxcvbnm') res = [] for i in words: x = i.lower() setx = set(x) if setx<=set1 or setx<=...
476
164
import pymongo from pymongo.database import Database __author__ = 'pryormic' if __name__ == '__main__': mongoClient = pymongo.MongoClient("localhost", 27017) for item in mongoClient.db.matcher.find(): try: del item['profile_picture'] except KeyError: pass prin...
340
106
"" from .utils import (plot_lr_loss, plot_metrics)
52
21
from toolz import curry @curry def path(keys, dict): """Retrieve the value at a given path""" if not keys: raise ValueError("Expected at least one key, got {0}".format(keys)) current_value = dict for key in keys: current_value = current_value[key] return current_value
307
96
from data_refinery_common.utils import get_env_variable LOCAL_ROOT_DIR = get_env_variable("LOCAL_ROOT_DIR", "/home/user/data_store") # We store what salmon ouptuts as its version, therefore for # comparisions or defaults we shouldn't just store the version string, # we need something with the pattern: 'salmon X.X.X' C...
547
193
import datetime import os import string import time from bson.json_util import dumps from json import loads from pymongo import MongoClient from utils import SongRequest, UserPayload TEMP_MOVIE_DETAILS = """ Title: Maison Ikkoku | Synopsis: Maison Ikkoku is a bitter-sweet romantic comedy involving a group of madcap ...
4,680
1,354
import numpy as np import tensorflow as tf import gym import logz import scipy.signal import os import time from multiprocessing import Process import shutil class MyArgument(object): def __init__(self, exp_name='vpg', env_name='CartPole-v1', n_iter=100, ...
20,200
5,885
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 4 19:05:22 2020 @author: ggruszczynski """ import numpy as np from numpy import linalg as LA def dot_product(u,v): return u @ v def calc_condition_number_naive(f, u, v, delta): cond_number = LA.norm(f(u+delta, v) - f(u,v)) / LA.norm(f(u,...
664
313
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2018-07-28 23:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tournament', '0181_auto_20180610_2123'), ] operations = [ migrations.AlterField( model_name='modrequest...
891
320
from typing import Optional, Tuple from paramak import RotateMixedShape class RotateSplineShape(RotateMixedShape): """Rotates a 3d CadQuery solid from points connected with splines. Args: rotation_angle: The rotation_angle to use when revolving the solid. Defaults to 360.0. stp_...
1,000
326
/** * Description: not PyPy3, solves CF Factorisation Collaboration * Source: own * Verification: * https://codeforces.com/contest/1091/problem/G * https://open.kattis.com/problems/catalansquare */ from math import * import sys, random def nextInt(): return int(input()) def nextStrs(): return input().split() ...
1,212
558
import unittest import numpy as np from src.commons import Box from src.observer.base_observer import BaseObserver from src.observer.noise_observer import NoiseObserver from src.observer.shift_observer import ShiftObserver class ObserverTests(unittest.TestCase): """Tests for the all Observer.""" #@unittest.ski...
1,908
720
import cv2 import numpy as np import os import json import time from datetime import datetime def image_string(image): image_encode=cv2.imencode('.jpg',image)[1] imagelist=image_encode.tolist() image_string=json.dumps(imagelist) return image_string def string_image(imagestring): image_list=json.loa...
3,352
1,280
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.15.2) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x11\xc6\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x01\xc0\x...
95,661
89,424
from stan import StanData, StanDict from pprint import pprint if __name__ == '__main__': data_1 = StanData() data_1[1499763761] = StanDict(metric_1=1) # TODO: Double indexing if adding as StanDict data_1[1499763761]['metric_2'] = 2 data_1[1499763761]['metric_3'] = 3 data_1.append(1499763762, Stan...
1,544
625
import tensorflow as tf __all__ = [ 'create_attention_images', ] """Reference: https://github.com/tensorflow/nmt/blob/master/nmt/attention_model.py""" def create_attention_images(final_context_state): try: attention_images = final_context_state.alignment_history.stack() except AttributeError: ...
701
239
from datetime import datetime from decimal import Decimal from typing import Optional import numpy as np from cryptofeed_werks.controllers import NonSequentialIntegerMixin from cryptofeed_werks.models import Symbol from .api import get_bitfinex_api_timestamp, get_trades class BitfinexMixin(NonSequentialIntegerMixi...
2,604
813
from reclaimer.constants import * from reclaimer.util import fourcc_to_int # maps tag class four character codes(fccs) in # their string encoding to their int encoding. stubbs_tag_class_fcc_to_be_int = {} stubbs_tag_class_fcc_to_le_int = {} # maps tag class four character codes(fccs) in # their int encoding to...
893
385
from flask import Flask,Blueprint def create_app(config_name): app=Flask(__name__) from app.api.v2 import blue as v2 app.register_blueprint(v2) return app
185
69
#An iterator is an object that contains a countable number of values. #An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. #Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next...
3,276
1,043
# Type annotations are pretty awesome: # https://medium.com/analytics-vidhya/type-annotations-in-python-3-8-3b401384403d from typing import Dict import fitz # pip install pymupdf def get_bookmarks(filepath: str) -> Dict[int, str]: # WARNING! One page can have multiple bookmarks! bookmarks = {} with fitz...
530
189
import random import time from mcnf_dynamic import * from instance_mcnf import generate_instance, mutate_instance from k_shortest_path import k_shortest_path_all_destination from launch_dataset_dynamic import analyse_results_list def update_graph_capacity(graph, path, demand, reverse_graph=False): # deecrease th...
8,346
2,865
""" This is adapt from evennia/evennia/commands/default/player.py. The licence of Evennia can be found in evennia/LICENSE.txt. """ import time from django.conf import settings from evennia.server.sessionhandler import SESSIONS from evennia.commands.command import Command from evennia.utils import utils, create, search...
2,058
632
"""Tools to aid in parallelizing a function call. Default method is MPI, if available. Fallback is concurrent.futures. If all else fails, final fallback is serial. Author: Seth Axen Email: seth.axen@gmail.com """ import os import sys import logging from copy import copy import multiprocessing try: from itertools ...
20,002
5,316
#FLM: AT URL file import urllib f = urllib.urlopen('http://www.andrestorresi.com.ar/test.txt') readdata = f.read() readdata2 = unicode( readdata, "iso-8859-1" ) f.close() print readdata2
187
82
#! /usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2019/3/10 5:21 PM # @Author : xiaoliji # @Email : yutian9527@gmail.com """ 1~n整数中1出现的次数。 >>> countDigitOne(12) 5 """ def countDigitOne(n: int) -> int: counter, i = 0, 1 while i <= n: divider = i * 10 counter += (n // d...
405
199
import os import random import argparse import logging import json import time import multiprocessing as mp import scipy.sparse as ssp from tqdm import tqdm import networkx as nx import torch import numpy as np import dgl #os.environ["CUDA_VISIBLE_DEVICES"]="1" def process_files(files, saved_relation2id, add_traspose...
22,957
8,518
import math class LinearDecay(): def __init__(self, opt, optimizer, iter_num): self.optimizer = optimizer self.init = opt.lr self.tot = iter_num * opt.epoch self.st = iter_num * opt.decay_start_epoch if(self.st < 0): self.st = self.tot self.cnt = 0 self.state_dict = self.optimizer.state_dict() def ste...
652
286
import numpy as np from numba import jit import random import time import argparse ############################################## ######### PARÁMETROS FÍSICOS ################ ############################################## Q = 1.3 NUM_PARTICLES = 100000 #Número de partículas NUM_PARTICLES_BULGE = int(0.14 ...
23,698
9,683
#!/usr/bin/env python3 """ Author : treevooor <treevooor@localhost> Date : 2021-11-09 Purpose: Apples and bananas """ import argparse import os # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Apple...
1,526
442
''' Author: Shuailin Chen Created Date: 2021-07-06 Last Modified: 2021-08-18 content: siamese HR18 with background splitting ''' _base_ = [ './siam_hr18_512x512_40k_s2looking.py' ] model = dict( decode_head=dict( post_process=dict( type='SetConstValue', position=0, ...
348
145
adict = {'name': 'bob', 'age': 23} print('bob' in adict) # bob是字典的key么? print('name' in adict) # True print(len(adict)) # 2 for key in adict: print('%s: %s' % (key, adict[key])) print('%(name)s: %(age)s' % adict)
221
110
"""Plot a snapshot of the particle distribution""" # -------------------------------- # Bjørn Ådlandsvik <bjorn@ho.no> # Institute of Marine Research # November 2020 # -------------------------------- import numpy as np import matplotlib.pyplot as plt from netCDF4 import Dataset from postladim import ParticleFile #...
1,774
795
class Weapon: '''Create a weapon Init Parameters: damage [int] How much damage this weapon deals rate [int] How much ticks it takes for this weapon to prepare for next shoot range [int] Range of the weapon ignore_armor [bool] If this weapon ignores armor (armor value ...
1,447
422
#!/usr/bin/env python # little mock app to handle ouput file parameters # i.e. to create them import os import shutil import sys from CTDopts.CTDopts import CTDModel, _InFile, _OutFile # from argparse import ArgumentParser # parser = ArgumentParser(prog="mock.py", description="MOCK", add_help=True) # parser.add_arg...
1,945
654
# -*- coding: utf-8 -*- from __future__ import unicode_literals import collections from cubes_lite.query import Request, Response __all__ = ( 'ListSQLRequest', 'ListSQLResponse', 'OneRowSQLRequest', 'OneRowSQLResponse', ) class ListSQLResponse(Response): def __init__(self, *args, **kwargs): ...
1,323
377
import bpy import sys dir = "C:/Users/foggy/Appdata/roaming/python37/site-packages" sys.path.append(dir) from flask import Flask, request, render_template from werkzeug.utils import secure_filename import eventlet from eventlet import wsgi app = Flask(__name__) @app.route('/') def hello_world(): return render_te...
1,166
427
import os import unittest import warnings from src import ROOT_PATH from src.dockerstats import DockerStats class ParserTest(unittest.TestCase): def setUp(self): path = os.path.join(ROOT_PATH, "tests", "resources", "data.csv") self.ds = DockerStats(path) def test_dataframe_creation(self): ...
2,292
862
#!/usr/bin/env python3 # 26.04.21 # Assignment lab 06 # Master Class: Machine Learning (5MI2018) # Faculty of Economic Science # University of Neuchatel (Switzerland) # Lab 6, see ML21_Exercise_6.pdf for more information # https://github.com/RomainClaret/msc.ml.labs # Authors: # - Romain Claret @RomainClaret # - Sy...
3,889
1,555
import numpy as np import pickle import sys import pandas as pd import seaborn as sns import matplotlib.pyplot as plt plt.switch_backend('agg') import argparse import os from tqdm import tqdm import math import helper map_dict = { 'avg': "Average", 'min': "Minimum", 'max': "Maximum", 'last': "Last", "spanish": "...
17,294
6,951
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 26 10:28:54 2021 @author: woojae-macbook13 """ from pandas import* import pandas as pd import numpy as np # path = ".\\" filename = "pr1.xlsx" # dataset = pd.read_excel(path+filename) dataset = pd.read_excel(filename) order = "고객" itemcode = "it...
3,061
1,648
# Generated by Django 2.0.3 on 2018-04-16 10:45 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('admin', '0004_auto_20180416_1037'), ] operations = [ migrations.RemoveField( model_name='organizationrole', name='organizati...
879
259
def ngram(n, terms): """An iterator for iterating n-gram terms from a text, for example: >>> list(ngram(2, ['Today', 'is', 'my', 'day'])) [['Today', 'is'], ['is', 'my'], ['my', 'day']] >>> list(ngram(3, ['Today', 'is', 'my', 'day'])) [['Today', 'is', 'my'], ['is', 'my', 'day']] ...
468
193
from __future__ import division from __future__ import absolute_import import os import sys import shutil import time import random import argparse import torch import torch.backends.cudnn as cudnn import torchvision.datasets as dset import torchvision.transforms as transforms import matplotlib.pyplot as plt from torc...
52,494
16,737
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import itertools import re from collections import namedtuple from .base_service import Servi...
6,753
1,917
__node_daemon__ = 'lbrycrdd' __node_cli__ = 'lbrycrd-cli' __node_bin__ = '' __node_url__ = ( 'https://github.com/lbryio/lbrycrd/releases/download/v0.17.2.1/lbrycrd-linux.zip' # 'https://github.com/lbryio/lbrycrd/releases/download/v0.17.3.1/lbrycrd-linux-1731.zip' ) __spvserver__ = 'lbry.wallet.server.coin.LBCRe...
493
219
#!/usr/bin/env python # -*- coding: utf-8 -*- """logdweb admin views.""" try: import simplejson as json except ImportError: import json import time from django.core.urlresolvers import reverse from django.http import HttpResponse, Http404, HttpResponseRedirect from django_jinja2 import render_to_response, ...
6,797
2,150
import pytest from iocage.lib.ioc_fetch import IOCFetch require_root = pytest.mark.require_root require_zpool = pytest.mark.require_zpool @require_root @require_zpool def test_fetch(release, server, user, password, auth, root_dir, http, _file, hardened): IOCFetch(release, server, user, password, a...
432
142
from .dev import * # overrides for stage environment mapServiceJson = 'http://localhost:6080/arcgis/rest/services/DEQEnviro/MapService/MapServer?f=json' securedServiceJson = 'http://localhost:6080/arcgis/rest/services/DEQEnviro/Secure/MapServer?f=json' webdata = r'C:\inetpub\wwwroot\deqenviro\webdata' sgid = {'ENVIRON...
537
215
from __future__ import print_function import requests import time import sys from lxml import html import urlparse from util import * __author__ = 'iwharris' def request_auth_desktop(base_url, client_id, client_secret, scope, redirect_uri, state=''): """Makes an auth request to the Moves API. scope may be '...
4,999
1,470
""" Runtime environment settings """ import os as _os import sys as _sys def is_idle() -> bool: """Returns True if the script is running within IDLE, False otherwise""" return 'idlelib' in _sys.modules def is_powershell() -> bool: """Returns True if the script is running within PowerShell, False otherw...
1,011
325
# python file: test.py print("This is my first python program")
63
18
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jul 22 21:22:58 2018 @author: bruce """ import pandas as pd import os import numpy as np from scipy import fftpack from scipy import signal import matplotlib.pyplot as plt pkl_file=pd.read_pickle('/Users/bruce/Documents/uOttawa/Project/audio_brainst...
5,907
2,988
import torch import torch.nn as nn import torch.nn.functional as F # 说明:target1和target2 是两个目标模型,后面的mnists1和mnists2 是用于训练vae的模型。 # 我们攻击的时候,就选择target1和target2就行,不要选择后面两个模型。 # target1的模型权重就是那个mnist_gpu,target2的模型权重是mnist_models/checkpoints/mnist_target_2_best.pth.tar class MNIST_target_1(nn.Module): def __init__(self...
4,511
1,920
import newspaper from newspaper import Article # url = 'http://fox13now.com/2013/12/30/new-year-new-laws-obamacare-pot-guns-and-drones/' def text_extraction(url): article = Article(url) article.download() article.parse() text = article.text text = text.replace("\n\n"," ") # '\n' -> '' ...
339
126
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Oct 19 18:00:30 2016 @author: yannick """ import sys with open(sys.argv[1], "r") as fichier_lu: CONTENU = fichier_lu.readlines() [1::2] CONTENU = [ elt.strip("\n\r\t ") for elt in CONTENU ] for elta in CONTENU: REVERSE = [ elta.replace("A...
860
372
# 13. Accept any city from the user and display monument of that city. City Monument Delhi Red Fort Agra Taj Mahal Jaipur Jal Mahal city=input("Enter any city (Delhi, Agra, Jaipur, Lucknow, Kanpur) : ") city=city.lower() if city=="delhi": print("Monument: Red Fort") elif city=="agra": print("Monument: Taj Mahal...
561
187
"""To test how auto-detection of handler-class works with classes from other modules""" from rdisq.request.message import RdisqMessage class MessageFromExternalModule(RdisqMessage): pass
192
53
from ..wave_cs_enums import WaveType from ..wave_description_base import WaveMissionDescriber ###################################################### JA = WaveMissionDescriber() # fmt: off JA.missions[WaveType.MaxVoltage] = "1回で$1ボルテージを獲得する" JA.missions[WaveType.UseCardUniq] = "$1人のスクールアイドルでアピールする" JA.missions[WaveT...
609
314
from jsonbender.core import Bender, Context, bend, BendingException from jsonbender.list_ops import FlatForall, Forall, Filter, Reduce from jsonbender.string_ops import Format from jsonbender.selectors import F, K, S, OptionalS from jsonbender.control_flow import Alternation, If, Switch __version__ = '0.9.2'
313
101
# -*- coding: utf-8 -*- """Public section, including homepage and signup.""" import datetime from flask import Blueprint, flash, redirect, render_template, request, url_for, jsonify, session, g, abort from flask_login import login_required, login_user, logout_user, current_user from flask_cors import CORS, cross_origin...
7,889
2,351
# Generated by Django 3.2.6 on 2021-09-08 18:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mobiles', '0001_initial'), ] operations = [ migrations.AlterField( model_name='product_details', name='star', ...
391
133
#!/usr/bin/env python3 # # Script to read a GDS file, and replace a single cell structure with a cell of # the same name from a different GDS file. If a checksum is provided, then # the cell contents will be checked against the checksum before allowing the # replacement. The checksum is just the sum of the lengt...
4,724
1,478
#!/usr/bin/env python3 ''' IRLOME maps ''' __author__ = "Nick Dickens" __copyright__ = "Copyright 2018, Nicholas J. Dickens" __email__ = "dickensn@fau.edu" __license__ = "MIT" import matplotlib.pyplot as plt import mplleaflet points = [] with open("../web/data/user_data.csv") as in_fh: for line in in_fh: line ...
527
212
from django.contrib import admin from django.contrib.auth import get_user_model admin.site.register(get_user_model())
118
34
#Calculates the factorial of x, so 5! = 1*2*3*4*5 = 120 def factorial(x): product = 1 n = 1 while n <= x: product = product*n n += 1 return product
188
82
from sys import argv 2 3 script, filename = argv 4 5 txt = open(filename) 6 7 print(f"Here's your file {filename}:") 8 print(txt.read()) 9 10 print("Type the filename again:") 11 file_again = input("> ") 12 13 txt_again = open(file_again) 14 15 print(txt_again.read())
269
110
# Question: are sweeping alleles in infants present in mom? # Idea: store data on allele frequency in mom for each sweeping allele in infant from utils import sample_utils as su, parse_midas_data, substitution_rates_utils, config, temporal_changes_utils, snps_utils, core_gene_utils, gene_diversity_utils import numpy a...
6,787
2,496
from mindoc import MinDoc from markdown import Markdown from easy_mindoc import load_cfg, write_config import sys, getopt, os import typer app = typer.Typer() '当前工作路径' os.getcwd() @app.command() def config(user: str, cookies: str): typer.echo("正在设置用户和cookies") user = load_cfg().get('user', {}) user['us...
2,132
819
from __future__ import with_statement from contextlib import contextmanager from functools import wraps import logging @contextmanager def error_trapping(ident=None): ''' A context manager that traps and logs exception in its block. Usage: with error_trapping('optional description'): m...
821
227
import sys, os import json import redis import shutil from crypto.vncCrypto import VncCrypto from crypto.cryptoFernet import cryptoFernet from datetime import datetime, date, time from random import randint import psutil import uuid from werkzeug.utils import secure_filename import webbrowser #=====================...
2,850
874
ADAPTER_DICT = { 'django_celery_beat': { 'PeriodicTask': ['task'] } }
86
37
from django.test import TestCase from django.test import Client from .models import Escolaridade class EscolaridadeTestCase(TestCase): def setUp(self): Escolaridade.objects.create(escolaridade="Médio") Escolaridade.objects.create(escolaridade="Fundamental") def test_escolaridade_exists(s...
1,004
338
#!/usr/bin/env python3 # ===================== # Зависнуть у маркера # ===================== import numpy as np import rospy import cv2 import cv2.aruco as aruco from sensor_msgs.msg import Image from cv_bridge import CvBridge from aruco_calibration import Calibration as clb from drone_api import * from math import ...
4,799
1,839
import SageTensorSpace as TS MS = MatrixSpace(GF(7), 5, 6) M = MS.random_element() t = TS.TensorFromMatrices([M], 2, 1) # Testing a property U = VectorSpace(GF(7), 5) V = VectorSpace(GF(7), 6) assert all(M[i][j] == t((U.basis()[i], V.basis()[j]))[0] for i in range(5) for j in range(6))
288
139
# Reference: https://stackoverflow.com/questions/40427435/extract-images-from-idx3-ubyte-file-or-gzip-via-python # Based on answer by UdaraWanasinghe import os import gzip import numpy as np import torch import torch.nn.functional as F home_dir = os.path.expanduser('~') parent_dir = "Datasets/Images/MNIST/" def trai...
3,933
1,257
"""5_3 to 6_0 Revision ID: b92770a7b6ca Revises: 396303c07e35 Create Date: 2021-04-12 09:33:44.399254 """ from alembic import op import sqlalchemy as sa from manager_rest.storage import models # revision identifiers, used by Alembic. revision = 'b92770a7b6ca' down_revision = '396303c07e35' branch_labels = None depe...
7,968
2,738
from django.db.backends.base.validation import BaseDatabaseValidation class DatabaseValidation(BaseDatabaseValidation): def check(self, **kwargs): return [] def check_field(self, field, **kwargs): return []
233
60
#PBS -N UnBalance #PBS -m ae #PBS -q long #PBS -l nodes=1:opteron:ppn=2 """Test handling of extreme load-unbalancing.""" from asap3 import * from asap3.md import MDLogger from ase.lattice.cubic import FaceCenteredCubic import numpy as np from asap3.mpi import world #DebugOutput("UnBalance.%d.out") #set_verbose(1) pr...
1,763
792
# Programowanie I R # Funkcje: argumenty # Funkcja z trzema argumentami: name, surname, age def printPersonalData(name, surname, age): print(f"Imię i nazwisko: {name} {surname}") print(f"Wiek: {age}") # Argumenty pozycyjne ************************************************************** print("Argu...
2,721
963
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="vortex-http", version="0.4.1", description="aiohttp wrapped web framework", author="Chris Lee", author_email="sihrc.c.lee@gmail.com", packages=find_packages(), install_requires=[ "aiodns==2.0.0", ...
541
213
#!/usr/bin/env python3 import os from datetime import datetime, timedelta import errno import time import USBKey class Files(): import sys import csv from datetime import datetime, date, time, timedelta import os from os import path import shutil # import urllib # for python 3 : import u...
47,745
12,475
import os import sys from pathlib import Path from datetime import timedelta from django.conf import global_settings from django.utils.translation import gettext_lazy as _ import django.conf.locale # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent sys...
5,835
2,086
# Need to import path to test/fixtures and test/scripts/ # Ex : export PYTHONPATH='$PATH:/root/test/fixtures/:/root/test/scripts/' # # To run tests, you can do 'python -m testtools.run tests'. To run specific tests, # You can do 'python -m testtools.run -l tests' # Set the env variable PARAMS_FILE to point to your ini ...
1,531
500
from __future__ import with_statement #!/usr/bin/env python2.5 """ ############################################################################# ## ## file : excepts.py ## ## description : see below ## ## project : Tango Control System ## ## $Author: Sergi Rubio Manrique, srubio@cells.es $ ## ## $Revision: 20...
11,681
3,558
#Análisis de Algoritmos 3CV2 # Alan Romero Lucero # Josué David Hernández Ramírez # Práctica 4 Divide y vencerás import matplotlib.pyplot as plt import numpy as np import gb """                              Variables globales: proposed2: Función propuesta para el algoritmo Quicktime. Dependiendo si ...
4,345
1,634
estiloFondo = ("QMainWindow{\n" "background-color: white;}") estiloFrame = ("QFrame{\n" "background-image: url(ui.png);}\n") estiloNombre = ("QLabel{\n" "color: #E84C70;}\n") estiloTitulo = ("QLabel{\n" "color: #2F475E;}\n") estiloLine = ("QLineEdit {\n" "color: black;\n" "background: transpa...
1,207
618
import simArch.gemm_trace_wrapper as gemm_trace def run_net( ifmap_sram_size=1, # in K-Word filter_sram_size=1, # in K-Word ofmap_sram_size=1, # in K-Word array_h=32, array_w=32, data_flow='ws', word_size_bytes=1, wgt_bw_opt=False, topology_file=None, net_name=None, offset_l...
4,260
1,335
from datetime import datetime, timedelta from django.shortcuts import render from django.template import RequestContext import api def index(request): uid = request.COOKIES.get("uid") data = None if not uid: uid, _ = api.create_new_user() else: data = api.get_saved_cities(uid) res...
550
180