text
string
size
int64
token_count
int64
from sqlite_framework.sql.item.base import SqlItem from sqlite_framework.sql.item.column import Column class TableConstraint(SqlItem): def str(self): raise NotImplementedError() class ColumnListTableConstraint(TableConstraint): def __init__(self, constraint_type: str, *columns: Column): supe...
566
157
from .report_group import GroupReport from .report_single import SingleReport
78
19
""" Mixin for returning history frames. """ from collections import deque from typing import Deque from rx.core.typing import Observable from baboon_tracking.models.frame import Frame class HistoryFramesMixin: """ Mixin for returning history frames. """ def __init__(self, history_fr...
724
228
import json import html from pathlib import Path from elm_doc.utils import Namespace # Note: title tag is omitted, as the Elm app sets the title after # it's initialized. PAGE_TEMPLATE = ''' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="shortcut icon" size="16x16, 32x32, 48x48, 64x64, 128...
1,746
611
''' 实验名称:水位传感器 版本:v1.0 日期:2021.1 作者:01Studio 【www.01Studio.org】 说明:通过水位传感器对水位测量并显示。 ''' #导入相关模块 import time from machine import Pin,SoftI2C,ADC from ssd1306 import SSD1306_I2C #初始化oled i2c = SoftI2C(scl=Pin(10), sda=Pin(11)) #软件I2C初始化:scl--> 10, sda --> 11 oled = SSD1306_I2C(128, 64, i2c, addr=0x3c) #OLED显示屏初始化:128...
1,031
743
from typing import Annotated Problem = Annotated[str, "code cfs problems have, ex. 1348B"] ProblemWidth = int CFSSectionsData = tuple[int, ...]
147
54
import pandas as pd import numpy as np import matplotlib.pyplot as plt ### import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize # from nltk.stem import WordNetLemmatizer from nltk.stem import PorterStemmer ### from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import con...
2,666
914
# -*- coding: utf-8 -*- import csv import json outdirectory = "outputCSV/" tweetsFile = "tweets.txt"; outputFile = "mostUsedHasgtags.csv"; tweetsList = [] # List that contains all the tweets readed from a file hashtagTable = {}; # Dictionary with key= hashtags and value= frecuency for this hashtag """ Returns ...
4,032
1,389
import time import json import argparse import websocket import requests import github MY_NAME = 'kit' # should be able to avoid this in the future TOKEN = 'XXXXXXX' GITHUB_USERNAME_BY_SLACK_USERNAME = { "adam": "adamsmith", # XXXXXXX ... } channel_ids_by_name = {} channel_names_by_id = {} next_id = 0 def send...
4,346
1,734
import discord import requests from discord.ext import commands class Meme(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def meme(self,ctx): r=requests.get("https://memes.blademaker.tv/api?lang=en") res=r.json() title=res['title'] ...
656
236
target_num = 0 j = 0 while target_num == 0: pent_ind = float((1 + ( 1 + 24*j*(2*j-1))**.5)/6) tri_ind = float((-1 + (1+8*j*(2*j-1)))/2) if pent_ind.is_integer() and tri_ind.is_integer(): num = j*(2*j-1) if num != 1 and num != 40755: target_num = num j += 1 print(target_num)...
717
262
#!/usr/bin/python # -*- coding: utf-8 -*- # Importo les llibreries import socket import RPi.GPIO as GPIO import time # Faig la configuració bàsica del GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) # Només utilitzo el 18. Es podria fer un bucle per activar-ne diversos alhora. # Indico ...
801
337
## ------------------------------------------------------------------------------------------------- ## -- Project : MLPro - A Synoptic Framework for Standardized Machine Learning Tasks ## -- Package : mlpro.rl.envmodels ## -- Module : mlp_robotinhtm ## -----------------------------------------------------------------...
16,820
5,775
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author : 陈坤泽 # @Email : 877362867@qq.com # @Date : 2021/02/22 10:29 """ 对icdar2013的三种测评方法的接口封装 官方原版处理两个 zip 文件,这里扩展支持目录、内存对象 """ import re from pyxllib.xl import File, Dir, shorten class IcdarEval: """ >>> gt = {'1.abc': [[158, 128, 411, 181], [443, 128...
3,474
1,821
import os import numpy as np import torch from transformers import BertTokenizer from tensorflow.keras.utils import to_categorical from NewDataLoader import * from config import * import warnings class Features: def __init__(self, **kwargs): self.max_len = kwargs.get('max_len', 250) self.categor...
6,441
2,170
from airflow import DAG from operators import LoadDimensionOperator def load_dim_subdag( parent_dag_name: str, task_id: str, redshift_conn_id: str, sql_statement: str, do_truncate: bool, table_name: str, **kwargs, ): """ Airflow's subdag wrapper. Implements LoadDimensionOperator op...
1,233
383
# coding: utf-8 from __future__ import print_function from __future__ import absolute_import from __future__ import division from src.yolo_net import YoloTest, Yolo import torch import cv2 import numpy as np def read_image(path): img1 = cv2.imread(path) img1 = cv2.resize(img1, (224, 224)) img1 = img1.tr...
1,816
795
# coding=utf-8 """ Google Earth Engine MODIS Collections """ from . import Collection, TODAY, Band from functools import partial IDS = [ 'MODIS/006/MOD09GQ', 'MODIS/006/MYD09GQ', 'MODIS/006/MOD09GA', 'MODIS/006/MYD09GA', 'MODIS/006/MOD13Q1', 'MODIS/006/MYD13Q1' ] START = { 'MODIS/006/MOD09GQ': '2000-...
11,572
4,413
""" This module provides a method to generate a random number between 0 and the specified number """ import random import math def random_num(max): """ Generates a random number Parameters: max(int): the range upper limit Returns: int: the random number """ return math.floor(rando...
338
95
class Printer(object): """ """ def __init__(self): self._depth = -1 self._str = str self.emptyPrinter = str def doprint(self, expr): """Returns the pretty representation for expr (as a string)""" return self._str(self._print(expr)) def _print(self, expr): ...
847
243
import math import numpy as np def rotate(pts, angle, pivot=(0., 0.)): pivot = np.asarray(pivot) angle = math.pi*angle/180 c, s = np.cos(angle), np.sin(angle) rotation = np.array([[c, -s], [s, c]]) return (np.asarray(pts) - pivot) @ rotation + pivot
272
107
import ctypes import struct from .dave_define import * from .dave_enum import * from .dave_msg_id import * from .dave_msg_struct import * from .dave_struct import *
166
58
# -*- coding: utf-8 -*- """@package Methods.Machine.Conductor.check Check that the Conductor is correct @date Created on Thu Jan 22 17:50:02 2015 @copyright (C) 2015-2016 EOMYS ENGINEERING. @author pierre_b """ from pyleecan.Methods.Machine.LamSlotWind.check import Lam_WindCheckError def check(self): """Check th...
551
212
from pathlib import Path from typing import List import cv2 import numpy as np from shapely import geometry from shapely.strtree import STRtree from wholeslidedata.annotation.structures import Annotation, Point, Polygon from wholeslidedata.image.wholeslideimage import WholeSlideImage from wholeslidedata.image.wholesli...
3,414
1,082
import pytest from ..slicing_tuples import tuple_slice @pytest.mark.parametrize('names, ages, cities, expected', [ (('Gitau', 'Kanyoi', 'Ndegwa'), (13, 24, 5), ('Njogu-ini', 'Limuru', 'Kamae'), ( ('Gitau', 13, 'Njogu-ini'), ('Kanyoi', 24, 'Limuru'), ('Ndegwa', 5, 'Kamae') )), (('Totua', 'Suhi'...
578
252
# -*- coding: utf-8 -*- """This class maintains the internal dfTimewolf state. Use it to track errors, abort on global failures, clean up after modules, etc. """ from dataclasses import dataclass from concurrent.futures import ThreadPoolExecutor, Future import importlib import logging import threading import tracebac...
28,653
8,452
### Implements database management for Authentication Server and TGS ### from Query import * from sqlite3 import * from config import * class DBManager(object): def __init__(self, dbname): try: self.conn = connect(dbname) self.cursor = self.conn.cursor() except Exception as e: print str(e) def creat...
1,374
574
from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Person from .serializers import PersonSerializer @api_view(['GET']) def list_people(request): people = Person.objects.all() serializer = PersonSerializer(people, m...
451
128
import numpy as np import matplotlib.pyplot as plt field_width = 396 #cm field_hight = 180 #cm goal_length = 180 #cm threshold = 36 field_width_threshold_num = field_width / threshold + 1 field_width_threshold = [Y * threshold - field_width / 2.0 for Y in xrange(field_width_threshold_num)] field_hight_threshold_num =...
8,867
3,109
from pytest import raises from gsea_api.molecular_signatures_db import MolecularSignaturesDatabase def test_load(): msigdb_7_1 = MolecularSignaturesDatabase('tests/test_msigdb', version=7.1) assert msigdb_7_1.version == '7.1' assert msigdb_7_1.gene_sets == [ { 'name': 'c2.cp.reactome'...
1,089
447
from django.contrib import admin, auth from django.contrib.auth.models import Group from django.shortcuts import get_object_or_404, redirect, render from django.urls import path, reverse, reverse_lazy from django.utils.translation import gettext_lazy as _ from adminsortable2.admin import SortableAdminMixin from froid...
11,387
3,201
try: import unittest2 as unittest except: import unittest from mpegdash.parser import MPEGDASHParser class XML2MPDTestCase(unittest.TestCase): def test_xml2mpd_from_string(self): mpd_string = ''' <MPD xmlns="urn:mpeg:DASH:schema:MPD:2011" mediaPresentationDuration="PT0H1M52.43S" minBuffer...
2,995
1,160
def BinarySearchIt(A, low, high, key): while low <= high: mid = low + ((high - low)//2) if key == A[mid]: return mid elif key < A[mid]: high = mid - 1 else: low = mid + 1 return low - 1 arr = [3, 5, 8, 10, 12, 15, 18, 20, 20, 50, 60] low = 1 ...
513
207
#--- Day 2: Bathroom Security --- from typing import List def parse(input_data: str) -> List[List[str]]: lines = input_data.strip().split() directions = [list(line) for line in lines] return directions def move1(x, y, direction): if direction == 'U': y -= 1 elif direction == 'D': ...
2,133
839
#!/usr/bin/python3 import argparse import koji import os from pprint import pprint def main(): parser = argparse.ArgumentParser(description="osbuild koji client") parser.add_argument("--url", metavar="URL", type=str, default="https://localhost/kojihub", help="T...
2,875
876
# -*- coding: utf-8 -*- """Main module {{cookiecutter.project_name}} """ from __future__ import absolute_import from __future__ import unicode_literals
153
51
from config import * from utils import * import datetime import pickle indir_vocab_jnames = VOCAB_JNAMES indir_bio_srt = BIO_SRT indir_sorted_fperson_fname = SORTED_FPERSON_FNAME indir_sorted_lperson_fname = SORTED_LPERSON_FNAME print indir_vocab_jnames with open(indir_vocab_jnames,'rb') as v: all_vocab=pickle...
5,382
1,871
from rich.console import Console from rich.table import Table from rich.progress import track from time import sleep import sys class Profile(object): def get_datas(self, datas): try: print(datas['login']) print(datas['name']) print(datas['bio']) print(data...
2,182
552
# coding: utf-8 import datetime from flask_login import login_required, current_user from flask import Blueprint, request from app.libs.http import jsonify, error_jsonify from app.libs.db import session from app.serializer.notice import NoticeParaSchema from app.model.notice import Notice bp_admin_notification = B...
2,459
944
from fixture.orm import ORMfixture from model.group import Group from model.contact import Contact import random db = ORMfixture(host='127.0.0.1', name='addressbook', user='root', password='') def test_delete_contact_from_group(app): if len(db.get_contact_list()) == 0: app.contact.create(Contact...
1,345
453
from django.urls import reverse_lazy from django.contrib.auth import get_user_model from django.views.generic import CreateView from . import forms User = get_user_model() class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('login') template_name = 'accounts/signup.htm...
323
99
#!/usr/bin/env python # -*- encoding: utf-8 -*- from torch.nn import Module from torch.nn.modules.loss import _Loss from torch.optim import Optimizer from colossalai.builder import build_gradient_handler from colossalai.context import ParallelMode from colossalai.core import global_context as gpc from colossalai.logg...
6,498
1,696
import numpy as np import cv2 cap = cv2.VideoCapture('motion.avi') ret, frame = cap.read() gs_im0 = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) points_prev = cv2.goodFeaturesToTrack(gs_im0, 100, 0.03, 9.0, False) while(cap.isOpened()): ret, frame = cap.read() gs_im1 = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)...
718
326
import math class Renderer: # Convenience methods def drawCircle( self, radius = 10, res = 30): pass class FilledPolygon(): def __init__(): pass def render(self): if len class PolyLine(): def __init__(): pass def make_circle(radius = 10, res = 20, filled = ...
574
194
"""Tests for the servo classes.""" from typing import List, Optional, Type import pytest from j5.backends import Backend from j5.boards import Board from j5.components.servo import Servo, ServoInterface, ServoPosition class MockServoDriver(ServoInterface): """A testing driver for servos.""" def get_servo_p...
2,770
842
frase = str(input('Digite uma frase: ')).lower() print('Sobre a letra "a": \nQuantas vezes ela aparece? {} vezes;'.format(frase.count('a'))) print('Em que posição ela aparece pela primeira vez? {};'.format(frase.strip().index('a')+1)) print('Em que posição ela aparece pela última vez? {}.'.format(frase.strip().rfind('a...
327
117
from django.contrib.auth.mixins import LoginRequiredMixin from django.views import View from django.views.generic import ListView from django.utils.http import is_safe_url from django.contrib import messages from rest_framework import status from django.core.exceptions import ObjectDoesNotExist from django.shortcuts im...
7,546
2,109
"""InterviewBit. Programming > Arrays > Rotate Matrix. """ class Solution: """Solution.""" def rotate(self, A): """Rotate matrix.""" n = len(A) for l in range(0, n // 2): # l = level for o in range(0, n - (l * 2) - 1): # o = offset tlr, tlc = l, l + o #...
1,843
784
# Copyright (c) 2019, 2020, Oracle Corporation and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. connect('weblogic', 'welcome1', 't3://DOMAINNAME-admin-server:7001') # get all JDBC Properties dsCounter = 0 allJDBCResources = cmo.getJDBCSyst...
2,334
756
class No: def __init__(self, dado): self._dado = dado self._direita = None self._esquerda = None self._pai = None def get_dado(self): return self._dado def get_direita(self): return self._direita def get_esquerda(self): return self._...
682
245
from rdr_service import clock from rdr_service.dao.biobank_stored_sample_dao import BiobankStoredSampleDao from rdr_service.dao.participant_dao import ParticipantDao from rdr_service.model.biobank_stored_sample import BiobankStoredSample from rdr_service.model.participant import Participant from tests.helpers.unittest_...
1,283
409
import socket, os, atexit from flask import Flask, jsonify, request from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask.helpers import send_from_directory, url_for from zeroconf import ServiceInfo, Zeroconf from pantryflask.config import FlaskConfig from pantryflask.auth import token_a...
2,769
906
# # Copyright 2017 Mycroft AI 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 to in writ...
39,370
11,302
# Defines a velocity profile, which is the big object we've been # working towards. from math import sqrt, ceil import json class PlanningPoint(object): # pylint: disable=too-many-instance-attributes # planning points unfortunately require this much data def __init__(self, position, time, radius, distanc...
6,976
2,016
import os import subprocess test_set_path = '/Users/runelangergaard/Documents/SmartAnnotation/data/test_set' test_imgs = os.listdir(test_set_path) test_imgs cwd_path = '/Users/runelangergaard' os.chdir(cwd_path) for img in test_imgs: full_path = os.path.join(test_set_path, img) subprocess.run([ "scp",...
472
199
import random import grom grom.debug(False) dirName = "dump\\" inputName = "example.bmp" outputName = "output.bmp" g = grom.Genome(dirName + inputName, partition=[ ('head', 0x76), ('raw') ]) print(g) print(g.partition) g.apply(lambda x: 255 - x, ['raw']) g(dirName + outputName, pause=False)
304
126
################################################################################ # 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...
3,351
866
""" Problem: You are given a list of N points (x1, y1), (x2, y2), ..., (xN, yN) representing a polygon. You can assume these points are given in order; that is, you can construct the polygon by connecting point 1 to point 2, point 2 to point 3, and so on, finally looping around to connect point N to point 1. Determin...
2,195
764
# Copyright 2021 Alexis Lopez Zubieta # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publi...
968
248
# Author: Fabio Rodrigues Pereira # E-mail: fabior@uio.no # Author: Per Morten Halvorsen # E-mail: pmhalvor@uio.no # Author: Eivind Grønlie Guren # E-mail: eivindgg@ifi.uio.no try: from Oblig3.packages.preprocess import load_raw_data, filter_raw_data, pad from Oblig3.packages.preprocess import OurCONLLUData...
2,546
983
import logging import os import random import string import unittest import warnings from boxsdk.exception import BoxAPIException, BoxOAuthException from parsons.box import Box from parsons.etl import Table """Prior to running, you should ensure that the relevant environment variables have been set, e.g. via # Note...
11,176
3,557
import matplotlib.pyplot as plt import numpy as np import cv2 '''Erosion Method''' def erosion(image, kernel): img_height = image.shape[0] img_width = image.shape[1] kernel_height = kernel.shape[0] kernel_width = kernel.shape[1] h = kernel_height//2 w = kernel_width//2 ...
3,961
1,680
# Generated by Django 3.1.5 on 2021-02-07 08:19 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='FirstMajorSubject', fields=[ ('id', models....
1,652
456
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) lm = LoginManager(app) from app import views, models, oauth
239
78
""" https://leetcode.com/problems/to-lower-case/ Difficulty: Easy Given a string s, return the string after replacing every uppercase letter with the same lowercase letter. Example 1: Input: s = "Hello" Output: "hello" Example 2: Input: s = "here" Output: "here" Example 3: Input: s = "LOVELY" Outp...
511
180
import align_tools as at import matplotlib.pyplot as plt import numpy as np from collections import Counter def h(x): if x>0: return 1 else: return 0 def get_counter(arr, lower_sat=None, upper_sat=None): result = {} for val in arr: if (upper_sat is None or val < upper_sat) and ...
2,495
1,043
from django.apps import AppConfig class SaltConfig(AppConfig): name = 'apps.salt'
88
29
import os from pygears.hdl.sv import SVModuleInst from .ip_resolver import IPResolver class SVVivModuleInst(SVModuleInst): def __init__(self, node, lang=None): resolver = IPResolver(node) super().__init__(node, resolver.lang, resolver) @property def is_generated(self): return True...
1,266
423
import shutil import tempfile from pathlib import Path from typing import Dict import click from commodore.config import Config from .parameters import ClassNotFound, InventoryFactory, InventoryFacts def _cleanup_work_dir(cfg: Config, work_dir: Path): if not cfg.debug: # Clean up work dir if we're not...
1,841
582
begin_unit comment|'# Copyright (c) 2013 Intel, Inc.' nl|'\n' comment|'# Copyright (c) 2013 OpenStack Foundation' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in ...
25,468
12,045
"""Variational autoencoder model.""" from typing import Tuple import torch from torch import nn from torch.nn import functional as F class BaseVAE(nn.Module): """Base class for creating variational autoencoders (VAEs). The module is designed to connect user-specified encoder/decoder layers to form a la...
4,045
1,352
from django.http.response import HttpResponse from rest_framework import serializers, viewsets from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from .excel import Excel XLSX_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' class ExportVie...
2,037
579
# Copyright (c) 2018 Serguei Kalentchouk et al. All rights reserved. # Use of this source code is governed by an MIT license that can be found in the LICENSE file. from node_test_case import NodeTestCase, cmds class TestClamp(NodeTestCase): def test_clamp(self): node = self.create_node('Clamp', {'input': ...
1,593
672
import pytest from models import TodoItem pytestmark = [ pytest.mark.usefixtures("use_db"), ] @pytest.fixture def chat(factory): return factory.chat() @pytest.fixture def items(factory, chat): return [ factory.item(chat=chat, text="Hello"), factory.item(chat=chat, text="Nice!"), ] ...
1,111
417
import copy import json from django.contrib import admin from django.db import models from web.multilingual.data_structures import MultiLingualTextStructure from web.multilingual.form import MultiLingualFormField, MultiLingualRichTextFormField, \ MultiLingualRichTextUploadingFormField from web.multilingual.widget...
3,945
1,038
from django.test import TestCase from shop.models import Product from django.contrib.auth.models import User from coupons.forms import CouponForm class CartAddViewTest(TestCase): def setUp(self): self.data = {"quantity" : 2, "update" : False} self.product = Pro...
2,859
897
from __future__ import annotations import asyncio from typing import Any import asynctest.mock # type: ignore import pytest # type: ignore import pytest_mock._util # type: ignore pytest_mock._util._mock_module = asynctest.mock class EventLoopClockAdvancer: """ A helper object that when called will advan...
2,134
627
#=============================================================================# # # # MODIFIED: 15-Jan-2019 by C. Purcell # # # ...
1,247
330
# -*- coding: utf-8 -*- """ Physical or mathematical constants. Since every code has its own conversion units, this module defines what QE understands as for an eV or other quantities. Whenever possible, we try to use the constants defined in :py:mod:aiida.common.constants:, but if some constants are slightly differen...
985
392
# This file is MACHINE GENERATED! Do not edit. # Generated by: tensorflow/python/tools/api/generator/create_python_api.py script. """Public API for tf.keras.applications namespace. """ from __future__ import print_function as _print_function import sys as _sys from keras.api._v2.keras.applications import densenet fr...
2,639
881
from flash.vision.embedding.image_embedder_model import ImageEmbedder, ImageEmbedderDataPipeline
97
29
import os import sys import logging from configparser import ConfigParser from .open_struct import OpenStruct from .section_struct import SectionStruct # TODO: use file lock when read/write def choose_theirs(section, option, mine, theirs): '''Always prefer values for keys from file.''' return theirs def c...
5,554
1,525
import origen # pylint: disable=import-error import pytest, pathlib, os, stat, abc from os import access, W_OK, X_OK, R_OK from tests.shared import clean_falcon, clean_compiler, tmp_dir def user_compiler(): ''' End users should access the compiler via ``origen.app.compiler``. ''' return origen.app.co...
10,327
3,078
from flask import Flask, jsonify, request import predict import socket app = Flask(__name__) @app.route('/') @app.route('/home') def home(): """Renders the home page.""" return ( "Welcome Guest!!!" ) #to spedicy route after url @app.route('/api', methods=['POST']) def get_tasks(): #get url fro...
999
351
# (c) 2016, Hao Feng <whisperaven@gmail.com> __version__ = '0.1.0'
68
39
from Dimension_Reduction import Viewer import pandas as pd view_tool = Viewer() reduc = 'pca' suffix = '5' data_plot = pd.read_csv(f"{reduc}_dim2_{suffix}.csv", delimiter=",") models = ['km', 'fuzz', 'gmm', 'dbsc', 'hier', 'spec' ] for model in models: print(model) labels = pd.read_csv(f"labels_{mo...
418
168
from collections import UserList from dataclasses import dataclass, field from datetime import datetime from typing import List, Dict, Any, Optional, Type DATE_FORMAT = '%Y-%m-%d %H:%M:%S %Z' def parse_date(tumblr_date: str) -> datetime: return datetime.strptime(tumblr_date, DATE_FORMAT) @dataclass class Link:...
6,621
2,253
from jobs_scraper import JobsScraper # Let's create a new JobsScraper object and perform the scraping for a given query. position_var = "Python" scraper = JobsScraper(country="ca", position=position_var, location="Toronto", pages=3) df = scraper.scrape() df.to_csv(rf'{position_var} jobs.csv', index = False)
311
112
import tarfile, sys,os from PyQt4.QtCore import * from PyQt4.QtGui import * app = QApplication(sys.argv) try: zfile = tarfile.open(sys.argv[1], "r:gz" ) zfile.extractall(sys.argv[2]) zfile.close() mb = QMessageBox('Red-R Updated', "Red-R has been updated'", QMessageBox.Informa...
810
293
from ctypes import * #from multiprocessing import Process, Queue import queue import time from threading import Lock,Thread from fastapi import FastAPI from fastapi import Request from fastapi import WebSocket, WebSocketDisconnect import uvicorn #from yolo_service import * import socket import random from typing import...
9,346
3,139
import numpy as np from pyqmc.slater import sherman_morrison_row from pyqmc.slater import sherman_morrison_ms def test_sherman_morrison(): ratio_err, inv_err = run_sherman_morrison() assert ratio_err < 1e-13, f"ratios don't match {ratio_err}" assert inv_err < 1e-13, f"inverses don't match {inv_err}" ...
2,389
1,031
#!/usr/bin/env python3 import sys import socket import time import numpy as np import matplotlib.pyplot as plt HOST = '10.49.234.234' PORT = 2055 def command_to_licel(licelcommand): data=None with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) s.sendall(bytes(licelcommand+...
1,543
633
# Copyright 2012 Nebula, 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 agree...
13,860
3,803
## Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. ## Note: ## The solution set must not contain duplicate triplets. ## Example: ## Given array nums = [-1, 0, 1, 2, -1, -4], ## A solution set is: ## [ ## ...
2,278
794
from django.db import models from user.models import UserModel class MoimModel(models.Model): title = models.CharField(max_length=20) creator = models.ForeignKey(UserModel, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) starts_at = models.DateTimeField() max_attende...
684
215
import os import click from developers_chamber.git_utils import get_current_branch_name from developers_chamber.gitlab_utils import \ create_merge_request as create_merge_request_func from developers_chamber.scripts import cli DEFAULT_API_URL = os.environ.get('GITLAB_API_URL', 'https://gitlab.com/api/v4') DEFAUL...
1,809
585
# Copyright 2021 IBM Corp. # # 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, sof...
15,790
5,092
import unittest from os import getcwd from click.testing import CliRunner from openvariant.commands.openvar import cat class TestCatCommand(unittest.TestCase): def test_cat_command(self): runner = CliRunner() result = runner.invoke(cat, [f'{getcwd()}/tests/data/dataset']) self.assertEqu...
2,261
739
import torch import torch.nn as nn class ResidualEncoderBlock(nn.Module): """ Implements ResidualBlock for rectangular feature maps with input shape == output shape OR input shape == (output shape)*2 ie in all dimensions (except the batch dimension). In the latter case, input_shape must be even i...
4,766
1,552
from camera import Camera def main() -> None: try: camera = Camera() camera.start_camera_loop() except KeyboardInterrupt: print('Application closed (KeyboardInterrupt)') if __name__ == '__main__': main()
246
76