text
string
size
int64
token_count
int64
import logging import os import io from fastapi import APIRouter, Depends, Header from fastapi.responses import FileResponse, StreamingResponse from fastapi import HTTPException, status import pyarrow as pa import pyarrow.parquet as pq from data_service.api.query_models import ( InputTimePeriodQuery, InputTimeQue...
6,856
1,961
from utils import sanitize class Bonus: def __init__(self, number, leadin="", texts=None, answers=None, category="", subcategory="", tournament="", round=""): self.number = number self.leadin = leadin self.texts = texts self.answers = answers ...
1,976
603
import json import argparse from argus.callbacks import MonitorCheckpoint, \ EarlyStopping, LoggingToFile, ReduceLROnPlateau from torch.utils.data import DataLoader from src.datasets import FreesoundDataset, FreesoundNoisyDataset, RandomDataset from src.datasets import get_corrected_noisy_data, FreesoundCorrecte...
5,389
1,886
#Day 1.3 Exercise!! #First way I thought to do it without help name = input("What is your name? ") print(len(name)) #Way I found to do it from searching google print(len(input("What is your name? ")))
202
68
from typing import TypedDict from .utils.Classes.String import String from .utils.assert_string import assert_string from .utils.merge import merge class _IsStrongPasswordOptions(TypedDict): min_length: int min_uppercase: int min_lowercase: int min_numbers: int min_symbols: int return_score: ...
3,524
1,151
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals # Python imports. import logging import datetime import calendar # Django imports. from django.db import transaction # Rest Framework imports. from rest_framework import serializers # Third Party Library imports # local imports....
1,691
479
from __future__ import absolute_import, unicode_literals import warnings from wagtail.wagtailcore.blocks import * # noqa warnings.warn("wagtail.wagtailadmin.blocks has moved to wagtail.wagtailcore.blocks", UserWarning, stacklevel=2)
237
81
import codecs from datetime import datetime, timedelta from optparse import make_option from os import path, unlink from django.conf import settings from django.core.management.base import BaseCommand, CommandError import commonware.log from olympia import amo from olympia.addons.models import Addon, Persona from ol...
5,197
1,483
import numpy as np import pickle import matplotlib.pyplot as plt import os import fnmatch folder = "GP/" ktype = "lin/" matrices=os.listdir(folder+ktype) for matrix in matrices: if fnmatch.fnmatch(matrix, '*_val_*'): with open(folder+ktype+matrix, "rb") as pickleFile: results = pickle.load(pick...
663
201
#!/usr/bin/env python2.7 # coding=utf-8 import logging import traceback import time from FATERUI.common.camera.camera import Camera from . import CameraMindVision from FATERUI.common.camera.common_tools import * import cv2 # from aoi.common.infraredcontrol import infraredcontrol from time import sleep import datetim...
5,919
1,773
import pytest @pytest.fixture(scope="session") def test_data(): from pathlib import Path module_dir = Path(__file__).resolve().parent test_dir = module_dir / "test_data" return test_dir.resolve() @pytest.fixture(scope="session") def database(): return "jobflow_test" @pytest.fixture(scope="ses...
2,307
764
# This script allows to download a single file from a remote ZIP archive # without downloading the whole ZIP file itself. # The hosting server needs to support the HTTP range header for it to work import zipfile import requests import argparse class HTTPIO(object): def __init__(self, url): self.url = url...
2,142
647
import Image import readMDA import h5py import os import numpy from mmpad_image import open_mmpad_tif import numpy as np import scipy as sp import sys #import libtiff from cxparams import CXParams as CXP class CXFileReader(object): """ file_reader A generic and configurable file reader. The file r...
5,928
1,716
""" Support for file notification. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/notify.file/ """ import logging import os import homeassistant.util.dt as dt_util from homeassistant.components.notify import ( ATTR_TITLE, DOMAIN, BaseNotificationSer...
1,881
521
""" Example 035: Scheduled sending and delayed routing """ from os import path from docusign_esign.client.api_exception import ApiException from flask import render_template, session, Blueprint, request from ..examples.eg035_scheduled_sending import Eg035ScheduledSendingController from ...docusign import authentica...
2,561
806
#-- THIS LINE SHOULD BE THE FIRST LINE OF YOUR SUBMISSION! --# def tally(costs, discounts, rebate_factor): cost = sum(costs) discount = sum(discounts) pre = (cost - discount) * rebate_factor if pre < 0: return 0 else: return round(pre, 2) #-- THIS LINE SHOULD BE THE LAST LINE OF ...
584
256
#!/usr/bin/env python3 """ Given a set of dominos, construct a linear sequence For example, if the set of dominos is [ (0,0) (1,0), (1,1)] then a valid linear sequence of length four would be (0,0),(0,1),(1,1),(1,0) In this script we first create a set of dominos to sample from. Then every permutation of that set is t...
2,450
955
## Unit 4 Project - Two Player Game ## Gavin Weiss - Computer Programming II ## The Elder Scrolls X # A fan made 2 player game successor the The Elder Scrolls Series # Two players start off in an arena # Can choose starting items # Can choose classes ## Libraries import time # Self explanatory import rand...
3,418
1,200
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import subprocess from catapult_base import cloud_storage from telemetry.core import platform from telemetry.util import image_util from telemetry.util impo...
6,689
1,941
"""Proxy to handle account communication with Renault servers.""" from __future__ import annotations from collections.abc import Awaitable from datetime import timedelta import logging from typing import Callable, TypeVar from renault_api.kamereon.exceptions import ( AccessDeniedException, KamereonResponseExc...
2,545
651
def soma (a,b): print(f'A = {a} e B = {b}') s=a+b print(f'A soma A + B ={s}') #Programa Principal soma(4,5)
122
68
#!/usr/bin/env python3 # =================================================================================== # Copyright (C) 2019 Fraunhofer Gesellschaft. All rights reserved. # =================================================================================== # This Acumos software file is distributed by Fraunhofer G...
2,270
690
# -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the...
1,169
373
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jan 20 08:40:22 2017 @author: fabio """ import ee import ee.mapclient ee.Initialize() collection = ee.ImageCollection('MODIS/MCD43A4_NDVI') lista = collection.toList(10) #print lista.getInfo() image = ee.Image('LC8_L1T/LC81910312016217LGN00') #prin...
836
352
# Copyright 2019 The Bazel 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 applicable la...
3,107
1,080
from django.contrib import admin from .models import Contato, Venda, FormaPagamento admin.site.register(Contato) admin.site.register(Venda) admin.site.register(FormaPagamento)
177
58
import os import re import urllib from datetime import datetime from pathlib import Path from typing import Dict, List, Tuple, Union from money.currency import Currency from money.money import Money from werkzeug.utils import secure_filename from pome import g from pome.models.encoder import PomeEncodable RECORDED_T...
11,967
3,675
from __future__ import unicode_literals from __future__ import print_function import moya from moya.compat import text_type from requests_oauthlib import OAuth1Session def get_credentials(provider, credentials): client_id = credentials.client_id or provider.get('client_id', None) client_secret = credentials...
4,350
1,237
""" Cartesian genetic programming """ import operator as op import random import copy import math from settings import VERBOSE, N_COLS, LEVEL_BACK class Function: """ A general function """ def __init__(self, f, arity, name=None): self.f = f self.arity = arity self.name = f....
6,599
2,063
from historia.pops.logic.logic_base import LogicBase from historia.economy.enums.resource import Good class RefinerLogic(LogicBase): def perform(self): bread = self.get_good(Good.bread) tools = self.get_good(Good.tools) iron_ore = self.get_good(Good.iron_ore) if bread is None or i...
824
278
import argparse import cv2 import numpy as np import os import _pickle as pickle from descriptors import HOG #from skimage.morphology import skeletonize # run image filtering and HOG feature extraction def main(im_path, desc_name): print('[INFO] Preparing to extract features for images in \'' + im_path + '\'') ...
2,386
729
import abc class SpecSource(abc.ABC): @abc.abstractmethod def describe(self) -> str: """ Returns: str to print in case there is an error constructing extractor for tracing back """ raise NotImplementedError() class UnknownSource(SpecSource): def describe(sel...
363
100
from django.contrib import admin from .models import Placement_Company_Detail,Profile,StudentBlogModel,ResorcesModel admin.site.register(Placement_Company_Detail) admin.site.register(Profile) admin.site.register(StudentBlogModel) admin.site.register(ResorcesModel)
265
78
import torch as t import torch_geometric.utils as utils def qw_score(graph): """ 未实现qw_score,采用度数代替 :param graph: """ score = utils.degree(graph.edge_index[0]) return score.sort() def pre_processing(graph, m, score, trees): score, indices = score indices.squeeze_() old_edges = gr...
3,730
1,436
from typing import Optional, Any class Node: def __init__(self, key: int = 0, val: int = 0): self.key: int = key self.val: int = val self.freq: int = 0 self.pre: Optional[Node] = None self.next: Optional[Node] = None class DLList: def __init__(self): self.size =...
5,463
1,991
#/* # * Copyright (C) 2017 - This file is part of libecc project # * # * Authors: # * Ryad BENADJILA <ryadbenadjila@gmail.com> # * Arnaud EBALARD <arnaud.ebalard@ssi.gouv.fr> # * Jean-Pierre FLORI <jean-pierre.flori@ssi.gouv.fr> # * # * Contributors: # * Nicolas VIVET <nicolas.vivet@ssi.gouv.fr> ...
3,263
1,861
import csv from pathlib import Path from datetime import datetime from lps.models import * from lps.schemas import * SEED_FOLDER_PATH = Path("db/seeds/") def import_from_csv(csv_filename): with open(SEED_FOLDER_PATH / csv_filename) as csv_file: csv_read = csv.DictReader(csv_file, delimiter=',') ...
3,332
1,113
def GCD(a,b): if b == 0: return a else: return GCD(b, a%b) a = int(input()) b = int(input()) print(a*b//(GCD(a,b)))
141
68
""" Build a derived collection with the maximum value from each 'group' defined in the source collection. """ __author__ = 'Dan Gunter <dkgunter@lbl.gov>' __date__ = '5/21/14' from matgendb.builders import core from matgendb.builders import util from matgendb.query_engine import QueryEngine _log = util.get_builder_lo...
2,121
559
from __future__ import unicode_literals from dvc.output.ssh import OutputSSH from dvc.dependency.base import DependencyBase class DependencySSH(DependencyBase, OutputSSH): pass
184
57
import torch import torch.nn as nn import optflow.compute_tvl1_energy as compute_tvl1_energy def EPE(input_flow, target_flow, sparse=False, mean=True): EPE_map = torch.norm(target_flow-input_flow,2,1) if sparse: EPE_map = EPE_map[target_flow != 0] if mean: return EPE_map.mean() else: ...
1,775
606
import numpy as np import time import cv2 import argparse import sys import os import glob import json from pathlib import Path class ObjectDetector: def file_exist(file_names_list: list) -> bool: if all(list(map(os.path.isfile,file_names_list))): return True else: print("P...
8,070
2,445
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
15,921
4,596
import numpy as np def _check_mne(name): """Helper to check if h5py is installed""" try: import mne except ImportError: raise ImportError('Please install MNE-python to use %s.' % name) return mne def raw_to_mask(raw, ixs, events=None, tmin=None, tmax=None): """ A function to ...
5,669
1,746
import collections from itertools import combinations from collections import Counter class Solution: def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]: visit = collections.defaultdict(list) for t, u, w in sorted(zip(timestamp, username, website...
508
144
import random async def magicEightBall(ctx, message=True): if message: eightBall = random.randint(0, 19) outlooks = [ "As I see it, yes.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again."...
870
243
import pymysql.cursors from ..mod_check import app @app.task def check(host, port, username, password, db): result = None connection = None try: connection = pymysql.connect(host=host, port=port, user=username, ...
970
235
import time import board import busio from digitalio import DigitalInOut from adafruit_esp32spi import adafruit_esp32spi from adafruit_esp32spi import adafruit_esp32spi_wifimanager import neopixel # Import Philips Hue Bridge from adafruit_hue import Bridge # Get wifi details and more from a secrets.py file ...
2,087
846
# # Copyright (c) 2013-2018 Joris Vink <joris@coders.se> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUT...
2,081
677
# -*- coding:utf-8 -*- """ """ __date__ = "14/12/2017" __author__ = "zhaojm"
77
48
import asyncio import logging import traceback import uuid from typing import Optional, Tuple, Any, Callable from pesto.ws.core.payload_parser import PayloadParser, PestoConfig from pesto.ws.core.pesto_feature import PestoFeatures from pesto.ws.core.utils import load_class, async_exec from pesto.ws.features.algorithm_...
3,710
1,030
# -*- coding: utf-8 -*- import logging import os import re import sys class Helpers: def __init__(self, logger=None): if logger is None: self.logger = logging.getLogger(__name__) else: self.logger = logger @staticmethod def extract_sequence_num(filename): s...
1,858
534
import configparser import os import typing from sitri.providers.base import ConfigProvider class IniConfigProvider(ConfigProvider): """Config provider for Initialization file (Ini).""" provider_code = "ini" def __init__( self, ini_path: str = "./config.ini", ): """ ...
1,353
386
from typing import Any, Dict, List from xpanse.const import V2_PREFIX from xpanse.endpoint import ExEndpoint from xpanse.iterator import ExResultIterator class IpRangeEndpoint(ExEndpoint): """ Part of the Assets v2 API for handling IP Ranges. See: https://api.expander.expanse.co/api/v1/docs/ """ ...
9,512
2,553
from bfio import BioReader import argparse, logging import numpy as np from pathlib import Path import filepattern, multiprocessing, utils from concurrent.futures import ThreadPoolExecutor COLORS = ['red', 'green', 'blue', 'yellow', 'magenta', 'cyan', 'gray']...
8,337
2,477
from kinetics.reaction_classes.reaction_base_class import Reaction class Generic(Reaction): """ This Reaction class allows you to specify your own rate equation. Enter the parameter names in params, and the substrate names used in the reaction in species. Type the rate equation as a string in rate_equa...
1,175
307
from ctypes import * from migi.decorators import stdcall @stdcall('MessageBoxW', 'User32.dll', interceptable=True) def _native_message_box_w(hwnd: c_void_p, content: c_wchar_p, title: c_wchar_p, flags: c_uint32) -> c_int32: if wstring_at(content) == "I'm in": return _native_message_box_w.call_original(hw...
718
270
from adapters.adapter_with_battery import AdapterWithBattery from devices.switch.selector_switch import SelectorSwitch class HeimanAlarmRemoteAdapter(AdapterWithBattery): def __init__(self): super().__init__() self.switch = SelectorSwitch('Remote', 'action') self.switch.add_level('Off', No...
1,002
301
# -*- coding: utf-8 -*- """ """ import scrapy from tennis_model.tennis_model_scraper.tennis_model_scraper import items class TennisDataCoUkSpider(scrapy.Spider): name = "tennis_data_co_uk" allowed_domains = ["www.tennis-data.co.uk"] start_urls = ["http://www.tennis-data.co.uk/alldata.php"] custom_...
1,236
419
from aoc20211219a import * def aoc(data): sensors, _ = slam(parse(data)) return max(sum(abs(x) for x in sub(a, b)) for a in sensors for b in sensors)
160
70
import json import requests from .exceptions import ( RequestsError, RequestsTimeoutError, RPCError ) _default_endpoint = 'http://localhost:9500' _default_timeout = 30 def base_request(method, params=None, endpoint=_default_endpoint, timeout=_default_timeout) -> str: """ Basic RPC request ...
2,739
766
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import socket import threading import rospy from publisher import * import cv2 import imagezmq import numpy as np from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError def parse_sent_msg(msg): ctr, frame_time = msg.split() fra...
3,430
1,083
import sys import numpy import numpy as np from snappy import Product from snappy import ProductData from snappy import ProductIO from snappy import ProductUtils from snappy import FlagCoding ############## import csv ###############MSVR from sklearn.svm import SVR from sklearn.preprocessing import StandardScaler fro...
3,179
1,185
import fiona d = { "type": "Feature", "id": "0", "properties": { "ADMINFORES": "99081600010343", "REGION": "08", "FORESTNUMB": "16", "FORESTORGC": "0816", "FORESTNAME": "El Yunque National Forest", "GIS_ACRES": 55829.81, "SHAPE_AREA": 0.0193062316937,...
23,097
15,150
from __future__ import print_function import argparse, sys from .utils import is_textfile def contains_crlf(filename): with open(filename, mode='rb') as file_checked: for line in file_checked.readlines(): if line.endswith(b'\r\n'): return True return False def main(argv=Non...
850
290
if __name__ == "__main__": print("Nothing yet...")
55
20
import base64 from sqlalchemy import Column, String, LargeBinary from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm.exc import NoResultFound from vantage6.common.globals import STRING_ENCODING from .base import Base, Database class Organization(Base): ...
2,317
647
from checkov.common.models.enums import CheckResult, CheckCategories from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck class EKSSecretsEncryption(BaseResourceCheck): def __init__(self): name = "Ensure EKS Cluster has Secrets Encryption Enabled" id = "CKV_AWS_58" ...
865
259
""" AnalysisNode is the base class that all analysis nodes inherit from. """ import logging import operator from functools import reduce from random import random from time import time from typing import Tuple, Sequence, List, Dict, Optional from celery.canvas import Signature from django.conf import settings from dja...
46,176
13,342
import os import traceback from flask import render_template, send_from_directory, current_app, g from .emailing import email def init_standard_views(app): @app.route("/favicon.ico") def favicon(): return send_from_directory( os.path.join(app.root_path, "static"), "f...
2,077
687
# 'from ... import ...' statement from sys import exit def main(): exit(0) main()
87
29
from dataclasses import dataclass from typing import List from typing import Union from postmanparser.description import Description from postmanparser.exceptions import InvalidObjectException from postmanparser.exceptions import MissingRequiredFieldException @dataclass class FormParameter: key: str value: s...
1,455
366
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import pip import os import sys def err(msg): print "\033[31m✗ \033[0m%s" % msg def ok(msg): print "\033[32m✓ \033[0m%s" % msg def main(): cwd = os.getcwd() json_file = os.path.join(cwd, 'dependencies.json') if os.path.isfile(json_file) =...
844
297
""" Console scripts David Megginson April 2015 This is a big, ugly module to support the libhxl console scripts, including (mainly) argument parsing. License: Public Domain Documentation: https://github.com/HXLStandard/libhxl-python/wiki """ from __future__ import print_function import argparse, json, logging, os, ...
36,148
11,115
# # @lc app=leetcode id=1807 lang=python3 # # [1807] Evaluate the Bracket Pairs of a String # # @lc code=start import re class Solution: def evaluate(self, s: str, knowledge: list[list[str]]) -> str: mapping = dict(knowledge) return re.sub(r"\((\w+?)\)", lambda m: mapping.get(m.group(1), "?"), s)...
338
139
#Heron's formula# import math unit_of_measurement = "cm" side1 = int(input("Enter the length of side A in cm: ")) side2 = int(input("Enter the length of side B in cm: ")) side3 = int(input("Enter the length of side C in cm: ")) braket1 = (side1 ** 2) * (side2**2) + (side1**2)*(side3**2) + (side2**2)*(side3**2) brake...
787
314
from __future__ import absolute_import, division, print_function import numpy as np import wx from dials.array_family import flex from dials_viewer_ext import rgb_img class wxbmp_from_np_array(object): def __init__( self, lst_data_in, show_nums=True, palette="black2white", lst_data_mask_in=None ): ...
4,605
1,665
import numpy as np def check_x_y(x, y): assert isinstance(x, np.ndarray) and isinstance(y, np.ndarray) assert np.ndim(x) <= 3 and np.ndim(y) <= 2 assert len(x) == len(y)
191
85
""" CSharp (С#) domain for sphinx ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sphinxsharp Pro (with custom styling) :copyright: Copyright 2021 by MadTeddy """ import re import warnings from os import path from collections import defaultdict, namedtuple from docutils import nodes from docutils.parsers.rst import...
34,772
10,658
# Generated by Django 3.2.7 on 2021-10-02 08:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('articles', '0002_auto_20211002_1019'), ] operations = [ migrations.AddField( model_name='article', name='published_a...
404
145
from KratosMultiphysics import ParallelEnvironment, IsDistributedRun if IsDistributedRun(): from KratosMultiphysics.mpi import DataCommunicatorFactory import KratosMultiphysics.KratosUnittest as UnitTest import math class TestDataCommunicatorFactory(UnitTest.TestCase): def setUp(self): self.registere...
5,622
1,647
from __future__ import print_function try: import vkaudiotoken except ImportError: import path_hack from vkaudiotoken import supported_clients import sys import requests import json token = sys.argv[1] user_agent = supported_clients.KATE.user_agent sess = requests.session() sess.headers.update({'User-Agent'...
643
248
# -*- coding: utf-8 -*- import os import sys from pprint import pprint root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt # noqa: E402 exchange = ccxt.binance({ 'apiKey': 'SmweB9bNM2qpYkgl4zaQSFPpSzYpyoJ6B3BE9rCm0XYcAdIE0b7n6bm11e8j...
811
355
# Copyright 2018 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import itertools import os import re from . import base class OutProc(base.ExpectedOutProc): def __init__(self, expected_outcomes, basepath, expected_...
2,235
688
from django.urls import path from . import views app_name = "users" urlpatterns = [ path("all/", view=views.UserList.as_view(), name="all_user"), path("<int:user_id>/password/", view=views.ChangePassword.as_view(), name="change password"), path("<int:user_id>/follow/", view=views.FollowUser.as_view(), name...
604
203
import pytest from Thycotic import Client, \ secret_password_get_command, secret_username_get_command, \ secret_get_command, secret_password_update_command, secret_checkout_command, secret_checkin_command, \ secret_delete_command, folder_create_command, folder_delete_command, folder_update_command from tes...
3,132
1,264
import os import glob import pandas as pd import xml.etree.ElementTree as ET def xml_to_csv(path): xml_list = [] for xml_file in glob.glob(path + '/*.xml'): tree = ET.parse(xml_file) root = tree.getroot() for member in root.findall('object'): value = (root.find('filename')....
1,046
340
import _nnet import numpy as np import IPython net = _nnet.Nnet() net.read('/home/maohz12/online_50h_Tsinghua/exp_train_50h/lstm_karel_bak/nnet/nnet_iter14_learnrate7.8125e-07_tr1.2687_cv1.6941') # Test1 blobs = net.layers[0].get_params() x = blobs[1].data.flatten() x_test = np.fromfile('test/1.bin', 'f') assert np.s...
1,190
563
__author__ = 'Aaron Yang' __email__ = 'byang971@usc.edu' __date__ = '10/28/2020 4:52 PM' # import re # # # def format_qs_score(score_str): # """ # help you generate a qs score # 1 - 100 : 5 # 141-200 : 4 # =100: 4 # N/A 3 # :param score_str: # :return: # """ # score = 3 # if...
1,329
525
# -*- coding: utf-8 -*- import json from itertools import chain from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ObjectDoesNotExist from django.db.models import BooleanField from django.forms import modelform_factory from django.utils.lru_cache import lru...
4,311
1,330
import sys, os, json, jinja2, redis from jinja2 import Template r_server = redis.StrictRedis('127.0.0.1', db=2) i_key = "owner-info" json_data = r_server.get(i_key) if json_data is not None: data = json.loads(json_data) main_domain = data['Hostname'] fqdn = sys.argv[1] + ".ext." + main_domain config_template...
597
232
def Linear_Search(Test_arr, val): index = 0 for i in range(len(Test_arr)): if val > Test_arr[i]: index = i+1 return index def Insertion_Sort(Test_arr): for i in range(1, len(Test_arr)): val = Test_arr[i] j = Linear_Search(Test_arr[:i], val) Test_arr.pop(i) ...
569
207
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots['test_keywords 1'] = '[{"lineno": 7, "source": [" a\\n"], "value": "1"}, {"lineno": 7, "source": [" a\\n"], "value": "2"}, {"lineno": 7,...
631
269
import sys from PySide2.QtWidgets import QApplication, QMainWindow from PySide2.QtCore import QFile from lesson_10_mainWidget import Ui_MainWindow class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) if __name...
443
151
import jax.numpy as jnp import numpy as np from jax import random from algorithms import Game, GHA, Oja, Krasulina, Numpy def test_pca(): """ At the moment just checks they all run. Returns ------- """ n = 10 p = 2 n_components = 2 batch_size = 2 epochs = 10 key = random...
1,208
426
import numpy as np from radix import radixConvert c = radixConvert() a = np.load("../../data/5/layer4.npy") print(a.shape) a = a*128 a = np.around(a).astype(np.int16) print(a) a = np.load('../../data/6.npy') a = a*128 a = np.around(a).astype(np.int8) print(a.shape) for i in range(84): print(i) print(a[i]) ''...
971
459
class Wrapper(object): wrapper_classes = {} @classmethod def wrap(cls, obj): return cls(obj) def __init__(self, wrapped): self.__dict__['wrapped'] = wrapped def __getattr__(self, name): return getattr(self.wrapped, name) def __setattr__(self, name, value): set...
541
186
from saifooler.classifiers.classifier import Classifier import torch import json import os class ImageNetClassifier(Classifier): def __init__(self, model, *args, **kwargs): super().__init__(model, *args, **kwargs) self.std = torch.tensor([0.229, 0.224, 0.225], device=self.device) self.mea...
1,237
422
#!/usr/bin/env python # coding: utf-8 # conda install pytorch>=1.6 cudatoolkit=10.2 -c pytorch # wandb login XXX import json import logging import os import re import sklearn import time from itertools import product import numpy as np import pandas as pd import wandb #from IPython import get_ipython from keras.prepro...
12,130
4,386
from django.shortcuts import render from .models import GameMeta def index(request): return render(request, 'go_server_app/index.html') def dashboard(request): return render(request, 'go_server_app/dashboard.html', {'games_list': GameMeta.objects.all()}) def game(request, game_id): game_meta = GameMe...
515
173