text
string
size
int64
token_count
int64
import itertools import typing from typing import Any from PyQt5 import QtCore from PyQt5.QtCore import QModelIndex, pyqtSignal, QObject from PyQt5.QtGui import QColor from PyQt5.QtWidgets import QAbstractItemDelegate, QWidget, QStyleOptionViewItem, QSpinBox class CustomNode(object): def __init__(self, data=None...
7,877
2,248
import multiprocessing as mp from pyrallel.map_reduce import MapReduce NUM_OF_PROCESSOR = max(2, int(mp.cpu_count() / 2)) def test_map_reduce_number(): def mapper(x): return x def reducer(r1, r2): return r1 + r2 mr = MapReduce(3, mapper, reducer) mr.start() mr.add_task(1) ...
1,761
793
import argparse import Evtx.Evtx as evtx import pandas as pd import xmltodict import re parser = argparse.ArgumentParser(description="Convert Windows EVTX event log file to DataFrame.") parser.add_argument("evtx", type=str, help="Path to the Windows EVTX event log file") args = parser.parse_args() with evtx.Evtx(args...
707
238
sandwich_meat={ 1:{'chicken':3}, 2:{'beef':5}, 3:{'pork':4}, 4:{'bacon':4}, 5:{'sausage':4}, 6:{'omelette':2}, 7:{'none':0} } sandwich_sauce=['mayonnaise','ketchup','yellow mustard','black pepper sauce','cheese','none'] sandwich_vegetable=['lettuce','sliced tomatoes','sliced pickles','...
562
261
import math import numpy as np from scipy import signal, fftpack def pre_emphasize(data, pre_emphasis=0.97): return np.append(data[0], data[1:] - pre_emphasis * data[:-1]) def hz_to_mel(hz): return 2595 * math.log10(1 + hz / 700) def mel_to_hz(mel): return 700 * (10 ** (mel / 2595) - 1) def make_mel...
1,553
620
''' Unpack SEC EIS File is an example of a plug-in to the GUI menu that will save the unpacked contents of an SEC EIS File in a directory. (c) Copyright 2012 Mark V Systems Limited, All rights reserved. ''' def unpackEIS(cntlr, eisFile, unpackToDir): from arelle.FileSource import openFileSource filesource = ...
2,688
840
#!/usr/bin/env python # This file is part of pyacoustid. # Copyright 2012, Lukas Lalinsky. # # 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 restriction, including # without limitati...
2,251
638
from app.views.dashboard.leadership.index import leaderships from app.views.dashboard.leadership.delete import leadership_delete from app.views.dashboard.leadership.activation import leadership_activated
203
55
# Button Groups in Python import PyQt5 from PyQt5.QtWidgets import QApplication, QHBoxLayout, QLabel, QButtonGroup, QMainWindow, QDialog, QPushButton, QVBoxLayout import sys from PyQt5 import QtGui from PyQt5.QtGui import QFont, QPixmap from PyQt5.QtCore import QSize class window(QDialog): def __init__(...
3,071
1,054
#!/usr/bin/env python3 # # MIT License # # (C) Copyright 2020-2022 Hewlett Packard Enterprise Development LP # # 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 restriction, including w...
20,126
6,337
from decimal import Decimal from django.core.exceptions import ValidationError from django.db import models from app.utils import get_balances class Transaction(models.Model): ledger = models.ForeignKey( 'ledger.Ledger', on_delete=models.PROTECT, related_name='transactions' ) date ...
3,071
919
# python-telegram-quiz # @author: Aleksandr Gordienko # @site: https://github.com/aleksandrgordienko/melissa-quiz from random import randint from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Question(Base): __tablename__ = 'qu...
2,335
683
import docx import time import os from os import system from pprint import pprint finished = False def getText(filename): print(filename) doc = docx.Document(filename) fullText = [] for para in doc.paragraphs: fullText.append(para.text) pprint(fullText) def clear(): try: system('cls') except: system('...
1,246
491
class Solution: def uniqueOccurrences(self, arr: List[int]) -> bool: hashMap = {} for num in arr: if num not in hashMap: hashMap[num] = 1 else: hashMap[num] += 1 array = hashMap.values() unique = {} for num in array: ...
2,014
553
from .dataset import Dataset from .model import Model from .transform import Transform
87
21
import networkx as nx from py2neo import Graph, Node, Relationship import pandas as pd import random graph = Graph("bolt://localhost:7687", auth=("neo4j", "Password")) def importGexf(gexffilepath, depth = 0): ''' Reads gexf network file from hyphe, update or create all nodes and relationships in neo4j data...
5,707
1,944
from code_base.excess_mortality.decode_loc_vars import * DECODE_DEMO_COL = { 'excess_mortality_by_sex_age_country': 'age,sex,unit,geo\\time', 'excess_mortality_by_sex_age_nuts3': 'unit,sex,age,geo\\time', 'europe_population_by_age_and_sex': 'freq;unit;sex;age;geo\TIME_PERIOD' } DECODE_DEMO_REPL = { 'e...
4,023
2,296
""" The MIT License (MIT) Copyright (c) 2017-2018 Nariman Safiulin 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 restriction, including without limitation the rights to use, copy, modif...
4,510
1,253
import os from pathlib import Path from typing import Any, Dict, Union import numpy as np def isdicom(path: Union[str, Path]) -> bool: """ Judge whether a given file is a valid dicom. Args: path: given file path. Returns: True if given path is a valid dicom, otherwise False. """ ...
775
269
import tensorflow as tf import numpy as np import os, datetime, itertools, shutil, gym, sys from tf_rl.common.visualise import plot_Q_values from tf_rl.common.wrappers import MyWrapper, CartPole_Pixel, wrap_deepmind, make_atari """ TF basic Utility functions """ def eager_setup(): """ it eables an eager ex...
28,704
9,475
from collections import namedtuple, OrderedDict import json __author__ = 'kollad' def isnamedtuple(obj): """Heuristic check if an object is a namedtuple.""" return isinstance(obj, tuple) \ and hasattr(obj, "_fields") \ and hasattr(obj, "_asdict") \ and callable(obj._asdict) ...
2,284
737
import setuptools with open("README.md") as readmeFile: long_description = readmeFile.read() setuptools.setup( name="musketeer", version="0.0.1", author="Daniil Soloviev", author_email="dos23@cam.ac.uk", description="A tool for fitting data from titration experiments.", long_description=lo...
1,079
347
from django.test import TestCase # Create your tests here. from webapp.forms import contains_all_letters class SCheckerTestCase(TestCase): def setup(self): pass def test_lower_case(self): text = 'abcdefghijklmnopqrstuvwxyz' answer = contains_all_letters(text) self.assertEqual(answer,True) def test_upper...
1,358
577
import copy import math import operator import random import sys from concurrent import futures import numpy as np import requests class FitnessFunctionCaller: """Class for returning the fitness function of an individual.""" def __init__(self, *args): functional_parts = [] # Full case with ...
16,338
4,546
from typing import Mapping, Any, List class HiroClientError(Exception): def __init__(self, *args: object) -> None: super().__init__(*args) class OntologyValidatorError(HiroClientError): message: str warnings: List[str] errors: List[str] def __init__(self, data: Mapping[str, Any]) -> Non...
1,638
448
from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from . import models, serializers from yoongram.notifications import views as notifications_views class ExploreUsers(APIView): def get(self, request, format=None): last_five = models.Us...
8,098
2,473
''' Basic Python tutorial neural network. Based on "A Neural Network in 11 Lines of Python" by i am trask https://iamtrask.github.io/2015/07/12/basic-python-network/ ''' import numpy as np class ToyNN(object): ''' Simple two-layer toy neural network ''' def __init__(self, inputs=3, outputs=1): ...
2,507
809
import pytest from gaphor import UML from gaphor.core.modeling import Diagram from gaphor.core.modeling.modelinglanguage import ( CoreModelingLanguage, MockModelingLanguage, ) from gaphor.SysML.modelinglanguage import SysMLModelingLanguage from gaphor.UML.deployments.connector import ConnectorItem from gaphor....
1,122
341
pozehug = [ 'https://media1.tenor.com/images/4d89d7f963b41a416ec8a55230dab31b/tenor.gif?itemid=5166500', 'https://media1.tenor.com/images/c7efda563983124a76d319813155bd8e/tenor.gif?itemid=15900664', 'https://media1.tenor.com/images/daffa3b7992a08767168614178cce7d6/tenor.gif?itemid=15249774', 'https://media1....
14,317
6,431
import numpy as np from numba import jit @jit def wilders_loop(data, n): """ Wilder's Moving Average Helper Loop Jit used to improve performance """ for i in range(n, len(data)): data[i] = (data[i-1] * (n-1) + data[i]) / n return data @jit def kama_loop(data, sc, n_er, length): ...
3,730
1,428
# Copyright (c) 2016 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 json import os import netlog_viewer_project import webapp2 from webapp2 import Route def _RelPathToUnixPath(p): return p.replace(os.sep, '/'...
1,441
491
# -*- coding: utf-8 -*- import json import os from crontab import CronTab from flask import Flask, request from pathlib import Path from pretty_cron import prettify_cron app = Flask(__name__) @app.route('/', methods=['GET']) def home(): return Path(app.root_path + '/index.html').read_text() @app.route('/create'...
3,991
1,225
""" Examples to demonstrate ops level randomization Author: Chip Huyen Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research" cs20si.stanford.edu """ import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import tensorflow as tf # Example 1: session is the thing that keeps track of random state c = tf.rand...
1,196
506
# -*- coding: utf-8 -*- ''' 通用工具类 ''' import time import MySQLdb import jieba import ast import random, sys # 日志类 import requests sys.setrecursionlimit(1000000) class Logger(object): def __init__(self, filename='default.log', stream=sys.stdout): self.terminal = stream self.log = open(filename, ...
5,651
2,755
#!/usr/bin/env python3 from numpy import* n, *a = map(int, open(0).read().split()) a = array(a) print(int(min(abs(cumsum(a)-(sum(a)/2)))*2))
140
64
import unittest try: from nose_parameterized import parameterized except: print("*** Please install 'nose_parameterized' to run these tests ***") exit(0) import oandapyV20.contrib.requests as req import oandapyV20.definitions.orders as OD import oandapyV20.types as types class TestContribRequests(unitt...
11,836
3,863
from kvaut.automator.custom_automator import CustomAutomator class JobItemAutomator(CustomAutomator): def is_match(self, value=None, **custom_attributes): if 'status' not in custom_attributes: return False project = self._target.project return value == project.name and custom...
371
98
import torch import torch.nn as nn import torch.nn.functional as F __all__ = ['NonLocalBlock', 'GCA_Channel', 'GCA_Element', 'AGCB_Element', 'AGCB_Patch', 'CPM'] class NonLocalBlock(nn.Module): def __init__(self, planes, reduce_ratio=8): super(NonLocalBlock, self).__init__() inter_planes = plan...
12,225
4,271
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import re import shutil from .builder import BuilderBase class CargoBuilder(BuilderBase): def __init...
17,315
5,023
from setuptools import setup, find_packages setup( name="GSimulator", packages=find_packages(exclude=['*test']), version="0.1.1", author="Eric Wong", description='This package allows user to \ simulate conductance of quantum wires', author_email='c.wing.wong.19@ucl.ac.uk', install_r...
500
167
# coding: utf-8 # In[4]: from keras.layers import Activation, Dense, Dropout from keras.layers.advanced_activations import LeakyReLU, PReLU, ThresholdedReLU, ELU from keras import regularizers # In[5]: def get_activation_layer(activation): """ Returns the activation layer given its name """ if a...
3,995
1,168
class Tournament: def __init__(self): # Dictionary of games played, scored, conceded, gd, points self.tables = {'A': {}, 'B': {}, 'C': {}, 'D': {}, 'E': {}, 'F': {}, 'G': {}, 'H':{}} self.groups_finished = False self.records = {} self.references = {} from parsers.utils import read_json self.r = read_js...
3,618
1,621
from typing import Union, Sequence import event _actions = {} """_actions = { 'action_name': { 'event1event2': { 'event1': ..., 'event2': ... } } }""" def addaction(name: str): if name not in _actions: _actions[name] = {} def rem...
4,905
1,509
import os from os.path import join, getsize from PIL import Image from tqdm import tqdm import numpy as np import argparse parser = argparse.ArgumentParser() parser.add_argument('--dataset_dir', type=str, help='dataset directory') parser.add_argument('--model', type=str, default='abc_0000', help='subdirectory containi...
1,604
569
from scan_the_code_classifier import ScanTheCodeClassifier
59
18
#!/usr/bin/env python3 """ Author : patarajarina Date : 2019-02-25 Purpose: Rock the Casbah """ import argparse import sys import os # -------------------------------------------------- def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Argparse Python sc...
2,959
880
#!/usr/bin/env python3 '''RFC 2131 DHCP message structures.''' # Copyright (c) 2018 Inocybe Technologies. # # 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/LICE...
4,251
1,297
# encoding utf-8 import os from dotenv import find_dotenv,load_dotenv from requests import session import logging #payload for login to kaggle payload = { 'action':'login', 'username': os.environ.get("KAGGLE_USERNAME"), 'password': os.environ.get("KAGGLE_PASSWORD") } def extract_data(url, file_path): ...
1,883
641
from django.contrib import admin from core.models import Country, State, Address admin.site.register(Country) admin.site.register(State) admin.site.register(Address)
168
48
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django_extensions.db.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("splash", "0005_auto_20150422_2236")] operations = [ migrations.AlterField( model_name="spl...
770
229
'''10. Write a Python program to get a string which is n (non-negative integer) copies of a given string. Tools: input function, slicing''' word = str(input("Type in any string or word: ")) n = int(input("Enter the number of repititions: ")) ans = "" for i in range(n): ans = ans + word print(ans)
314
102
#!/usr/bin/env python """ Hajos utilities. """ from util import * # Hajos Sum def hajosSum(G1, G2, x1, y1, x2, y2): G = [] for i in range(len(G1)): G.append(G1[i][:]) G[i].extend([0 for x in range(len(G2)-1)]) for i in range(len(G2)-1): G.append([0 for x in range(len(G1) + l...
19,245
6,771
i="meee" u="you" print(i," and ",u)
39
25
import unittest import bigcommerce.api from bigcommerce.connection import Connection, OAuthConnection from bigcommerce.resources import ApiResource from mock import MagicMock, patch, Mock class TestBigcommerceApi(unittest.TestCase): """ Test API client creation and helpers""" def test_create_basic(self): ...
2,085
607
"""Defines the Movie class""" import webbrowser class Movie(object): """This class provides a way to store movie related information.""" def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube, movie_release_date): self.title = movie_title sel...
638
193
# Generated by Django 3.2 on 2021-05-02 21:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('slalom', '0002_remove_trick_owner'), ] operations = [ migrations.AddField( model_name='trick', name='video1', ...
722
231
# encoding=utf8 import logging # 引入logging模块 from logging.handlers import TimedRotatingFileHandler from sync_conf import log_bese_path, log_backup_count, log_msg_level # 日志 logfile = log_bese_path + '/logs/' + 'binlog_sync.log' logger = logging.getLogger() logger.setLevel(log_msg_level) # 按日分割日志,默认日志保留7份 fh = Tim...
629
263
""" Copyright 2003 Mitsubishi Electric Research Laboratories All Rights Reserved. Permission to use, copy and modify this software and its documentation without fee for educational, research and non-profit purposes, is hereby granted, provided that the above copyright notice and the following...
12,208
4,240
# flake8: noqa from torch.nn.modules import * from .common import Flatten, GaussianNoise, Lambda, Normalize from .lama import LamaPooling, TemporalAttentionPooling, TemporalConcatPooling from .pooling import ( GlobalAttnPool2d, GlobalAvgAttnPool2d, GlobalAvgPool2d, GlobalConcatAttnPool2d, GlobalCon...
457
174
#!/usr/bin/env python3 # coding=utf-8 """ Strategy to eliminate redundant lines. - remove redundant lines - calculate the correct key for a given level """ NORMAL_COST_PER_POWERUP = { # level: [stardust, candy] 2.5: [ 200, 1], 4.5: [ 400, 1], 6.5: [ 600, 1], 8.5: [ 800, 1], 10.5: [ 1000, 1], 12.5:...
1,559
999
import PySimpleGUI as sg def build_login(): """ Construye la ventana del inicio de sesion del usuario""" layout =[[sg.T("Usuario", size=(8,1)), sg.InputText(key='-USER-')], [sg.T("Contraseña", size=(8,1)), sg.InputText(key='-PASS-')], [sg.Submit("LogIn", size=(15,1), pad=(0,15))], ...
516
189
# -*- coding: utf-8 -*- ''' Formatter class test ==================== ''' import unittest from tests.testutils import print_testtitle, validate_with_fail from builder.core import formatter as fm class FormatterTest(unittest.TestCase): @classmethod def setUpClass(cls): print_testtitle(fm.__name__, 'F...
446
138
from ._reliabili import reliability_analysis __all__ = [ "reliability_analysis", ]
86
30
from functools import singledispatch from pynasqm.trajectories.fluorescence import Fluorescence from pynasqm.trajectories.absorption import Absorption @singledispatch def get_reference_job(traj_data): raise NotImplementedError(f"traj_data type not supported by get_refer\n"\ f"{traj_da...
1,296
500
from ps2_census.enums import ResistType from ps2_analysis.enums import DamageTargetType from ps2_analysis.fire_groups.damage_profile import DamageLocation, DamageProfile def test_damage_delta(): dp: DamageProfile = DamageProfile( max_damage=100, max_damage_range=1234, min_damage=100, ...
6,283
2,666
#ModBUS Communication between Schneider EM6436 Meter and Raspberry Pi #First beta version. #The meter is set with the following settings #Communication : (RS484 to RS232 to USB) - BaudRate = 19200, Parity = N, Stopbits = 1, Device ID=1 (Hardcode in meter) #Electical Settings: APri:50, Asec: 5, VPri: 415, Vsec:415, SYS:...
5,418
1,993
from flask import Flask, render_template, json, request, redirect, session, jsonify from flaskext.mysql import MySQL from werkzeug import generate_password_hash, check_password_hash mysql = MySQL() app = Flask(__name__) # randomly generated encryption & decryption key, ensures security of a communications session app...
2,350
603
from django.db import models # Importamos o User do sistema para utilizar os dados dos usuários que registramos no admin do django # (desta forma não precisamos criar uma tabela específica no models para representar os usuários). from django.contrib.auth.models import User from datetime import datetime class Event...
1,359
437
def rolling_mean(data): return [take_rolling_mean(df) for df in data] def take_rolling_mean(df): window = 20 columns_to_take_rolling_mean = [ "pupil_diameter", "saccade_duration", "duration", "saccade_length", ] for column in columns_to_take_rolling_mean: df...
434
150
import json from datetime import datetime, timedelta from typing import Any import jwt from starlette.requests import Request from starlette.responses import JSONResponse from starlette.status import HTTP_403_FORBIDDEN from passlib.context import CryptContext from fastapi import Depends, Security, HTTPException from f...
2,264
722
def test_ex1(): import psi4 import numpy as np import resp # Initialize molecule mol = psi4.geometry(""" C 1.45051389 -0.06628932 0.00000000 H 1.75521613 -0.62865986 -0.87500146 H 1.75521613 -0.62865986 0.87500146 H 1.92173244 0.90485897 0.00000000 C -0....
2,577
1,172
''' Created on 09 Nov 2013 @author: michael ''' import json import urllib2 import urllib from django.conf import settings import facebook def validate_access_token(access_token): ''' Validate a Facebook access token ''' # Get an app access token app_token = facebook.get_app_access_token( ...
741
245
import db from pen import Pen from idea import Idea MIN_ENJOYMENT = 0.5 MIN_RELEVANT = 2 MAX_DEPTH = 3 MIN_ACCEPTABLE_SCORE = 0.5 def list_ideas(pen): ideas = db.load_all_ideas() # double link all relevant ideas for name, data in ideas.items(): for other_name, other_data in ideas.items(): ...
2,776
909
import datetime import pysc2.agents.myAgent.myAgent_6.config.config as config from pysc2.agents.myAgent.myAgent_6.decisionMaker.DQN import DQN import pysc2.agents.myAgent.myAgent_6.smart_actions as sa import pysc2.agents.myAgent.myAgent_6.tools.handcraft_function as handcraft_function from pysc2.env.environment impor...
6,988
2,063
# from sklearn.utils import shuffle # import util as ut # import os # import pandas as pd # import training_util as tut # import numpy as np # def sample_2000(): # file_paths, file_names, pose_type = ut.get_csvs_paths( # os.path.join("5-people-csvs")) # init = list.pop(file_paths) # ds = pd.read_...
2,064
820
# Copyright 2021 Google LLC. 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 a...
8,696
2,744
# python program to generate an assembly file which checks if mis-predictions # occur In addition to this, the GHR is also filled with ones (additional # test case) uses assembly macros from typing import Dict, List, Union, Any # To-Do -> Create another function which prints the includes and other # assembler directi...
5,675
1,843
# Generated by Django 2.1.5 on 2019-02-14 21:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account_request', '0001_initial'), ] operations = [ migrations.AlterField( model_name='accountrequest', name='divisi...
975
294
import datetime import scrapy from kingfisher_scrapy.base_spider import CompressedFileSpider from kingfisher_scrapy.util import components, handle_http_error class UruguayHistorical(CompressedFileSpider): """ Domain Agencia Reguladora de Compras Estatales (ARCE) Spider arguments from_date ...
2,017
630
import re class Convertor(): def __init__(self, tagslabels={}): self._tagslabels = tagslabels def _handleLabel(self, tag): if tag in self._tagslabels.keys(): return self._tagslabels[tag] return tag def _handleSingle(self, t): entities = [] index = 0 ...
1,136
375
import pydlbot_ui as Ui import sys from PyQt5 import QtGui, QtCore, QtWidgets from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import time import threading if __name__ == '__main__': p = threading.Thread(target=main) p.start() for i in range(3): t = th...
634
226
# -*- coding: utf-8 -*- """ The view of files module. """ from flask import Blueprint, request from src.modules.files.files import Files from src.utils.http_exception import BadRequestException blueprint = Blueprint('files-deprecated', __name__) files: Files = None def init_app(app): """ This will be called by...
6,832
2,330
"""Users views.""" # Django REST Framework from rest_framework.viewsets import GenericViewSet from rest_framework.mixins import (ListModelMixin, RetrieveModelMixin, UpdateModelMixin) from rest_framework import status from rest_framework.decorators i...
2,109
586
from __future__ import print_function from topologylayer.functional.persistence import SimplicialComplex, persistenceForwardCohom from topologylayer.util.process import remove_zero_bars import torch # first, we build our complex s = SimplicialComplex() # a cycle graph on vertices 1,2,3,4 # cone with vertex...
1,069
458
import rospy import threading import importlib from collections import deque from custom_msgs.msg import * def Subscriber(topic_name,type_str, window): #creates a subscriber for topic topic_name #using the class given as a string: type_str # in the form package_name/message_type # or in the form package_name.msg.mess...
4,020
1,184
import math import numpy as np import torch import torch.nn.functional as F from torch import nn from torch.utils.data import DataLoader, random_split from torch.utils.tensorboard import SummaryWriter import torchvision # from torchvision.models.detection.backbone_utils import resnet_fpn_backbone # from torchvision.o...
19,324
7,201
#!/usr/bin/python3 import zipfile from pwn import * # pip3 install pwn banner = """ ____ __ __ __ ____ _ ___ __ / __ )/ /___ _____/ /____ __ ____ ___ __/ /_____ / __ \ | / / | / / / __ / / __ \/ ___/ //_/ / / /_____/ __ `/ / / / __/ __ \/ /_/ ...
3,278
1,237
from django.conf import settings from django.utils import timezone from .base import default_config, numeric, lowercase_alphabetic, uppercase_alphabetic config = default_config config.update(settings.VERIFICATION) VERIFICATION_CODE_FIELD = 'verification_code' VERIFICATIONS = config.get('VERIFICATIONS') CODE_LENGTH = ...
1,621
623
import socket import fcntl import os import time import queue import logging import traceback from .controller import Controller, ControllerTypes from ..bluez import BlueZ from .protocol import ControllerProtocol from .input import InputParser from .utils import format_msg_controller, format_msg_switch class Control...
13,078
3,613
import frappe from datetime import datetime # bench execute mfi_customization.mfi.patch.set_first_responded_on_issue.execute def execute(): for d in frappe.get_all("Issue"): for tk in frappe.get_all("Task",{"issue": d.name}, ['attended_date_time', 'status']): if tk.attended_date_time: frappe.db.set_value("Is...
391
154
from __future__ import division, print_function, unicode_literals import cocos.euclid as eu import unittest import copy try: import cPickle as pickle except Exception: import pickle import io class Test_Vector2(unittest.TestCase): def test_instantiate(self): xy = (1.0, 2.0) v2 = eu.Vector...
12,144
5,113
#!/usr/local/bin/python3 import sys from multiprocessing import Pool from timeit import default_timer as timer from config import Config from cgp.functionset import FunctionSet from cgp.genome import Genome import numpy as np import numpy.random from random import randint from tetris_learning_environment import E...
3,769
1,277
#!/usr/bin/env python2 import sys sys.path.append('../../../src/') import cgmap as cg import mdtraj as md import md_check as check ############################### config ##################################### input_traj = "protein.trr" input_top = "protein.pdb" output_traj = "protein.trr" output_top = "protein.pdb...
3,175
1,099
# -*- coding: utf-8 -*- # Function that loads a checkpoint and rebuilds the model import torch from torch import nn from collections import OrderedDict from torchvision import datasets, transforms, models def save_checkpoint(model, checkpoint_path, output_categories): ''' Save the trained deep...
3,726
1,104
import copy import torch from torch import nn from torch.utils.data import DataLoader from torchtext.data import Batch def averge_models(models, device=None): final_model = copy.deepcopy(models[0]) if device: models = [model.to(device) for model in models] final_model = final_model.to(device) averaged_paramete...
7,689
2,923
from django.shortcuts import redirect, render from django.views.generic import TemplateView class SignUpView(TemplateView): template_name = 'registration/signup.html' #homePage def home(request): if request.user.is_authenticated: if request.user.is_teacher: return redirect('teachers:my_jo...
525
164
from .rank_and_validate import BootstrappedRankAndValidate __all__ = ["BootstrappedRankAndValidate"]
102
34
from os import read import sys import pegtree as pg import csv from pegtree.optimizer import optimize peg = pg.grammar('yk.tpeg') parse = pg.generate(peg) VAR_literal = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' NAME_literal = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ' VAL_literal = 'abcdefgh...
6,119
2,029
country=["Brazil","Russia","India","China","South Africa"] capitals={"Brazil":"Brasilia","Russia":"Moscow","India":"New Delhi", "China":"Beijing","South Africa":["Pretoria","Cape Town","Bloemfontein"]} print(country) print(capitals) print(capitals["South Africa"][1])
270
107
import math import os from PyQt5 import QtCore from PyQt5.QtWidgets import QGridLayout, QLabel, QPushButton, QFrame, QTextEdit, QInputDialog, QSizePolicy, QAction, QMessageBox from Core.DieClock import DieClock from Core.WildernessTravelManager import WildernessTravelManager from Interface.Widgets.LineEditMouseWheelE...
17,501
5,355