text string | size int64 | token_count int64 |
|---|---|---|
import requests
import configparser
from email_validator import validate_email, EmailNotValidError
from mailchimp import OnCampusJobList
import email_notifier
import groupme_bot
config = configparser.ConfigParser()
config.read('config.ini')
google_config = config['GOOGLE']
def is_valid_recaptcha(recaptcha_response) ... | 1,397 | 430 |
import logging
import os
from datetime import datetime
from enum import Enum
from typing import Optional
from pydantic import BaseModel, Field, HttpUrl, SecretStr, ValidationError
from ..DataGoKr import DataGoKr
# logging
logger = logging.getLogger(__file__)
# debug only
KMA_API_KEY = os.getenv("KMA_API_KEY")
####... | 4,704 | 1,639 |
import numpy as np
from pivpy import io, pivpy
import matplotlib.pyplot as plt
import os
import pkg_resources as pkg
path = pkg.resource_filename("pivpy", "data")
fname = os.path.join(path, "Insight", "Run000002.T000.D000.P000.H001.L.vec")
# def test_get_dt():
# """ test if we get correct delta t """
# _, _,... | 3,135 | 1,394 |
import unittest
import networkx as nx
from nose.tools import assert_equal, assert_raises, \
assert_true
from .util import json_load
from .test_util import make_path
from hig import construct_hig_from_interactions
from interactions import InteractionsUtil as IU
class HIGTest(unittest.TestCase):
def setUp(self)... | 1,807 | 589 |
from traits.api import HasTraits, Bool, Enum, List, Str
from numpy import array, cos, sin
class ElementalRotationDefinition(HasTraits):
'''
A definition of an elemental rotation and its angle's name
'''
angle_name = Str("undefined angle")
axis = Enum('around_x', 'around_y', 'around_z')
isClock... | 5,608 | 1,630 |
def merge_sort(ls: list):
# 2020/9/19 二路归并排序
length = len(ls)
if length <= 1:
return ls
idx = length // 2
piece1 = ls[:idx]
piece2 = ls[idx:]
piece1 = merge_sort(piece1)
piece2 = merge_sort(piece2)
sorted_ls = []
# 2020/9/19 合并的算法
while len(piece1) != 0 and len(pie... | 854 | 376 |
#!/usr/bin/python3
import pandas as pd
import numpy as np
from glob import glob
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from sklearn.metrics import classification_report, confusion_matrix
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import... | 4,952 | 1,680 |
import pytest
import numpy as np
from numpy.testing import assert_array_almost_equal
from pylops.utils import dottest
from pylops import LinearOperator
from pylops.basicoperators import MatrixMult
from pylops.signalprocessing import Sliding1D, Sliding2D, Sliding3D
par1 = {'ny': 6, 'nx': 7, 'nt': 10,
'npy': ... | 3,468 | 1,425 |
"""Tests various errors that can be thrown by binding."""
from typing import Generator, List, Tuple, Union
from dinao.backend import Connection
from dinao.binding import FunctionBinder
from dinao.binding.binders import BoundedGeneratingQuery
from dinao.binding.errors import (
BadReturnTypeError,
CannotInferMa... | 6,203 | 1,874 |
import json
class BaseSerializer:
type_ = None
def __init__(self, obj):
if isinstance(obj, self.type_):
self.data = self.to_json(obj)
elif isinstance(obj, str):
self.data = json.loads(obj)
elif isinstance(obj, dict):
self.data = obj
else:
... | 1,773 | 505 |
# [Root Abyss] Guardians of the World Tree
MYSTERIOUS_GIRL = 1064001 # npc Id
sm.removeEscapeButton()
sm.lockInGameUI(True)
sm.setPlayerAsSpeaker()
sm.sendNext("We need to find those baddies if we want to get you out of here.")
sm.setSpeakerID(MYSTERIOUS_GIRL)
sm.sendNext("But... they all left")
sm.setPlayerAsSpeake... | 1,078 | 435 |
seaweedfs_master = "http://localhost:9333" #do not add slash to end (after port) | 80 | 29 |
#!/usr/bin/env python3
import unittest
from textwrap import dedent
from datetime import timedelta
from parse import parse_block, TranslationShift
class TestTranslationShift(unittest.TestCase):
def test_eq(self):
self.assertEqual(TranslationShift('name', 'lang'), TranslationShift('name', 'lang'))
... | 3,462 | 1,187 |
""" Test oleform basic functionality """
import unittest
from os.path import join
import sys
# Directory with test data, independent of current working directory
from tests.test_utils import DATA_BASE_DIR
if sys.version_info[0] <= 2:
from oletools.olevba import VBA_Parser
else:
from oletools.olevba3 import V... | 5,018 | 1,908 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Shortener
@admin.register(Shortener)
class ShortenerAdmin(admin.ModelAdmin):
list_display = ('id', 'short_url', 'link_url', 'status', 'created')
fields = ('short_url', 'link_url', 'status', '... | 593 | 191 |
import os
import ipaddress
import numpy as np
import pandas as pd
import datetime
import boto3
import gzip
import json
from signal_processing import signalProcess
BUCKET_NAME = os.environ.get("BUCKET_NAME", None)
VPC_FLOW_LOGS_PATH = os.environ.get("VPC_FLOW_LOGS_PATH", None)
FINDINGS_PATH = os.environ.get("FINDINGS_... | 6,484 | 2,294 |
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument("--text", type=str, help="path to original text file")
parser.add_argument("--train", type=str, help="path to original training data file")
parser.add_argument("--valid", type=str, help="path to original validation data file")
parser.ad... | 2,062 | 634 |
from typing import Callable, Iterator
from mabel.data.formats import dictset as ds
class Groups:
__slots__ = "_groups"
def __init__(self, dictset: Iterator, column: str, dedupe: bool = False):
"""
Group By functionality for Iterables of Dictionaries
Parameters:
dictset: I... | 4,219 | 1,085 |
# geonet.region
# Interface for managing region objects
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Wed Jan 17 06:49:35 2018 -0500
#
# ID: region.py [] benjamin@bengfort.com $
"""
Interface for managing region objects
"""
##########################################################################... | 12,181 | 3,184 |
import cli
cli.cli()
| 21 | 9 |
#!/usr/bin/env python3
#
# Copyright (c) 2019 Miklos Vajna and contributors.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""The test_webframe module covers the webframe module."""
from typing import List
from typing import TYPE_CHECKING
from typing import Tupl... | 1,539 | 459 |
# 11 List Comprehensions
products = [
("Product1", 15),
("Product2", 50),
("Product3", 5)
]
print(products)
# prices = list(map(lambda item: item[1], products))
# print(prices)
prices = [item[1] for item in products] # With list comprehensions we can achive the same result with a clenaer code
print(pric... | 504 | 182 |
from six import itervalues
def visit(d, op):
"""Recursively call op(d) for all list subelements and dictionary 'values' that d may have."""
op(d)
if isinstance(d, list):
for i in d:
visit(i, op)
elif isinstance(d, dict):
for i in itervalues(d):
visit(i, op)
cl... | 1,092 | 332 |
from triton.ecs import System
from .events import *
from .components import *
class ProjectileSystem(System):
def initialize(self):
self.on(TickEvent, self.handle_cooldowns)
self.on(TickEvent, self.on_shootevent)
def handle_cooldowns(self, event):
for e, (g,) in self.registry.get_comp... | 1,081 | 329 |
# ArrayBaseList.py
# 배열 기반 리스트 클래스
class ArrayBaseList :
def __init__(self) :
self.list = []
self.count = 0
# 배열 기반 리스트 삽입 함수
def add(self, data) :
self.list.append(data)
self.count += 1
# 배열 기반 리스트 탐색 함수
def search(self, data) :
return [index for index, s... | 1,988 | 1,108 |
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow
app = QApplication([])
main_window = QMainWindow()
first_widget = QLabel('hello world !!!', parent=main_window)
main_window.setCentralWidget(first_widget)
main_window.show()
app.exec_() | 250 | 84 |
from functools import reduce
def bfs(root, points):
queue = [root]
visited_states = {root}
basin_size = 1
while len(queue) > 0:
i, j = queue[0]
queue = queue[1:]
ps = [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]
for n in ps:
if n not in visited_states... | 1,429 | 553 |
import datetime
import factory
import uuid
from kolibri.auth.test.test_api import FacilityUserFactory
from .. import models
class ContentSessionLogFactory(factory.DjangoModelFactory):
class Meta:
model = models.ContentSessionLog
user = factory.SubFactory(FacilityUserFactory)
content_id = uuid.u... | 1,101 | 327 |
from django.urls import path
from . import views
urlpatterns = [
path('new', views.new_list, name='new_list'),
path('<list_id>/', views.view_list, name='view_list'),
path('users/<email>/', views.my_lists, name='my_lists'),
] | 237 | 83 |
#!/usr/bin/env python
import logging
from pymongo import MongoClient
from credentials import DBNAME, DBUSER, DBPASS, DBAUTH
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Mo... | 1,268 | 622 |
import os
import random
from xml.etree import ElementTree as ET
import numpy as np
from PIL import Image
from PIL.ImageDraw import ImageDraw
from sources import BaseSource
from sources.preloaded import PreLoadedSource
class OnlineSource(BaseSource):
def __init__(self, data_root):
self._root = data_root
... | 12,206 | 3,748 |
#!/usr/bin/env python
from __future__ import division
import txros
import numpy as np
import mil_tools
from mil_misc_tools.text_effects import fprint
from navigator import Navigator
import math
from twisted.internet import defer
from mil_tools import rosmsg_to_numpy
from mil_misc_tools import ThrowingArgumentParser
__... | 6,329 | 2,027 |
import discord
import random
from asd import *
from mtgsdk import Card
from mtgsdk import Set
from mtgsdk import Type
from mtgsdk import Supertype
from mtgsdk import Subtype
from mtgsdk import Changelog
client=discord.Client()
@client.event
async def on_ready():
print('logged in as')
print... | 8,205 | 3,359 |
# -*- coding: utf-8 -*-
# quiz-orm/app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
# konfiguracja aplikacji
app.config.update(dict(
SECRET_KEY='bardzosekretnawartosc',
DATABASE=os.path.join(app.root_path, 'quiz.db'),
SQLALCHEMY_DATABASE_URI='sqlite:/... | 543 | 222 |
"""Module to hold the instance of the cache"""
from flask.ext.cache import Cache
cache = Cache()
| 100 | 30 |
#!/usr/bin/env python3
import datetime
import json
import loadPath # Adds the project path.
import linkograph.labels as llabels
import linkograph.linkoCreate as llinkoCreate
import ontologyExtraction as oe
import os
import sys
def print_usage():
print("usage:", sys.argv[0], "<JSON commands filename> ...")
def ... | 2,143 | 642 |
from flask import jsonify, request
from app import authenticated_service
from app.dao import templates_dao
from app.schema_validation import validate
from app.v2.errors import BadRequestError
from app.v2.template import v2_template_blueprint
from app.v2.template.template_schemas import (
create_post_template_previ... | 1,523 | 448 |
import graphene
from graphene_django import DjangoObjectType
#models
from mdm_inventory.clients.models import Client
#types
from mdm_inventory.clients.graphql.types import ClientType
class QueryClient(graphene.ObjectType):
clients = graphene.List(ClientType)
def resolve_clients(root, info):
return C... | 357 | 107 |
import torch
from torch.utils.data import Dataset, DataLoader
from torch.distributions.multivariate_normal import MultivariateNormal
import numpy as np
from tqdm import tqdm
import random
def get_rotation(theta):
rad = np.radians(theta)
c, s = np.cos(rad), np.sin(rad)
R = np.array([[c, -s],
... | 4,923 | 1,685 |
#!/usr/bin/env python3
from damgard_jurik.crypto import EncryptedNumber, PrivateKeyRing, PrivateKeyShare, PublicKey, keygen
| 125 | 43 |
import datetime
import typing
from src import core
from src.todo import domain, adapter
__all__ = ("SqlAlchemyTodoService",)
class SqlAlchemyTodoService(domain.TodoService):
def __init__(self, /, uow: core.SqlAlchemyUnitOfWork):
self._uow = uow
def all(self, /, user_id: int) -> typing.List[domain.T... | 2,387 | 803 |
import datetime
from django.test import TestCase
from django.utils import timezone
from rest_framework import status
from rest_framework.test import APIRequestFactory, force_authenticate
from api.parties.participants.views import ParticipantsAPIView
from apps.parties.models import Party
from apps.users.models import U... | 4,013 | 1,285 |
from setuptools import (find_packages, setup)
from rap import betterjpeg
setup(
name=betterjpeg.__pkgname__,
description=betterjpeg.__description__,
version=betterjpeg.__version__,
packages=["rap.betterjpeg"],
entry_points="""
[console_scripts]
betterjpeg=rap.betterjpeg.... | 348 | 113 |
class orgApiPara:
setOrg_POST_request = {"host": {"type": str, "default": ''},
"port": {"type": int, "default": 636},
"cer_path": {"type": str, "default": ''},
"use_sll": {"type": bool, "default": True},
"a... | 3,450 | 924 |
df.rolling(window = 10, center = False).apply(lambda x: x[1]/x[2])[1:10] | 72 | 34 |
# -*- coding: utf-8 -*-
"""
Created on Sat May 23 11:28:30 2020
@author: rener
"""
import numpy as np
import pandas as pd
import os
from datetime import date
import time
import sys
dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)
#%% For the various companies we have data going back differen... | 1,653 | 541 |
import bs4
import urllib
from base_online_scraper import base_online_scraper as scraper
BASE_URL = 'http://catalog.northeastern.edu'
INITIAL_PATH = '/course-descriptions/'
fp = urllib.urlopen(BASE_URL + INITIAL_PATH)
soup = bs4.BeautifulSoup(fp, 'lxml')
nav_menu = soup.find("div", {"id": "atozindex"}).find_all('a', h... | 434 | 175 |
import pandas as pd
import numpy as np
import re
import spacy
import string
import sklearn
from html.parser import HTMLParser
from joblib import load
import tensorflow as tf
nlp = spacy.load('en_core_web_sm')
tfidf = load('tfidf.joblib')
wordlist = load('wordlist.joblib')
tf.keras.backend.clear_session()
model = tf... | 2,343 | 808 |
from lit.fields.base import Field
from lit.fields.base import TextType
class TextField(Field):
sql_type = TextType()
py_type = str
| 141 | 45 |
from datetime import datetime
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Optional
from typing import Type
from evidently.analyzers.base_analyzer import Analyzer
from evidently.analyzers.cat_target_drift_analyzer import CatTargetDriftAnalyzer
from evidently.model_profi... | 1,763 | 509 |
import re, logging
from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext as _
from django.contrib.localflavor.us.forms import USStateSelect,\
USPhoneNumberField
from models import Preference, ShippingWeight, ShippingPrice, ShippingItem, TaxState, DnsShop, EmailNo... | 5,719 | 1,662 |
###############################################################################
# Copyright Maciej Patro (maciej.patro@gmail.com)
# MIT License
###############################################################################
from cmake_tidy.utils.app_configuration.configuration import ConfigurationError
| 306 | 62 |
import logging
import sys
import unittest
from nanome import Plugin, PluginInstance
from nanome.util import Logs
if sys.version_info.major >= 3:
from unittest.mock import MagicMock, patch
else:
# Python 2.7 way of getting magicmock. Requires pip install mock
from mock import MagicMock, patch
... | 6,331 | 1,950 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://www.mozilla.org/en-US/MPL/2.0/.
import warnings
from unittest import TestCase
import pytest
def pytest_addoption(parser):
parser.addop... | 2,416 | 709 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# C++ version Copyright (c) 2006-2007 Erin Catto http://www.box2d.org
# Python version by Ken Lauer / sirkne at gmail dot com
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any dam... | 2,439 | 785 |
__copyright__ = "Copyright (C) 2019 Zachary J Weiner"
__license__ = """
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, c... | 26,827 | 11,373 |
#!/usr/bin/env python
import requests
import sys, subprocess, datetime, json, itertools, os.path, threading, argparse, logging
from adls_copy_utils import AdlsCopyUtils
log = logging.getLogger(__name__)
def update_files_owners(account, container, sas_token, work_queue):
log = logging.getLogger(threading.currentT... | 4,121 | 1,205 |
from tensorflow import keras
from util import ArcfaceLoss, inference_loss, identity_loss
import numpy as np
import os
import wn
weight_decay = 5e-4
H, W, C = (150, 300, 3)
nb_classes = 5004
lambda_c = 0.2
lr = 6e-4
feature_size = 512
final_active = 'sigmoid' # for siamese net
# labels: not one-hot
class BaseModel(... | 10,822 | 3,518 |
stringa = 'corso di Informatica'
i = 0
while (i < len(stringa)):
print stringa[i]
i = i + 1
| 102 | 46 |
# python
#
# Copyright 2020 The usbmon-tools 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | 1,383 | 451 |
#Import Dependencies
import numpy as np
import pandas as pd
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
#Set Engine
engine = create_engine("sqlite:///Resources/hawa... | 4,055 | 1,438 |
#!/usr/bin/python3
#-----------------bot session-------------------
UserCancel = 'You have cancel the process.'
welcomeMessage = ('User identity conformed, please input gallery urls ' +
'and use space to separate them'
)
denyMessage = 'You are not the admin of this bot, conversatio... | 1,539 | 386 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import pandas as pd
url_list = []
title_list = []
summary_list = []
date_list = []
# source_list = []
url = 'https://edition.cnn.com/search?size=30&q=terror&sort=newest'
# keyword_list = ['terror']
# for keyword ... | 1,923 | 703 |
import pytest
from bearboto3.ec2 import (
EC2Client,
EC2ServiceResource,
)
from beartype import beartype
from beartype.roar import (
BeartypeCallHintPepParamException,
BeartypeCallHintPepReturnException,
BeartypeDecorHintPep484585Exception,
)
# ============================
# EC2Client
# ==========... | 1,964 | 685 |
def first_negative(values):
for v in values:
if v<0:
return v
# If an empty list is passed to this function, it returns `None`:
my_list = []
print(first_negative(my_list)
| 230 | 73 |
# --==[ Screens ]==--
from libqtile import bar
from libqtile.config import Screen
from ..utils.settings import wallpaper
from ..extras.widgets import widgets
screens = [
Screen(
wallpaper = wallpaper,
wallpaper_mode = 'fill',
top = bar.Bar(
# Source in widgets.py
w... | 680 | 211 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Usage:
>>> from renamer import Renamer
>>> Renamer().rename(file)
"""
import os
from fuzzywuzzy import fuzz
try:
from parser import Parser
except:
from .parser import Parser
class Renamer:
def __init__(self):
self.infos = None
... | 1,942 | 615 |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | 2,320 | 681 |
from intermol.decorators import *
class TorsionTorsionCMAP(object):
@accepts_compatible_units(None, None, None, None, None, None, None, None,
None, None)
def __init__(self, atom1, atom2, atom3, atom4, atom5, atom6, atom7, atom8, type, chart):
"""
"""
self.type = type
... | 723 | 249 |
from django.test import TestCase
from opentech.apply.funds.tests.factories import ApplicationSubmissionFactory
from .factories import ReviewFactory, ReviewOpinionFactory
from ..options import MAYBE, NO, YES
class TestReviewQueryset(TestCase):
def test_reviews_yes(self):
submission = ApplicationSubmission... | 3,671 | 1,001 |
import asyncio
import json
import os
from datetime import datetime, timedelta
import aiohttp
import tweepy
from dateutil.parser import parse
from fpl import FPL, utils
from pymongo import MongoClient
from constants import lineup_markers, twitter_usernames
dirname = os.path.dirname(os.path.realpath(__file__))
client =... | 3,677 | 1,234 |
import os
from datetime import date, timedelta
from config import config
from inputoutput.readers import CSVInputReader, InputReader, Input2000Reader
from models.article import Article
from models.tuser import TUser
from models.tweet import Tweet
TWEETS_DIR = os.path.join(config.PCLOUD_DIR, 'tweets')
TWEET_USERS_DIR ... | 4,519 | 1,606 |
# -*- coding: utf-8 -*-
#
# John C. Thomas 2021 gpSTS
###########################################
###Configuration File######################
###for gpSTS steering of experiments######
###########################################
import os
import numpy as np
from gpsts.NanonisInterface.nanonis_interface import Nanonis
... | 6,905 | 2,384 |
# -*- coding: utf-8 -*-
'''
@author: xxzhwx
'''
from types import IntType
def is_int_type(num):
# 对象身份比较
if type(num) is IntType:
return True
return False
def is_int_typeX(num):
if isinstance(num, int):
return True
# if type(num) is int:
# return True
... | 490 | 207 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from hwt.hdl.constants import NOP, READ, WRITE
from hwt.interfaces.utils import addClkRstn, propagateClkRstn
from hwt.simulator.simTestCase import SingleUnitSimTestCase
from hwtLib.common_nonstd_interfaces.addr_data_hs import AddrDataHs
from hwtLib.handshaked.ramAsHs impo... | 3,883 | 1,482 |
# Copyright (c) ZenML GmbH 2022. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | 1,195 | 471 |
from typing import Generic, List, Optional, Type, TypeVar, Union, Dict, Any
from uuid import UUID
from fastapi import HTTPException
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.db.sqlalchemy.database import Base
ModelType = TypeVar("ModelTyp... | 2,226 | 704 |
"""squeezenet in pytorch
[1] Song Han, Jeff Pool, John Tran, William J. Dally
squeezenet: Learning both Weights and Connections for Efficient Neural Networks
https://arxiv.org/abs/1506.02626
"""
import torch
import torch.nn as nn
from .channel_selection import channel_selection
class Fire(nn.Module):
... | 2,982 | 1,220 |
"""
Output a list of star ratings for each business ID
"""
from mrjob.job import MRJob
from mrjob.protocol import JSONValueProtocol
from itertools import izip
class MRRatingsPerBusinesses(MRJob):
INPUT_PROTOCOL = JSONValueProtocol
def mapper(self, _, review):
if review['type'] == 'review':
biz_id = review['b... | 749 | 291 |
from datetime import datetime
from logging import info
from pathlib import Path
from typing import List
import requests
from celery import shared_task
from django.conf import settings
from django.contrib.admin.options import get_content_type_for_model
from requests import HTTPError
from tika import parser
from web.dat... | 9,937 | 3,466 |
from ...hek.defs.ustr import *
| 32 | 14 |
import json
import pandas as pd
import os
def read_json(file_path):
file = open(file_path, 'r')
data = json.load(file)
file.close()
return data
def read_all_json_files(JSON_ROOT):
df = pd.DataFrame() # create empty data frame
for file_name in os.listdir(JSON_ROOT): # iterate through direct... | 674 | 212 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import logging
from opencensus.ext.azure.log_exporter import AzureLogHandler
log = logging.getLogger(__name__)
class TelemetryLogger:
"""Utils class for opencensus azure monitor"""
def __init__(
self, enable_telemetry=True, in... | 2,685 | 725 |
# -*- coding: utf-8 -*-
from . import ruleset
import re
import operator
class LangSense(object):
def detect(self, string, country_hint=None):
if type(string) == str:
text = string.decode('utf-8').lower()
else:
text = string.lower()
shortlist_char = self._char_shortlist(text)
shortlist_... | 3,569 | 1,222 |
#-*- coding : utf-8-*-
import os
import json
import yaml
import glob
import jieba
import pickle
import datetime
import argparse
from collections import Counter
from concurrent.futures import ProcessPoolExecutor, Executor, as_completed
def task_one_gram(news):
gram1 = {}
with open('./training/pinyin_table/一二... | 11,695 | 4,242 |
import sys
import time
def main():
sys.stdout.write('this is stdout')
sys.stdout.flush()
sys.stderr.write('this is stderr')
sys.stderr.flush()
# Give the debugger some time to add a breakpoint.
time.sleep(5)
for i in range(1):
time.sleep(0.5)
pass
print('this is print')... | 329 | 112 |
# AMZ-Driverless
# Copyright (c) 2019 Authors:
# - Huub Hendrikx <hhendrik@ethz.ch>
#
# 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 ... | 2,985 | 901 |
import unittest
import torch
import data_model as dm
import normflowpy as nf
from experiments import constants
def generate_model_dict():
return {constants.DIM: 4,
constants.THETA_MIN: 0.3,
constants.THETA_MAX: 10,
constants.SIGMA_N: 0.1,
}
class FlowToCRBTest(uni... | 1,188 | 408 |
# Copyright 2012 NEC Corporation
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | 15,310 | 4,732 |
import threading
import time
import airobot.utils.common as arutil
from airobot.ee_tool.ee import EndEffectorTool
from airobot.utils.arm_util import wait_to_reach_jnt_goal
class Robotiq2F140Pybullet(EndEffectorTool):
"""
Class for interfacing with a Robotiq 2F140 gripper when
it is attached to UR5e arm i... | 8,532 | 2,609 |
# coding: utf-8
from __future__ import division
import argparse
import os
import sys
from matplotlib.animation import FuncAnimation
from pylab import *
from flow import schrodinger_flow_2D
from util import normalize_2D, advance_pde
from lattice import make_lattice_2D, make_border_wall_2D, make_periodic_2D, RESOLUTI... | 4,907 | 1,521 |
import unittest
from setup.settings import *
from numpy.testing import *
from pandas.util.testing import *
import numpy as np
import dolphindb_numpy as dnp
import pandas as pd
import orca
class FunctionTruedivideTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# connect to a DolphinDB server... | 3,170 | 1,373 |
import os
from django.conf import settings
def get_location(directory, path, current="", parser=None):
"""Returns a tuple (directory, path)
params:
- directory: [Directory] Directory containing the currently parsed file
- path: [str] Path to the file needed
... | 3,217 | 904 |
"""
:Description: PasteScript Template to generate a GitHub hosted python package.
Let you set the package name, a one line description, the Licence (support
GPL, LGPL, AGPL and BSD - GPLv3 by default) and the author name, email and
organisation variables::
paster create -t gh_package <project name>
.. note::
... | 7,309 | 2,233 |
import ast
import base64
import dash
import dash_core_components as dcc
from dash.dependencies import Input, Output, State
import dash_html_components as html
import dash_table as dt
import io
import json
from lmfit.model import load_modelresult
from lmfit.model import save_modelresult
import numpy as np
import os
impo... | 26,158 | 7,848 |
(n,m) = [int(x) for x in input().split()]
loop_range = n + m
set_m = set()
set_n = set()
for _ in range(n):
set_n.add(int(input()))
for _ in range(m):
set_m.add(int(input()))
uniques = set_n.intersection(set_m)
[print(x) for x in (uniques)]
| 252 | 114 |
from ncclient import manager
from xml.dom import minidom
import xmltodict
huaweiautomation = {'address':'ios-xe-mgmt-latest.cisco.com',
'netconf_port': 10000, 'username': 'developer', 'password': 'C1sco12345'}
huawei_manager = manager.connect(host = huaweiautomation["address"], port = huaweiautomation["netconf_port"... | 1,284 | 471 |
#!/usr/bin/python
# Pizza Till
# Lewis Shaw
import os
import sys
import time
import re
isProgramRuning = True
welcomeMessageDisplay = False
lastShownMenu = 0
order = { "pizzas": [] }
customer = { "customerName": None, "customerPhoneNumber": None, "customerAddress": { "postcode": None, "houseNumber": None } }
class... | 10,337 | 3,306 |
import numpy as np
from numpy import array
from numpy.linalg import det
from numpy.linalg import matrix_rank
from numpy.linalg import solve
"""
*** remember the following useful tools***
from numpy import transpose
from numpy import dot
from numpy import argmax
from numpy import abs
from numpy.linalg import eig
fr... | 4,294 | 1,367 |
""" from https://github.com/keithito/tacotron """
"""
Defines the set of symbols used in text input to the model.
The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details.
For the th... | 2,520 | 1,026 |