text string | size int64 | token_count int64 |
|---|---|---|
from cffi import FFI
ffibuilder = FFI()
ffibuilder.cdef("""
int test(int t);
""")
ffibuilder.set_source("_pi_cffi",
"""
#include "brute.h"
""",
sources=['brute.c'])
if __name__ == "__main__":
ffibuilder.compile(verbose = Tru... | 323 | 115 |
"""Board Module"""
import copy
from typing import Tuple, List
from src.coordinate import Coordinate
from src.snake import Snake
class Board:
"""Track the cooardinates for all snakes and food in the game."""
def __init__(self, data):
self._data = data
self._snakes = None
self._foods = No... | 2,392 | 729 |
import os
import zipfile
from typing import List
import pandas as pd
import urllib
from personalized_nlp.settings import STORAGE_DIR
from personalized_nlp.utils.data_splitting import split_texts
from personalized_nlp.datasets.datamodule_base import BaseDataModule
class WikiDataModule(BaseDataModule):
def __init... | 2,349 | 779 |
# Generated by Django 4.0 on 2022-03-03 02:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('App', '0009_alter_song_holiday_alter_songfileinput_holiday'),
]
operations = [
migrations.RemoveField(
model_name='user',
... | 522 | 166 |
import os
import warnings
from django.conf import settings
CAPTCHA_FONT_PATH = getattr(settings, 'CAPTCHA_FONT_PATH', os.path.normpath(os.path.join(os.path.dirname(__file__), '..', 'fonts/Vera.ttf')))
CAPTCHA_FONT_SIZE = getattr(settings, 'CAPTCHA_FONT_SIZE', 22)
CAPTCHA_LETTER_ROTATION = getattr(settings, 'CAPTCHA_L... | 3,653 | 1,599 |
from __future__ import absolute_import, division, print_function, \
with_statement
import logging
import os.path
import time
import tornado.escape
import tornado.gen
import tornado.ioloop
from tornado.test.util import unittest
from tornado.testing import AsyncHTTPTestCase, gen_test
import tornado.web
from pilbox... | 11,009 | 3,741 |
#!/usr/bin/env python
from scipy import *
from pylab import *
#from pylab import imshow
#!
#! Some graphical explorations of the Julia sets with python and pyreport
#!#########################################################################
#$
#$ We start by defining a function J:
#$ \[ J_c : z \rightarrow z^2 + c \]
#... | 1,202 | 525 |
# Generated by Django 2.2.21 on 2021-06-23 12:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('resources', '0125_add_timmi_payload_model'),
]
operations = [
migrations.AddField(
model_name=... | 535 | 175 |
import logging
from lora_multihop import serial_connection, variables
def config_module(configuration=variables.MODULE_CONFIG):
if serial_connection.execute_command(configuration, [variables.STATUS_OK]):
serial_connection.execute_command('AT+SEND=1', [variables.STATUS_OK])
serial_connection.execu... | 1,307 | 395 |
#!/usr/bin/env python
# Copyright (c) 2013-2014, Rethink Robotics
# 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 code must retain the above copyright notice,
# ... | 6,287 | 2,083 |
import abc
from typing import Dict, Callable
import tensorflow as tf
from flink_ml_framework.context import Context
from flink_ml_framework.java_file import *
from ..runner import tf_helper, io_helper
from ..runner.output_writer import DirectOutputWriter
try:
from flink_ml_tensorflow.tensorflow_context import TF... | 4,461 | 1,343 |
import pytest
ENCODING = 'utf-8'
@pytest.fixture(scope='function', autouse=True)
def setup_case(request):
def destroy_case():
from corm import annihilate_keyspace_tables, SESSIONS
annihilate_keyspace_tables('mykeyspace')
for keyspace_name, session in SESSIONS.copy().items():
if... | 12,450 | 3,952 |
import json
import os
from utilities.SaveLoadJson import SaveLoadJson as SLJ
from utilities.LineCount import LineCount as LC
import subprocess
from geolite2 import geolite2
class getData:
#Get Data Functions ------------------------------------------------------
@staticmethod
def getDATA():
resu... | 6,337 | 1,743 |
from nemo.collections.nlp.losses.sgd_loss import SGDDialogueStateLoss
| 70 | 27 |
# -*- coding: utf-8 -*-
from .settings import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['LOCAL_DB_NAME'],
'USER': os.environ['LOCAL_DB_USER'],
'PASSWORD': os.environ['LOCAL_DB_PASSWORD']... | 382 | 153 |
def area(larg, comp):
a = larg * comp
print(f'A dimensão é {a}')
print('Controle de terrenos')
print('-' * 20)
l = float(input('qual a largura do terreno: '))
c = float(input('qual o comprimento do terreno: '))
area(l , c) | 231 | 92 |
import datetime
ano = (datetime.datetime.now()).year
nasc = int(input("Digite o seu ano de nascimento: "))
categoria = 0
if (ano - nasc) <= 9:
categoria = str("MIRIM")
elif 9 < (ano - nasc) <= 14:
categoria = str("INFANTIL")
elif 14 < (ano - nasc) <= 19 :
categoria = str("JUNIOR")
elif 19 < (ano - nasc) <= ... | 443 | 181 |
import torch
def ndcg_binary_at_k_batch_torch(X_pred, heldout_batch, k=100, device='cpu'):
"""
Normalized Discounted Cumulative Gain@k for for predictions [B, I] and ground-truth [B, I], with binary relevance.
ASSUMPTIONS: all the 0's in heldout_batch indicate 0 relevance.
"""
batch_users = X_pre... | 1,689 | 699 |
# All credit to https://stackoverflow.com/questions/46571448/tkinter-and-a-html-file - thanks DELICA - https://stackoverflow.com/users/7027346/delica
from cefpython3 import cefpython as cef
import ctypes
try:
import tkinter as tk
from tkinter import messagebox
except ImportError:
import Tkinter as tk
impo... | 5,029 | 1,595 |
import re
def do_substitution(in_lines):
lines_iter = iter(in_lines)
defn_lines = []
while True:
try:
line = lines_iter.next()
except StopIteration:
raise RuntimeError("didn't find line starting with ---")
if line.startswith('---'):
break
e... | 1,010 | 344 |
# Generated by Django 3.2.12 on 2022-03-28 11:57
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('events', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='eventhero',
options={'verbose_name_plural': ... | 354 | 124 |
#!/usr/bin/env python3
# encoding: utf-8
import sys
import urllib.parse
import selenium.webdriver
def exit():
driver.quit()
sys.exit(0)
driver = selenium.webdriver.Firefox()
# for some reason, detectportal.firefox.com and connectivitycheck.gstatic.com are not blocked
# therefore, they cannot be used to detect con... | 799 | 259 |
#!/usr/bin/env python
import os
from collections import OrderedDict
import cPickle as pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.cm import get_cmap
from matplotlib import style
from scipy import stats
from scipy import integrate
... | 1,539 | 576 |
#!/usr/local/bin/python2.7
from flask import Flask
import sys
from flask_frozen import Freezer
from upload_s3 import set_metadata
from config import AWS_DIRECTORY
app = Flask(__name__)
app.config.from_object('config')
from views import *
# Serving from s3 leads to some complications in how static files are served
i... | 1,041 | 358 |
#!/usr/bin/python
from setup import *
payload = open(sys.argv[1], "rb").read()
dtb = open(sys.argv[2], "rb").read()
if len(sys.argv) > 3:
initramfs = open(sys.argv[3], "rb").read()
initramfs_size = len(initramfs)
else:
initramfs = None
initramfs_size = 0
compressed_size = len(payload)
compressed_addr... | 1,799 | 748 |
import json
import os
import multiprocessing
import struct
import importlib
from socketserver import TCPServer, StreamRequestHandler
def plugin_module_import(name):
try:
return importlib.import_module(name)
except ModuleNotFoundError as e:
prompt = 'plugin {} not found, please install it first... | 1,313 | 386 |
def keychain_value_iter(d, key_chain=None, allowed_values=None):
key_chain = [] if key_chain is None else list(key_chain).copy()
if not isinstance(d, dict):
if allowed_values is not None:
assert isinstance(d, allowed_values), 'Value needs to be of type {}!'.format(
allowed_v... | 537 | 154 |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from . import helpers
# Create your views here.
@csrf_exempt
def convert_video(request, version):
# Get video
video = reques... | 565 | 163 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | 2,981 | 899 |
from itertools import count
import numpy as np
class Particle(object):
"""Object containing all the properties for a single particle"""
_ids = count(0)
def __init__(self, main_data=None, x=np.zeros(2)):
self.id = next(self._ids)
self.main_data = main_data
self.x = np.array(x)
... | 2,332 | 842 |
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField
from wtforms.validators import Required
class UpdateProfile(FlaskForm):
about = TextAreaField('Tell us about you.',validators = [Required()])
submit = SubmitField('Submit')
class PitchForm(FlaskForm):
pitch = TextAre... | 501 | 148 |
import re
import astrodata
from astrodata import (astro_data_tag, TagSet, astro_data_descriptor,
returns_list)
from astrodata.fits import FitsLoader, FitsProvider
from ..soar import AstroDataSOAR
class AstroDataSAMI(AstroDataSOAR):
__keyword_dict = dict(data_section='DATASEC', gain='GAIN'... | 4,840 | 1,482 |
# -*- coding: utf-8 -*-
#単なる継承
class Base(object):
def __init__(self):
pass
def meth(self, int):
return self._meth(int)
def _meth(self, int):
return int
class Pow(Base):
def _meth(self, int):
return pow(int,int)
| 264 | 109 |
import os, sys
import numpy as np
import cv2
import random
import torch
from configs import Config
from kernelGAN import KernelGAN
from data import DataGenerator
from learner import Learner
import tqdm
DATA_LOC = "/mnt/data/NTIRE2020/realSR/track2" # "/mnt/data/NTIRE2020/realSR/track1"
DATA_X = "DPEDiphone-tr-x" # ... | 1,957 | 790 |
from unittest import TestCase
from pyRdfa import pyRdfa
class NonXhtmlTest(TestCase):
"""
RDFa that is in not well-formed XHTML is passed through html5lib.
These tests make sure that this RDFa can be processed both from
a file, and from a URL.
"""
target1 = '<og:isbn>9780596516499</og:isbn>'... | 731 | 292 |
from setuptools import setup, find_packages
from os.path import join, dirname
setup(
name='pyoai',
version='2.4.6.b',
author='Infrae',
author_email='rob.cermak@gmail.com',
url='https://github.com/jr3cermak/robs-kitchensink/tree/master/python/pyoai',
classifiers=["Development Status :: 4 - Beta"... | 1,150 | 362 |
import torch
from torch import nn
import math
#0 left hip
#1 left knee
#2 left foot
#3 right hip
#4 right knee
#5 right foot
#6 middle hip
#7 neck
#8 nose
#9 head
#10 left shoulder
#11 left elbow
#12 left wrist
#13 right shoulder
#14 right elbow
#15 right wrist
def random_rotation(J3d):
J = J3d # need copy????
ba... | 4,201 | 1,906 |
from des109 import moeda
preco = float(input('Digite o preço pretendido: €'))
print(f'''A metade do preço é {(moeda.metade(preco))}
O dobro do preço é {(moeda.dobra(preco))}
Aumentando o preço 10% temos {(moeda.aumentar(preco, 10))}
Diminuindo o preço 13% temos {(moeda.aumentar(preco, 13))}''')
| 303 | 138 |
#!/usr/bin/env python2
import xmlrpclib
db = 'odoo9'
user = 'admin'
password = 'admin'
uid = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/2/common')\
.authenticate(db, user, password, {})
odoo = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/2/object')
installed_modules = odoo.execute_kw(
db, uid, ... | 474 | 177 |
from abc import *
import numpy as np
###########################################################
class AbstractFeatureExtractor(object):
@abstractmethod
def extract(self, object):
return
###########################################################
class EntityFeatureExtractor(AbstractFeatureExtractor... | 10,971 | 3,442 |
from django.db import models
class UserRestrictedQuerySet(models.QuerySet):
"""
Query-set base class for models which apply per-instance permissions
based on the user accessing them.
"""
def for_user(self, user):
"""
Filters the query-set to those instances that the
given u... | 521 | 140 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... | 31,879 | 9,088 |
import os
import glob
import cv2
import numpy as np
import torch
from torchvision.transforms import transforms
from natsort import natsorted
from models import resmasking_dropout1
from utils.datasets.fer2013dataset import EMOTION_DICT
from barez import show
transform = transforms.Compose(
[
transforms.ToPI... | 2,420 | 1,014 |
import time
import colorama
def gerenciador_de_pagamento():
preço = float(str(input('Preço das compras: R$')))
print('''Escolha de pagamento:
[ 1 ]A vista dinheiro/cheque: 10% de desconto.
[ 2 ]A vista no cartão: 5% de desconto.
[ 3 ]Em até duas 2x no cartão: preço formal.
[ 4 ]3x ou mais no car... | 1,727 | 686 |
"""
Created on 2 Apr 2017
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
from collections import OrderedDict
from scs_core.data.json import JSONable
# --------------------------------------------------------------------------------------------------------------------
class AbstractTopic(JSONable):... | 1,786 | 425 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... | 11,286 | 3,253 |
import json
from pygments import highlight
from pygments.lexers import JsonLexer
from pygments.formatters import TerminalFormatter
def print_json_obj(json_object):
json_str = json.dumps(json_object, indent=4, sort_keys=True)
print(highlight(json_str, JsonLexer(), TerminalFormatter()))
def print_json_str(jso... | 393 | 121 |
#!/usr/bin/env python3
import os
from opendbc.can.parser import CANParser
from cereal import car
from selfdrive.car.interfaces import RadarInterfaceBase
RADAR_MSGS_C = list(range(0x2c2, 0x2d4+2, 2)) # c_ messages 706,...,724
RADAR_MSGS_D = list(range(0x2a2, 0x2b4+2, 2)) # d_ messages
LAST_MSG = max(RADAR_MSGS_C + RA... | 3,486 | 1,375 |
"""
wrapper for ccmake command line tool
"""
import subprocess
name = 'ccmake'
platforms = ['linux', 'osx']
optional = True
not_found = "required for 'fips config' functionality"
#-------------------------------------------------------------------------------
def check_exists(fips_dir) :
"""test if ccmake is in t... | 911 | 244 |
import os
import numpy as np
import tensorflow as tf
from image_quality.utils import utils
class TrainDataGenerator(tf.keras.utils.Sequence):
'''inherits from Keras Sequence base object, allows to use multiprocessing in .fit_generator'''
def __init__(self, samples, img_dir, batch_size, n_classes, basenet_preproc... | 4,251 | 1,434 |
from Test import Test, Test as test
'''
Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.
Example:
Given an input string of:
apples, pears # and bananas
grapes
bananas !apples
The output expecte... | 1,914 | 624 |
# -*- coding: utf-8 -*-
"""
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, Versi... | 6,221 | 1,880 |
# Authors: Robert Luke <mail@robertluke.net>
#
# License: BSD (3-clause)
import numpy as np
from mne import Annotations, create_info
from mne.io import RawArray
def simulate_nirs_raw(sfreq=3., amplitude=1.,
sig_dur=300., stim_dur=5.,
isi_min=15., isi_max=45.):
"""
... | 2,061 | 631 |
from cryptomodel.cryptostore import user_notification, user_channel, user_transaction, operation_type
from mongoengine import Q
from cryptodataaccess import helpers
from cryptodataaccess.helpers import if_none_raise, if_none_raise_with_id
class TransactionRepository:
def __init__(self, config, log_error):
... | 3,650 | 1,027 |
""" util.auth2: Authentication tools
This module is based off of util.auth, except with the action
paradigm removed.
"""
from flask import session
from app.models import Account
from app.util import course as course_util
# Session keys
SESSION_EMAIL = 'email'
def create_account(email: str, password: str, f... | 1,536 | 458 |
from PyQt5.QtWidgets import *
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
class PstaticWidget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self... | 1,125 | 375 |
import numpy as np
from pymoo.core.algorithm import Algorithm
from pymoo.core.population import Population
from pymoo.util.termination.no_termination import NoTermination
from pyallocation.allocation import FastAllocation
from pyallocation.problem import AllocationProblem
def exhaustively(problem):
alloc = FastA... | 1,719 | 570 |
import os
class Config:
CSRF_ENABLED = True
SECRET_KEY = 'your-very-very-secret-key'
SQLALCHEMY_DATABASE_URI = 'postgresql:///flask_template_dev'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = True
class Development(Config):
ENV = 'development'
DEBUG = True
TESTING = False
... | 602 | 280 |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | 2,651 | 846 |
import itertools
import numpy as np
import pandas as pd
def find_intersections(formula_lists,group_labels,exclusive = True):
"""
Docstring for function pyKrev.find_intersections
====================
This function compares n lists of molecular formula and outputs a dictionary containing the intersections... | 3,571 | 939 |
import os
import glob
import shutil
from tinytag import TinyTag
""" root = 'C:/'
copy_to = '/copy to/folder'
tag = TinyTag.get('C:/Users/jchap/OneDrive/Pictures/(VERYRAREBOYZ) (feat. $ki Mask The Slump God and Drugz).mp3')
print(tag.artist)
print('song duration: '+str(tag.duration))
"""
f = []
f=glob.gl... | 5,386 | 1,640 |
#import modules
import os
import csv
#input
csvpath = os.path.join('Resources', 'budget_data.csv')
#output
outfile = os.path.join('Analysis', 'pybankstatements.txt')
#declare variables
months = []; total_m = 1; net_total = 0; total_change = 0; monthly_changes = []; greatest_inc = ['', 0]; greatest_dec = ['', 0]
#open... | 1,636 | 597 |
from enum import Enum
from constants.globals import HEALTH_EMOJIS
NETWORK_ERROR = '😱 There was an error while getting data 😱\nAn API endpoint is down!'
HEALTH_LEGEND = f'\n*Node health*:\n{HEALTH_EMOJIS[True]} - *healthy*\n{HEALTH_EMOJIS[False]} - *unhealthy*\n' \
f'{HEALTH_EMOJIS[None]} - *unknown*... | 1,502 | 689 |
import random
import fire
import json
import os
import numpy as np
import tensorflow as tf
import pytumblr
import mysql.connector
import datetime
from random import seed
import model, sample, encoder
def interact_model(
model_name='1558M',
seed=None,
nsamples=1,
batch_size=1,
length=None,
tempe... | 3,993 | 1,266 |
from sys import version_info
if version_info[0] <= 2 and version_info[1] <= 4:
def all(iterable):
for element in iterable:
if not element:
return False
return True
else:
all = all
| 233 | 69 |
from rest_framework import serializers
from cms.api.serializers import UniCMSContentTypeClass, UniCMSCreateUpdateSerializer
from cms.medias.serializers import MediaSerializer
from . models import Carousel, CarouselItem, CarouselItemLink, CarouselItemLinkLocalization, CarouselItemLocalization
class CarouselForeignK... | 3,839 | 1,023 |
#!/usr/bin/env python3
"""
Copyright (c) 2018-2021 Intel Corporation
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 applic... | 7,298 | 2,449 |
# coding: utf-8
"""
[AHOI cookbook](/ahoi/docs/cookbook/index.html) [Data Privacy](/sandboxmanager/#/privacy) [Terms of Service](/sandboxmanager/#/terms) [Imprint](https://sparkassen-hub.com/impressum/) © 2016‐2017 Starfinanz - Ein Unternehmen der Finanz Informatik # noqa: E501
OpenAPI sp... | 8,174 | 2,704 |
# Copyright 2015-2017 ARM Limited, Google and contributors
#
# 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 applica... | 10,366 | 3,257 |
from enum import Enum
class BlueprintType(Enum):
"""
A blueprint is a pipeline template in horizon, and must be specified when creating a new pipeline
Nonlinear
===============================================================================================================
A nonlinear pipeline co... | 6,813 | 1,522 |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render
from django.urls import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.utils import timezone
from olaf.models import *
from olaf.forms import *
from... | 6,758 | 2,374 |
from __future__ import print_function
import argparse
import torch
import torch.utils.data
import matplotlib.pyplot as plt
from torch import nn, optim
from torch.nn import functional as F
from torchvision import datasets, transforms
from torchvision.utils import save_image
from torch.utils.tensorboard import SummaryWri... | 2,343 | 775 |
from __future__ import absolute_import, division, print_function
from appr.auth import ApprAuth
from appr.commands.command_base import CommandBase, PackageSplit
class LogoutCmd(CommandBase):
name = 'logout'
help_message = "logout"
def __init__(self, options):
super(LogoutCmd, self).__init__(opti... | 1,567 | 460 |
from django.apps import AppConfig
class MusicaConfig(AppConfig):
name = 'musica'
| 87 | 28 |
#!/usr/bin/env python
'''tzwhere.py - time zone computation from latitude/longitude.
Ordinarily this is loaded as a module and instances of the tzwhere
class are instantiated and queried directly
'''
import collections
try:
import ujson as json # loads 2 seconds faster than normal json
except:
try:
i... | 10,370 | 2,981 |
from mindmeld.models.helpers import register_query_feature
@register_query_feature(feature_name='average-token-length')
def extract_average_token_length(**args):
"""
Example query feature that gets the average length of normalized tokens in the query„
Returns:
(function) A feature extraction func... | 706 | 194 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
def getstatus(code):
if code == "1000":
value = "Success!"
elif code == "1001":
value = "Unknown Message Received"
elif code == "1002":
value = "Connection to Fishbowl Server was lost"
elif code == "1003":
value = "Some Requests ... | 4,783 | 1,492 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# [Import start]
from flask import Blueprint, jsonify
# [Import end]
app = Blueprint(
'hoge',
__name__,
url_prefix='/hoge'
)
@app.route('/test')
def hoge():
return "\nhogehoge"
| 239 | 99 |
#!/usr/bin/env python3
import apt_pkg
import sys
from apt_pkg import CURSTATE_INSTALLED, version_compare
from operator import lt, le, eq, ge, gt
# Function mappings for relationship operators.
relation_operators = {"<<": lt, "<=": le, "=": eq, ">=": ge, ">>": gt}
# Set up APT cache.
apt_pkg.init()
cache = apt_pkg.Ca... | 2,383 | 706 |
# Generated by Django 3.0.7 on 2020-08-24 06:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('datasets', '0008_auto_20200821_1427'),
]
operations = [
migrations.AddField(
model_name='rawdar',
name='AsB',
... | 11,707 | 3,383 |
print "Hello World!"
print "Trying my hand at Git!"
print "Something else"
for i in range(10):
print i
| 107 | 36 |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic import DetailView, ListView
from projects.models import Project
from status.models import Status
from .models import Task
from .forms import TaskForm, FilterForm
... | 3,784 | 1,084 |
import os
import math
import time
import geohash
import geojson
from geojson import MultiLineString
from shapely import geometry
import shapefile
import numpy
import datetime as dt
import pandas as pd
import logging
logger = logging.getLogger(__name__)
source_shape_file_path = "C:/temp/2018/"
threshold = 60*60
cols = ... | 2,083 | 681 |
import pygame_sdl2
pygame_sdl2.import_as_pygame()
import pygame
import os
import random
import math
from Ball import Ball
def save_state(balls):
"""
Saves the game state.
"""
stateString = ""
with open("state.txt", "w") as f:
for ball in balls:
stateString += "{} {} {} {} {}".f... | 3,965 | 1,171 |
from __future__ import division
import math, copy
import argparse
from brownian import Brownian
import scipy
import LLRcalc
class sprt:
def __init__(self, alpha=0.05, beta=0.05, elo0=0, elo1=5, elo_model="logistic"):
assert elo_model in ("logistic", "normalized")
self.elo_model = elo_model
... | 6,408 | 2,266 |
#
# 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... | 17,956 | 6,718 |
"""Simple Hail query example."""
import click
import hail as hl
from bokeh.io.export import get_screenshot_as_png
from analysis_runner import output_path
GNOMAD_HGDP_1KG_MT = (
'gs://gcp-public-data--gnomad/release/3.1/mt/genomes/'
'gnomad.genomes.v3.1.hgdp_1kg_subset_dense.mt'
)
@click.command()
@click.op... | 1,253 | 515 |
import uuid
import time
import socket
import struct
class PtpIpConnection(object):
"""docstring for PtpIP"""
def __init__(self):
super(PtpIpConnection, self).__init__()
self.session = None
self.session_events = None
self.session_id = None
self.cmd_queue = []
se... | 17,420 | 6,117 |
"""
How to load morphologies of certain cells from the database.
"""
#this is an expected failure right now, as morphology is not implemented
from __future__ import absolute_import
from __future__ import print_function
import PyOpenWorm as P
from PyOpenWorm.context import Context
from PyOpenWorm.worm import Worm
from ... | 869 | 260 |
from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import SimpleTestCase
from corehq.apps.app_manager.const import (
AUTO_SELECT_RAW,
AUTO_SELECT_CASE,
WORKFLOW_FORM,
WORKFLOW_MODULE,
WORKFLOW_PREVIOUS,
WORKFLOW_ROOT,
WORKFLOW_PARENT_MODULE,
)
fr... | 18,159 | 6,508 |
# Copyright 2020 The TensorFlow Authors. 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 applica... | 19,888 | 6,169 |
eval(input("Enter a expression ")) | 34 | 10 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# load dataset into Pandas DataFrame
df = pd.read_csv("D:\Python_programs\ML\Iris Data\KPCA\iris.csv")
#df.to_csv('iris.csv')
from sklearn.preprocessing import StandardScaler
features = ['sepal length', 'sepal width', 'petal length', 'petal width... | 2,959 | 1,064 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List, Pattern
from recognizers_text.utilities import RegExpUtility
from recognizers_number.number import BaseNumberParser
from recognizers_number.number.italian.extractors import ItalianIntegerExtractor,... | 13,377 | 3,981 |
"""SQLite Driver implementation."""
# pylint: disable=R0201
import os
import sqlite3
from typing import Any, AnyStr, List, NoReturn, Optional, Tuple
from pydbrepo.drivers.driver import Driver
class SQLite(Driver):
"""SQLite Driver connection class.
Environment variables:
DATABASE_URL: Database fil... | 4,704 | 1,274 |
import numpy as np
from PuzzleLib import Config
from PuzzleLib.Backend import gpuarray, Blas
from PuzzleLib.Backend.Dnn import batchNormNd, batchNormNdBackward
from PuzzleLib.Variable import Variable
from PuzzleLib.Modules.Module import ModuleError, Module
class BatchNormND(Module):
def __init__(self, nd, maps, e... | 3,036 | 1,259 |
xs = ('foo', 'bar',
'baz'<caret> | 38 | 18 |
from concurrent import futures
from forecaster.prophet import Forecaster as ProphetForecaster
from multiprocessing import Event, Process, cpu_count
from pythonjsonlogger import jsonlogger
import contextlib
import grpc
import logging
import model.api.forecast_pb2_grpc as grpc_lib
import os
import signal
import socket
im... | 6,038 | 1,876 |
def test_setupcall():
"""
Test the call of the setup function
"""
import jupyter_libertem_proxy as jx
print("\nRunning test_setupcall...")
print(jx.setup_libertem())
| 191 | 64 |
# Copyright 2020 DeepMind Technologies Limited. 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 ... | 14,221 | 4,183 |