text string | size int64 | token_count int64 |
|---|---|---|
from .helpers import get_pylint_output, write_output
from ..automation_tools import read_json
def find_warnings():
print('Generating warnings in all of pygsti. This takes around 30 seconds')
config = read_json('config/pylint_config.json')
blacklist = config['blacklisted-warnings']
command... | 575 | 173 |
import os, sys
import numpy
import scipy.constants as codata
from syned.storage_ring.magnetic_structures.undulator import Undulator
from syned.storage_ring.magnetic_structures import insertion_device
from PyQt5.QtGui import QPalette, QColor, QFont
from PyQt5.QtWidgets import QMessageBox, QApplication
from PyQt5.QtC... | 47,316 | 16,845 |
# Django
from django.urls import re_path
# Test App
from .views import index
urlpatterns = [
re_path(r'^$', index, name='index'),
]
| 139 | 51 |
# Copyright 2011 Nicholas Bray
#
# 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... | 5,927 | 2,183 |
#!/usr/bin/env python
import sys
from datetime import datetime
from random import SystemRandom
import bcrypt
import sqlite3
import client
import db
import settings
conn = db.DB(settings.database)
conn.debug = True
c = conn.cursor
db.rewrite_entropy_file(settings.entropy_file)
rand = SystemRandom()
def rand_choice... | 3,655 | 1,404 |
def main() -> None:
s = input()
print(s * (6 // len(s)))
if __name__ == "__main__":
main()
| 112 | 49 |
'''
Вводится последовательность из N чисел. Найти произведение и
количество положительных среди них чисел
'''
proizvedenie = 1
a = input().split(" ")
for i in range(0, len(a)):
proizvedenie *= int(a[i])
print("Произведение " + str(proizvedenie))
print("Кол-во чисел " + str(len(a))) | 286 | 114 |
# 执行用时 : 348 ms
# 内存消耗 : 13 MB
# 方案:哈希表
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 创建哈希表{value:idx}
record = {}
# 遍数组
for idx, value in enumerate(nums):
... | 553 | 245 |
#!/usr/bin/env python3
# encoding: utf-8
#
# This file is part of ckanext-doi
# Created by the Natural History Museum in London, UK
import logging
from ckan.lib.helpers import lang as ckan_lang
from ckan.model import Package
from ckan.plugins import PluginImplementations, toolkit
from ckanext.doi.interfaces import I... | 9,939 | 2,934 |
"""Voce deve criar uma classe carro que vai assumir dois atributos compostos por duas classes:
1) Motor
2) Direcao
O motor terá a responsabilidade de controlar a velocidade.
Ele Oferece os seguintes atributos:
1) Atribuo de dado velocidade
2) Método acelerar, que deverá incrementar 1 unidade
3) Médoto freardecrement... | 3,417 | 1,398 |
# -*- coding: utf-8 -*-
from enum import IntEnum, unique
from typing import Optional, Any
class SDKException(Exception):
@unique
class Code(IntEnum):
OK = 0
KEY_STORE_ERROR = 1
ADDRESS_ERROR = 2
BALANCE_ERROR = 3
DATA_TYPE_ERROR = 4
JSON_RPC_ERROR = 5
Z... | 3,482 | 1,075 |
# -*- coding: utf-8 -*-
from model.movie import Movie
from model.user import User
from fixture.selenium_fixture import app
def test_add_movie(app):
app.session.login(User.Admin())
old_list = app.movie.get_movie_list()
app.movie.add_movie(Movie(film_name='name', film_year='2016'))
new_list = app.movie.... | 528 | 192 |
# Argument handling
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--run", action="store_true",
help="Start the learning process")
parser.add_argument("-m", "--memories", type=int, default=100,
help="Number of runs of demonstration data to... | 3,752 | 1,264 |
#!/usr/bin/env python
# 2020 (c) Tim Rogers, Purdue University
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the fo... | 20,561 | 6,285 |
'''@file numpy_float_array_as_tfrecord_reader.py
contains the NumpyFloatArrayAsTfrecordReader class'''
import os
import numpy as np
import tensorflow as tf
import tfreader
import pdb
class NumpyFloatArrayAsTfrecordReader(tfreader.TfReader):
'''reader for numpy float arrays'''
def _read_metadata(self, datadir... | 2,005 | 571 |
import telegram
from telegram.ext.filters import MessageFilter
from apps.telegram_bot.preferences import global_preferences
class CryptoCurrencyFilter(MessageFilter):
"""A custom MessageFilter that filters telegram text messages by
the condition of entering the list of BUTTONS_CRYPTO_CURRENCIES_FROM.
"""... | 643 | 180 |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.2.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Custom renderer in P... | 2,664 | 1,008 |
import json
import praw
from Analysis.Common import Constants
def get_reddit_instance(config_json_fname: str = Constants.CONFIG_FNAME):
"""
Given path to a file containing the credentials for reddit API's client_id, secret, user agent. This will return
the praw instance.
:param config_json_fname:
... | 668 | 202 |
def get_next_target(page):
start_link = page.find('<a href=')
if start_link == -1:
return None,0
else:
start_quote = page.find('"', start_link)
end_quote = page.find('"', start_quote + 1)
url = page[start_quote + 1:end_quote]
return url, end_quote
| 301 | 107 |
# author: Drew Botwinick, Botwinick Innovations
# title: occasionally trivial support functions for aggregating data for python 2/3 [only numpy as dependency]
# NOTE: these functions are generally tested meant for 1D although they may apply or be easily extended to nd
# license: 3-clause BSD
import numpy as np
flat_m... | 3,249 | 950 |
#
# @lc app=leetcode id=107 lang=python3
#
# [107] Binary Tree Level Order Traversal II
#
# https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/
#
# algorithms
# Easy (48.66%)
# Likes: 1105
# Dislikes: 201
# Total Accepted: 289.3K
# Total Submissions: 572.4K
# Testcase Example: '[3,9,2... | 1,485 | 561 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2011 Rosen Diankov (rosen.diankov@gmail.com)
#
# 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/li... | 3,383 | 1,076 |
import metrics
def rate(artToCatSim, label, membershipData, categoryTree, artNamesDict, catNamesDict):
# countBefore1 = artToCatSim.count_nonzero()
# for article in membershipData:
# id_and_categories = article.split('\t')
# articleId = int(id_and_categories[0])
# del id_and_categories... | 2,328 | 837 |
def test_socfaker_application_status(socfaker_fixture):
assert socfaker_fixture.application.status in ['Active', 'Inactive', 'Legacy']
def test_socfaker_application_account_status(socfaker_fixture):
assert socfaker_fixture.application.account_status in ['Enabled', 'Disabled']
def test_socfaker_name(socfaker_f... | 495 | 167 |
#!/usr/bin/env python
from __future__ import print_function
import roslib
roslib.load_manifest('begineer_tutorial')
import sys
import rospy
import cv2
import numpy as np
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
class image_converter:
def __init_... | 1,241 | 480 |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/bdd100k_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
# model
model = dict(
bbox_head=dict(
num_c... | 461 | 212 |
"""
You are given an integer array nums and an integer k.
In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.
Return the maximum number of operations you can perform on the array.
Example 1:
Input: nums = [1,2,3,4], k = 5
Output: 2
Explanation: Starting with ... | 1,278 | 454 |
import mock
from testify import setup, assert_equal, TestCase, run
from testify.assertions import assert_not_equal
from tests.assertions import assert_mock_calls
from tests.testingutils import autospec_method
from tron.core import service, serviceinstance
from tron import node, command_context, event, eventloop
from t... | 8,377 | 2,477 |
import os
from pathlib import Path
ABS_PATH_OF_TOP_LEVEL_DIR = os.path.abspath(os.path.dirname(Path(__file__)))
| 113 | 47 |
import tkinter as tk
from tkinter.font import Font
from tkinter import *
from tkinter import messagebox
from models.Store import Store
from models.ShoppingCart import ShoppingCart
import datetime
def viewStore():
global storeWindow
storeLabelFrame = LabelFrame(storeWindow, text="Store Items",)
storeLabel... | 4,558 | 1,470 |
"""
This module defines the database classes.
"""
import json
import zlib
from typing import Any
import gridfs
from bson import ObjectId
from maggma.stores.aws import S3Store
from monty.dev import deprecated
from monty.json import MontyEncoder
from pymatgen.electronic_structure.bandstructure import (
BandStructur... | 15,919 | 4,769 |
from django.db import models
# Create your models here.
class Case(models.Model):
name = models.CharField(max_length =100)
email = models.EmailField(max_length=100, unique=True)
message = models.CharField(max_length=500, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
| 296 | 105 |
from abc import ABCMeta, abstractmethod # Required to create an abstract class
import numpy as np
from scipy import spatial # For nearest neighbour lookup
import tensorflow as tf
class BaseFeaturizer(metaclass=ABCMeta):
"""Interface for featurizers
Featurizers take images that are potentially from different v... | 3,032 | 877 |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rt... | 897 | 254 |
from __future__ import (
absolute_import, division, print_function, unicode_literals)
from operator import itemgetter
def fixdate(ds):
dmy = ds.split('/')
# BUG (!?): don't understand but stolen from ubs-ch-fr.py
return '.'.join((dmy[1], dmy[0], dmy[2]))
mapping = {
'has_header': True,
'date... | 477 | 170 |
from unittest import TestCase
from parameterized import parameterized
from logtf_analyser.utils import convert_id3_to_id64
class TestConvert_id3_to_id64(TestCase):
def test_convert_id3_to_id64(self):
id64 = convert_id3_to_id64("[U:1:22202]")
self.assertEqual(id64, 76561197960287930)
@param... | 732 | 297 |
# -*- coding: utf-8 -*-
"""Binding energy workchain"""
from copy import deepcopy
from aiida.common import AttributeDict
from aiida.engine import append_, while_, WorkChain, ToContext
from aiida.engine import calcfunction
from aiida.orm import Dict, Int, SinglefileData, Str, StructureData, Bool
from aiida.plugins impo... | 14,191 | 4,399 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestCont... | 5,716 | 1,725 |
# spaCyをインポートし、日本語のnlpオブジェクトを作成
import spacy
nlp = spacy.blank("ja")
# テキストを処理
doc = nlp("私はツリーカンガルーとイッカクが好きです。")
# 「ツリーカンガルー」のスライスを選択
tree_kangaroos = doc[2:4]
print(tree_kangaroos.text)
# 「ツリーカンガルーとイッカク」のスライスを選択
tree_kangaroos_and_narwhals = doc[2:6]
print(tree_kangaroos_and_narwhals.text)
| 297 | 205 |
class InterfaceWriter(object):
def __init__(self, output_path):
self._output_path_template = output_path + '/_{key}_{subsystem}.i'
self._fp = {
'pre': {},
'post': {},
}
def _write(self, key, subsystem, text):
subsystem = subsystem.lower()
fp = se... | 841 | 274 |
import numpy
import numbers
import math
import struct
from six.moves import zip
from .. import SetIntersectionIndexBase, SearchResults, EmptySearchResults
def _check_numpy ():
missing = []
for fn in ("zeros", "empty", "digitize", "resize", "concatenate", "unique", "bincount", "argsort"):
if not getatt... | 10,757 | 3,102 |
# Generated by Django 3.1.5 on 2021-01-16 08:15
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Repository',
fields=[
('id', models.AutoFie... | 685 | 203 |
import sys
import os
import time
from basic.common import ROOT_PATH,checkToSkip,makedirsforfile
from basic.util import readImageSet
from simpleknn.bigfile import BigFile, StreamFile
from basic.annotationtable import readConcepts,readAnnotationsFrom
from basic.metric import getScorer
if __name__ == "__main__":
t... | 2,668 | 911 |
import ast
from ast import *
from collections.abc import Iterable
from .astalyzer import FreeVarFinder
from ..base import LanguageNode, ComplexNode, BaseGenerator
from ...helpers import StringWithLocation
from ...runtime.debug import TemplateSyntaxError
import sys
try: # pragma: no cover
import sysconfig
... | 24,369 | 7,301 |
# Format of training prompt
defaultPrompt = """I am a Cardiologist. My patient asked me what this means:
Input: Normal left ventricular size and systolic function. EF > 55 %. Normal right ventricular size and systolic function. Normal valve structure and function
Output: Normal pumping function of the left and right ... | 389 | 105 |
"""
Programs scraper
"""
import re
import src.scrape.util.helpers as helpers
import src.settings as settings
from src.logger import get_logger
_LOG = get_logger("programs_scraper")
def programs():
"""
Scrapes list of programs
:return: List, of program codes
"""
_LOG.debug("scraping list of progra... | 682 | 231 |
from django import forms
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.forms.formsets import DELETION_FIELD_NAME
from django.utils.module_loading import import_string
from django.utils.translation import ugettext
import swapper
from wagtail_revie... | 2,219 | 670 |
import numpy as np
from myutils import *
from easydict import EasyDict as edict
def dcg_at_k(r, k, method=1):
r = np.asfarray(r)[:k]
if r.size:
if method == 0:
return r[0] + np.sum(r[1:] / np.log2(np.arange(2, r.size + 1)))
elif method == 1:
return np.sum(r / np.log2(np.... | 20,466 | 6,611 |
import numpy as np
#Simulater Setting
#------------------------------
MINUTES=60000000000
TIMESTEP = np.timedelta64(10*MINUTES)
PICKUPTIMEWINDOW = np.timedelta64(10*MINUTES)
#It can enable the neighbor car search system to determine the search range according to the set search distance and the size of the grid.
#It u... | 987 | 355 |
from ursina import *
from copy import copy
class MinecraftClone(Entity):
def __init__(self):
super().__init__()
c = Cylinder(6, height=1, start=-.5)
verts = c.vertices
tris = c.triangles
vertices = list()
triangles = list()
colors = list()
# for z... | 4,716 | 1,578 |
import sys
import traceback
import copy
import importlib
from gemini.gemini_compiler import *
from gemini.utils import *
def main(argv=sys.argv[1:]):
print('gemini compiler entry point')
filename = copy.deepcopy(argv[0])
arguments = copy.deepcopy(argv[1:])
compiler = GeminiCompiler()
src_code = ... | 1,646 | 510 |
#!/usr/bin/env python3
import subprocess
import sys, getopt, os
import threading
import argparse
cwd = os.getcwd()
path = cwd + "/port_scanner_files/"
ip_list_file = path + "input/IP_list.txt"
nmap_output_file = path + "temp_output/nmap_output"
#the scorchedearth option runs every nmap scan that doesn't require an ad... | 4,513 | 1,478 |
from helpers import create_connection, execute_query
connection = create_connection(
"postgres", "postgres", "admin", "127.0.0.1", "5432"
)
create_database_query = "CREATE DATABASE ekatte"
execute_query(connection, create_database_query)
connection = create_connection(
"ekatte", "postgres", "admin", "127.0.0... | 1,535 | 522 |
# -*- coding: utf-8 -*-
"""
This module contains the tool of Events
"""
import os
from setuptools import setup, find_packages
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
version = '0.2'
long_description = (
read('README.txt')
+ '\n' +
'Change history\n'
... | 1,964 | 677 |
from torchvision import models
import json
import numpy as np
import torch
from collections import OrderedDict
from operator import itemgetter
import os
def return_top_5(processed_image):
# inception = models.inception_v3(pretrained=True)
inception = models.inception_v3()
inception.load_state_dict(torch.lo... | 1,053 | 380 |
#!/usr/bin/env python3
from collections import defaultdict
from itertools import permutations
def main():
places = defaultdict(lambda: {})
with open('input', 'r') as fp:
for line in fp.read().split('\n'):
a = line.split(' ')
places[a[0]][a[2]] = int(a[4])
places[a[2... | 816 | 271 |
import pickle
from pytest import raises
from typedpy import Structure, serialize
from typedpy.fields import Generator
class Foo(Structure):
g: Generator
def test_generator_wrong_type():
with raises(TypeError):
Foo(g=[])
def test_generator():
foo = Foo(g=(i for i in range(5)))
assert sum(... | 504 | 172 |
"""
Workflow based on Python classes
"""
class StateMetaclass(type):
def __init__(cls, name, bases, dict):
super(StateMetaclass, cls).__init__(name, bases, dict)
abstract = dict.pop('abstract', False)
if not abstract:
cls.forward_transitions = []
cls.backward_transi... | 5,624 | 1,610 |
from django.contrib import admin
from app.models import *
from app.admin.tip import ReadingTipAdmin
from app.admin.user import UserAdmin
# Register your models here.
admin.site.register(User, UserAdmin)
admin.site.register(ReadingTip, ReadingTipAdmin)
| 254 | 75 |
abilities = {1: 'Stench', 2: 'Drizzle', 3: 'Speed Boost', 4: 'Battle Armor', 5: 'Sturdy', 6: 'Damp', 7: 'Limber',
8: 'Sand Veil', 9: 'Static', 10: 'Volt Absorb', 11: 'Water Absorb', 12: 'Oblivious', 13: 'Cloud Nine',
14: 'Compound Eyes', 15: 'Insomnia', 16: 'Color Change', 17: 'Immunity', 18: ... | 5,551 | 2,718 |
from crypt import methods
import os
import pickle
import pandas as pd
import lightgbm
from flask import Flask, request, Response
from healthinsurance.HealthInsurance import HealthInsurance
# loading model
model = pickle.load( open( 'model/LGBM_Model.pkl', 'rb' ) )
# initialize API
app = Flask( __name__ )
@app.route(... | 1,371 | 414 |
# %% [markdown]
# # How to define a scikit-learn pipeline and visualize it
# %% [markdown]
# The goal of keeping this notebook is to:
# - make it available for users that want to reproduce it locally
# - archive the script in the event we want to rerecord this video with an
# update in the UI of scikit-learn in a f... | 2,490 | 785 |
from nltk.corpus import wordnet as wn
import json
from pyinflect import getAllInflections, getInflection
import re
import inflect
import urllib.parse
from SPARQLWrapper import SPARQLWrapper, JSON
from urllib.parse import quote
from py_thesaurus import Thesaurus
import sys, getopt
WN_NOUN = 'n'
WN_VERB = 'v'
WN_ADJECTI... | 23,423 | 7,788 |
STRICTDOC_GRAMMAR = r"""
Document[noskipws]:
'[DOCUMENT]' '\n'
// NAME: is deprecated. Both documents and sections now have TITLE:.
(('NAME: ' name = /.*$/ '\n') | ('TITLE: ' title = /.*$/ '\n')?)
(config = DocumentConfig)?
('\n' grammar = DocumentGrammar)?
free_texts *= SpaceThenFreeText
section_contents... | 3,951 | 1,640 |
# Copyright 2019 RedLotus <ssfdust@gmail.com>
# Author: RedLotus <ssfdust@gmail.com>
#
# 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
#
# Unles... | 1,683 | 587 |
# https://www.youtube.com/watch?v=bf_UOFFaHiY
# http://www.trex-game.skipser.com/
from PIL import ImageGrab, ImageOps
import pyautogui
import time
from numpy import *
class Cordinates():
replayBtn = (962, 530)
dinosaur = (664, 536) # dinaosaur standing
# dinosaur = (686, 548) # dinosaur down
#730= x co... | 1,236 | 486 |
# Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import entities
from mixbox import fields
import cybox.bindings.win_event_object as win_event_binding
from cybox.objects.win_handle_object import WinHandle
from cybox.common import ObjectProperties, Str... | 735 | 229 |
from .base import *
# Sends an email to developers in the ADMIN_EMAILS list if Debug=False for errors
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': [],
'class': 'django.utils.log.AdminEma... | 1,883 | 619 |
import tkinter as tk
root = tk.Tk()
def motion(event):
x, y = event.x, event.y
print('{}, {}'.format(x, y))
root.bind('<Motion>', motion)
root.mainloop() | 163 | 67 |
# coding=utf-8
"""This module, nexus_db.py, defines a basic started database for the Nexus Server."""
import pika
import json
import time
from scripts.docker.wait_for_rabbit_host import WaitForRabbitMQHost
from libraries.database_abstraction.sql.sqlite import sqlite_db
from libraries.database_abstraction.sql.sqlite i... | 3,552 | 1,113 |
#! /usr/bin/env python
"tdcsm command-line interface"
import argparse
from pathlib import Path
from typing import Any, Sequence, Callable, List, Optional
from logging import getLogger
from .tdgui import coa as tdgui
from .tdcoa import tdcoa
from .model import load_filesets, load_srcsys, dump_srcsys, SrcSys, FileSet, ... | 7,429 | 2,737 |
import itertools
import asyncio
from async_timeout import timeout
from functools import partial
from youtube_dl import YoutubeDL
from discord.ext import commands
from discord import Embed, FFmpegPCMAudio, HTTPException, PCMVolumeTransformer, Color
ytdlopts = {
'format': 'bestaudio/best',
'extractaudio': True,
... | 12,247 | 3,865 |
'''
Classes based on SchItem for parsing and rendering $Sheet sub-sheets
inside a .sch file.
'''
from .schitem import SchItem
class Sheet(SchItem):
keyword = '$Sheet'
_by_keyword = {}
def render(self, linelist):
linelist.append(self.keyword)
self.S.render(self, linelist)
self.U.ren... | 2,584 | 855 |
#!/usr/bin/env python
import os
import pickle
import json
import argparse
from collections import defaultdict
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser()
parser.add_argument('path', help="Tf path to event files from which to extract variables")
parse... | 1,988 | 647 |
from rotating_proxies.policy import BanDetectionPolicy
class MyPolicy(BanDetectionPolicy):
def response_is_ban(self, request, response):
# use default rules, but also consider HTTP 200 responses
# a ban if there is 'captcha' word in response body.
ban = super(MyPolicy, self).response_is_ban... | 551 | 151 |
import os
import argparse
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile
from tensorflow.python.framework import dtypes
from tensorflow.python.tools import strip_unused_lib
tf.enable_eager_execution()
parser = argparse.ArgumentParser()
# export types
parser.add_argument("-... | 8,162 | 2,408 |
# TestSwiftPrivateDeclName.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org... | 3,594 | 1,200 |
input_name = '../examples/diffusion/laplace_time_ebcs.py'
output_name_trunk = 'test_laplace_time_ebcs'
from tests_basic import TestInputEvolutionary
class Test(TestInputEvolutionary):
pass
| 195 | 68 |
import boto3
exceptions = boto3.client('iot1click-devices').exceptions
ForbiddenException = exceptions.ForbiddenException
InternalFailureException = exceptions.InternalFailureException
InvalidRequestException = exceptions.InvalidRequestException
PreconditionFailedException = exceptions.PreconditionFailedException
Ran... | 518 | 111 |
#!/usr/bin/env python3.5
#-*- coding:utf-8 -*-
"""Functions handling images."""
import subprocess
import os
# supported ImageMagic Formats?
def getDateTimeOriginal(filePath) :
"""If image has DateTimeOriginal then returns it as a string. If it's missing or there isn't EXIF at all then returns empty string."""
... | 1,826 | 534 |
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... | 18,415 | 5,216 |
# This was built from the tutorial https://www.raywenderlich.com/24252/beginning-game-programming-for-teens-with-python
import pygame, math, random
from pygame.locals import *
import pyganim
# 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
pygame.display... | 2,259 | 818 |
li=["a","b","d"]
print(li)
str="".join(li)#adding the lists value together
print(str)
str=" ".join(li)#adding the lists value together along with a space
print(str)
str=",".join(li)#adding the lists value together along with a comma
print(str)
str="&".join(li)#adding the lists value together along with a &
print(st... | 322 | 109 |
import os
file=open("C:/Users/michael.duran\OneDrive - Thomas Greg/Documents/Audisoft/Thomas/Inmofianza/TeamQA/SeleniumInmofianza/src/classes/datos.txt","w")
file.write("Primera línea" + os.linesep)
file.write("Segunda línea")
file.close() | 240 | 97 |
from egyptian_data_generator.helpers import Helpers
class Finance:
def americanexpressCreditCardNumber(self):
return self.generateCreditCardNumber("americanexpress")
def discoverCreditCardNumber(self):
return self.generate("discover")
def mastercardCreditCardNumber(se... | 1,962 | 657 |
def limpar(*args):
telaPrincipal = args[0]
cursor = args[1]
banco10 = args[2]
sql_limpa_tableWidget = args[3]
telaPrincipal.valorTotal.setText("Valor Total:")
telaPrincipal.tableWidget_cadastro.clear()
telaPrincipal.desconto.clear()
telaPrincipal.acrescimo.clear()
sql_limpa_tableW... | 349 | 135 |
from os import environ
import logging
from bson.objectid import ObjectId
from bson.errors import InvalidId
from flask import Flask, jsonify, abort
from flask_pymongo import PyMongo
from typing import List, Dict
from pymongo import MongoClient, errors
from mongoflask import MongoJSONEncoder, find_restaurants
app = Fla... | 1,736 | 589 |
import subprocess
def Settings( **kwargs ):
flags = [
'-x',
'c++',
'-Wall',
'-Wextra',
'-Wno-unused-parameter',
'-std=c++14',
'-I',
'.',
'-I', 'third_party/googletest/googletest/include',
'-I', 'third_party/abseil-cpp',
'-I', 'third_party/libbcf',
'-pthread',
]
... | 434 | 179 |
"""Lookout - Assisted Code Review"""
import pkg_resources
pkg_resources.declare_namespace(__name__)
| 101 | 32 |
# can I have a comment here?
import re
a = 538734
print(re.search('a', "helalo") != None)
print(re.search('a', "hallo") != None)
a = 30 * 25
for i in range(0,5):
print(i)
'''
This is a sigma $\sigma$ symbol in markdown and a forall $\forall$ symbol too!
Here's some mathematics $ 1 + 2 - 3 * 5 / 15$ and "qu... | 789 | 372 |
import re
from random import randrange
def test_phones_on_homepage(app):
contact_from_homepage = app.contact.get_contact_list()[0]
contact_from_editpage = app.contact.get_contact_info_from_edit_page(0)
assert contact_from_homepage.all_phones_from_homepage == merge_phones_like_on_homepage(contact_from_editp... | 2,061 | 681 |
import argparse
import logging
import sys
import json
import plotly.offline
import plotly.graph_objs as go
sys.path.append(sys.path[0] + "/..")
from utils.fileprovider import FileProvider
from preprocessing.reader import EvalitaDatasetReader
from nltk.tokenize import TweetTokenizer
logging.getLogger().setLevel(loggi... | 8,352 | 2,524 |
"""
Modeling Relational Data with Graph Convolutional Networks
Paper: https://arxiv.org/abs/1703.06103
Code: https://github.com/tkipf/relational-gcn
Difference compared to tkipf/relation-gcn
* l2norm applied to all weights
* remove nodes that won't be touched
"""
import argparse
import numpy as np
import time
import ... | 6,596 | 2,241 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import re
from glob import glob
from io import open
from os.path import basename
from os.path import splitext
import setuptools
from os import path
# Single sourcing the version -
def read(*n... | 2,992 | 916 |
import subprocess
from hop import Stream
from hop.auth import Auth
from hop import auth
from hop.io import StartPosition
from hop.models import GCNCircular
import argparse
import random
import threading
import time
from functools import wraps
import datetime
import numpy
import uuid
from dotenv import load_dotenv
impor... | 11,080 | 3,391 |
import mraa # For accessing the GPIO
import time # For sleeping between blinks
global led
def init_led(pin):
global led
led = mraa.Gpio(pin) # Get the LED pin object
led.dir(mraa.DIR_OUT) # Set the direction as output
led.write(0)
def write_led(signal):
global led
led.wri... | 992 | 317 |
from collections import deque
def list_manipulator(numbers, *args):
numbers = deque(numbers)
action = args[0]
direction = args[1]
if action == 'add':
parameters = [int(x) for x in args[2:]]
if direction == 'beginning':
[numbers.appendleft(x) for x in parameters[::-1]]
... | 1,511 | 507 |
from django.urls import reverse
from ..links.document_file_links import (
link_document_file_delete, link_document_file_download_quick
)
from ..links.favorite_links import (
link_document_favorites_add, link_document_favorites_remove
)
from ..links.trashed_document_links import link_document_restore
from ..mod... | 6,738 | 2,032 |
import discord
from discord.ext import commands
class anime(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
def setup(bot):
bot.add_cog(anime(bot)) | 218 | 77 |
from jumpscale import j
from zerorobot.service_collection import ServiceNotFoundError
from testconfig import config
import random
class BrigeManager:
def __init__(self, parent, service_name=None):
self.bridge_template = 'github.com/threefoldtech/0-templates/bridge/0.0.1'
self._parent = parent
... | 1,770 | 524 |