text string | size int64 | token_count int64 |
|---|---|---|
import cc_dat_utils
#Part 1
input_dat_file = "data/pfgd_test.dat"
#Use cc_dat_utils.make_cc_level_pack_from_dat() to load the file specified by input_dat_file
#print the resulting data
data = cc_dat_utils.make_cc_level_pack_from_dat(input_dat_file)
print(data) | 263 | 103 |
'''
Created on Jun 14, 2020
@author: peter
'''
import sys
import re
import tarfile
from os import path
import xml.etree.ElementTree as ET
import logging
from gen_drum_kit.importer.importer_base import ImporterBase
from gen_drum_kit.builder.builder_hydrogen import Builder_Hydrogen
from gen_drum_kit.util ... | 4,808 | 1,512 |
import collections
def unknown():
raise Exception()
l = [1] # 0 [<int|str>]
l.append(2) # 0 [<int|str>] # 2 (<int|str>) -> None
l.append('')
l[0] = 1
l[0] = ""
l2 = list(l) # 0 [<int|str>]
l2 = sorted(l) # 0 [<int|str>]
x = collections.deque(l2).pop() # 0 <int|str>
l2 = reversed(l) # 0 iterator of <int|str>
l2 =... | 3,094 | 1,642 |
import matlab.engine
import matlab
import numpy as np
import PIL
import matplotlib.pyplot as plt
import sys
print(sys.version_info[0:2])
if sys.version_info[0:2] != (3, 8) and sys.version_info[0:2] != (3, 7) and sys.version_info[0:2] != (3, 6):
raise Exception('Requires python 3.6, 3.7, or 3.8')
eng = matlab.eng... | 2,001 | 703 |
from collections import defaultdict
import pieces
class RulesEnforcer(object):
"""
Enforces the rules of the game
Examines the move, and determines whether its a valid move or not.
"""
letter_dict = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7}
pos_letters = letter_dict.keys()
pos_nums... | 6,642 | 1,938 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bacnetd import SingleBACnetdService
from bacnetd import BACnetdService
__all__ = [
SingleBACnetdService,
BACnetdService,
]
| 178 | 74 |
from skimage.util import img_as_float
from skimage import io, filters
# from skimage.viewer import ImageViewer
import numpy as np
def split_image_into_channels(image):
"""Look at each image separately"""
red_channel = image[:, :, 0]
green_channel = image[:, :, 1]
blue_channel = image[:, :, 2]
ret... | 2,280 | 818 |
from datetime import datetime
from backend.backend.classes_main import Order, OrderItemStateUpdate, OrderUpdate, StatusHistory
from backend.backend.exceptions import NoOrderFoundException
from backend.backend.repository import get_order_by_id, update_items, update_order_status, get_orders, create_order
from backend.ba... | 2,116 | 604 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import deque
puzzle_input = 377
# puzzle_input = 3
my_circular_buffer = deque()
my_circular_buffer.append(0)
for i in range(1, 50000000+1):
new_pos = puzzle_input % len(my_circular_buffer)
my_circular_buffer.rotate(-new_pos-1)
my_circular_b... | 425 | 180 |
from botocore.configprovider import os, SmartDefaultsConfigStoreFactory
class AioSmartDefaultsConfigStoreFactory(SmartDefaultsConfigStoreFactory):
async def merge_smart_defaults(self, config_store, mode, region_name):
if mode == 'auto':
mode = await self.resolve_auto_mode(region_name)
... | 1,524 | 396 |
#!/usr/bin/python3
# This file is part of libmodulemd
# Copyright (C) 2017-2018 Stephen Gallagher
#
# Fedora-License-Identifier: MIT
# SPDX-2.0-License-Identifier: MIT
# SPDX-3.0-License-Identifier: MIT
#
# This program is free software.
# For more information on the license, see COPYING.
# For more information on fre... | 3,302 | 1,153 |
import logging
import pytest
from tests.common.utilities import wait_until
from utils import get_crm_resources, check_queue_status, sleep_to_wait
CRM_POLLING_INTERVAL = 1
CRM_DEFAULT_POLL_INTERVAL = 300
MAX_WAIT_TIME = 120
logger = logging.getLogger(__name__)
@pytest.fixture(scope='module')
def get_function_conple... | 2,268 | 859 |
# -*- coding: utf-8 -*-
from mamonsu.lib.const import Template
class ZbxTemplate(object):
mainTemplate = u"""<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
<version>2.0</version>
<groups>
<group>
<name>Templates</name>
</group>
</groups>
<templates>
<templ... | 7,991 | 2,474 |
"""This module contains exceptions defined for Rhasspy Desktop Satellite."""
class RDSatelliteServerError(Exception):
"""Base class for exceptions raised by Rhasspy Desktop Satellite code.
By catching this exception type, you catch all exceptions that are
defined by the Hermes Audio Server code."""
cla... | 1,164 | 289 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 17:48:49 2017
@author: abhilasha
Using SKLearns API for performing Kmeans clustering.
Using sklearn.datasets.make_blobs for generating randomized gaussians
for clustering.
"""
import numpy as np
from matplotlib import pyplot as plt
from skle... | 1,084 | 416 |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
# Tests for classical explainer
from interpret_text.experimental.classical import ClassicalTextExplainer
from sklearn.model_selection impor... | 1,388 | 403 |
import argparse
from create_python_app.path_utils import *
from create_python_app.create_gitignore_file import create_gitignore_file
from create_python_app.create_license_file import create_license_file
from create_python_app.create_makefile_file import create_makefile_file
from create_python_app.create_readme_file imp... | 1,378 | 444 |
# Lexical Analyzer
import re # for performing regex expressions
tokens = [] # for string tokens
source_code = 'int result = 100;'.split() # turning source code into list of words
# Loop through each source code word
for word in source_code:
... | 1,113 | 348 |
import time
class User:
"""
A class representing a users information.
NOTE: Defaults are attributes that pinylib expects
"""
def __init__(self, **kwargs):
# Default's.
self.lf = kwargs.get('lf')
self.account = kwargs.get('account', '')
self.is_owner = kwargs.get('ow... | 5,114 | 1,506 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
python系统内的异常
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- Buffer... | 2,696 | 769 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ====================
# Set-up
# ====================
# Import required modules
import re
__author__ = 'Victoria Morris'
__license__ = 'MIT License'
__version__ = '1.0.0'
__status__ = '4 - Beta Development'
# ====================
# Regular ex... | 3,386 | 1,449 |
import platform
import pytest
from unittest.mock import MagicMock
from PyQt5 import QtWidgets
if platform.system() == "Darwin":
@pytest.fixture
def widget(qtbot, main_window):
from podcastista.ShowsTab import ShowsTab
widget = ShowsTab(main_window)
qtbot.addWidget(widget)
yield... | 1,334 | 396 |
# -*- coding: utf8 -*-
import CubeModel
methodIDs = {1 : "TLPU", 2 : "TLPD", 3 : "TVMPU", 4 : "TVMPD", 5 : "TRPU", 6 : "TRPD",
7 : "TFPR", 8 : "TFPL", 9 : "TOMPR", 10 : "TOMPL", 11 : "TBPR", 12 : "TBPL",
13 : "TUPR", 14 : "TUPL", 15 : "THMPR", 16 : "THMPL", 17... | 1,999 | 666 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 3,494 | 1,291 |
#
# Python init file
#
| 23 | 10 |
# Copyright 2010 New Relic, 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... | 1,925 | 545 |
import token_def
# To get Authorization Code
# https://kauth.kakao.com/oauth/authorize?client_id=cc335daa766cc74b3de1b1c372a6cce8&response_type=code&redirect_uri=https://localhost.com
KAKAO_APP_KEY = "cc335daa766cc74b3de1b1c372a6cce8" # REST_API app key
AUTHORIZATION_CODE = "flzXSvhelQ3LLzmAKyo5-bQsafEyGOyFAMyK4N-dT... | 890 | 413 |
from bxcommon.test_utils.abstract_test_case import AbstractTestCase
from bxcommon import constants
from bxcommon.messages.bloxroute.abstract_bloxroute_message import AbstractBloxrouteMessage
from bxcommon.messages.bloxroute.bloxroute_message_control_flags import BloxrouteMessageControlFlags
class TestAbstractBloxrout... | 1,717 | 510 |
# Implementor
class drawing_api:
def draw_circle(self, x, y, radius):
pass
# ConcreteImplementor 1/2
class drawing_api1(drawing_api):
def draw_circle(self, x, y, radius):
print('API1.circle at %f:%f radius %f' % (x, y, radius))
# ConcreteImplementor 2/2
class drawing_api2(drawing_api):
d... | 1,139 | 420 |
#! /usr/bin/env python3.6
"""
server.py
Stripe Sample.
Python 3.6 or newer required.
"""
import stripe
import json
import os
import requests
#flask
from flask import Flask, render_template, jsonify, request, send_from_directory, session, Session
from flask_session import Session
from dotenv import load_dotenv, find... | 6,162 | 1,995 |
import argparse
import logging
from pathlib import Path
import dask
import h5py
import joblib
import numpy as np
import pandas as pd
from dask.diagnostics import ProgressBar
from tqdm import tqdm
from dsconcept.get_metrics import (
get_cat_inds,
get_synth_preds,
load_category_models,
load_concept_mode... | 3,992 | 1,396 |
class Solution:
# @param {integer} k
# @param {integer} n
# @return {integer[][]}
def combinationSum3(self, k, n):
nums = range(1, 10)
self.results = []
self.combination(nums, n, k, 0, [])
return self.results
def combination(self, nums, target, k, start, result):
... | 1,359 | 394 |
"""Email module"""
#pylint: disable=too-few-public-methods
import json
import os
import falcon
import requests
from mako.template import Template
import sendgrid
from sendgrid.helpers.mail import Email, To, Content, Mail
from .hooks import validate_access
FROM_EMAIL = "no-reply@sf.gov"
SUBJECT = "Appointment Offering"... | 3,543 | 1,140 |
from ._factorize import factorize
| 34 | 10 |
class Solution {
public:
bool leadsToDestination(int n, vector<vector<int>>& edges, int source, int destination) {
for(auto & edge : edges) {
int u = edge[0], v = edge[1];
graph[u].push_back(v);
}
vector<bool> visited(n, false);
return dfs(source, destination,... | 752 | 232 |
from report_tools.renderers import ChartRenderer
class MyChartRenderer(ChartRenderer):
@classmethod
def render_piechart(cls, chart_id, options, data, renderer_options):
return "<div id='%s' class='placeholder'>Pie Chart</div>" % chart_id
@classmethod
def render_columnchart(cls, chart_id, opti... | 767 | 231 |
from flask import Flask, request
from flask import render_template
from flask_mysqldb import MySQL
import TimeCalc
from datetime import datetime, timedelta
app = Flask(__name__)
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_DB'] = '... | 2,849 | 898 |
from unittest import TestCase
from src.tree import ChildrenTree
class TestChildrenTree(TestCase):
def test_height(self):
tree = ChildrenTree(1, [[], [3, 4], [], [], [0, 2]])
self.assertEqual(3, tree.height())
| 233 | 76 |
from conans import ConanFile, Meson, tools
from conans.errors import ConanInvalidConfiguration
import os
class LibnameConan(ConanFile):
name = "gtk"
description = "libraries used for creating graphical user interfaces for applications."
topics = ("conan", "gtk", "widgets")
url = "https://github.com/bi... | 5,183 | 1,662 |
# this file is for debug
import os
import yaml
SECONDS_OF_A_DAY = 3600*24
MILLISECONDS_PER_SEC = 1000
config = yaml.load(open(os.path.join(os.path.dirname(__file__),'config.yaml')), yaml.FullLoader)
SAMPLE_NUM = config['sample_number']
workloadDir = "../CSVs/%i" % SAMPLE_NUM
def generateActionIATMapping():
actio... | 1,346 | 496 |
#!/usr/bin/env python
# http://sim.okawa-denshi.jp/en/CRtool.php
# A RC circuit can act as a low pass filter when fed different AC frequencies if we hook
# them up in a serial way
# We can calculate various values of the filters using the formulas below
from math import *
def cutoff_frequency(R, C):
return 1/(2*... | 1,047 | 449 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... | 4,860 | 1,573 |
# https://sites.google.com/view/elizagen-org/the-original-eliza
from dataclasses import dataclass
from typing import List, Pattern
import re
import random
from rich.console import Console
from rich.panel import Panel
from time import sleep
class Eliza:
def __init__(self):
pass
def translate(self, str... | 13,700 | 4,249 |
import argparse
import hashlib
import json
import os
import sys
import tarfile
import trio
from ..common.botocore import (
create_async_session,
create_async_client,
partial_client_methods,
)
from ..common.serialization import json_dumps_canonical
async def upload_file(ecr, limit, fctx) -> str:
asyn... | 5,110 | 1,421 |
X = int(input())
Y = int(input())
soma = 0
if X > Y:
troca = Y
Y = X
X = troca
sam = X
while sam <= Y:
if sam%13 != 0:
soma = soma + sam
sam += 1
print(soma)
| 186 | 86 |
import phonenumbers
from phonenumbers import geocoder
phone = input('type phone number format(+551100000000): ')
phone_number = phonenumbers.parse(phone)
print(geocoder.description_for_number(phone_number, 'pt'))
| 217 | 80 |
from bs4 import BeautifulSoup
from pathlib import Path
import os
def extract_page_content(html_string, folder_path_str):
"""Extract contents of a page from a report*b.html file.
Parameters
----------
html_string : str
The HTML content of the report*b.html page to be extracted, as a str.
fo... | 20,307 | 5,721 |
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source ... | 4,096 | 1,526 |
#!/usr/bin/env python
import re
import sys
import subprocess
import os
def main(*args):
with open('main.cpp') as file:
tests = file.read()
cases = []
with open('template_all_names.txt') as file:
while True:
name = file.readline().strip('\n')
desc = f... | 870 | 283 |
import csv
import datetime
import io
import logging
import os
import tempfile
from typing import Any, Callable, List, Mapping, Optional, Set
import pandas as pd # type: ignore
from doltpy.cli import Dolt
from doltpy.shared.helpers import columns_to_rows
logger = logging.getLogger(__name__)
CREATE, FORCE_CREATE, RE... | 6,093 | 1,971 |
# @author Avtandil Kikabidze
# @copyright Copyright (c) 2008-2015, Avtandil Kikabidze aka LONGMAN (akalongman@gmail.com)
# @link http://longman.me
# @license The MIT License (MIT)
import os
import sys
import re
import sublime
directory = os.path.dirname(os.path.realpath(__file_... | 3,816 | 1,109 |
from typing import List, Optional
from attr import dataclass
from fastapi import APIRouter, Security
from fastapi.exceptions import HTTPException
from fastapi import Header
from pydantic import BaseModel
from pydantic.tools import parse_obj_as
from splash.api.auth import get_current_user
from splash.service import Spl... | 2,048 | 618 |
#!/usr/bin/env libtbx.python
#
# iotbx.xds.xds_cbf.py
#
# James Parkhurst, Diamond Light Source, 2012/OCT/16
#
# Class to read the CBF files used in XDS
#
from __future__ import absolute_import, division, print_function
class reader:
"""A class to read the CBF files used in XDS"""
def __init__(self):
pass
... | 1,635 | 564 |
# utils for graphs of the networkx library
import copy
import networkx as nx
from networkx.algorithms.shortest_paths import shortest_path
from typing import Any, Union, Optional, Iterator, Iterable, Tuple, Dict, List, cast
LEFT = 0
RIGHT = 1
def top_nodes(graph: nx.Graph,
data: bool = False) -> Union[I... | 6,267 | 1,995 |
#-------------------------------------------------------------------------------------------------------
# Copyright (C) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
#-------------------------------------------------------------... | 29,476 | 8,528 |
pMMO_dna_seq = 'ATGAAAACTATTAAAGATAGAATTGCTAAATGGTCTGCTATTGGTTTGTTGTCTGCTGTTGCTGCTACTGCTTTTTATGCTCCATCTGCTTCTGCTCATGGTGAAAAATCTCAAGCTGCTTTTATGAGAATGAGGACTATTCATTGGTATGACTTATCTTGGTCTAAGGAAAAGGTTAAAATAAACGAAACTGTTGAGATTAAAGGTAAATTTCATGTTTTTGAAGGTTGGCCTGAAACTGTTGATGAACCTGATGTTGCTTTTTTGAATGTTGGTATGCCTGGTCCTGTTTTTATTAGAAAAG... | 16,305 | 9,333 |
"""
Handles all requests that coming from phone
"""
import socketserver
import bot
from bot import TVBot
class TCPSocketHandler(socketserver.StreamRequestHandler):
"""
Handles the tcp socket connection
"""
def handle(self):
self.bot = TVBot()
while True:
self.data = ... | 1,304 | 411 |
import pandas as pd
from . import K
from .epidemic_curves import epidemic_curve
from .utils import cases
from .. import formulas
from ..diseases import disease as get_disease
from ..docs import docstring
ARGS = """Args:
model ({'SIR', 'SEIR', 'SEAIR', etc}):
Epidemic model used to compute R(t) from K(... | 3,640 | 1,218 |
# Copyright (c) 2021 Rikai Authors
#
# 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 t... | 5,099 | 1,697 |
from typing import List
from collections import defaultdict
class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
domain_visits = defaultdict(int)
for cpdomain in cpdomains:
count, domain = cpdomain.split()
dots_idx = [i for i, char in enumerate(do... | 813 | 266 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""Test case for pyparser."""
from __future__ import division, print_function
import os
import re
import textwrap
import tokenize
from future.builtins import open
import pyparser
def _make_tuple(op):
return lambda x: (op, x)
NL = tokenize.NL
NEWLINE = tokenize.NE... | 15,752 | 4,825 |
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import random
from copy import deepcopy
from sys import maxsize
import numpy as np
from .utils import create_metric_config, is_preset_performance, \
get_mixed_preset_config, evaluate_model, get_num_of_quantized_ops
from .... | 29,139 | 7,962 |
# Generated by Django 3.2 on 2021-07-03 21:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='room',
old_name='created_app',
new_nam... | 353 | 122 |
"""MEF Eline Exceptions."""
class MEFELineException(Exception):
"""MEF Eline Base Exception."""
class EVCException(MEFELineException):
"""EVC Exception."""
class ValidationException(EVCException):
"""Exception for validation errors."""
class FlowModException(MEFELineException):
"""Exception for ... | 417 | 119 |
import numpy as np
from Orange.base import Learner, Model
from Orange.modelling import Fitter
from Orange.classification import LogisticRegressionLearner
from Orange.classification.base_classification import LearnerClassification
from Orange.data import Domain, ContinuousVariable, Table
from Orange.evaluation import C... | 4,724 | 1,418 |
import yaml
from javaSerializationTools import JavaString, JavaField, JavaObject, JavaEndBlock
from javaSerializationTools import ObjectRead
from javaSerializationTools import ObjectWrite
if __name__ == '__main__':
with open("../files/7u21.ser", "rb") as f:
a = ObjectRead(f)
obj = a.readContent()... | 2,049 | 598 |
#!/usr/bin/env python
import sys
base31=pow(2,31)
base32=pow(2,32)
base=0xFFFFFFFF
'''
mysql 中processlist和mysql.log中记录的 threadid不一致.因此做一个转换
from :processlist.threadid -> mysql.log.threadid
'''
def long_to_short(pid):
if pid <base31:
return pid
elif base31 <= pid < base32:
return pid -base32
... | 634 | 256 |
# Copyright (c) 2021 homuler
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
"""Proto compiler
Macro for generating C# source files corresponding to .proto files
"""
def csharp_proto_src(name, proto_src, deps):
"... | 1,756 | 597 |
from bertopic._bertopic import BERTopic
__version__ = "0.9.1"
__all__ = [
"BERTopic",
]
| 94 | 45 |
# coding=utf-8
from django.shortcuts import render, redirect
from django.core.paginator import Paginator
from models import *
from haystack.views import SearchView
# Create your views here.
def index(request):
category_list = Category.objects.all()
array = []
for category in category_list:
news =... | 2,597 | 963 |
import asyncio
import uuid
class MockChannel:
def __init__(self):
self.published = []
self.acked = []
self.nacked = []
async def publish(self, *args, **kwargs):
self.published.append({"args": args, "kwargs": kwargs})
async def basic_client_ack(self, *args, **kwargs):
... | 4,267 | 1,223 |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^bot/', views.webhook, name='bot'),
url(r'^foodcenter/', views.food_center_webhook, name= 'food'),
# url(r'^relay/', vi)
] | 210 | 84 |
"""Common configure functions for bgp"""
# Python
import logging
import re
# Unicon
from unicon.core.errors import SubCommandFailure
log = logging.getLogger(__name__)
def configure_l2vpn_storm_control(
device, interface, service_instance_id, storm_control
):
""" Configures storm control under service insta... | 3,874 | 1,073 |
from os import environ
from MagiSlack.io import MagiIO
from MagiSlack.module import MagiModule
def hello_world(*args, **kwargs):
return f"HELLO WORLD! user {kwargs['name']}, {kwargs['display_name']}"
if __name__ == '__main__':
print('Magi Start!')
print('='*30)
print('MagiModule Initializing.')
... | 590 | 216 |
# Copyright (C) 2016-2018 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#... | 2,234 | 712 |
import pymsteams
from discord_webhook import DiscordWebhook
from notifiers import get_notifier
def slack(webhook, host):
slack = get_notifier("slack")
slack.notify(message=f"Credentials guessed for host: {host}", webhook_url=webhook)
def teams(webhook, host):
notify = pymsteams.connectorcard(webhook)
... | 560 | 184 |
#!/usr/bin/env python
import sys
from cms.test_utils.cli import configure
from cms.test_utils.tmpdir import temp_dir
import os
def main():
with temp_dir() as STATIC_ROOT:
with temp_dir() as MEDIA_ROOT:
configure(
'sqlite://localhost/cmstestdb.sqlite',
ROOT_URLC... | 716 | 238 |
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
class EmbeddingDataFrameWrapper:
def __init__(self, path_to_csv, embedder=None, text_column="text", pooling="embedding", print_results=True):
self.embed_df = pd.read_pickle(path_to_csv)
self.embedder = em... | 2,639 | 814 |
import gym
import numpy as np
# wrapper classes are anti-patterns.
def FlatGoalEnv(env, obs_keys, goal_keys):
"""
We require the keys to be passed in explicitly, to avoid mistakes.
:param env:
:param obs_keys: obs_keys=('state_observation',)
:param goal_keys: goal_keys=('desired_goal',)
"""
... | 1,716 | 577 |
# -*- coding: UTF-8 -*-
import re
import simplejson as json
import datetime
import multiprocessing
import urllib.parse
import subprocess
from django.contrib.auth import authenticate, login
from django.db.models import Q
from django.db import transaction
from django.conf import settings
from django.views.decorators.... | 23,967 | 8,561 |
from ._scrape import scrape_handler
from ._binary_data import data_handler
from ._crds import crds_handler
__all__ = ["scrape_handler", "data_handler"]
| 154 | 55 |
from .base_block_storage import BaseBlockStorage
| 49 | 13 |
from django.conf import settings
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, \
PermissionsMixin
from django.core.mail import send_mail
from django.db import models
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import... | 12,816 | 3,682 |
"""
Test for magnetic_drag.py. Uses test values and outputs given by
the laminated sheet experiment in [1].
"""
import pytest
from hyperloop.Python.pod.magnetic_levitation.magnetic_drag import MagDrag
import numpy as np
from openmdao.api import Group, Problem
def create_problem(magdrag):
root = Group()
prob =... | 881 | 324 |
def get_dosages(connection):
cursor = connection.cursor()
query = ("SELECT * from dosage")
cursor.execute(query)
response = []
for (dosage_id, dosage_name) in cursor:
response.append({
'dosage_id': dosage_id,
'dosage_name': dosage_name
})
retur... | 494 | 167 |
# Copyright (C) 2018-2021 kornia
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
"""Modified from https://kornia.readthedocs.io/en/v0.1.2/_modules/torchgeometry/losses/tversky.html"""
import torch
import torch.nn as nn
import torch.nn.functional a... | 4,681 | 1,492 |
import socket
import config
def main():
# get the login info, which is extracted from the packet
f = open('data/msg.txt', 'r')
msg = f.read()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (config.HOST, config.PORT)
print 'connecting to %s port %s' % server_address
... | 689 | 245 |
import jtweeter
access_token = "TWITTER_APP_ACCESS_TOKEN"
access_token_secret = "TWITTER_APP_ACCESS_TOKEN_SECRET"
consumer_key = "TWITTER_APP_CONSUMER_KEY"
consumer_secret = "TWITTER_APP_CONSUMER_SECRET"
user_id = 000000000 #user id of twitter user to simulate.
def main():
jtweeter.tweet(access_token, ac... | 424 | 175 |
"""Join API Handler."""
from pymongo import Connection
from pymongo.errors import InvalidId
from bson.objectid import ObjectId
from cgi import escape
from urlparse import parse_qs
from json import dumps
from urllib import unquote
POST_REQUIRED_PARAMS = ("user", "community",)
MAX_COMMUNITIES = 25
# XXX: Move into nea... | 4,899 | 1,427 |
# -*- coding: utf-8 -*-
import csv
import pkg_resources
import textwrap
import click
from tabulate import tabulate
default_data = pkg_resources.resource_filename('nobeldb', 'data/nobel.csv')
def reader(fh):
rows = csv.DictReader(fh)
for row in rows:
yield {k: v.decode('latin-1') for k, v in row.ite... | 1,040 | 350 |
import pickle
import numpy as np
def fetch_file(path):
with open(path, 'rb') as fp:
return pickle.load(fp)
def fetch_adj_mat(column):
if column == 0:
return A1
elif column == 1:
return A2
elif column == 2:
return A3
# elif column == 3:
# return A4
print(... | 2,359 | 954 |
#!/usr/bin/env python
# Name : Simple Bruteforce v.0.1
# Author: mirfansulaiman
# Indonesian Backtrack Team | Kurawa In Disorder
# http://indonesianbacktrack.or.id
# http://mirfansulaiman.com/
# http://ctfs.me/
#
# have a bug? report to doctorgombal@gmail.com or PM at http://indonesianbacktrack.or.id/forum/user-10440.... | 2,066 | 759 |
import requests
import sys, traceback
from flask import session, abort
from werkzeug.local import LocalProxy
from functools import wraps
strapi_session = LocalProxy(lambda: _get_strapi_session())
null_session = LocalProxy(lambda: _get_null_session())
def clear_strapi_session():
_pop_strapi_session()
def _get_str... | 2,826 | 851 |
from sys import stdout
from evaluate_expression import *
from operations_and_expressions import *
from write import *
regs = ["r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"]
relational_ops = [ ">", ">=", "<", "<=", "!=", "=="]
allocationTable = {}
globalTable = {}
stack = []
BYTE_SIZE = 8
IF_NUMBER = 0
WHILE_NU... | 20,228 | 7,008 |
from time import sleep
n1 = int(input('Primeiro valor: '))
n2 = int(input('Segundo valor: '))
op = 0
while op != 5:
print(''' [ 1 ] somar
[ 2 ] multiplicar
[ 3 ] maior
[ 4 ] novos números
[ 5 ] sair do programa''')
op = int(input('>>>>> Qual é a sua opção? '))
if op == 1:
s = n1 +... | 990 | 374 |
c = int(input('digite o primeiro numero: '))
b = int(input('digite o segundo numero: '))
a = int(input('digite o terceiro numero: '))
cores= {'vermelho': '\033[0;31m',
'azul' : '\033[1;34m',
'zero': '\033[m' }
# qual o maior
maior = a
if b > c and b > a:
maior = b
if c > b and c > a:
maior = c
p... | 569 | 237 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def read_text_file():
# get filename
fname = raw_input('Enter filename: ')
print
# attempt to open file for reading
try:
fobj = open(fname, 'r')
except IOError, e:
print '*** file open error:', e
else:
# display content... | 1,547 | 493 |
# coding=utf-8
common_mysql_config = {
'user': 'root',
'passwd': '',
'host': '127.0.0.1',
'db': 'autotrade',
'connect_timeout': 3600,
'charset': 'utf8'
}
yongjinbao_config = {"account": "帐号", "password": "加密后的密码"}
guangfa_config = {"username": "加密的客户号", "password": "加密的密码"}
yinghe_config = {... | 12,212 | 4,926 |
#!/usr/bin/python
'''
PyTicTacToe - Tic Tac Toe in Python
http://ruel.me
Copyright (c) 2010, Ruel Pagayon - ruel@ruel.me
All rights reserved.
Redistribution and use in source and binary forms, with or without
* Redistributions of source code must retain the above copyright
notice, this list of conditions ... | 8,894 | 3,983 |
"""
Module comparison superimposes most probable local density, maximum
cooperativity, time of maximum cooperativity and ratio of transversal and
longitudinal correlations at time of maximum cooperativity, as functions of
the Péclet number, for different trajectories in the phase diagram (either
varying persistence tim... | 22,484 | 7,371 |