text
string
size
int64
token_count
int64
import json import os import numpy as np from numpy import genfromtxt SECOND_TO_MILLIS = 1000 SECOND_TO_MICROS = 1000000 SECOND_TO_NANOS = 1000000000 TIME_UNIT_TO_DECIMALS = {'s': 0, "ms": 3, "us": 6, "ns": 9} def parse_time(timestamp_str, time_unit): """ convert a timestamp string to a rospy time if a ...
6,426
2,171
from app import db # Junction Tables for many-to-many relationships campaign_users = db.Table('campaign_users', db.Column('campaign', db.Integer, db.ForeignKey('campaigns.id'), primary_key=True), db.Column('user', db.Integer, db.ForeignKey('users.username'), primary_key=True), ) campaign_vehicles = db.Table('...
7,160
2,314
from typing import List from django.shortcuts import render from django.views.generic.detail import DetailView from django.views.generic.list import ListView from assignment.models import Assignment from course.models import Course class CourseListView(ListView): template_name = 'course/course_list.html' model...
806
236
from django.apps import AppConfig class AldrynSearchConfig(AppConfig): name = 'aldryn_search' def ready(self): from . import conf # noqa
157
51
from datetime import datetime def strip_value(data, *path): element = path[0] value = data.get(element) if len(path) == 1: data[element] = "__STRIPPED__" return value else: if isinstance(value, dict): return strip_value(value, *path[1:]) elif isinstance(valu...
606
189
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None #Binary Tree class BinaryTree(object): def __init__(self, root): self.root = Node(root) def search(self, find_val): """Return True if the value is in the tre...
3,077
864
__source__ = 'https://leetcode.com/problems/stone-game/' # Time: O() # Space: O() # # Description: Leetcode # 877. Stone Game # # Alex and Lee play a game with piles of stones. # There are an even number of piles arranged in a row, # and each pile has a positive integer number of stones piles[i]. # # The objective of ...
4,203
1,472
from django.apps import AppConfig class SponsorshipsAppConfig(AppConfig): name = 'project_pawz.sponsorships' verbose_name = "Sponsorships"
149
51
import re only_letters = re.compile("[a-zA-Z]") def is_all_upper(text: str) -> bool: # check if text has actual content has_no_content = len(only_letters.findall(text)) == 0 return False if has_no_content else text.upper() == text if __name__ == '__main__': print("Example:") print(is_all_upper(...
745
254
# sudo scrapy runspider GeoFabrikSpider.py import scrapy import os import urlparse from scrapy.selector import Selector import subprocess from time import sleep class GeoFabrikSpider(scrapy.Spider): name = "geofabrik_spider" start_urls = ['https://download.geofabrik.de/'] def parse(self, response): ...
1,661
478
# Copyright (c) 2010, Mats Kindahl, Charles Bell, and Lars Thalmann # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # ...
3,252
1,067
def iterative_levenshtein(string, target, costs=(1, 1, 1)): """ piglaker modified version : return edits iterative_levenshtein(s, t) -> ldist ldist is the Levenshtein distance between the strings s and t. For all i and j, dist[i,j] will contain the Levenshtein...
2,348
726
from ._loggo2 import JsonLogFormatter, LocalLogFormatter, Loggo # noqa: F401 __version__ = "10.1.2" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
168
69
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of Advent of Code 2020 # https://github.com/scorphus/advent-of-code-2020 # Licensed under the BSD-3-Clause license: # https://opensource.org/licenses/BSD-3-Clause # Copyright (c) 2020, Pablo S. Blum de Aguiar <scorphus@gmail.com> from aoc import strip...
1,762
633
# coding=utf-8 import matplotlib.pyplot as plt import numpy as np if __name__ == '__main__': rows = [10000] col = 10000 iteration = 10 params = [ {'id': '01', 'strategy': 'rep', 'p': 10, 'repNum': 1}, {'id': '02', 'strategy': 'rep', 'p': 10, 'repNum': 2}, {'id': '03', 'strategy'...
3,349
1,457
#!/usr/bin/env python import sys, time from backend import daemon import itchat import time from ipcqueue import posixmq import logging import datetime as dt import threading import time logFileDir = "/opt/crontab/IpcToItchat/" nowDateTime = dt.datetime.now().strftime('%Y%m%d%H%M%S') pyFilename = sys.argv[0].split('/...
2,077
704
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """mlbgame functions for the people API endpoints. This module's functions gets the JSON payloads for the mlb.com games API endpoints. .. _Google Python Style Guide: http://google.github.io/styleguide/pyguide.html """ from mlbgame.data import request def get_person...
3,979
1,061
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import csv import getopt import io import itertools import logging import numbers import os import re import sqlite3 import string import sys import textwrap import time try: import readline except ImportError: pass try: ...
25,571
6,827
""" Definition of an :class:`~django_analyses.filters.output.output_definition.OutputDefinitionFilter` for the :class:`~django_analyses.models.output.definitions.OutputDefinition` model. """ from django_analyses.models.output.definitions.output_definition import \ OutputDefinition from django_filters import rest_f...
726
198
from django.apps import AppConfig class MypageConfig(AppConfig): name = 'mypage'
87
29
import psycopg2 class Additional(object): @staticmethod def findExistRow(connection, tableName): cursor = connection.cursor() cursor.execute("""SELECT "{}Id" FROM public."{}" OFFSET floor(random()) LIMIT 1;""" .format(tableName, tableName)) value = cursor.fetcha...
3,225
935
""" Created on Mar 12, 2018 @author: SirIsaacNeutron """ import tkinter import tkinter.messagebox import hanoi DEFAULT_FONT = ('Helvetica', 14) class DiskDialog: """A dialog window meant to get the number of Disks per Tower for the Tower of Hanoi puzzle. """ def __init__(self): self._dialog...
12,008
3,621
import email, json, os, re import magic import ssdeep import hashlib import datetime def md5(fname): hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def sha1(fname): hash_sha1 = ...
4,801
1,624
#!/usr/bin/env python """Create edges and nodes from a list of sequences that are a given hamming distance apart""" import itertools import sys import operator import numpy as np import argparse from general_seq import conv from general_seq import seq_IO from plot import conv as pconv import matplotlib.pyplot as plt i...
5,937
2,345
import os import pickle from Utils import DirectoryUtils, IOUtils, LoggingUtils # Write to the disk the structure such that will be # persistent. from Utils.FilesUtils import readConfigFile def writePersistentStructure(filename, structure): try: writeSerializer = open(filename, "wb") pickle.dum...
1,664
491
"""Module :mod:`perslay.utils` provide utils functions.""" # Authors: Mathieu Carriere <mathieu.carriere3@gmail.com> # Theo Lacombe <theo.lacombe@inria.fr> # Martin Royer <martin.royer@inria.fr> # License: MIT from __future__ import absolute_import from __future__ import division from __future__ impo...
5,046
2,004
# TODO: this may want to move to Invoke if we can find a use for it there too? # Or make it _more_ narrowly focused and stay here? class NothingToDo(Exception): pass class GroupException(Exception): """ Lightweight exception wrapper for `.GroupResult` when one contains errors. .. versionadded:: 2.0 ...
389
110
import matplotlib.pyplot as plt import numpy as np from flatland.core.grid.grid4_utils import get_new_position from flatland.envs.agent_utils import TrainState from flatland.utils.rendertools import RenderTool, AgentRenderVariant from utils.fast_methods import fast_count_nonzero, fast_argmax class AgentCanChooseHelp...
20,183
5,656
from flask import request from flask_restful import Resource from flask_jwt_extended import get_jwt_claims, get_jwt_identity, jwt_required from app.cache import redis_client
182
61
#!/usr/bin/env python3 import tuxedo as t if __name__ == '__main__': buf = {'TA_CLASS': ['T_SVCGRP'], 'TA_OPERATION': ['GET']} assert t.tpimport(t.tpexport(buf)) == buf assert t.tpimport(t.tpexport(buf, t.TPEX_STRING), t.TPEX_STRING) == buf assert t.Fname32(t.Fldid32('TA_OPERATION')) == 'TA_OPERATIO...
1,792
926
from rest_framework import serializers from ..models import Term, Meaning, Comment, Example class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' # class TranslatorsChatSerializer(serializers.ModelSerializer): # class Meta: # model = Tra...
1,746
494
def tail(xs): """ Напишете функция в Python, която взима списък и връща нов списък, който се състои от всички елементи **без първия** от първоначалния списъка. **Не се грижете, ако списъка е празен** >>> tail([1, 2, 3]) [2, 3] >>> tail(["Python"]) [] """ pass
302
138
#!/usr/bin/python import re from itertools import cycle from collections import namedtuple, defaultdict, OrderedDict import boto3 from ansible.module_utils.basic import AnsibleModule # import logging # boto3.set_stream_logger('', logging.DEBUG) HostInfo = namedtuple('HostInfo', 'tag_id public_ip user') InstancePara...
12,094
3,681
""" Copyright 2012-2019 Ministerie van Sociale Zaken en Werkgelegenheid 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...
20,289
5,610
#!/usr/bin/env python # Copyright (c) 2020 Janky <box@janky.tech> # All right reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # ...
3,564
1,144
from __future__ import absolute_import from django.conf.urls import url from django.contrib.auth.decorators import login_required from . import views urlpatterns = [ url(r'^swagger.json/$',views.swagger_json_api), url(r'^swagger/$', login_required(views.swagger)), url(r'charts/$', login_required(views.Char...
970
363
# # jomiel-kore # # Copyright # 2019-2020 Toni Gündoğdu # # # SPDX-License-Identifier: Apache-2.0 # """TODO.""" try: # py38+ from importlib.metadata import version as metadata_version from importlib.metadata import PackageNotFoundError except ModuleNotFoundError: from importlib_metadata import version as...
1,023
312
import logging import numpy as np from gunpowder.nodes.batch_filter import BatchFilter logger = logging.getLogger(__name__) class TanhSaturate(BatchFilter): '''Saturate the values of an array to be floats between -1 and 1 by applying the tanh function. Args: array (:class:`ArrayKey`): ...
883
261
import os from django.conf import settings from django.http.response import HttpResponse from django.shortcuts import get_object_or_404 from rest_framework.generics import ListAPIView, RetrieveUpdateAPIView, RetrieveAPIView from rest_framework.pagination import PageNumberPagination from rest_framework.authentication im...
2,497
708
import requests, json, time, random, datetime, threading, pickle from termcolor import colored sitekey = "6Ld-VBsUAAAAABeqZuOqiQmZ-1WAMVeTKjdq2-bJ" def log(event): d = datetime.datetime.now().strftime("%H:%M:%S") print("Raffle OFF-S by Azerpas :: " + str(d) + " :: " + event) class Raffle(object): def __init__(...
3,542
1,659
class Button(object): def __init__(self, url, label, get=''): self.url = url self.label = label self.get = get
142
47
from sys import platform if 'win' in platform: from .winreg import * elif 'linux' in platform: from posixreg import * import posixreg posixreg.__init__()
163
54
""" Core functionality for feature computation Lukas Adamowicz Copyright (c) 2021. Pfizer Inc. All rights reserved. """ from abc import ABC, abstractmethod from collections.abc import Iterator, Sequence import json from warnings import warn from pandas import DataFrame from numpy import float_, asarray, zeros, sum, m...
13,956
4,638
# Copyright 2017 AT&T Intellectual Property. All other 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...
4,013
1,360
import logging import lccv import numpy as np import sklearn.datasets from sklearn import * import unittest from parameterized import parameterized import itertools as it import time from sklearn.experimental import enable_hist_gradient_boosting # noqa import openml import pandas as pd def get_dataset(openmlid): ...
17,650
6,027
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2013 The Plaso Project Authors. # Please see the AUTHORS file for details on individual 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 L...
4,099
1,404
class Solution: def getFormattedEMail(self, email): userName, domain = email.split('@') if '+' in userName: userName = userName.split('+')[0] if '.' in userName: userName = ''.join(userName.split('.')) return userName + '@' + domain def numUniqueEmail...
496
150
import random from grid import Grid from grid import Cell class Prim(): def grid_to_list(self, grid): """ Place all cells from grid matrix into a list :param grid: a Grid object :return: a list of all cells contained in the grid """ list = [] for r in range(g...
1,175
333
# This file implements file system operations at the level of inodes. import time import secfs.crypto import secfs.tables import secfs.access import secfs.store.tree import secfs.store.block from secfs.store.inode import Inode from secfs.store.tree import Directory from cryptography.fernet import Fernet from secfs.typ...
14,065
4,672
from __future__ import division import io import matplotlib as mpl import matplotlib.pyplot as plt import networkx as nx import numpy import os import tensorflow as tf def figure_to_buff(figure): """Converts the matplotlib plot specified by 'figure' to a PNG image and returns it. The supplied figure is closed a...
3,355
970
class SendResult: def __init__(self, result={}): self.successful = result.get('code', None) == '200' self.message_id = result.get('message_id', None)
160
57
from typing import Type from letsdoit.lib.core import * class SearchSublist3r: def __init__(self, word): self.word = word self.totalhosts = list self.proxy = False async def do_search(self): url = f'https://api.sublist3r.com/search.php?domain={self.word}' response = a...
610
189
from spinnman.messages.eieio.eieio_type import EIEIOType from spinnman.messages.eieio.data_messages.eieio_with_payload_data_message\ import EIEIOWithPayloadDataMessage from spinnman.messages.eieio.data_messages.eieio_data_header\ import EIEIODataHeader from spinnman.messages.eieio.data_messages.eieio_data_messa...
959
317
from .GlobalData import global_data from .utils.oc import oc import requests import time import logging class App: def __init__(self, deployment, project, template, build_config,route=""): self.project = project self.template = template self.deployment = deployment self.build_conf...
4,505
1,357
import cv2 import numpy as np from keras.models import load_model bg = None def run_avg(image, acc_weight): global bg if bg is None: bg = image.copy().astype("float") return cv2.accumulateWeighted(image, bg, acc_weight) def segment(image, threshold=10): global bg diff = cv2.absdif...
4,463
1,478
#!/usr/bin/env python from __future__ import unicode_literals import os import sys import tarfile import shutil import tempfile from contextlib import contextmanager from pymatgen.io.gaussian import GaussianInput, GaussianOutput from tinydb import TinyDB @contextmanager def cd(run_path, cleanup=lambda: True): ...
4,829
1,620
# coding: utf-8 # ************************ # SHAPE STUFF # ************************ import ctypes from pyglet.gl import * from .globs import * from .constants import * from .pvector import * from .primitives import _smoothFixHackBegin, _smoothFixHackEnd from math import * __all__ = ['beginShape', 'vertex', 'normal...
14,007
4,790
'''This module implements the USB transport layer for PTP. It exports the PTPUSB class. Both the transport layer and the basic PTP implementation are Vendor agnostic. Vendor extensions should extend these to support more operations. ''' from __future__ import absolute_import import atexit import logging import usb.cor...
22,531
5,808
import re from operator import itemgetter from django.conf import settings from django.utils import simplejson from django.db import models from nltk.tokenize.simple import SpaceTokenizer from nltk.stem import LancasterStemmer WORDS_IGNORED = ( 'after', 'that', 'with', 'which', 'into', 'when', 'than', 'them', 't...
4,598
1,416
from Fs.Xci import Xci from Fs.pXci import uXci from Fs.pXci import nXci from Fs.Nca import Nca from Fs.Nsp import Nsp from Fs.Rom import Rom from Fs.Nacp import Nacp from Fs.Pfs0 import Pfs0 from Fs.Hfs0 import Hfs0 from Fs.Ticket import Ticket from Fs.File import File def factory(name): if name.endswith('.xci'): ...
618
282
# -*- coding: utf-8 -*- """ Created on Wed Jan 3 10:27:50 2018 @author: James Jiang """ all_lines = [line.rstrip('\n') for line in open('Data.txt')] def has_two_pairs(string): for i in range(len(string) - 1): pair = string[i:i + 2] if (pair in string[:i]) or (pair in string[i + 2:]): ...
808
295
import asyncio, discord, json from discord.ext.commands import Bot from discord.ext import commands from tinydb import TinyDB, Query from tinydb.operations import delete, increment ''' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - SETUP - - - - - - - - - - - - - - - - - - - - - - - - - - - - -...
4,708
1,532
import appdaemon.plugins.hass.hassapi as hass import datetime import globals # # App which turns on the light based on the room the user is currently in # # # Args: # room_sensor: the sensor which shows the room the user is in. example: sensor.mqtt_room_user_one # entity: The entity which gets turned on by alexa/snips....
2,080
658
#!/usr/bin/env python ''' Calculating the emissions from deposits in Platypus stable accounts ''' import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, EngFormatter, PercentFormatter from strategy_const import * from const import * def boosted_pool_...
4,074
1,460
""" @date 30.08.2019 @author Anna.Shavrina@acronis.com @details :copyright: 2003–2019 Acronis International GmbH, Rheinweg 9, 8200 Schaffhausen, Switzerland. All rights reserved. """ from ManagementAPI.ManagementClient.how_to_create_client import create_client from ManagementAPI.ManagementClient.how_to_delete_client ...
1,477
467
#!/usr/bin/env python3 import os, sys, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) parentdir = os.path.dirname(parentdir) sys.path.insert(0, parentdir) import unittest import datetime from datetime import date from src.holide i...
6,276
2,137
import pkgutil import sys from argparse import ArgumentParser from importlib import import_module from typing import Any, List, Type from datastore.migrations import BaseMigration, MigrationException, PrintFunction, setup class BadMigrationModule(MigrationException): pass class InvalidMigrationCommand(Migratio...
4,705
1,300
from types import FunctionType import numpy as np import pandas as pd from functools import partial from multiprocessing import Pool, cpu_count def get_levenshtein_distance(str1: str, str2: str) -> float: """ Computes the Levenshtein distance between two strings :param str1: first string :param str...
2,221
728
import requests_cache import os.path import tempfile try: from requests_cache import remove_expired_responses except ModuleNotFoundError: from requests_cache.core import remove_expired_responses def caching( cache=False, name=None, backend="sqlite", expire_after=86400, allowable_codes=(200...
3,540
1,088
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception """Facility for symbolically referencing type variables. Type variables are instances of the TypeVar class, which is u...
1,441
504
import os, sys exp_id=[ "exp1.0", ] env_source=[ "file", ] exp_mode = [ "continuous", #"newb", #"base", ] num_theories_init=[ 4, ] pred_nets_neurons=[ 8, ] pred_nets_activation=[ "linear", # "leakyRelu", ] domain_net_neurons=[ 8, ] domain_pred_mode=[ "onehot", ] mse_amp=[ 1e-7, ] simplify_criteria=[ '\("DLs",...
2,867
1,319
# To ensure fairness, we use the same code in LDAM (https://github.com/kaidic/LDAM-DRW) to produce long-tailed CIFAR datasets. import torchvision import torchvision.transforms as transforms import numpy as np from PIL import Image import random import os import cv2 import time import json import copy from utils.utils ...
10,304
3,527
import os import errno import stat import logging from io import BytesIO from time import time, mktime, strptime from fuse import FuseOSError, Operations, LoggingMixIn logger = logging.getLogger('dochub_fs') def wrap_errno(func): """ @brief Transform Exceptions happening inside func into meaningful ...
6,428
2,025
# Generated by Django 2.1.4 on 2019-01-10 04:07 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('algolab_class_API', '0010_submithistory'), ] operations = [ migrations.Rem...
2,239
708
""" Python wrapper for the Spider API """ from __future__ import annotations import json import logging import time from datetime import datetime, timedelta from typing import Any, Dict, ValuesView from urllib.parse import unquote import requests from spiderpy.devices.powerplug import SpiderPowerPlug from spiderpy.d...
11,266
3,249
""" Persister module contains part of the http-nudger which consumes records from Kafka and stores them into the database """ import json import logging from pathlib import Path from typing import List import aiokafka import asyncpg from .helpers import create_kafka_consumer, create_postgres_connection_pool from .url...
3,548
1,012
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Liblzf(AutotoolsPackage): """LibLZF is a very small data compression library. It cons...
724
291
from __future__ import absolute_import, division, print_function import unittest import numpy as np from numpy.testing import assert_array_equal, assert_allclose from dynd import nd, ndt import blaze import unittest import tempfile import os, os.path import glob import shutil import blaze # Useful superclass for ...
15,565
5,664
import torch import torch.nn as nn from torch3d.nn import SetAbstraction class PointNetSSG(nn.Module): """ PointNet++ single-scale grouping architecture from the `"PointNet++: Deep Hierarchical Feature Learning on Point Sets in a Metric Space" <https://arxiv.org/abs/1706.02413>`_ paper. Args: in_...
1,457
591
import unittest.mock as mock import pytest from brainstorm.scripts import engine from brainstorm.games import calc # def test_player_ready(monkeypatch): # with monkeypatch.context() as m: # m.setattr('builtins.input', lambda prompt="": "y") # result = engine.player_ready() # assert result is ...
325
101
#1 celsius=float(input("请输入一个摄氏度:>>")) fahrenheit=(9 / 5) *celsius + 32 print("华氏温度为:%.1f" % fahrenheit) #2 radius=float(input("请输入圆柱体的半径:>>")) length=float(input("请输入圆柱体的高:>>")) area= radius*radius*3.14159265 volume=area*length print("The area is %.4f" % area ) print("The volume is %.1f" % volume) #...
1,328
771
"""Implementation for bot classes.""" import asyncio from dataclasses import InitVar, field from typing import Any, Callable, Dict, List from weakref import WeakSet from loguru import logger from pydantic.dataclasses import dataclass from botx import concurrency, exception_handlers, exceptions, shared, typing from b...
5,595
1,502
#!/usr/bin/python3 import argparse import json import os import subprocess class OrkaAnsibleInventory: def __init__(self): self.vm_data = None self.filtered_data = None self.inventory = { 'group': {'hosts': []}, 'vars': [], '_meta': { '...
4,242
1,332
import boto3 import datetime import requests import pytest from unittest.mock import patch from reports.reporting import release_summary from collections import Counter from functools import partial ENTITIES = [ 'participants', 'biospecimens', 'phenotypes', 'genomic-files', 'study-files', 'rea...
8,647
3,131
# Django Library from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django.utils.translation import ugettext_lazy as _ # Thirdparty Library from apps.base.models import PyFather # Tabla de Empleados class PyEmployee(PyFather): name = models.CharField('No...
875
281
from django.apps import AppConfig class PlayersConfig(AppConfig): name = 'players'
89
28
import os import signal import atexit import json import time from pathlib import Path import subprocess import argparse import pprint from distutils.util import strtobool children_pid = [] @atexit.register def kill_child(): for child_pid in children_pid: os.kill(child_pid, signal.SIGTERM) cmd_parser = ...
8,063
2,387
######################################################## # Copyright (c) 2015-2017 by European Commission. # # All Rights Reserved. # ######################################################## extends("BaseKPI.py") """ Transmission usage (%) ---------------------- Indexed by * sco...
2,410
694
# Generated by Django 2.0.3 on 2018-05-05 17:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bloguser', '0002_auto_20180504_1808'), ] operations = [ migrations.AddField( model_name='userprofile', name='image_u...
672
230
# -*- coding: utf-8 -*- import os import datetime import logging import requests import numpy import cv2 import zbar from Queue import Queue from threading import Thread from PIL import Image logger = logging.getLogger(__name__) TEMP_DIR = os.path.join(os.getcwd(), 'temp') def get_temp_dir(): """Create TEMP_DIR ...
10,808
3,176
import graphene from django.db import transaction from graphene import InputObjectType, Mutation, Field, ObjectType from graphene_django.types import DjangoObjectType from graphql_jwt.decorators import login_required from rescape_graphene import REQUIRE, graphql_update_or_create, graphql_query, guess_update_or_create, ...
4,495
1,274
# DO NOT CHANGE THIS FILE! This file is auto-generated by facade.py. # Changes will be overwritten/lost when the file is regenerated. from juju.client.facade import Type, ReturnMapping from juju.client._definitions import * class ApplicationFacade(Type): name = 'Application' version = 8 schema = {'de...
72,977
14,640
import sys from .config import Configurable, Directive, commit, create_code_info class Config: """The object that contains the configurations. The configurations are specified by the :attr:`Action.config` class attribute of :class:`Action`. """ pass class AppMeta(type): """Dectate metaclas...
4,637
1,242
from collections import OrderedDict from django.contrib.auth import get_user_model # If used custom user model from rest_framework import serializers UserModel = get_user_model() class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated...
1,127
302
import pytest import torch.nn as nn from numpy.testing import assert_allclose from receptivefield.pytorch import PytorchReceptiveField from receptivefield.image import get_default_image from receptivefield.types import ImageShape class Linear(nn.Module): """An identity activation function""" def forward(self...
2,542
938
#!/usr/bin/env python3 import typing from .utils import ClassDictMeta from .issueParser import * from .linter import * from miniGHAPI.GitHubAPI import * from miniGHAPI.GHActionsEnv import *
192
62
import sys if len(sys.argv) != 4 : print 'usage:', sys.argv[0], 'index_fn id_mapping_fn output_fn' exit(9) a = open(sys.argv[1]) a.readline() header = a.readline() dir = a.readline() #build map: filename -> set of bad samples mp = {} mp_good = {} mp_bad = {} for line in a : t = line.split() mp[t[0]] = set() ...
831
381
import json from app import utils def test_add_user(test_app, test_database): client = test_app.test_client() response = client.post( "/users", data=json.dumps( {"username": "onlinejudge95", "email": "onlinejudge95@gmail.com",} ), content_type="application/json", ...
7,147
2,401
from threading import * from tkinter import * from tkinter.filedialog import askopenfilename import tkinter, tkinter.scrolledtext import os import sys import urllib.request import glob import time import hashlib import quarantaene from vta import vtapi import argparse os_name = sys.platform terminations = [] if "win"...
15,814
5,392
import tensorflow as tf import numpy as np import os import time from utils import random_batch, normalize, similarity, loss_cal, optim from configuration import get_config from tensorflow.contrib import rnn config = get_config() def train(path): tf.reset_default_graph() # reset graph # dra...
8,421
2,805