text string | size int64 | token_count int64 |
|---|---|---|
import matplotlib.pyplot as plt
from mpldatacursor import datacursor
import pandas as pd
class ChangeTypeStatisticPlot():
def __init__(self):
self.reset()
def reset(self):
self.intervals = {
"changedChunksAll":[],
"changedChunksBlock":[],
"changedChunksBl... | 8,688 | 2,501 |
# heavily inspired by https://stackoverflow.com/a/21882672
def split_cpe_string(string):
ret = []
current = []
itr = iter(string)
for ch in itr:
if ch == "\\":
try:
# skip the next character; it has been escaped!
current.append(next(itr))
e... | 606 | 172 |
"""
--- Day 17: Spinlock ---
Suddenly, whirling in the distance, you notice what looks like a massive, pixelated hurricane: a deadly spinlock. This
spinlock isn't just consuming computing power, but memory, too; vast, digital mountains are being ripped from the ground
and consumed by the vortex.
If you don't move qui... | 4,221 | 1,334 |
s=input();
k=int(input())
for i in s:
elif ord(i)>=97 and ord(i)<=122:
y=k%26;x=ord(i)-96;
if x+y>26:
print(chr(y-(26-x)+96),end="")
else:
print(chr(x+y+96),end="")
elif ord(i)>=65 and ord(i)<=90:
y = k % 26;x=ord(i)-64;
if x+y>26:
prin... | 611 | 292 |
from requests import get
from bs4 import BeautifulSoup
import sys
import re
fileName = ''
weaponFlavorTexts = []
weaponTitles = []
dismissedFlavorTexts = ['An Awoken gift from the Reef, marked with the Queen\'s crown.', 'A prestigious trophy earned in battle during the Trials of Osiris.', 'Executor-issued sidearm fo... | 6,573 | 1,965 |
SEQ_IDS_TRAIN = ["%04d" % idx for idx in [0, 1, 3, 4, 5, 9, 11, 12, 15, 17, 19, 20]]
SEQ_IDS_VAL = ["%04d" % idx for idx in [2, 6, 7, 8, 10, 13, 14, 16, 18]]
TIMESTEPS_PER_SEQ = {"0000": 154, "0001": 447, "0002": 233, "0003": 144, "0004": 314, "0005": 297, "0006": 270,
"0007": 800, "0008": 390, "00... | 494 | 365 |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
def hash_index(v, group):
"""
Hash values to store hierarchical index
:param v: index value
:param group: variables from which index was derived
:return: str
v = [1, 2]
group = ['q1', 'q2]
ret... | 1,191 | 448 |
"""
Problem generator that creates random solutions for a Genetic Programming
problem -- symbolic regression. Briefly, this problem involves estimating
the (polynomial) line that best fits a set of data points.
For testing purposes, these data points are generated from a test function,
but (random) data points could b... | 6,186 | 1,951 |
"""
Views show job status.
**Component**: views
:Macro: views
:Entry Point: jenkins_jobs.views
"""
import logging
import xml.etree.ElementTree as XML
import jenkins_jobs.modules.base
import jenkins_jobs.modules.helpers as helpers
logger = logging.getLogger(__name__)
def all_view(parser, xml_parent, data):
... | 48,355 | 13,806 |
from .abstractaudioplayer import AbstractAudioPlayer, AudioPlayerError
from ctypes import windll
class AudioPlayerWindows(AbstractAudioPlayer):
def __init__(self, filename):
super().__init__(filename)
self._alias = "A{}".format(id(self))
def _mciSendString(self, command):
return windl... | 1,602 | 493 |
# https://leetcode.com/problems/two-city-scheduling/
# Easy (51.19%)
# Total Accepted: 3,913
# Total Submissions: 7,644
import math
class Solution(object):
def twoCitySchedCost(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
def comp(c1, c2):
r... | 992 | 331 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from __future__ import print_function
import os
import threading
import utils.logger as logger
class CheckerLog(object):
def __init__(self, checker_name):
""" Creates a log file of a specified name
@param checker_name: The... | 1,238 | 383 |
from menpofit.lucaskanade.residual import SSD
from menpofit.lucaskanade.base import LucasKanade
class AppearanceLucasKanade(LucasKanade):
def __init__(self, model, transform, eps=10**-6):
# Note that the only supported residual for Appearance LK is SSD.
# This is because, in general, we don't kno... | 907 | 260 |
from time import time
from weakref import WeakKeyDictionary
from scrapy.http import Response
from scrapy.utils.httpobj import urlparse_cached
from .base import CachePolicy, parse_cachecontrol, rfc1123_to_epoch
class RFC2616Policy(CachePolicy):
""" Cache Policy following RFC 2616, implementing browser-like
ca... | 7,672 | 2,216 |
from .schema import Schema, is_mobile_screen_event, first_letter_up, split_text
def compute_kotlin(schema: Schema) -> str:
"""Compute the output for Kotlin."""
is_screen = is_mobile_screen_event(schema.klass)
result = """/*
* Copyright (c) 2021 New Vector Ltd
*
* Licensed under the Apache License, Vers... | 4,608 | 1,341 |
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Product, Category
from .forms import ProductForm, ProductImageForm
from django.contrib import messages
from django.conf import settings
from hokudai_furima.chat.models import Talk, Chat
from hokudai_fu... | 15,103 | 4,793 |
#!/usr/bin/env python
__all__ = ["plot1d","plot2d"] | 52 | 23 |
from django import forms
from utilities.forms import BootstrapMixin, ExpandableNameField, form_from_model
from virtualization.models import VMInterface, VirtualMachine
__all__ = (
'VMInterfaceBulkCreateForm',
)
class VirtualMachineBulkAddComponentForm(BootstrapMixin, forms.Form):
pk = forms.ModelMultipleCho... | 911 | 265 |
#!/usr/bin/python3
#
# Copyright © 2017 jared <jared@jared-devstation>
#
# Generates data based on source material
import analyze
markov_data = analyze.data_gen()
| 168 | 65 |
from gazette.spiders.base import FecamGazetteSpider
class ScOtacilioCostaSpider(FecamGazetteSpider):
name = "sc_otacilio_costa"
FECAM_QUERY = "cod_entidade:180"
TERRITORY_ID = "4211751"
| 200 | 92 |
#!/usr/bin/env python3
#! -*-conding:utf-8 -*-
#!@Time :2018/4/11 17:14
#!@Author :@liuweqia
#!@File :class.py
import pygame,random
from pygame.locals import *
from pygame import Rect
class Arrow(pygame.sprite.Sprite):
def __init__(self, x, y, property=0):
pygame.sprite.Sprite.__init__(self)
#... | 10,373 | 3,581 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created by Kanson on 2020/1/12 16:03.
"""
import random
import datetime
def tid_maker():
a = int (datetime.datetime.now ().timestamp ())
b = int (''.join ([str (random.randint (0, 9)) for i in range (3)]))
a = str (a)
b = str (b)
c = a + b
retur... | 324 | 139 |
# from imageio import formats
class ImageFormat(object):
def __repr__(self):
# attrs = list()
for key, val in self.__dict__.items():
print str(key), ": ", str(val)
# return str(attrs)
def __init__(self, ext, bit_depth, data_space):
self._extension = ext
... | 6,016 | 1,864 |
import pandas as pd
import numpy as np
import pickle
train_comment_path = '/Users/slade/Documents/YMM/Code/UCGPCG/src/jobs/terror_recognition/train_model/new_model/comment_cutwords.csv'
train_comment_data = pd.read_csv(open(train_comment_path, 'rU'), header=0)
train_comment_data = train_comment_data.sort_values(['lab... | 1,194 | 465 |
import operator
import os
from tqdm import tqdm
PART_SIZE = 100
def solve2(teams, pizzas):
if len(pizzas) < 1:
return
for team in tqdm(teams):
if len(pizzas) < 1:
break
maxScore = 0
maxScoreIdx = 0
for i, pizza in enumerate(pizzas[0:PART_SIZE]):
... | 4,215 | 1,590 |
# Advent of Code 2019
# challenge day 7
# https://adventofcode.com/2019/day/7
from itertools import permutations
def grav_asis_prog(arr, entrada, output, i=0):
flag = True
while i <= len(arr):
# Add
if arr[i] % 100 == 1:
par1, par2, par3 = arr[i+1:i+4]
mod... | 4,524 | 1,820 |
__version__ = '17.11'
from .base import DAL
from .objects import Field
from .helpers.classes import SQLCustomType
from .helpers.methods import geoPoint, geoLine, geoPolygon
| 180 | 64 |
import cadquery as cq
import cqparts
from cadquery import Solid
from cqparts.params import *
from cqparts.display import render_props, display
from cqparts.constraint import Fixed, Coincident
from cqparts.constraint import Mate
from cqparts.utils.geometry import CoordSystem
class Belt(cqparts.Part):
# Parameters
... | 1,349 | 461 |
from rest_framework import serializers
from core.models import Tag, Author, Book
class TagSerializer(serializers.ModelSerializer):
"""Serializer for tag objects"""
class Meta:
model = Tag
fields = ('id', 'name')
read_only_fields = ('id',)
class AuthorSerializer(serializers.ModelSer... | 1,497 | 419 |
import discord
from discord.ext import commands
from config import TOKEN
import os
bot = commands.Bot(command_prefix=">>")
@bot.event
async def on_ready():
print("Ready")
@bot.command()
async def ping(ctx):
latency = round(bot.latency * 1000, 2) # 364.98 ms
await ctx.send(f"**Latency:** {latency} ms")
f... | 436 | 179 |
import os
import json
import boto3
import botocore
from datetime import date
def lambda_handler(event, context):
dynamodb = boto3.resource('dynamodb', region_name = 'us-east-1')
dynamoTable = "oneconnect-jenkins-dev"
print(event)
request = event['Records'][0]['cf']['request']
headers = request['... | 3,335 | 874 |
from api import db
class Base(db.Model):
__abstract__=True
id = db.Column(db.Integer, primary_key=True)
date_created = db.Column(db.DateTime)
date_modified = db.Column(db.DateTime)
class Item(Base):
__tablename__ = 'Item'
def __init__(self, name):
self.name = name
name = db.Colum... | 402 | 143 |
# Given 2 strings, give a new string made of the fist, middle and last character
#each string
string1 = "david"
string2 = "fishe"
middle1 = int((len(string1)/2))
middle2 = int((len(string2)/2))
print(string1[0] + string2[0] + string1[middle1] + string2[middle2] + string1[-1:] + string2[-1:])
| 294 | 111 |
# -*- coding: utf-8 -*-
"""Export utilities."""
| 49 | 23 |
"""
Test load_data.py module.
"""
import pytest
from src import load_data
def test_parse_s3():
"""Correctly splits bucket and path."""
bucket, path = load_data.parse_s3("s3://my-bucket/my-path")
assert bucket == "my-bucket"
assert path == "my-path"
def test_parse_s3_long_path():
"""Correctly sp... | 669 | 243 |
import Cyclops,sys
from xml.dom.ext.reader import Sax2
from xml.dom import ext
def test():
data = sys.stdin.read()
doc = Sax2.FromXml(data)
b1 = doc.createElementNS("http://foo.com","foo:branch")
c1 = doc.createElementNS("http://foo.com","foo:child1")
c2 = doc.createElementNS("http://foo.com","f... | 1,041 | 402 |
import torch
from torch.utils.data.dataset import Dataset
from torchvision import transforms
import torchvision.transforms.functional as TF
import numpy as np
from PIL import Image, ImageFilter, ImageDraw
import pandas as pd
import matplotlib as mpl
mpl.use('Agg')
from matplotlib import cm
import matplotlib.pyplot a... | 20,957 | 7,096 |
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 appl... | 1,678 | 538 |
"""empty message
Revision ID: 3fe295f88b49
Revises: 907bade2acf1
Create Date: 2017-05-23 15:06:40.128657
"""
# revision identifiers, used by Alembic.
revision = '3fe295f88b49'
down_revision = '907bade2acf1'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic ... | 634 | 256 |
import connexion
import six
from swagger_server.models.bill_list import BillList # noqa: E501
from swagger_server import util
from client import bcosclient as bcos
import json
from client.datatype_parser import DatatypeParser
from client.common import transaction_common
# #找到abi文件
# def default_abi_file(contractn... | 2,053 | 759 |
# -*- coding: utf-8 -*-
from django.db import models, migrations
import rels.django
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migr... | 5,531 | 1,738 |
# -*- coding: utf-8 -*-
import sys
import analyze as al
import common as cm
import app as ap
def do_analyze():
# 変数不足時は終了
if not sys.argv[1]:
return
youtube_url = sys.argv[1]
# ID部分の取り出し
youtube_id = al.get_youtube_id(youtube_url)
if not youtube_id:
return
queue_path = a... | 1,197 | 496 |
import busio
from digitalio import DigitalInOut
import board
import adafruit_rfm9x
class LoRaSender():
"""Manages sending messages on LoRa radio
Specifically interfaces with the RFM9x module that we are
currently connecting to the ScrubCam as part of the Adafruit
Radio+OLED Bonnet.
"""
def ... | 857 | 314 |
"""
Generates and returns a dictionary containing the superset of (i.e., all)
legal moves on a four player chessboard.
"""
from math import atan2
from copy import deepcopy
row_size = 14
raster_size = row_size * row_size
DIRECTIONS = [(1, 0), (1, 1), (0, 1), (-1, 1), # straight lines
(-1, 0), (-1, -1), ... | 4,130 | 1,737 |
from toil.common import Toil
from toil.job import Job
class LocalFileStoreJob(Job):
def run(self, fileStore):
# self.TempDir will always contain the name of a directory within the allocated disk space reserved for the job
scratchDir = self.tempDir
# Similarly create a temporary file.
... | 719 | 208 |
from torch.utils import data
import torch
import os
from collections import defaultdict
import numpy as np
from utils.vocab import Vocabulary, build_vocab
import random
from nltk import word_tokenize
from LM.lm_config import Config
config = Config()
class Yelp(object):
"""The Yelp dataset."""
def __init__(s... | 2,527 | 880 |
from public import db
from libs.model import ModelMixin
from sqlalchemy import text, func
from flask_login import UserMixin, login_manager
class User(db.Model, ModelMixin, UserMixin):
__tablename__ = 'account_users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=T... | 770 | 260 |
from django.db import models
class Contact(models.Model):
"""basic contact number"""
name = models.CharField(max_length=256)
number = models.CharField(max_length=256)
description = models.TextField()
def __str__(self):
return "%s : %s " % (self.name, self.number)
| 295 | 94 |
import binascii
import os
import struct
from smbprotocol.structure import BoolField, BytesField, EnumField, \
IntField, ListField, Structure, StructureField, DateTimeField
from pypsexec.exceptions import PAExecException
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
from... | 511,100 | 386,346 |
#!/usr/bin/env python3
# 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 writing, software
... | 1,026 | 325 |
# This file is auto-generated, don't edit it. Thanks.
from alibabacloud_tea_rpc.client import Client as RPCClient
from alibabacloud_ocr20191230 import models as ocr_20191230_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_tea... | 60,224 | 18,166 |
"""
当我们获取的预结构的聚类数大于实际的聚类数时,我们需要对预结构中的簇进行调整(合并)
此处我们选用k-means算法进行簇与簇之间的合并
"""
from sklearn.cluster import KMeans
import numpy as np
import pandas as pd
# 假设簇核集样本为第1、3、4、5个样本
core = [0, 2, 3, 4]
# 假设簇环集样本为第2、6个样本
halo = [1, 5]
# 如果能将halo中的样本的类别标记为[1,2]则说明标记对了
# 假设核结构为【1 3 4 2】
core_structure = [1, 3, 4, 2]
pre_structur... | 1,639 | 1,005 |
# Copyright 2021 Vaticle
#
# 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 writing, soft... | 22,408 | 4,537 |
from pandas_datareader import data as pdr
import pandas as pd
import numpy as np
from datetime import timedelta
from get_all_tickers import get_tickers as gt
import ipywidgets as widgets
import requests
class Helper:
def getParameters(self):
forecast = widgets.Text(
value='7;14;30',
... | 7,545 | 2,348 |
#
# This Python script is a combination of various scripts and a pickle found at
# https://github.com/sloria/textblob-aptagger which are licensed under
# the MIT License https://github.com/sloria/textblob-aptagger/blob/dev/LICENSE
# for those scripts: Copyright 2013 Matthew Honnibal
#
# more in detail explanation of ho... | 10,592 | 3,208 |
import argparse
import json
import re
import sys
sys.path.append("..")
from src.core.lexicon import Lexicon, add_lexicon_arguments
from src.core.schema import Schema
from stop_words import get_stop_words
from src.core.event import Event
from src.model.vocab import is_entity
from src.model.preprocess import Preprocesso... | 3,374 | 1,031 |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2011, Cabo Communications A/S
# All rights reserved.
#
import models
from flaskext import wtf
class JobForm(wtf.Form):
url = wtf.html5.URLField('URL', [
wtf.Required('Hmm, husk du skal at indtaste en URL'),
wtf.URL('Hey, URLen er ikke gyldig!')
])
... | 562 | 223 |
# SCRIPT: ufoRig
# DESCRIPTION: A GUI based low level tool for editing
# DESCRIPTION: Unified Font Object (.UFO) files
# -----------------------------------------------------------
# (C) Vassil Kateliev, 2021 (http://www.kateliev.com)
# ------------------------------------------------------------
# https://github.c... | 5,157 | 2,013 |
'''
Description:
displays covid data for local and national, covid news articles
with links to those articles and scheduled updates.
Takes input data and then uses it to schedule updates.
updates data when scheduled.
'''
import json
import sched
import time
import logging
from typing import Callabl... | 7,290 | 2,109 |
user_input = input("Please enter a string ")
# length = len(user_input)
# print(user_input[length::-1])
# l = "".join(list(reversed(user_input)))
# print(l)
print(user_input[::-1])
| 184 | 74 |
"""
Benchmarks for the CUDA backend.
"""
from __future__ import division
import math
import sys
import numpy as np
def _jit_setup1():
from numba import cuda, float32, float64
def addmul(x, y, out):
i = cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x
if i >= x.shape[0]:
ret... | 10,454 | 4,145 |
from typing import Optional
import httpx
import shortuuid
from fastapi import Response
from starlette import status
from starlette.responses import JSONResponse
from ..dependencies import core
from ..dependencies.models.user import User
from ..internals.globals import SSU
async def get(id: str):
user = User(id=... | 4,256 | 1,277 |
import unittest
from src.supermarket import *
from test_helpers import *
import sqlite3
class TestItem(unittest.TestCase):
def setup(self):
self.database_path = 'example.db'
init_empty_database(self.database_path)
database.Database.database_path = self.database_path
def teardown(self)... | 2,161 | 662 |
FROM tensorflow/tensorflow:2.3.1-gpu
#ENV version_tf=2.4.0
ENV version_tf=2.3.1
RUN apt-get update && apt-get install -y --quiet --no-install-recommends \
vim \
wget
# python
RUN pip install -q --upgrade pip
COPY ./requirements.txt ./
RUN pip install -r requirements.txt -q
WORKDIR /work
#ENTRYPOINT ["/bin/bash"]
... | 361 | 144 |
from TechApp import db, models
from TechApp.models import Loja
import unittest
class TechAppTestCase(unittest.TestCase):
def setUp(self):
# create the database
db.drop_all()
db.create_all()
def test_obter_lojas(self):
db.session.add(Loja('Macavi'))
db.session.add(Loja('Casas Bahia'))... | 1,515 | 573 |
import re
from .settings import Settings
class _RE:
"""
Regular Expressions wrapper
"""
@classmethod
def instance(cls):
if not hasattr(cls, "_instance"):
cls._instance = cls()
return cls._instance
def __init__(self):
self.patterns = {}
def get(self, ... | 2,263 | 549 |
# Copyright 2022 Garena Online Private 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 agre... | 14,959 | 5,241 |
from datetime import datetime
time = datetime.now()
print(time, type(time))
print("----------------------")
time = str(time)
print(time, type(time))
print("----------------------")
time = datetime.now()
# time = "1618815060"
print(time, type(time))
time = time.strftime('%Y-%m-%d %H:%M:%S')
print(time, ... | 333 | 127 |
from app import app
if __name__ == '__main__':
app.run(
app.config['HOST'],
app.config['PORT'],
app.config['DEBUG']
)
| 155 | 52 |
import datetime, pytz
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.http import HttpResponseServerError
from django.http import HttpResponseBadRequest
from django.urls import reverse
from blockchain.blockexplorer import get_address
from blockchain.v2.receive import rece... | 3,024 | 904 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'tandylayout.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, ... | 21,194 | 7,206 |
"""599. Minimum Index Sum of Two Lists
https://leetcode.com/problems/minimum-index-sum-of-two-lists/
"""
from typing import List
class Solution:
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
ans = []
idx_sum = 2000
store = dict()
for i, v in enumerate(l... | 656 | 209 |
class Solution:
def XXX(self, s: str) -> int:
n = len(s)
start, end = 0, -1
for i in range(n):
if i == 0 and s[i] != " ":
start = i
if s[i] != " " and s[i-1] == " ":
start = i
if s[i] == " " and s[i-1] != " ":
... | 431 | 151 |
# Generated by Django 3.2.2 on 2021-05-15 15:45
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Circuit",
fields=[
... | 13,793 | 3,180 |
precos = [0,4.00,4.50,5.00,2.00,1.50]
codigo, quantidade = input().split(' ')
valor = precos[int(codigo)] * float(quantidade)
print(f'Total: R$ {valor:.2f}')
| 159 | 83 |
from blackcat.postprocessing.post_processor import BlackCatPostProcessor
from blackcat.postprocessing.steps.trim_to_relevant_data import PostStepFlattenRelevantData
class TestPostProcessor(object):
TEST_OBJ = {
'node': {
'securityVulnerability': {'test-field': True},
'dismisser': '... | 1,009 | 309 |
from .django_cache import DjangoCache
from .omnistone import Omnistone | 70 | 21 |
#from flask_wtf import FlaskForm
from wtforms import Form, StringField, PasswordField, validators
class RegistrationForm(Form):
username = StringField('Username', [validators.Length(min = 4, max = 20), validators.Required()], id = "input_fields")
password = PasswordField('New Password', [validators.DataRequire... | 480 | 135 |
"""FixedTfidfVectorizer."""
import numpy as np
from sklearn.feature_extraction.text import (
TfidfVectorizer as SklearnTfidfVectorizer,
VectorizerMixin,
)
from sklearn.utils import check_array
from foreshadow.base import BaseEstimator
from foreshadow.wrapper import pandas_wrap
@pandas_wrap
class FixedTfidfV... | 1,881 | 578 |
from django.contrib.auth import logout
import datetime
from settings import SESSION_IDLE_TIMEOUT
class SessionIdleTimeout(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.user.is_authenticated:
current_datetime = d... | 771 | 200 |
# Network representation learning with Line algorithm
# Author: Sebastian Haslebacher 2021-12-22
import networkx as nx # https://networkx.org/documentation/stable/tutorial.html
import numpy as np
import random
import argparse
import pickle
class Sampler:
"""
Maintains data-structure for negative sampling.
... | 3,828 | 1,261 |
from sys import argv
if len(argv) < 3:
exit(1)
device_id = argv[1]
sensor_type = argv[2]
import logging
import os
from dotenv import load_dotenv
from devolo_home_control_api.homecontrol import HomeControl
from devolo_home_control_api.mydevolo import Mydevolo
load_dotenv()
logging.disable()
mydevolo = Mydevolo(... | 777 | 304 |
import setuptools
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Education',
'Operating System :: Microsoft :: Windows :: Windows 10',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3'
]
with open('README.md', 'r') as fh:
long_descri... | 779 | 255 |
""" Order model. """
# Django
from django.db import models
class Order(models.Model):
# Model b
""" Order model. """
# User information
user = models.ForeignKey("users.User", on_delete=models.CASCADE, related_name="orders")
first_name = models.CharField(max_length=100)
last_name = models.Char... | 1,399 | 449 |
import json
from csv import reader
from tetpyclient import RestClient
#Tetration IP address
API_ENDPOINT="https://x.x.x.x"
csvName="apps.csv"
restclient = RestClient(API_ENDPOINT, credentials_file='credentials.json', verify=False)
#Scope ID's that are used most Frequently, the ID can be found in the GUI by clicking th... | 1,424 | 431 |
# Copyright (c) 2019 Platform9 Systems Inc.
#
# 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 ... | 2,893 | 882 |
from pathlib import Path
from typing import Optional
class Filter:
"""
The filter is one of the sub-components of the *Organizer*. An organizer is associated with a
single filter. The organizer relies on the filter to filter out files that do not correspond
to episode files. Thus, it calls the filter ... | 2,440 | 623 |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... | 3,243 | 1,003 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: spaceone/api/monitoring/plugin/event.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _r... | 12,805 | 4,831 |
import numpy as np
import scipy
from scipy.special import cbrt
from GPy.models import GradientChecker
_lim_val = np.finfo(np.float64).max
_lim_val_exp = np.log(_lim_val)
_lim_val_square = np.sqrt(_lim_val)
_lim_val_cube = cbrt(_lim_val)
from GPy.likelihoods.link_functions import Identity, Probit, Cloglog, Log, Log_ex_1... | 6,783 | 2,526 |
#!/usr/bin/env python
from ridgeback_msgs.msg import *
from warthog_msgs.msg import *
import rospy
from std_msgs.msg import *
from colour import Color
import lightPatterns
STATE = "IDLE"
def RAINBOWS():
global STATE
node = rospy.init_node('platform_indicator_light_controller')
rate = rospy.get_param('~u... | 2,510 | 910 |
from platypush.plugins import Plugin, action
class SwitchPlugin(Plugin):
"""
Abstract class for interacting with switch devices
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
@action
def on(self, device, *args, **kwargs):
""" Turn the device on """
raise... | 1,161 | 332 |
from datetime import timedelta
from functools import partial
import itertools
from parameterized import parameterized
import numpy as np
from numpy.testing import assert_array_equal, assert_almost_equal
import pandas as pd
from toolz import merge
from zipline.pipeline import SimplePipelineEngine, Pipeline, CustomFacto... | 115,957 | 37,954 |
#
# @lc app=leetcode.cn id=463 lang=python3
#
# [463] 岛屿的周长
#
# https://leetcode-cn.com/problems/island-perimeter/description/
#
# algorithms
# Easy (59.76%)
# Total Accepted: 5.4K
# Total Submissions: 9K
# Testcase Example: '[[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]'
#
# 给定一个包含 0 和 1 的二维网格地图,其中 1 表示陆地 0 表示水域。
#
# ... | 1,407 | 823 |
import matplotlib.pyplot as plt
import numpy as np
import os
from os import path as osp
import argparse
import sys
sys.path.append("..")
import Basics.sensorParams as psp
from compose.dataLoader import dataLoader
from compose.superposition import SuperPosition, fill_blank, cropMap
parser = argparse.ArgumentParser()
pa... | 3,411 | 1,316 |
from paddle import fluid
import numpy as np
import os
from PIL import Image
import config
from tools import hdf5_manager
_image_mean = np.array(config.dc['ImageMean'], dtype='float32').reshape((3, 1, 1))
_image_std = np.array(config.dc['ImageStd'], dtype='float32').reshape((3, 1, 1))
def process_image(img):
if ... | 3,285 | 1,083 |
import cassiopeia as cass
from cassiopeia import Summoner
import csv
import collections
import pandas as pd
import random
with open("api_key.txt","r") as f:
api_key=f.read()
#settings
settings = cass.get_default_config()
settings["pipeline"]["RiotAPI"]["api_key"]=api_key
settings["logging"]["print_calls"]=Fal... | 2,791 | 850 |
#-*- coding: utf-8 -*-
from datetime import datetime
import re
from analysis import Analysis
from src.shell.parser.type import TypeLogParser
class TypeAnalysis(Analysis):
def __init__(self, pgm, logfile, data=None):
Analysis.__init__(self, pgm, logfile)
self.data = data
if data == None:
... | 8,161 | 2,502 |
#
# Autogenerated by Thrift Compiler
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py:new_style
#
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from ttypes import *
EDAM_ATTRIBUTE_LEN_MIN = 1
EDAM_ATTRIBUTE_LEN_MAX = 4096
EDAM_ATTRIBUTE_RE... | 7,771 | 4,504 |
from django.shortcuts import render
from .models import Categories, SocialMedia
from django.contrib import messages
from django.core.mail import send_mail
from django.conf import settings
from django.template.loader import render_to_string
# Create your views here.
def index(request):
media_links = SocialMedia.ob... | 1,998 | 514 |