text string | size int64 | token_count int64 |
|---|---|---|
# Copyright (c) 2017 Huawei, 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 a... | 5,154 | 1,507 |
import csp
rgb = ['R', 'G', 'B']
d2 = {'A': rgb, 'B': rgb, 'C': ['R'], 'D': rgb}
v2 = d2.keys()
n2 = {'A': ['B', 'C', 'D'],
'B': ['A', 'C', 'D'],
'C': ['A', 'B'],
'D': ['A', 'B']}
def constraints(A, a, B, b):
if A == B: # e.g. NSW == NSW
return True
if a == b: # e.g. W... | 1,931 | 813 |
"""Nothing special, just calling sample.test.show()"""
from sample.scoping import function
def run():
print """
Scoping
1. function run
"""
function.run1()
print """
2. function run
"""
function.run2()
| 247 | 82 |
"""
Copyright (c) 2021 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance with t... | 2,504 | 823 |
from random import randint
import time
import random
def One_OR_Two(): #Right here its saying that for number 1 press it will roll one dice And when number 2 pressed it will roll 2 and ect.
if input("Do you want 1 dice or 2? \n\1 for 1(Die) \n2 for 2(Dice) :") == '1':
print("The dice rolled",random.rand... | 1,174 | 363 |
# coding: utf-8
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn import svm
from scipy import stats
class SVM1():
def __init__(self,train):
#train the algorithm once
self.train = pd.read_csv(train,delimiter=",",sep='\s*,\s*')
self.tr... | 5,224 | 2,066 |
from os.path import abspath
from injectool import resolve, SingletonResolver
from pytest import mark
from pyviews.rendering import RenderingPipeline
from pyviews.rendering.setup import use_rendering
@mark.usefixtures('container_fixture')
class UseRenderingTests:
@staticmethod
def test_views_folder():
... | 836 | 234 |
"""
utility functions for ergm
"""
import numpy as np
import datetime
import sys
import networkx as nx
from itertools import combinations
# from scipy import sparse
def log_msg(*args, out=sys.stdout, **kwargs):
"""Print message m with a timestamp if out is not None."""
if out:
print(datetime.datetime... | 7,166 | 2,420 |
import sys
import locale
locale.setlocale(locale.LC_ALL, "tr_TR.utf-8")
cumle = "merhaba\tiyi\tmisiN?"
sesli="ıouieaüöIOUİEAÜÖ"
sesliler =""
sessizler=""
gecici=""
tur = "ğıüşöçĞİÜŞÖÇ"
ing = "giusocGIUSOC"
liste = ["ali", "veli", "samet"]
liste = [[1,2,3],[4,5,6],[7,8,9,10]]
liste2 = [1, 2, 3, "mehmed"]
w = op... | 533 | 291 |
import time
import btclib.ecc.dsa
import btclib.ecc.ssa
import coincurve
from btclib.hashes import reduce_to_hlen
from btclib.to_pub_key import pub_keyinfo_from_prv_key
import btclib_libsecp256k1.dsa
import btclib_libsecp256k1.ssa
prvkey = 1
pubkey_bytes = pub_keyinfo_from_prv_key(prvkey)[0]
msg_bytes = reduce_to_h... | 1,377 | 625 |
import abc
import numpy as np
from face_pose_dataset import core
class Estimator(abc.ABC):
def run(self, frame: np.ndarray) -> core.Angle:
raise NotImplementedError("Estimator is an abstract class")
def preprocess_image(self, frame: np.ndarray, bbox: np.ndarray) -> np.ndarray:
""" Proceed w... | 904 | 237 |
from collections import Counter
import logging
import random
import numpy as np
import jieba
from hah_classification.develop.IO import read_file, write_file
import pandas as pd
import os
logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO)
PAD_IDX = 0
UNK_IDX = 1
COLUMNS = ['location_traffic_convenienc... | 7,392 | 2,637 |
#!/usr/bin/env python
from __future__ import print_function, unicode_literals
import sys
import argparse
import json
from lumapps.utils import ApiCallError, get_conf, set_conf, FILTERS
from lumapps.client import ApiClient
import logging
LIST_CONFIGS = "***LIST_CONFIGS***"
def parse_args():
s = ""
for f in F... | 5,458 | 1,830 |
import re
import requests
from requests.exceptions import *
from bs4 import BeautifulSoup
from .excepts import *
from .helpers import process_image_url
class PreviewBase(object):
"""
Base for all web preview.
"""
def __init__(self, url = None, properties = None, timeout=None, headers=None, content=N... | 8,397 | 2,474 |
"""crest_endpoint.py: collection of public crest endpoints for Prosper"""
import sys
from os import path
from datetime import datetime
from enum import Enum
import logging
import ujson as json
from flask import Flask, Response, jsonify
from flask_restful import reqparse, Api, Resource, request
import publicAPI.forec... | 13,832 | 3,719 |
#!/bin/python3
import sys
from time import sleep
try:
import mysql.connector
except:
print('''Você precisa do modulo mysql_connector instalado, no README.md tem todos os passos necessários para
a instalação deste modulo.''')
print('='*30)
pritn("O script irá encerrar em 3 segundos. Bye!!")
sleep(3)
sys.exit(1)... | 1,536 | 633 |
import collections
import itertools
from dataclasses import dataclass
from typing import List
@dataclass
class Node:
value: int
depth: int
def add_numbers(number_one: List[Node], number_two: List[Node]) -> List[Node]:
new_number = [
Node(node.value, node.depth + 1)
for node in number_one... | 3,233 | 948 |
#!/usr/bin/env python3
from http.server import BaseHTTPRequestHandler, HTTPServer, SimpleHTTPRequestHandler
import json
import os
import mimetypes
import sys
# import api
bufsize = 4096
base_path = "./www"
class server(BaseHTTPRequestHandler):
def get_payload(self):
if not ('Content-Length' in self.heade... | 4,428 | 1,430 |
"""
A simple example for Reinforcement Learning using table lookup Q-learning method.
An agent "o" is on the left of a 1 dimensional world, the treasure is on the rightmost location.
Run this program and to see how the agent will improve its strategy of finding the treasure.
View more on my tutorial page: https://morv... | 5,771 | 1,759 |
import pandas as pd
import numpy as np
from fastai.structured import apply_cats
from io import StringIO
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
import seaborn as sns
import time
import os
from contextlib import contextmanager
from sklearn.metrics import mean_squared_error
def t... | 6,427 | 2,355 |
from labelcommander import listener
if __name__ == '__main__':
listener.listen()
| 86 | 26 |
from Zadanie3.AlarmClock import AlarmClock
class Checker:
def __init__(self):
self.alarm_clock = AlarmClock()
def remainder(self, file):
hour = self.alarm_clock.getTime()
if hour > 17:
self.alarm_clock.playWavFile(file)
self.alarm_clock.wavWasPlayed()
| 314 | 115 |
import platform
from pathlib import Path
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
primary_db: str
shared_folder: str
host_id: str
@classmethod
def default(cls):
primary_db_default = str(Path.home() / ".local/share/passmate/local.pmdb")
shared_folder_d... | 1,039 | 320 |
# __init__.py
# Marcio Gameiro
# 2021-01-05
# MIT LICENSE
from intervalmap.PlotIntervalMap import *
| 101 | 45 |
import neural_network_lyapunov.worlds as worlds
import neural_network_lyapunov.utils as utils
import neural_network_lyapunov.control_affine_system as mut
import pytinydiffsim as pd
import argparse
import torch
import yaml
def load_multibody(cfg):
world = pd.TinyWorld()
urdf_data = pd.TinyUrdfParser().load_u... | 4,902 | 1,773 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class Category(models.Model):
Name = models.CharField(max_length=50)
def __str__(self):
return self.Name
class Manufacturer(models.Model):
Name = models.CharField(max_length = 100)
AddressLine1 = mode... | 1,038 | 337 |
# Generated by Django 4.0.2 on 2022-02-17 22:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("base", "0034_outline_morale_on_targets_greater_than_and_more"),
]
operations = [
migrations.AddField(
model_name="outline",
... | 417 | 146 |
""" DIGITAL MULTIMETER CONTROL FUNCTIONS: open, measure, close """
import ctypes # import the C compatible data types
from sys import platform, path # this is needed to check the OS type and get the PATH
from os import sep # OS specific file path separators
# load the dynamic lib... | 5,210 | 1,751 |
from datetime import datetime
from flask import Flask, render_template, request, Response
import stream
import json
from shared import logger
from main import app
@app.route("/healthcheck")
def healthcheck():
return "ok"
@app.route('/cam/<camId>/stream', methods=['GET'])
def camstream(camId):
logger.info("Beg... | 403 | 117 |
# Enumeration for GPT disks utility (for Python 3)
#
# Other GPT utilities https://github.com/DenisNovac/GPTUtils
# Documentation https://en.wikipedia.org/wiki/GUID_Partition_Table
from enum import Enum
class PartitionType(Enum):
MBR="024DEE41-33E7-11D3-9D69-0008C781F39F"
EFI="C12A7328-F81F-11D2-BA4B-00A0C... | 2,107 | 1,168 |
from celery import Celery
from app import settings
broker_url = 'redis://:' + settings.REDIS_PASSWORD + '@redis:6379/0'
celery_app = Celery('recommdo', broker=broker_url, include=['app.celery.celery_worker'])
celery_app.conf.task_routes = {
"app.celery.celery_worker.import_and_analyze_purchases": {'queue': 'celer... | 446 | 173 |
from EventSystem import Event
import utils
class ActionSystem:
def __init__(self, player, rooms, tuiSystem, eventQueue):
self.__player = player
self.__rooms = rooms
self.__tuiSystem = tuiSystem
self.__eventQueue = eventQueue
# a mapping for input actions to functions
... | 4,765 | 1,305 |
import falcon
from . import CookieCreator, data_api, schemas
class AuthCookiesMixin:
schema = None
require_token = None
def cookies_data(self, request) -> dict:
token, _ = self.schema().load(request.media)
return CookieCreator(token)()
def set_cookies(self, request, response):
... | 1,192 | 375 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tensorflow as tf
import data as dt
import vng_model as md
import time
import csv
import math
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('train_dir', '/home/taivu/workspace/Pycharm_... | 14,394 | 4,485 |
import math
import scanpy.api as sc
import numpy as np
from granatum_sdk import Granatum
def main():
gn = Granatum()
adata = gn.ann_data_from_assay(gn.get_import("assay"))
min_cells_expressed = gn.get_arg("min_cells_expressed")
min_mean = gn.get_arg("min_mean")
max_mean = gn.get_arg("max_mean")
... | 1,417 | 537 |
"""
Edit shop preferences
"""
import datetime
from preferences.forms import MarketingForm, TaxStateEditForm
import logging
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse, Http404, HttpResponseForbidden
from django.shortcuts i... | 37,309 | 10,345 |
"""Handlers for albums' API calls."""
import json
from flask import request, current_app
from flask_login import login_required
from pagapp.support_functions import remove_danger_symbols
from pagapp.application_api import application_api
from pagapp.models import db
from pagapp.models.albums import Albums
from pagapp... | 3,538 | 1,064 |
import os,sys
import time
import logging
import sys
from datetime import timedelta
from subprocess import check_call
from DNBC4tools.__init__ import _root_dir
def str_mkdir(arg):
if not os.path.exists(arg):
os.system('mkdir -p %s'%arg)
def change_path():
os.environ['PATH'] += ':'+'/'.join(str(_root_di... | 2,097 | 674 |
import re
from mattermost_bot.bot import listen_to
from mattermost_bot.bot import respond_to
@respond_to('hi', re.IGNORECASE)
def hi(message):
message.reply('I can understand hi or HI!')
@listen_to('Can someone help me?')
def help_me(message):
# Message is replied to the sender (prefixed with @user)
me... | 346 | 118 |
from typing import Dict, AnyStr
import celery
import riberry
from . import patch, tasks, addons
from .executor import TaskExecutor
from .tracker import CeleryExecutionTracker
def send_task_process_rib_kwargs(self, *args, **kwargs):
riberry_properties = {}
if kwargs.get('kwargs'):
for key, value in k... | 3,432 | 1,076 |
import typing
from mypy_extensions import TypedDict
from amitypes.array import Array1d
__all__ = [
'TypedDict',
'PeakTimes',
'HSDSegementPeakTimes',
'HSDPeakTimes',
'Peaks',
'HSDSegmentPeaks',
'HSDPeaks',
'HSDSegmentWaveforms',
'HSDWaveforms',
'HSDAssemblies',
'HSDTypes',
]... | 2,753 | 883 |
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# -----------------------------------------------------------------------------
# Copyright 2019-2020 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 ob... | 4,975 | 1,729 |
import json
from flask import jsonify, abort, request, url_for
from . import api
from .. import db
from ..models import PredefinedConfiguration
from ..queries import query_all_predefined_configs, query_get_predefined_config_by_id
@api.route('/predefinedconfigs', methods=['GET'])
def get_predefined_configs():
pre... | 1,183 | 376 |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: inventory.py
@time: 2018-06-28 00:23
"""
import datetime
from libs.mysql_orm_op import DbInstance
from web_api.databases.bearings import db
from web_api.models.bearings import Inventory
db_instance = DbInstance(db)
def get_inve... | 2,918 | 1,127 |
import requests
import logging
import cmapPy.clue_api_client.setup_logger as setup_logger
import json
__authors__ = "David L. Lahr"
__email__ = "dlahr@broadinstitute.org"
logger = logging.getLogger(setup_logger.LOGGER_NAME)
class ClueApiClient(object):
"""Basic class for running queries against CLUE api
""... | 3,549 | 1,071 |
import sys, string, os, yaml
import Client.client as client
with open("config.yml", 'r') as cfg:
config = yaml.load(cfg, Loader=yaml.FullLoader)
client.runClient("192.168.1.131")
| 185 | 74 |
# -*- coding: utf-8 -*-
"""GTK.EntryCompletion()."""
import gi
gi.require_version(namespace='Gtk', version='3.0')
from gi.repository import Gtk, GObject, Gio
class MainWindow(Gtk.ApplicationWindow):
brazilian_states = [
(1, 'Acre'), (2, 'Alagoas'), (3, 'Amapá'), (4, 'Amazonas'),
(5, 'Bahia'), (... | 2,467 | 906 |
from nose.tools import *
from vii.Buffer import *
from vii.Signals import slot
class Receiver:
def __init__(self):
slot("updatedBuffer", self)
slot("filledBuffer", self)
slot("deletedFromBuffer", self)
slot("insertedIntoBuffer", self)
self.seen = {}
def receive(self, s... | 21,227 | 7,642 |
import numpy as np
from scipy.stats import norm
def simulate_gbm(s_0, mu, sigma, n_sims, T, N, random_seed=42, antithetic_var=False):
'''
Function used for simulating stock returns using Geometric Brownian Motion.
Parameters
----------
s_0 : float
Initial stock price
mu : float
... | 4,821 | 1,603 |
answer = input("Can Chickens Fly? YES/NO: ")
if answer == "YES":
answer = input("Can they fly well? YES/NO: ")
if answer == "YES":
answer = input("Have you ever seen a Chicken? YES/NO: ")
if answer == "YES":
print("You're lying to me")
else:
print("Go take a look at one")
else:
answer = input("Have you... | 797 | 310 |
from collections import namedtuple
import sys
def avg_marks_manual_input():
l = int(input("How many times?"))
r = namedtuple('r',input("Headers?").split(' '),rename=True)
a = [r._make(input().split(' ')) for i in range(l)]
print(f'{sum([int(i.marks) for i in a]) / l:.2f}')
first_line = sys.stdin.read... | 552 | 217 |
from .test_primitives import PRIM_FF
import magma as m
from magma.simulator import PythonSimulator
from magma.scope import *
def test_sim_ff():
class TestCircuit(m.Circuit):
io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit)) + m.ClockIO()
ff = PRIM_FF()
m.wire(io.I, ff.D)
m.wire(ff.Q, io.O)
... | 829 | 329 |
import gym
import time
import os
import matplotlib.pyplot as plt
import numpy as np
from gym.envs.registration import register
from agent import QAgent
register(
id='FrozenLake8x8NoSLip-v0',
entry_point='gym.envs.toy_text:FrozenLakeEnv',
# kwargs={"map_name": "8x8", 'is_slippery': False},
kwargs={'is_s... | 2,223 | 860 |
from tqdm import tqdm
input_path = "./test_word_per_line.txt"
output_path = "./test_cleaned.txt"
curr_id = ""
curr_sent = []
with open(output_path, mode="wt", encoding="utf-8") as f:
lines = open(input_path).readlines()
for idx, line in tqdm(enumerate(lines)):
if idx == 0:
continue
line = line.strip()
line_... | 625 | 277 |
import os
import pathlib
def get_data_path(file):
prefix = pathlib.Path(__file__).parent.resolve()
return os.path.abspath(os.path.join(prefix, file))
if __name__ == '__main__':
print(get_data_path('data/name.txt')) | 229 | 84 |
#!/usr/bin/env python
import argparse
import antlr4
from antlr4 import *
from language.antlr.Template2Lexer import Template2Lexer
from language.antlr.Template2Parser import Template2Parser
from language.antlr.Template2Listener import Template2Listener
from newbackends.pyrotranslator import PyroTranslator
from languag... | 1,583 | 524 |
__description__ = \
"""
experiments.py
Classes for loading experimental ITC data and associating those data with a
model.
Units:
Volumes are in microliters
Temperatures are in Kelvin
Concentrations are in molar
Energy is `units`, where `units` is specified when instantiating the
ITCExperiment cl... | 6,355 | 1,938 |
import re
from random import randint
from typing import Match
from typing import Optional
from retrying import retry
import apysc as ap
from apysc._expression import var_names
from tests.testing_helper import assert_attrs
class TestPathBezier3DContinual:
@retry(stop_max_attempt_number=15, wait_fi... | 2,743 | 995 |
# NB: Based on the work of Rapptz on RoboDanny
# src: https://github.com/Rapptz/RoboDanny/blob/rewrite/cogs/admin.py
# ======================================================================
# imports
# ======================================================================
from discord.ext import commands as cmds
import... | 2,108 | 633 |
from e14_b import MyDeck, MyCard
def demo_a():
card_2_heart = MyCard(2, '❤')
print(card_2_heart)
card_3_diamond = MyCard(3, '♦')
print(card_3_diamond)
card_13_spade = MyCard(13, '♠')
print(card_13_spade)
def demo_b():
cards_deck = MyDeck(num_of_deck=1)
cards_deck.shuffle_deck()
pr... | 817 | 326 |
import numpy as np
arr = np.arange(0,11)
print(arr) | 53 | 24 |
#!/usr/bin/env python
# coding=utf-8
from unittest.mock import MagicMock
render_template = MagicMock(return_value="this is a test")
| 135 | 45 |
from django.contrib import admin
from django.apps import apps
from reporting.models import *
admin.site.register(Report)
admin.site.register(ActionReport)
admin.site.register(Alert)
| 183 | 51 |
def connected_components(n, graph):
components, visited = [], [False] * n
def dfs(start):
component, stack = [], [start]
while stack:
start = stack[-1]
if visited[start]:
stack.pop()
continue
else:
visited[sta... | 616 | 158 |
# Copyright 2010-2018 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
"""Adds functionality for uploading files to the server and managing them. See
:doc:`/specs/uploads`.
"""
from lino import ad, _
class Plugin(ad.Plugin):
"See :doc:`/dev/plugins`."
verbose_name = _("Uploads")
menu_grou... | 976 | 375 |
from cloudferrylib.base.action import action
from fabric.api import run, settings
from cloudferrylib.utils import utils as utl
CLOUD = 'cloud'
BACKEND = 'backend'
CEPH = 'ceph'
ISCSI = 'iscsi'
COMPUTE = 'compute'
INSTANCES = 'instances'
INSTANCE_BODY = 'instance'
INSTANCE = 'instance'
DIFF = 'diff'
EPHEMERAL = 'ephem... | 2,097 | 701 |
import json
import logging
import random
import sys
from datetime import datetime
from typing import Iterator
import asyncio
from fastapi import FastAPI
from fastapi.responses import HTMLResponse, StreamingResponse
from fastapi.requests import Request
from fastapi.templating import Jinja2Templates
logging.basicConfig... | 1,672 | 485 |
import os
import threading
from tkinter import *
from tkinter import messagebox
from GeniusLyrics import search_song_lyrics, song_dict
class GeniusLyricsGUI:
def __init__(self, tk_root: Tk):
tk_root.resizable(width=False, height=False)
self.lyrics_frame = Frame(tk_root)
self.songName = St... | 2,666 | 867 |
from .. import vk
from .utils import check_ctypes_members, sequence_to_array, array, array_pointer
from ctypes import byref, c_uint32, c_float
def rect_2d(x, y, width, height):
return vk.Rect2D(
offset=vk.Offset2D(x=x, y=y),
extent=vk.Extent2D(width=width, height=height)
)
def framebuffer_cre... | 6,300 | 2,051 |
"""This module contains the MotorStateChangeEvent type."""
from raspy.components.motors import motor_state
class MotorStateChangeEvent(object):
"""The event that gets raised when a motor changes state."""
def __init__(self, old_state, new_state):
"""Initialize a new instance of MotorStateChangeEven... | 1,124 | 307 |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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.... | 2,537 | 882 |
import pandas as pd
def get_coef(estimator, var_names):
"""特徴量名と回帰係数が対応したデータフレームを作成する"""
# 切片含む回帰係数と特徴量の名前を抜き出してデータフレームにまとめる
df = pd.DataFrame(
data={"coef": [estimator.intercept_] + estimator.coef_.tolist()},
index=["intercept"] + var_names
)
return df | 302 | 170 |
import ftfy
from flask import Flask, request, Response
import os
app = Flask(__name__)
@app.route("/", methods=["GET"])
def index():
return '<!DOCTYPE html>\n<html><head><title>FTFY on the web</title><body><form method="POST" action="/"><textarea name="text"></textarea><br /><input type="submit" /></body></html>'... | 649 | 227 |
class Solution:
def minCostII(self, costs: List[List[int]]) -> int:
if not costs: return 0
lower_row = costs[-1]
k = len(lower_row)
for i in range(len(costs)-2, -1, -1):
curr_row = costs[i][:]
for j in range(k):
curr_row[j] += min(lower_row[:j... | 454 | 156 |
import time
from blessings import Terminal
term = Terminal()
with term.location():
for i in range(10):
t = i
l = len(str(t))
print(term.move(10, term.height-1) + 'This is', term.underline(str(t)))
time.sleep(1)
print(term.move(10, term.height - 1) + 'This is', l*' ')
... | 442 | 158 |
from dbr import DynamsoftBarcodeReader
dbr = DynamsoftBarcodeReader()
def InitLicense(license):
dbr.InitLicense(license)
def DecodeFile(fileName):
try:
results = dbr.DecodeFile(fileName)
textResults = results["TextResults"]
resultsLength = len(textResults)
print("count: " + st... | 1,399 | 391 |
from sklearn.preprocessing import StandardScaler
import numpy as np
from sklearn.metrics import r2_score
from matplotlib import pyplot as plt
import os
from matplotlib.lines import Line2D
from exp_variant_class import exp_variant#,PCA
from sklearn.decomposition import PCA
import argparse
from scipy import integrate
imp... | 3,963 | 1,693 |
from typing import List
from collections import defaultdict
class Solution:
def possibleBipartition(self, N: int, dislikes: List[List[int]]) -> bool:
graph = defaultdict(list)
for a, b in dislikes:
graph[a].append(b)
graph[b].append(a)
RED, BLUE = 0, 1
colo... | 1,100 | 408 |
#!/usr/bin/env python
# Wenchang Yang (wenchang@princeton.edu)
# Fri May 15 13:45:34 EDT 2020
if __name__ == '__main__':
from misc.timer import Timer
tt = Timer(f'start {__file__}')
import sys, os.path, os, glob
import xarray as xr, numpy as np, pandas as pd
#import matplotlib.pyplot as plt
#more imports
import... | 1,315 | 495 |
"""Update version numbers everywhere based on git tags."""
from __future__ import print_function
import os
import re
import json
import fileinput
import contextlib
import subprocess
try:
# prefer the backport for Python <3.5
from pathlib2 import Path
except ImportError:
from pathlib import Path
import colle... | 4,120 | 1,256 |
import tweepy
import time
print("this is my twitter bot")
CONSUMER_KEY = 'Xqpf3M4z5poRH6yp17lGXgUSU'
CONSUMER_SECRET = '2RVEN70Ti4QCl0kDMptrY4AnJF6kqEOBFdSEV1aZf3rBEN8AeL'
ACCESS_KEY = '732483098336595968-hH2jZVrpjKy0WxkM6dHzyZJ5kGgCrE9'
ACCESS_SECRET = '98B9BTk2toO3qLIppsMcsPThgOSoOf9GiGZ55OGFIypYE'
auth = tweepy.O... | 1,516 | 654 |
"""
Django settings for booktime project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# ... | 4,038 | 1,441 |
"""
paintbot main module
"""
from paintbot.game import ( # noqa
PaintGame
)
| 83 | 33 |
from .bt_pair_controller import set_bt_pairing, update_bt_device_config
| 73 | 26 |
import random
class crypto:
P = 2 ** 256 - 2 ** 32 - 2 ** 9 - 2 ** 8 - 2 ** 7 - 2 ** 6 - 2 ** 4 - 1 # prime number for modulus operations
order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 # order for the elliptic curve y^2=x^3+7 ,used in bitcoin
Gx = 550662630222773436695787... | 6,850 | 2,886 |
# coding: utf-8
import copy
import json
from fabkit import * # noqa
from fablib.base import SimpleBase
class Fio(SimpleBase):
def __init__(self):
self.data_key = 'sysbench'
self.data = {
'mysql': {
'user': 'sysbench',
'password': 'sysbench',
... | 2,062 | 651 |
# -*- coding: utf-8 -*-
from knowledgebase.db.base import Vertex as BaseVertex
from knowledgebase.db.base import Edge as BaseEdge
from knowledgebase.db.base import ElementView as BaseElementView
from knowledgebase.db.base import Graph as BaseGraph
from bson.objectid import ObjectId
from pymongo import MongoClient
fro... | 5,433 | 1,818 |
from setuptools import setup
setup(name='mbrl', version='0.1.0', packages=['mbrl'])
| 85 | 33 |
"""
Drawing Vector Fields
https://stackoverflow.com/questions/25342072/computing-and-drawing-vector-fields
Adding colorbar to existing axis
https://stackoverflow.com/questions/32462881/add-colorbar-to-existing-axis
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_loc... | 1,591 | 691 |
from main import db
from dataclasses import dataclass
import database
@dataclass
class User(db.Model):
__tablename__ = 'user'
id: str = db.Column(db.String, primary_key=True,
autoincrement=False)
target_weight: float = db.Column(db.Float, nullable=False)
height: float = db.Colu... | 2,809 | 724 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class LinearSuper(nn.Linear):
def __init__(self, super_in_dim, super_out_dim, bias=True, uniform_=None, non_linear='linear', scale=False):
super().__init__(super_in_dim, super_out_dim, bias=bias)
# super_in_dim a... | 2,755 | 882 |
from collections import abc
import copy
import yaml
def data_merge(a, b):
if isinstance(a, abc.Mapping):
if not isinstance(b, abc.Mapping):
raise TypeError('cannot merge {} into a dictionary'.format(b))
a = copy.deepcopy(a)
for k in b:
try:
a[k] = d... | 1,251 | 394 |
"""
oxasl.gui.calibration_tab.py
Copyright (c) 2019 University of Oxford
"""
from oxasl.gui.widgets import TabPage
class AslCalibration(TabPage):
"""
Tab page containing options for calibration
"""
def __init__(self, parent, idx, n):
TabPage.__init__(self, parent, "Calibration", idx, n)
... | 5,532 | 1,788 |
from .annodomini import AnnoDomini
__red_end_user_data_statement__ = (
"This cog stores data attached to a user ID for the purpose of running "
" the game and saving statistics.\n"
"This cog supports data removal requests."
)
def setup(bot):
bot.add_cog(AnnoDomini(bot))
| 295 | 96 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset
from torch.utils.data import DataLoader
x_train=torch.FloatTensor([[73,80,75],
[93,88,93],
[89,91,90],
[96,98,100],
... | 1,303 | 504 |
"""
Commands for ``minidcos docker``.
"""
| 42 | 17 |
class BianPlugin():
def ready(self):
return True
def run(self,core,*params):
err = "from halo_bian.bian.mixin_err_msg import ErrorMessages\n\n"
return {"err":err}
| 200 | 70 |
import re
import sys, os
import httplib2
import boto3, botocore
from BeautifulSoup import BeautifulSoup, SoupStrainer
from optparse import OptionParser
from botocore.client import Config
# Saving myself from passing around these variables
# Sorry!
globalBaseUrl = ""
globalLinkList = []
s3 = None
# https://stackover... | 6,792 | 2,698 |
# Generated by Django 3.2.6 on 2021-08-17 14:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plants', '0012_alter_photo_user'),
]
operations = [
migrations.AddField(
model_name='plant',
name='access_type',
... | 441 | 154 |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# coding: utf8
# Libs imports
import os
import json
import time
from datetime import datetime
# Rule #1: Always print arguments with str() function
# Rule #2: In order to avoid useless ping, add '_' before any player username if the command can be triggered by someone else... | 16,346 | 5,612 |