text string | size int64 | token_count int64 |
|---|---|---|
def countstrnum(gets):
list =[0,0,0,0]
for w in gets:
if (w>='a' and w<='z')|(w>='A'and w<='Z'):
list[0]+=1
elif w ==' ':
list[1]+=1
elif w>='0' and w<='9':
list[2]+=1
else:
list[3]+=1
return list
def main():
getstr = r... | 438 | 178 |
import os
from argparse import ArgumentParser
import torch
from hashlib import md5
import numpy as np
import glob
import re
from torch.nn import functional as F
from latent_rationale.snli.constants import UNK_TOKEN, PAD_TOKEN, INIT_TOKEN
from latent_rationale.snli.plotting import plot_heatmap
from latent_rationale.snl... | 16,629 | 5,379 |
import os
import sys
import logging
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import pandas as pd
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import numpy as np
import os
import pandas as pd
import re
import keras.layers as layers
from keras.models impo... | 1,709 | 571 |
import logging
from robot.model import SuiteVisitor
from .visitor_model import Keyword, Test, Suite, Message
from .service import RobotService
from .variables import ConfigurationVariables
logging.getLogger(name='reportportal_client').setLevel(logging.WARNING)
logging.getLogger(name='urllib3').setLevel(lo... | 1,437 | 439 |
import numpy as np
from pyraf import iraf
from pyraf.iraf import kepler
'''
Useful functions for Kepler light curve processing
Use this with the program 'makelc.py'
Originally by Jean McKeever
Edited and improved by Meredith Rawls
'''
# calculate orbital phase
# times must be a list of observation times in the same un... | 5,357 | 2,101 |
from .helpers import load_dataset
from .core import Merger
from .core import CategoryEncoder
from .core import Imputer
from .core import AttributeAdder
from .core import Pipesystem
from .core import OptimizedPipesystem | 220 | 61 |
"""
Functions used by different endopoints.
- To do basic operations
- To parse the filters request
- To manage access resolution
"""
import ast
import logging
import yaml
import requests
from pathlib import Path
from ..api.exceptions import BeaconBadRequest, BeaconServerError, BeaconForbidden, BeaconUnauthorised... | 17,649 | 4,517 |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse('hello, 世界!')
def my_test(request):
return HttpResponse('my_test!')
| 219 | 67 |
'''
@author: AWS Samples
@Link: https://docs.aws.amazon.com/deepracer/latest/developerguide/what-is-deepracer.html
@License: Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
'''
def reward_function(params):
'''
Example of rewarding the agent to follow the track center line
... | 990 | 313 |
import logging
from functools import partial, wraps
import petl
import requests
from github import Github as PyGithub
from github.GithubException import UnknownObjectException
from parsons.etl.table import Table
from parsons.utilities import check_env, files
logger = logging.getLogger(__name__)
def _wrap_method(de... | 14,498 | 3,853 |
# Copyright (c) 2015, Daniel Svensson <dsvensson@gmail.com>
#
# Permission to use, copy, modify, and/or 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 T... | 883 | 317 |
# -*- coding: utf-8 -*-
"""Tensorflow random seed
"""
import tensorflow as tf
import numpy as np
mu = 0
sigma = 0.3
# variables with/without function seed
fc1_W = tf.Variable(tf.truncated_normal(shape=(1, 2), mean=mu, stddev=sigma, seed=1))
fc2_W = tf.Variable(tf.truncated_normal(shape=(1, 2), mean=mu, stddev=sigma)... | 2,815 | 1,048 |
from django.db import models
from apps.funcionarios.models import Funcionario
class RegistroHoraExtra(models.Model):
motivo = models.CharField(max_length=100)
funcionario = models.ForeignKey(Funcionario, on_delete=models.PROTECT)
def __str__(self):
return self.motivo
| 291 | 91 |
Ongoing.... | 11 | 6 |
from __future__ import annotations
from pathlib import Path
from gd2c.gdscriptclass import GDScriptClass, GDScriptClassConstant, GDScriptFunctionConstant, GDScriptFunction, GDScriptGlobal, GDScriptMember, GDScriptFunctionParameter
from gd2c.variant import VariantType
from gd2c.bytecode import extract
from typing import... | 3,716 | 1,089 |
import torch
from torch import tensor, rand
import pyro
import torch.distributions.constraints as constraints
import pyro.distributions as dist
def transformed_data(D=None, K=None, N=None, y=None):
neg_log_K = -log(K)
return {'neg_log_K': neg_log_K}
def model(D=None, K=None, N=None, y=None, transformed_data... | 1,301 | 532 |
#!/usr/local/bin/python
__author__ = 'spouk'
__all__ = ('AdminkaPlugin',)
__version__ = 0.1
__name__ = 'AdminkaPLugin for Siberia'
__middleware__ = True
#---------------------------------------------------------------------------
# global imports
#----------------------------------------------------------------------... | 5,885 | 1,809 |
"""Provide base test class."""
from typing import Any, Callable
from nameko_sqlalchemy.database_session import Session
from jobs.dependencies.dag_handler import DagHandler
from jobs.service import JobService
from .exceptions import get_missing_resource_service_exception, get_not_authorized_service_exception
from ..ut... | 2,576 | 721 |
# Copyright 2020 Thomas Rogers
# SPDX-License-Identifier: Apache-2.0
from .manager import Manager
| 99 | 37 |
import datetime
from google.appengine.ext import ndb
class GameListing(ndb.Model):
# Game listing stuff
game_name = ndb.StringProperty(required=True)
game_status = ndb.StringProperty(required=True)
game_website = ndb.StringProperty()
listing_contact = ndb.StringProperty(required=True)
short_d... | 1,919 | 589 |
from __future__ import print_function
from stylelens_dataset.categories import Categories
from stylelens_dataset.objects import Objects
from pprint import pprint
import os
import urllib.request as urllib
# create an instance of the API class
category_api = Categories()
object_api = Objects()
def download_image_from_u... | 2,267 | 652 |
# Copyright 2022 The TensorFlow 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 applica... | 8,429 | 2,365 |
from __future__ import annotations
import toolsql
fourbyte_schema: toolsql.DBSchema = {
'tables': {
'function_signatures': {
'columns': [
{'name': 'id', 'primary': True},
{'name': 'created_at'},
{'name': 'text_signature', 'index': True},
... | 783 | 214 |
from urllib.parse import urlparse
import binascii
from twisted.trial.unittest import TestCase
from txaws.util import hmac_sha1, iso8601time, parse
class MiscellaneousTestCase(TestCase):
def test_hmac_sha1(self):
cases = [
(binascii.unhexlify(b"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
... | 2,493 | 893 |
import pygame
from pygame.locals import *
from .actor import Actor
from .actor import Player, Wall, Enemy, Bullet, NPC, Anime, Map
from .actor import Menu, Background, Button
from .actor import Delayer
import vgame
class Camera:
'''
主要负责处理镜头的处理,看看后续能够扩展出多少的功能。
'''
DEBUG = False
def __init__(sel... | 7,674 | 3,178 |
PROPERTIES = """
SELECT
p.id,
p.address,
p.city,
s.name AS status,
p.price,
p.description,
p.year
FROM property p
INNER JOIN (
SELECT sh.property_id, sh.status_id, sh.update_date
FROM status_history sh
INNER JOIN (
... | 844 | 294 |
# -*- coding: utf-8 -*-
# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Library containing functions to execute auto-update on a remote device.
TODO(xixuan): Make this lib support other update logic... | 60,654 | 18,149 |
import re
from typing import Optional, List, Any, Callable, Tuple
# Our special mark in markdown, e.g. :label:`chapter_intro`
md_mark_pattern = re.compile(':([-\/\\._\w\d]+):(`[\ \*-\/\\\._\w\d]+`)?')
# Same for md_mark_pattern, but for rst files
rst_mark_pattern = re.compile(':([-\/\\._\w\d]+):(``[\ \*-\/\\\._\w\d]+`... | 1,368 | 511 |
#!/usr/bin/env python3
from enum import Enum
# This computer will have these memory mapped registers:
# 0 = PC
# 1 = SP
# but I didn't implement them. Only the program counter exists and its not memory mapped
class Memory(object):
def __init__(self):
self.storage = {}
def __setitem__(self, addr, v... | 4,999 | 1,758 |
import tensorflow_graphics as gfx
import tensorflow as tf
lambertian = gfx.rendering.reflectance.lambertian
phong = gfx.rendering.reflectance.phong
def make_movie(keyframes, length, save_path):
frames_per_keyframe = length / tf.shape(keyframes)[0]
frames = interpolate(keyframes, frames_per_keyframe)
movi... | 1,332 | 476 |
"""
| Copyright (c) Tomas Johansson , http://www.programmerare.com
| The code in this library is licensed with MIT.
| The library is based on the C#.NET library 'sweden_crs_transformations_4net' (https://github.com/TomasJohansson/sweden_crs_transformations_4net)
| which in turn is based on 'MightyLittleGeodesy' (https... | 4,635 | 1,556 |
import copy
import json
import os
from typing import Any, Dict, List, NamedTuple
import click
import yaml
from dotenv import load_dotenv
from pygitguardian.models import PolicyBreak
from .git_shell import get_git_root, is_git_dir
from .text_utils import display_error
CONTEXT_SETTINGS = dict(help_option_names=["-h",... | 8,842 | 2,666 |
class BehaviorBlock:
def __init__(self, parent, method, description):
self.method = method
self.parent = parent
self.description = description
class Context(object):
def __init__(self, parent):
if parent is not None:
for attr in dir(parent.context):
... | 1,444 | 407 |
import requests
from multipledispatch import dispatch
class Source:
def __init__(self,url,query="query?query="):
self.url = url
self.query= query
def url(self):
#form url
pass
@dispatch(str)
def inputoutput(self, metricreq):
Aurl = self.url+self.query+metricreq... | 1,166 | 364 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Classes for handling mysql.
"""
import os
class LocalMySQL(object):
"""Class representing the local MySQL connection parameters."""
def __init__(
self,
request=None,
database=None,
user=None,
password=None,
... | 2,677 | 816 |
from mygrations.core.parse.parser import parser
from mygrations.formats.mysql.definitions.index import index
class index_primary(parser, index):
_index_type = 'primary'
has_comma = False
# PRIMARY KEY (`id`),
rules = [{
'type': 'literal',
'value': 'PRIMARY KEY'
}, {
'type':... | 966 | 309 |
from bauh.commons.system import run_cmd, SimpleProcess
def is_available() -> bool:
return bool(run_cmd('which timeshift', print_error=False))
def delete_all_snapshots(root_password: str) -> SimpleProcess:
return SimpleProcess(['timeshift', '--delete-all', '--scripted'], root_password=root_password)
def cr... | 499 | 159 |
#!/usr/bin/env python
import os
import subprocess
GOOS_TO_BAZEL = {
'darwin': 'osx',
'linux': 'linux',
}
GO_TOOL_SRC = ('pypi/pip_generate.go',)
# TODO: Build 32-bit versions?
GOARCH = 'amd64'
def main():
script_dir = os.path.dirname(__file__)
for src in GO_TOOL_SRC:
for goos, bazel_os in... | 813 | 305 |
import json
import requests
from .exchange import Exchange
class Poloniex(Exchange):
def __init__(self):
Exchange.__init__(self, "GDAX")
def PullData(self):
url = "https://poloniex.com/public?command=returnTicker¤cyPair=USDT_BTC"
response = requests.get(url)
ticker = response.json()['USDT_BTC']
d... | 445 | 166 |
import pandas as ___
import seaborn as ___
import matplotlib.pyplot as ___
# read in the data
___
# select the columns with 'mean' in the name
selected_columns = list(___)
# find the correlations
corr_matrix = ___
# make a plot
plt.___(figsize=(8,7), facecolor='white')
sns.___(data=___, cmap="YlGnBu")
plt.___("Correl... | 354 | 124 |
from decimal import localcontext
def precision(*args, **kwargs):
def decorator(f):
def inner_decorator(*a, **kwa):
with localcontext() as ctx:
ctx.prec = kwargs['prec']
return f(*a, **kwa)
return inner_decorator
return decorator
| 301 | 85 |
"""This module contains unit tests for lexer module."""
import pytest
import pseudo
from pseudo.pseudo_types import Operation, Operator, Int
__author__ = "Patryk Niedźwiedziński"
@pytest.fixture
def lexer():
"""Returns lexer object."""
lex = pseudo.lexer.Lexer("")
return lex
def test_is_keyword(lexer... | 3,178 | 1,114 |
from datetime import timedelta
from holobot.sdk.math import Range
class IConfigProvider:
def get_reason_length_range(self) -> Range[int]:
raise NotImplementedError
def get_decay_threshold_range(self) -> Range[timedelta]:
raise NotImplementedError
def get_warn_cleanup_interval(self) -> tim... | 717 | 227 |
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from common.functions import instance_get_thumbnail, common_clean
def user_render_reference(user, display_edit_link=False, field_name='admins'):
html = '<span ... | 1,901 | 628 |
# coding=utf8
from app import db
def get_databases():
sql = "SHOW DATABASES"
result = db.engine.execute(sql)
dbs = []
for row in result:
dbs.append(row['Database'])
return dbs
def get_tables(dbname):
sql = "SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='" + dbname + "'"
res... | 19,227 | 7,732 |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
# app.run()
x = "Hello world"
y = "hello"
z = "1 2 3"
print(x.lower().strip().split())
print(y.lower().strip().split())
print(z.lower().strip().split())... | 321 | 120 |
from pythonforandroid.recipe import CompiledComponentsPythonRecipe
from pythonforandroid.toolchain import warning
from os.path import join
class NumpyRecipe(CompiledComponentsPythonRecipe):
version = '1.15.1'
url = 'https://pypi.python.org/packages/source/n/numpy/numpy-{version}.zip'
site_packages_name =... | 1,931 | 658 |
# pylint: disable=wildcard-import,unused-wildcard-import
from selenium.common.exceptions import *
try:
from Levenshtein import distance as levenshteinDistance
except ImportError:
levenshteinDistance = None
def _create_exception_msg(
id_=None, class_name=None, name=None, tag_name=None,
parent... | 6,136 | 1,876 |
#
# Tambola / Housie Mobile Game
#
__author__ = 'nitin'
#import time
from player_ticket import PlayerTicket
class PlayerInputHandler:
def __init__(self, game_instance):
self._game_instance = game_instance
#Player Id will be sent by Client
# TODO Need to create player Ids in DB
... | 2,508 | 732 |
# Write a Python program to get numbers divisible by fifteen from a list using an anonymous function.
num_list = [45, 55, 60, 37, 100, 105, 220]
# use anonymous function to filter
result = list(filter(lambda x: (x % 15 == 0), num_list))
print("Numbers divisible by 15 are", result)
| 283 | 104 |
import sys
def main():
n = sys.stdin.readline().rstrip()
cnt = 1
for i in range(3):
if n[i] == n[i + 1]:
cnt += 1
if cnt == 3:
ans = "Yes"
break
else:
cnt = 1
else:
ans = "No"
print(ans)... | 366 | 147 |
"""
Show percentage of splicing events whose psi scores are inconsistent between pooled and single
==============================================================================================
"""
import flotilla
study = flotilla.embark(flotilla._shalek2013)
study.plot_expression_vs_inconsistent_splicing() | 308 | 81 |
a="hello \n"
b=int(input(" Enter the number of times:"))
h=a*b
print (h)
| 77 | 35 |
#-*- coding: utf-8 -*-
from .loggers import create_logger
from .mpd_player import MPDPlayer
mpd_player = MPDPlayer()
mpd_player.open()
logger = create_logger('mamiru')
| 174 | 70 |
'''
Module containing waveforms for any codeword based waveform generator.
This is the library containing pulses for
CBox (still uses old one)
QWG
UHFQC (not used yet)
'''
| 184 | 57 |
from functools import wraps
from flask import render_template, flash, redirect, url_for, request
from flask_login import login_user, logout_user, current_user, login_required
from app import app
from app.models import User, Task
from app.forms import (
LoginForm, RegistrationForm, AddTask,
EditTaskForPerformer,... | 6,369 | 1,961 |
# coding: utf-8
# # Stock Choice Decision Analysis
# Code written and commentated by Peter Sanders
# ### Load Relevant Packages
# In[1]:
from pandas_datareader import data
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from datetime import datetime
import numpy as np
import math
from sci... | 4,136 | 1,767 |
'''
Manage the route server.
'''
from ... pyaz_utils import _call_az
from . import peering
def create(hosted_subnet, name, resource_group, location=None, public_ip_address=None, tags=None):
'''
Create a route server.
Required Parameters:
- hosted_subnet -- The ID of a subnet where Route Server would ... | 4,282 | 1,166 |
import os
import mrcfile
import numpy as np
import pandas as pd
import networkx as nx
from igraph import Graph
from scipy import ndimage as ndi
from skimage import transform, measure
import tkinter as tk
from tkinter import ttk
import tkinter.filedialog
import matplotlib
from matplotlib import cm
import matplotlib.py... | 40,276 | 13,330 |
# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
# This software is distributed under the terms and conditions of the 'Apache-2.0'
# license which can be found in the file 'LICENSE' in this package distribution
# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
import sqlalchemy as sql
de... | 8,055 | 2,544 |
# Generated by Django 3.2.7 on 2021-10-02 22:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('asks', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Option',
fields=[
('id', mode... | 1,683 | 473 |
from openprocurement.api.utils import error_handler
from openprocurement.tender.core.procedure.state.bid import BidState as BaseBidState
class BidState(BaseBidState):
def status_up(self, before, after, data):
assert before != after, "Statuses must be different"
# this logic moved here from valida... | 650 | 188 |
from rest_framework_nested.serializers import NestedHyperlinkedModelSerializer
from rest_framework_nested.relations import NestedHyperlinkedRelatedField
from rest_framework import serializers
from api.models import User, Company, CompanyContact, Order, Item, Contact, OrderItem
import copy
class UserSerializer(seriali... | 4,903 | 1,404 |
# =================================================================
#
# Work of the U.S. Department of Defense, Defense Digital Service.
# Released as open source under the MIT License. See LICENSE file.
#
# =================================================================
import json
import sys
from django.core.man... | 1,703 | 460 |
import os.path
import pytest
from krun.config import Config
from krun.scheduler import ManifestManager
from krun.util import FatalKrunError
from krun.tests.mocks import MockPlatform, mock_platform
DEFAULT_MANIFEST = "krun.manifest"
TEST_DIR = os.path.abspath(os.path.dirname(__file__))
BLANK_EXAMPLE_MANIFEST = """eta... | 17,950 | 6,597 |
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('k', metavar='k', type=int, nargs='?',
help='number of classes of terminals (terminal-generating non-terminals)')
args = parser.parse_args()
# print("k = %d" % args.k)
print("""[A] |||... | 692 | 355 |
class NoopListener(object):
def __init__(self, iterable):
self.__iterable = iterable
def __iter__(self):
return iter(self.__iterable)
| 159 | 48 |
# -*- coding: utf-8 -*-
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input
from dash.dependencies import Output
from app import app
from app.custom_widgets import collapsable_card
from app.custom_widgets import container
from app.custom_widgets import custom_butt... | 5,924 | 1,936 |
'''
# Exemplo de encapsulamento da forma que é feita em Java
class P:
def __init__(self,x):
self.__x = x #<- tornando ele um atributo privado
def getX(self):
return self.__x
def setX(self, x):
if x > 0:
self.__x = x
p = P(10) #<- passei o primeiro valor que deve chamar... | 987 | 362 |
import argparse
import os
from gcc.tasks.node_classification import NodeClassification
from tests.utils import E2E_PATH, MOCO_PATH, get_default_args, generate_emb
def run(dataset, model, emb_path=""):
args = get_default_args()
args.dataset = dataset
args.model = model
args.emb_path = emb_path
tas... | 1,915 | 789 |
from rich import print
from nornir import InitNornir
from nornir.core.filter import F
from nornir_netmiko import netmiko_send_command
def main():
nr = InitNornir(config_file="config.yaml")
filt = F(groups__contains="ios")
nr = nr.filter(filt)
my_results = nr.run(
task=netmiko_send_command, com... | 563 | 201 |
import uuid
from datetime import datetime
from portality.api.current.data_objects.common import _check_for_script
from portality.lib import swagger, seamless, coerce, dates, dataobj
from portality import models
from copy import deepcopy
from portality.api.current.data_objects.common_journal_application import Outgoin... | 13,265 | 4,035 |
import os
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev'
ADMIN_EMAIL = os.environ.get('ADMIN_EMAIL') or 'nicearrack@163.com'
ADMIN_NAME = os.environ.get('ADMIN_NAME') or 'Arrack'
SITE_TITLE = 'Maybe'
SITE_SUBTITLE = 'Everything is not too late.'
SQLALCHEMY_TRACK_MO... | 1,147 | 447 |
import numpy as np
import pandas as dp
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
#engine = create_engine("sqlite:///Resources/hawaii.sqlite")
engine = create_engi... | 4,086 | 1,416 |
from django.contrib import auth
from django.db.transaction import atomic
from django.http import Http404
from django.shortcuts import redirect, render
from django.urls import reverse
from django.utils.encoding import force_text
from django.utils.http import urlsafe_base64_decode
from django.views import View
from djang... | 1,756 | 549 |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 30 13:42:47 2016
@author: DTump
"""
#Combines the featurevalues of the images with the labels assigned to the
#corresponding business. It trains an SVM on these featurevalues of the images
#to the labels of the trainset of the traindata and then
#predicts the labels th... | 4,035 | 1,512 |
# -*- coding: utf-8 -*-
import json
import uuid
from contextlib import contextmanager
from datetime import datetime
import mock
from pyramid import testing
from cliquet import initialization
from cliquet.events import ResourceChanged, ResourceRead, ACTIONS
from cliquet.listeners import ListenerBase
from cliquet.stora... | 7,171 | 2,206 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
frappe.delete_doc_if_exists("DocType", "User Permission for Page and Report") | 256 | 82 |
import os
os.system(f'cls & mode 85,20 & title GhostHook! - Version 1.4!')
from json import loads, dumps
from threading import Thread
from time import sleep
from sys import argv
import pystyle
from pystyle import *
import time
import requests
from colorama import Fore
import threading
import sys
def ... | 9,753 | 3,220 |
"""Map all bindings to PySide2
This module replaces itself with the most desirable binding.
Project goals:
Qt.py was born in the film and visual effects industry to address
the growing need for the development of software capable of running
with more than one flavour of the Qt bindings for Python - PySide... | 8,142 | 2,684 |
from __future__ import annotations
from dataclasses import dataclass, field
from chess.moves import Move
@dataclass
class Player:
"""Represents a chess player."""
color: str
score: int = 0
captures: list[Move] = field(default_factory=list)
| 260 | 82 |
#!/usr/bin/env python
import os
import requests
path = os.path.dirname(os.path.realpath(__file__))
if not os.path.isfile(f"{path}/config.py"):
print(f"⚠ No weather config found. Check out \"{path}/config.py\"")
exit()
else:
from config import *
url = f"https://api.openweathermap.org/data/2.5/weather?id=... | 676 | 263 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from appium import webdriver
server_base = "http://127.0.0.1:"
server_end = "/wd/hub"
capabilities = {
"platformName": "iOS",
"automationName": "XCUITest",
"platformVersion": "11.0",
"app": "/Users/hunter/Desktop/python/PythonAppium2/app/iOSFinancial.app... | 1,074 | 405 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: get_packages.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobu... | 8,821 | 3,318 |
import pytest
from cleo import CommandTester
from rabbit.__main__ import application
def test_consumer_command():
command = application.find("consumer")
ct = CommandTester(command)
assert "" == ct.io.fetch_output()
def test_file_not_found_event_command():
command = application.find("send-event")
... | 412 | 130 |
def validate_pin(pin):
| 24 | 10 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import Optional, TYPE_CHECKING
if TYPE_CHECKING:
from cdm.resolvedmodel.projections.projection_directive import ProjectionDirective
class InputVa... | 1,497 | 457 |
import rx3
from rx3 import operators as ops
from rx3.core import Observable
def _merge(*sources: Observable) -> Observable:
return rx3.from_iterable(sources).pipe(ops.merge_all())
| 187 | 65 |
# -*- coding: utf-8 -*-
import time
from pip_services3_components.log import CachedLogger, LogLevel
class LoggerFixture:
_logger: CachedLogger = None
def __init__(self, logger: CachedLogger):
self._logger = logger
def test_log_level(self):
assert self._logger.get_level() >= LogLevel.Not... | 1,155 | 349 |
# standard library
from typing import Union, List, Optional
# third party imports
import numpy as np
# local imports
from probeye.definition.sensor import Sensor
from probeye.subroutines import make_list, translate_prms_def
class NoiseModelBase:
def __init__(
self,
dist: str,
prms_def: U... | 11,511 | 2,903 |
# Tencent is pleased to support the open source community by making GNES available.
#
# Copyright (C) 2019 THL A29 Limited, a Tencent company. 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... | 5,050 | 1,568 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import matplotlib.animation as animation
# to get the distance of wave
# y = kx + b
# ax+by+cz+d = 0
class F:
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
de... | 1,224 | 595 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Speciallan
def main():
#gen coco pretrained weight
path = './work_dirs_bottle/cascade_rcnn_r50_fpn/checkpoints/'
import torch
num_classes = 11
model_coco = torch.load(path+"cascade_rcnn_dconv_c3-c5_r50_fpn_1x_20190125-dfa53166.pth") # weight
... | 1,470 | 687 |
# Copyright 2013-2015 ARM Limited
#
# 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 w... | 6,007 | 1,752 |
'''
Configuration script in Python.
Add a secret_key
'''
APP_CONFIG = {
'webapp2_extras.auth': {
'user_model': 'models.User',
'user_attributes': ['name', "email_address"]
},
'webapp2_extras.sessions': {
'secret_key': 'YOUR_SECRET_KEY'
}
}
APP_NAME = "pycoCMS"
MAIL_SENDER = 'pyc... | 337 | 135 |
# Echo client program
import socket, select, sys, threading
from Tkinter import *
HOST = 'localhost' # The remote host
PORT = 54321 # The same port as used by the server
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
def sending():
while 1:
sock.sendall(raw... | 627 | 223 |
#!/usr/bin/env python3
from socket import socket, AF_INET, SOCK_STREAM
from threading import Thread
from multiprocessing import cpu_count
import sys
def attack(host, port, num):
s = socket(AF_INET, SOCK_STREAM)
s.connect((host, port))
while True:
print('Thread {} : Sending request to {}:{}...'.fo... | 782 | 274 |
import numpy as np
from .BaseUtility import BaseUtility
class DummyUtility(BaseUtility):
def __init__(self):
super().__init__()
def utility_function(self, x):
return 100 * (1 - np.exp(-0.19 * x))
| 206 | 82 |
# Generated by Django 2.1 on 2019-01-26 07:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('comments', '0002_auto_20170603_1644'),
]
operations = [
migrations.AlterUniqueTogether(
name='commentflag',
unique_together=set(),
),
migrations.RemoveField(
... | 503 | 221 |
#!/usr/bin/env python
from setuptools import setup
setup(
name='netcli',
version='1.0',
packages=['netcli'],
include_package_data=True,
install_requires=[
'pygments>=2.0.2',
'prompt_toolkit>=1.0.0,<1.1.0',
'click>=4.0',
'fuzzyfinder>=1.0.0'
],
entry_points={
... | 528 | 201 |