text string | size int64 | token_count int64 |
|---|---|---|
"""Pre-process accessibility-based provincial OD matrix
Purpose
-------
Create province scale OD matrices between roads connecting villages to nearest communes:
- Net revenue estimates of commune villages
- IFPRI crop data at 1km resolution
Input data requirements
-----------------------
1. Correct paths to... | 23,748 | 7,514 |
import argparse
from datetime import datetime
import os
import torch.nn as nn
import torch.optim as optim
import torch.optim.lr_scheduler as sched
from pytorch_lightning import Trainer
from pytorch_lightning.loggers import TensorBoardLogger as tb
from module import LyftModule
from net import LyftNet
from dataset impo... | 2,478 | 846 |
from Model.deck import Deck
class Hand:
"""
Attributes:
_cards: list BlackjackCard
name: str
"""
def __init__(self, name="", *cards):
"""
Args:
name:
*cards:
"""
self._cards = list(cards)
self.name = name
class Blackjac... | 1,319 | 418 |
"""
Example Read recirpocal space cuts from CrysAlisPro
"""
import sys, os
import re
import numpy as np
import matplotlib.pyplot as plt
cf = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(cf, '..'))
import Dans_Diffraction as dif
print(dif.version_info())
def read_image(filename, resolution=0.8):
""... | 2,459 | 1,113 |
# Lint as: python3
# Copyright 2019 Google LLC
#
#
# 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 ag... | 4,339 | 1,356 |
from os import getenv
import traceback
import random
import discord
PREFIX = "yz "
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
async def on_message(self, message):
# we do not want the bot to reply ... | 948 | 321 |
from .base import Package
class DHL(Package):
barcode_pattern = r'^\d{10}$'
shipper = 'DHL'
@property
def valid_checksum(self):
chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1]
return int(chars) % 7 == int(check_digit)
| 278 | 102 |
import time
import traceback
from IocManager import IocManager
from datetime import datetime
from domain.operation.execution.services.OperationExecution import OperationExecution
from domain.operation.services.DataOperationJobService import DataOperationJobService
from infrastructor.data.RepositoryProvider import Rep... | 3,878 | 1,074 |
def thesaurus(*args, bool=True) -> dict:
if bool:
args = sorted(list(args))
dict_out = {}
for words in args:
dict_value = dict_out.setdefault(words[0], list())
if words not in dict_value:
dict_value.append(words)
dict_out[words[0]] = dict_value
... | 404 | 153 |
from .run import RunCommand
| 28 | 8 |
from django.core.management.base import BaseCommand
from django.conf import settings
from django.contrib.auth.models import User
from ...models import OBC_user
class Command(BaseCommand):
help = 'Delete all users.'
def handle(self, *args, **options):
print (User.objects.all().delete())
print... | 430 | 122 |
"""
Boiled down version of SAVP model from https://github.com/alexlee-gk/video_prediction
"""
from robonet.video_prediction.models.base_model import BaseModel
from robonet.video_prediction.utils import tf_utils
import tensorflow as tf
from collections import OrderedDict
from robonet.video_prediction import losses
from ... | 12,886 | 4,207 |
import unittest
from pysapets.elephant import Elephant
from pysapets.animal import Animal
import pysapets.constants as constants
from unittest.mock import patch
from io import StringIO
from copy import deepcopy
class ElephantTest(unittest.TestCase):
def setUp(self):
self.elephant = Elephant()
self.friends ... | 2,145 | 755 |
# -*- coding: utf-8
# Checkcase class implementation.
"""Checkcase class implementation.
There is three kinds of ways to fail a check:
- Warning: Generate a warning message but do not count as an error.
- Error: Generate an error message and count as an error.
- Failure: Generate a failure message and stop the run... | 6,013 | 1,485 |
import os, sys
import numpy as np
import imageio
import json
import random
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm, trange
import matplotlib.pyplot as plt
from models.sampler import StratifiedSampler, Import... | 8,200 | 2,800 |
def independence():
# Simply check that base can be imported.
import base
print "independence: ok"
| 113 | 34 |
#######################################
# School of Software Technology #
# Dalian University of Technology #
# yang lifan #
# 2862506026@qq.com #
#######################################
import numpy as np
import pandas as pd
df = pd.read_excel(r"lol\data\f... | 1,970 | 1,034 |
import torch
from meshcnn.models.layers import mesh_conv
class MeshConv(mesh_conv.MeshConv):
def create_GeMM(self, x, Gi):
Gishape = Gi.shape
# pad the first row of every sample in batch with zeros
padding = torch.zeros((x.shape[0], x.shape[1], 1), requires_grad=True, device=x.device)
... | 1,116 | 467 |
import math
import warnings
from typing import List
from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
class LinearWarmupCosineAnnealingLR(_LRScheduler):
def __init__(
self,
optimizer: Optimizer,
warmup_epochs: int,
max_epochs: int,
warmup_... | 3,389 | 1,150 |
from typing import Tuple
from compiler.errors.errors import FEOLError, FParsingError, FEOFError
from compiler.lexer.tokens import *
from compiler.lexer.readers import Reader
class Lexer:
def __init__(self, reader: Reader):
self.reader = reader
def lex_identifier(self) -> str:
"""Grab an iden... | 4,305 | 1,084 |
from dataservice.api.outcome.resources import OutcomeAPI
from dataservice.api.outcome.resources import OutcomeListAPI
| 118 | 34 |
import os
import time
import json
import datetime
import threading
import math
import re
import collections
import serial
import serial.tools.list_ports
from .ntrip_client import NTRIPClient
from ...framework.utils import (
helper, resource
)
from ...framework.context import APP_CONTEXT
from ..base.provider_base im... | 36,093 | 10,554 |
from typing import List
from itertools import product
import random
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
# s1 inmitate std practice
# nums = list(range(1,n+1))
# res = self.combinations(nums, k)
# return list(res)
# s2 DFS
# nums = l... | 2,250 | 758 |
import cv2
import numpy as np
class Image_Detector:
""" Detector class for performing
1) resizing to required image size
2) Perform inference on a new image using the trained network
Args:
label_dict: Dictionary of class_id mapped to class_names
frozen_graph: Tensorflow frozen graph of... | 4,082 | 1,220 |
from ...languages.datalog.minimal_models import MinimalModels
from parsers.datalog.datalog_solvers_parser import DatalogSolversParser
class IDLVMinimalModels(MinimalModels):
"""Represents IDLV's minimal models."""
def __init__(self, out, err=None):
super(IDLVMinimalModels, self).__init__(out, err)
... | 407 | 134 |
class Solution(object):
def findMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
pos = {0: -1}
v = 0
ans = 0
for i, n in enumerate(nums):
v += n * 2 - 1
if v in pos:
ans = max(ans, i - pos[v])
... | 381 | 125 |
# Copyright (c) 2009-2014 Simon Kennedy <sffjunkie+code@gmail.com>
#
# 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 a... | 1,548 | 556 |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 29 23:25:47 2015
Data incubator challenge question
"predicting power usage for new home owners" version 1.0
based on 2010 usage and weather data in Chicago
@author: Sangkyu Lee
"""
import pandas as pd
import numpy as np
import requests
import json
import calendar
from g... | 4,753 | 1,697 |
from datetime import datetime
from datetime import timedelta
from django.db import models
from django.db.models import Q
from django.core import serializers
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from django.utils.timezone import get_current_timezone
from django.utils imp... | 17,666 | 5,488 |
from setuptools import setup
# setuptools used instead of distutils.core so that
# dependencies can be handled automatically
# Extract version number from resync/_version.py. Here we
# are very strict about the format of the version string
# as an extra sanity check. (Thanks for comments in
# http://stackoverflow.com/... | 1,697 | 493 |
#
# Copyright (C) 2020 Arm Mbed. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
import os
import shutil
import filecmp
import subprocess
import sys
import textwrap
import unittest
from snippet import config as snippet_config
from tests import tmp_test_dir
from tests import sample_input_dir
class Test(... | 2,966 | 901 |
import pandas as pd
import numpy as np
import time
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
from tqdm import tqdm
import matplotlib.pyplot as plt
class DataSet(torch.utils.data.Dataset):
def __init__(self, dataPath, transform=None):
self.dataset = pd.read_csv(dataPat... | 6,705 | 2,520 |
import numpy as np
from abc import ABC, abstractmethod
from pathlib import Path
class IMCFile(ABC):
"""Shared IMC file interface"""
def __init__(self, path: Path) -> None:
super().__init__()
self._path = Path(path)
@property
def path(self) -> Path:
"""Path to the IMC file"""... | 625 | 189 |
import cv2
import glob
import os
import shutil
from tierpsy.processing.processMultipleFilesFun import processMultipleFilesFun
from tierpsy.summary.collect import calculate_summaries
path = './data/jpeg-30s/'
img_extension = "*.jpg"
fps = 10
masked_video_dir = path + 'MaskedVideos'
results_dir = path + 'Results'
parame... | 1,579 | 616 |
"""
Async DRACOON users adapter based on httpx and pydantic
V1.0.0
(c) Octavio Simone, November 2021
Collection of DRACOON API calls for user management
Documentation: https://dracoon.team/api/swagger-ui/index.html?configUrl=/api/spec_v4/swagger-config#/groups
Please note: maximum 500 items are returned in GET reque... | 16,306 | 5,008 |
############################################################################
# Copyright ESIEE Paris (2018) #
# #
# Contributor(s) : Benjamin Perret #
# ... | 1,758 | 452 |
"""Unit test package for python_boilerplate."""
| 48 | 14 |
class component:
__type__ = str()
data = object()
class query:
__type__ = str()
query_id = int()
class itemStack:
__identifier__ = str()
__type__ = str()
count = str()
item = str()
class block:
__identifier__ = str()
__type__ = str()
block_position = object()
tickin... | 338 | 115 |
import torch
import re
import logging
logging.basicConfig(level=logging.DEBUG)
x = torch.eye(3)
print(x)
r=re.match('sys_apply', 'sys_apply')
print(r)
logging.debug("a") | 171 | 68 |
#!/usr/bin/env python3
import numpy as np
import tensorflow as tf
from orakl.attr import MarginSampling
from ...helpers.utils import BaseTest
class Test(BaseTest):
def test_call_with_empty_data_pool(self):
ms = MarginSampling()
model = tf.keras.Model()
with self.assertRaises(AssertionEr... | 3,353 | 1,044 |
from abc import ABCMeta, abstractmethod
from typing import Set
class Base(metaclass=ABCMeta):
"""
A base class for ES model
"""
@abstractmethod
def get_id(cls) -> str:
# return a document id in ES
pass
@abstractmethod
def get_attrs(cls) -> Set:
# return a set of a... | 481 | 139 |
r"""
.. autofunction:: openpnm.models.physics.diffusive_conductance.ordinary_diffusion
.. autofunction:: openpnm.models.physics.diffusive_conductance.taylor_aris_diffusion
.. autofunction:: openpnm.models.physics.diffusive_conductance.generic_conductance
"""
import scipy as _sp
def ordinary_diffusion(target,
... | 13,196 | 4,267 |
import logging
import os
import tqdm
import codecs
import h5py
from scipy.sparse import coo_matrix, csr_matrix
from implicit.als import AlternatingLeastSquares
import numpy as np
log = logging.getLogger("implicit")
def calculate_similar_event(path, output_filename):
model = AlternatingLeastSquares()
a, b ... | 2,281 | 788 |
"""Define common units that are not SI units.
Source: http://physics.nist.gov/cuu/Units/outside.html
"""
from math import pi
from unum import Unum
from unum.units.si import *
unit = Unum.unit
min = MIN = unit( 'min' , 60 * s , 'minute' )
h = H =... | 2,606 | 951 |
class Project:
def newMilestone(self, milestone):
pass;
def milestones(self):
pass
def percentageCompleted(self):
pass
def completionSummary(self):
pass
def data(self):
pass
def projectName(self):
pass
class NoIssueException(Exception):
... | 411 | 120 |
import subprocess
import pandas as pd
import tempfile
import os
__all__ = ['runRscript']
def runRscript(Rcmd, inDf=None, outputFiles=0, removeTempFiles=None):
"""Runs an R cmd with option to provide a DataFrame as input and file
as output.
Params
------
Rcmd : str
String containing the R-... | 5,563 | 1,952 |
from flask import Flask, render_template, request
import trafficlights.controller as controller
import trafficlights.poller as poller
from trafficlights.updaters.teamcity_updater import TeamCityUpdater
from trafficlights.updaters.flash_updater import FlashUpdater
import os
import pwd
import logging
from logging.handler... | 1,790 | 580 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
google-calendar-notifier
Google Calendar から直近の予定を取得し、通知時刻になったらデスクトップに通知を表示する。
"""
import sys
from modules.Global import APPLICATION_NAME
from modules.Manager import Manager
import setproctitle
from PyQt5.QtWidgets import (QApplication, QWidget)
def main():
"""
... | 552 | 235 |
import logging
import pytest
from unittest import mock
from requests import RequestException
from elastalert.alerters.exotel import ExotelAlerter
from elastalert.loaders import FileRulesLoader
from elastalert.util import EAException
def test_exotel_getinfo():
rule = {
'name': 'Test Rule',
'type... | 6,121 | 2,139 |
# -*- coding: UTF-8 -*-
import argparse
import os
import shlex
import subprocess
import sys
def main(argv):
command = ""
path = os.path.dirname(os.path.abspath(__file__))
if sys.platform.startswith('win'):
command = os.path.join(path, "gensort.exe") + " -a -b%d %d %s\partition%d"
elif sys.pl... | 1,664 | 562 |
import torch
from torch import nn, Tensor
from torch.nn import functional as F
class PSAP(nn.Module):
def __init__(self, c1, c2):
super().__init__()
ch = c2 // 2
self.conv_q_right = nn.Conv2d(c1, 1, 1, bias=False)
self.conv_v_right = nn.Conv2d(c1, ch, 1, bias=False)
self.co... | 6,855 | 2,928 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import csv
import os
import random
from conllu import parse
def create_dataset(src_files, dest_path):
data = []
for sf in src_files:
with open(sf, 'rb') as f:
sent... | 2,318 | 746 |
#!c:\users\mpoyi tshibuyi\desktop\cv\ruth-restaurant-back-end\venv_restaurant\scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| 203 | 75 |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits import axes_grid1
import cPickle
import copy
import os
import echolect as el
params = {#'figure.subplot.left': 0.01,
#'figure.subplot.bottom': 0.01,
#'figure.subplot.right': .99,
#'figure.subplot.top':... | 5,471 | 2,221 |
import os
import json
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=str, default='nuscenes')
parser.add_argument('--step', type=int, default='-1')
parser.add_argument('--metric', type=str, default='mean_dist_aps')
parser.add_argument('--thresh', type=str, default="")
args = p... | 1,161 | 457 |
import typing
from .point import Point
from .action import Action
class Apple(object):
def __init__(self, point: Point):
self.position: Point = point
class Snake(object):
def __init__(self, x: int, y: int, length: int = 2):
self.length: int = length
self.initial_x: int = x
... | 1,924 | 611 |
import time
import visa
rm=visa.ResourceManager()
li=rm.list_resources()
for index in range(len(li)):
print(str(index)+" - "+li[index])
choice = input("Which device?: ")
vi=rm.open_resource(li[int(choice)])
print(vi.query("*idn?"))
vi.write("FUNC CURR")
vi.write("trace:clear")
vi.write("trace:feed two")
vi.write("... | 915 | 351 |
"""Tests for SSDP and discovery."""
import queue
import socket
import unittest.mock as mock
import pytest
import requests
from pywemo import ssdp
MOCK_CALLBACK_PORT = 8989
MOCK_IP_ADDRESS = "5.6.7.8"
@pytest.fixture()
def mock_interface_addresses():
"""Mock for util.interface_addresses."""
addresses = ["1... | 9,057 | 3,339 |
#1. Run an OLS regression using a different set of data. Use the regression
#class created in this chapter. Print the results.
#2. Create scatter plots of the observation and predicted values as demonstrated at the end of this chapter.
#3. Use the numpy libraries log function to log some or all value in your data.
... | 963 | 260 |
"""
***************************************
MCSH - A Minecraft Server Helper.
Coded by AllenDa 2020.
Licensed under MIT.
***************************************
Module Name: MCSH.logging
Module Revision: 0.0.1-18
Module Description:
A module for all the shared functions.
Including Logging, Downloading, ... | 4,563 | 1,352 |
# coding: utf-8
import argparse
import json
import time
import math
import os, sys
import itertools
import numpy as np
import os.path as osp
import torch
import torch.nn as nn
import torch.optim as optim
from core.dataset.corpus import get_lm_corpus
from core.configs import get_basic_parser
from core.trainer import ... | 6,366 | 1,861 |
# 33.使用单一的列表生成式来产生一个新的列表
# 该列表只包含满足以下条件的值,元素为原始列表中偶数切片
a = [1,2,5,8,10,3,18,6,20]
res = [i for i in a[::2] if i %2 ==0]
print(res) | 133 | 116 |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param t: the root of tree
@return: return a string
"""
def tree2str(self, t):
# write your code here
result = ""
... | 828 | 264 |
"""
Copyright (c) 2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writin... | 2,589 | 751 |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# Copyright 2018 ZhangT. All Rights Reserved.
# Author: ZhangT
# Author-Github: github.com/zhangt2333
# main.py 2019/1/18 10:24
from spider import *
def main():
username = input('请输入学号: ')
password = input('请输入密码: ')
print('下面将为你进行所有课的教评,一律好评,如需特... | 620 | 313 |
from django.apps import AppConfig
class DatabaseConfig(AppConfig):
name = 'food_reference_listing.database'
| 114 | 34 |
#import pandas as pd
import numpy as np
import random
from tqdm import tqdm
#from sklearn.linear_model import LinearRegression
#from pandas.core.common import SettingWithCopyWarning
#import warnings
#from .dbtonumpy import eurusd_prices
#warnings.simplefilter(action="ignore", category=SettingWithCopyWarning)
from datet... | 6,905 | 2,612 |
from itertools import islice, count
from functools import partial
import time
import os
import pytest
from streamexecutors import StreamThreadPoolExecutor, StreamProcessPoolExecutor
approx = partial(pytest.approx, abs=0.5)
test_classes = [StreamThreadPoolExecutor, StreamProcessPoolExecutor]
# pytest bu... | 3,824 | 1,318 |
from tkinter import *
from back_end import Database
import confirm_sets_page
import edit_workout_page
import config
database = Database("py_project.db")
class EditExercisePage:
def __init__(self, content, exercise, workout_id, workout_date, username):
self.show_edit_exercise_page(content, exercise, worko... | 1,997 | 667 |
from __future__ import print_function
import errno
import logging
import re
import socket
import sys
from pdb import Pdb
__version__ = "1.2.0"
PY3 = sys.version_info[0] == 3
def cry(message, stderr=sys.__stderr__):
logging.critical(message)
print(message, file=stderr)
stderr.flush()
class LF2CRLF_Fi... | 4,463 | 1,396 |
import os
import yaml
import io
from copy import deepcopy
import logging
import collections
from logging.handlers import TimedRotatingFileHandler
from bookiesports.normalize import IncidentsNormalizer
def get_version():
try:
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'VERSION')) ... | 9,258 | 2,556 |
# Generated by Django 2.0.5 on 2018-05-27 20:54
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0007_auto_20180527_2014'),
]
operations = [
migrations.AlterField(
model_name='parents',
... | 957 | 306 |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'DesignPhoto'
db.create_table(u'designs_designphoto', (
... | 9,221 | 2,955 |
#!/usr/bin/env python3
class Runtime:
pass
class Singleton(Runtime):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
class StringBuilder:
def __init__(self, encoding='ut... | 1,125 | 356 |
HistoryURL = "http://ichart.finance.yahoo.com/table.csv?s=%s"
import sys
import urllib2
ticker = sys.argv[1] # AAPL
response = urllib2.urlopen(HistoryURL % ticker)
csvdata = response.read()
print csvdata
"""
...
1998-02-23,20.125,21.624999,20.00,21.250001,119372400,0.694818
1998-02-20,20.50,20.5625,19.8125,20.00,81... | 506 | 260 |
#!/usr/bin/env python3
# Generates a list of files to be manually trimmed. To aid pre-processing of
# our existing files.
import glob
import os
import re
EMOVDB_CMUARCTIC_PATH = '/home/e/e-liang/is4152/tacotron2/cmuarctic.data' # Transcripts for emovdb dataset located in repo root
dataLookup = {}
with open(EMOVDB_C... | 1,894 | 729 |
import sys
import shlex
sys.path.append('..')
bamsnap_prog = "src/bamsnap.py"
from src import bamsnap
# import bamsnap
# bamsnap_prog = "bamsnap"
cmdlist = []
cmdlist.append("""
-bam ./data/test_SV1_softclipped_1.bam \
-title "Clipped read" \
-pos chr1:37775740 chr1:37775780 chr1:37775783 chr1:3777578... | 1,587 | 660 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
PERMISSIONS_NAMES = (
("Lectura","Lectura"),
("Escritura","Escritura"),
("Administrador","Administrador"),
("Superusuario","Superusuario")
)
class Permissions (models.Model):
p... | 943 | 305 |
# -*- coding: utf-8 -*-
# Copyright (C) 2017 Garth N. Wells
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opt... | 3,751 | 1,202 |
"""
Support for Homematic (HM-TC-IT-WM-W-EU, HM-CC-RT-DN) thermostats.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/thermostat.homematic/
"""
import logging
import socket
from xmlrpc.client import ServerProxy
from xmlrpc.client import Error
from collec... | 7,084 | 2,121 |
# This Python file uses the following encoding: utf-8
import phue
from PySide2.QtCore import QObject, Signal, Slot, Property
class BridgeAccess(QObject):
def __init__(self, ip, user, parent=None):
super(BridgeAccess, self).__init__(parent)
self.ip_val = ip
self.user_val = user
t... | 1,658 | 529 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : gnntc.py
# Author : Zhezheng Luo
# Email : luozhezheng@gmail.com
# Date : 08/02/2021
#
# This file is part of TOQ-Nets-PyTorch.
# Distributed under terms of the MIT license.
import torch
from torch import nn
from toqnets.nn.propnet import AgentEncoder, Rel... | 3,779 | 1,396 |
valid_count = 0
for line in open('input.txt'):
space_index = line.index(' ')
limits = [int(limit) for limit in line[:space_index].split('-')]
lo, hi = limits[0], limits[1]
colon_index = line.index(':')
letter = line[space_index+1:colon_index]
word = line[colon_index+1:]
letter_count = 0
... | 553 | 181 |
from evaluation.hand_calculation.hand_divider import HandDivider
from evaluation.hand_calculation.yaku_list.yakuman import KokushiMusou
class Agari:
@staticmethod
def is_agari(private_tiles, win_tile=None, melds=None):
"""
Determine whether a given hand is complete. Yaku are not counted.
... | 1,187 | 341 |
import os
import numpy as np
SEEDS = [1, 2, 3, 4, 5]
LOSS_TYPES = ["OCE_loss_final_with_prox_dynamic_L7_with_alpha", "CrossEntropy"]
ALPHAS = np.linspace(0.5, 0.9, 5) # Irrelevant for CrossEntropy
# SEEDS = [1, 3, 5]
# LOSS_TYPES = ['OCE_loss_final_with_prox_dynamic_L7_with_alpha_ablation_prox',
# ... | 2,961 | 922 |
from .analysis import *
from .utils import *
| 45 | 13 |
#Python3
#Crea una figura con un simbolo digitado
###### DEFINICIONES ######
def impr (anch):
print("*" * anch)
def anchofig(anc,sym):
print (sym*anc)
###### IMPLEMENTACION ######
ancho = int(input("Digite el ancho para el de asteriscos "))
for indice in range (1, ancho + 1):
impr(ancho)
ancho ... | 570 | 230 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Copyright 2019 University of Liege
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 requir... | 16,093 | 6,699 |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: XmlCommandArgument.py
from XmlCommandBase import XmlCommandBase
class XmlCommandArgument(XmlCommandBase):
def __init__(self):
XmlComman... | 2,039 | 648 |
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QWidget, QMessageBox
from PyQt5 import QtWidgets
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import pyqtSignal, QThread, QCoreApplication, Qt
from Ui_userPayWin import Ui_Dialog
import sys, utils
from alipay import AliPay
import qrcode, time, threadi... | 10,390 | 3,942 |
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is dis... | 6,125 | 2,022 |
import json
from django.contrib import admin
from django.utils.html import format_html
from devilry.apps.core.models import AssignmentGroup, Subject, Period, Assignment, PeriodTag, \
CandidateAssignmentGroupHistory, ExaminerAssignmentGroupHistory, Examiner, RelatedStudent, RelatedExaminer, \
AssignmentGroupHi... | 7,253 | 2,274 |
from __future__ import absolute_import
from warnings import warn
warn("IPython.utils.traitlets has moved to a top-level traitlets package.")
from traitlets import *
| 168 | 47 |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | 26,188 | 7,630 |
log_info = dict()
| 18 | 8 |
print('Unidades de Medida')
m = float(input('Digite uma distância em metros: '))
print(f'A distancia de {m}m corresponde a: ')
km = m/1000
hm = m/100
dam = m/10
m = m
dm = m * 10
cm = m * 100
mm = m * 1000
print(f"({km}km - {hm}hm - {dam}dam - {m}m - {dm:.0f}dm - {cm:.0f}cm - {mm:.0f}mm)")
| 293 | 157 |
from maintain_frontend import main
from flask_testing import TestCase
from unit_tests.utilities import Utilities
from flask import url_for
from unittest.mock import patch, MagicMock
from maintain_frontend.dependencies.session_api.session import Session
from maintain_frontend.models import SearchDetails
class TestEnte... | 7,472 | 2,366 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# quantization.py is used to quantize the activation of model.
from __future__ import print_function, absolute_import
import torch
import torch.nn.functional as F
from torch.nn import init
import torch.nn as nn
import pickle
from torch.nn.parameter import Parameter
from to... | 5,285 | 1,744 |
#!/usr/bin/python
class Annotations:
'''
Class to hold the annotation formats
To be used at multiple levels in tool flow for
comparison purposes
'''
#format strings
_connect_wire_str = 'connect wire {} ({}) to {}'
_latch_wire_str = 'latch wire {} ({}) before connecting to {}... | 2,240 | 777 |
import logging
from collections import OrderedDict
log = logging.getLogger('comprasnet')
class BaseDetail:
DETAIL_URL = None
def __init__(self, uasg_code, auction_code, *args, **kwargs):
self.uasg_code = uasg_code
self.auction_code = auction_code
def get_params(self):
raise Not... | 789 | 262 |