text
string
size
int64
token_count
int64
from django.db import models from utils.models import BaseModel from users.models import User, Address from goods.models import GoodsSKU # Create your models here. class OrderInfo(BaseModel): """订单信息""" PAY_METHOD = ['1', '2'] PAY_METHOD_CHOICES = ( (1, "货到付款"), (2, "支付宝"), ) OR...
2,245
959
from collections import defaultdict, Counter import os import gzip import json import pickle from json.decoder import JSONDecodeError import logging from typing import Dict import pdb from event import util from event.arguments.prepare.slot_processor import get_simple_dep, is_propbank_dep logger = logging.getLogger(_...
18,201
5,606
#!/usr/bin/python import random count = 20 test_set = [] while count: a = random.randrange(3,20) b = random.randrange(3,20) if a > b and a - b > 1: if (b, a-b) not in test_set: test_set.append((b, a-b)) count -= 1 elif b > a and b - a > 1: if (a, b-a) not in te...
478
201
from enum import Enum from functools import reduce from math import ceil from typing import Optional, Tuple from autovirt import utils from autovirt.exception import AutovirtError from autovirt.structs import UnitEquipment, RepairOffer logger = utils.get_logger() # maximum allowed equipment price PRICE_MAX = 100000 ...
4,570
1,484
#!/usr/bin/env python3 import re with open("input.txt") as f: content = f.read().strip() def ulen(content): ans = 0 i = 0 while i < len(content): if content[i] == "(": end = content[i:].find(")") + i instr = content[i+1:end] chars, times = map(int, content...
594
210
# pylint: disable=wrong-or-nonexistent-copyright-notice import itertools import math import numpy as np import pytest import sympy import cirq import cirq.contrib.quimb as ccq import cirq.testing from cirq import value def assert_same_output_as_dense(circuit, qubit_order, initial_state=0, grouping=None): mps_si...
17,397
6,729
import os from pathlib import Path from typing import Any, Dict from determined.common import util MASTER_SCHEME = "http" MASTER_IP = "localhost" MASTER_PORT = "8080" DET_VERSION = None DEFAULT_MAX_WAIT_SECS = 1800 MAX_TASK_SCHEDULED_SECS = 30 MAX_TRIAL_BUILD_SECS = 90 DEFAULT_TF1_CPU_IMAGE = "determinedai/environm...
6,574
2,453
from django.contrib.contenttypes.models import ContentType from rest_framework import serializers, exceptions from greenbudget.lib.rest_framework_utils.fields import ModelChoiceField from greenbudget.lib.rest_framework_utils.serializers import ( EnhancedModelSerializer) from greenbudget.app.budget.models import B...
7,340
1,983
import contextlib import logging import typing from typing import Any, Dict, Tuple import attr from dbnd._core.configuration import get_dbnd_project_config from dbnd._core.constants import ( RESULT_PARAM, DbndTargetOperationStatus, DbndTargetOperationType, TaskRunState, ) from dbnd._core.current impo...
13,152
3,525
import os import logging from json import loads, dumps from datetime import timedelta from argparse import ArgumentParser from redis import Redis from flask import Response, Flask, request app = Flask(__name__) log = logging.getLogger(__name__) parser = ArgumentParser() parser.add_argument("-a", "--address", ...
5,534
1,851
""" 启动此 spider 前需要手动启动 Chrome,cmd 命令如下: cd 进入 Chrome 可执行文件 所在的目录 执行:chrome.exe --remote-debugging-port=9222 此时在浏览器窗口地址栏访问:http://127.0.0.1:9222/json,如果页面出现 json 数据,则表明手动启动成功 启动此 spider 后,注意与命令行交互! 在 settings 当中要做的: # ROBOTSTXT_OBEY = False # 如果不关闭,parse 方法无法执行 # COOKIES_ENABLED = True # 以便 Request 值在传递时自动传递 cookies...
6,071
2,314
import nose import angr import logging l = logging.getLogger("angr.tests.test_bindiff") import os test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests') # todo make a better test def test_bindiff_x86_64(): binary_path_1 = os.path.join(test_location, 'x86_64', '...
2,109
806
from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # def handle_uploaded_file(f): # with open('screenshot.png', 'wb') as destination: # # for chunk in f.chunks(): # # destination.write(chunk) # destination.write(f) with open( BASE_DIR/'media'/'Greater_coat...
523
192
#!/usr/bin/env python3 # # Copyright 2018 Google LLC # # 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 ...
4,921
1,881
r""" Piezo-elasticity problem - linear elastic material with piezoelectric effects. Find :math:`\ul{u}`, :math:`\phi` such that: .. math:: - \omega^2 \int_{Y} \rho\ \ul{v} \cdot \ul{u} + \int_{Y} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) - \int_{Y_2} g_{kij}\ e_{ij}(\ul{v}) \nabla_k \phi = 0 \;, \qu...
4,960
2,014
# Desempacotamento de parametros em funcoes # somando valores de uma tupla def soma(*num): soma = 0 print('Tupla: {}' .format(num)) for i in num: soma += i return soma # Programa principal print('Resultado: {}\n' .format(soma(1, 2))) print('Resultado: {}\n' .format(soma(1, 2, 3, 4, 5, 6, 7, 8,...
326
143
import pandas from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from keras.utils import np_utils from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold from sklearn.preprocessing import LabelEncoder from skle...
2,876
1,210
from django.core.urlresolvers import reverse from sentry.models import Project from sentry.testutils import APITestCase class ProjectDetailsTest(APITestCase): def test_simple(self): project = self.project # force creation self.login_as(user=self.user) url = reverse('sentry-api-0-project-d...
1,848
565
# encoding: utf-8 """Unit-test suite for `pptx.table` module.""" import pytest from pptx.dml.fill import FillFormat from pptx.dml.border import BorderFormat from pptx.enum.text import MSO_ANCHOR from pptx.oxml.ns import qn from pptx.oxml.table import CT_Table, CT_TableCell, TcRange from pptx.shapes.graphfrm import G...
29,732
10,267
import numpy as np from imread import imread from . import file_path def test_read(): im = imread(file_path('star1.bmp')) assert np.any(im) assert im.shape == (128, 128, 3) def test_indexed(): im = imread(file_path('py-installer-indexed.bmp')) assert np.any(im) assert im.shape == (352, 162, 3)...
408
174
from serial import Serial from tqdm import tqdm import binascii import hashlib import struct import time import sys import os def if_read(ser, data_len): data = bytearray(0) received = 0 while received < data_len: tmp = ser.read(data_len - received) if len(tmp) == 0: ...
6,612
2,756
# -*- coding: utf-8 -*- import unittest from avro import avro_builder from avro import schema class TestAvroSchemaBuilder(unittest.TestCase): def setUp(self): self.builder = avro_builder.AvroSchemaBuilder() def tearDown(self): del self.builder @property def name(self): retu...
19,638
5,692
import random def estimate_pi(sims, needles): trials = [] for _ in xrange(sims): trials.append(simulate_pi(needles)) mean = sum(trials) / sims return mean # use a unit square def simulate_pi(needles): hits = 0 # how many hits we hit the circle for _ in xrange(needles): x = ran...
467
171
#!/usr/bin/env python3 # # This file is part of the MicroPython project, http://micropython.org/ # # The MIT License (MIT) # # Copyright (c) 2019 Damien P. George # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to d...
36,577
13,330
from PyQt4 import QtGui from ui_mant_libros_new import NewLibrosWindow from ui_mant_libros_edit import EditLibrosWindow from ui_mant_libros_id_edit import GetIdEditWindow # Debug only import inspect class MenuLibros(QtGui.QWidget): """ Ventana-menu para editar Libros """ def __init__(self): ...
2,289
815
import argparse import re import holdem_calc.holdem_functions as holdem_functions # Wrapper class which holds the arguments for library calls # Mocks actual argparse object class LibArgs: def __init__(self, board, exact, num, input_file, hole_cards): self.board = board self.cards = hole_cards ...
6,583
1,928
from flask import render_template, request, session, redirect from qbay.models import * from datetime import date from qbay import app def authenticate(inner_function): """ :param inner_function: any python function that accepts a user object Wrap any python function and check the current session to see ...
8,318
2,241
from datetime import timedelta from django.utils.timezone import now from preferences import preferences from rest_framework import fields, serializers from bikesharing.models import Bike, Station, VehicleType from cykel.serializers import EnumFieldSerializer class TimestampSerializer(fields.CharField): def to_...
6,998
1,893
import logging import re from anime_downloader.extractors.base_extractor import BaseExtractor from anime_downloader.sites import helpers logger = logging.getLogger(__name__) class VidStream(BaseExtractor): def _get_data(self): QUALITIES = { "360":[], "480":[], "720":[], "10...
1,095
380
import time import os from django.shortcuts import render, redirect from django.http import JsonResponse from django.views import View from django.conf import settings from .forms import File_uploadForm from .models import File_upload, SummaryRes from sim_v1.textsummary import TEXTSummary summary_document_dir = os....
2,799
870
""" Websocket based API for Home Assistant. For more details about this component, please refer to the documentation at https://developers.home-assistant.io/docs/external_api_websocket.html """ from homeassistant.core import callback from homeassistant.loader import bind_hass from . import commands, connection, const...
1,290
387
# # Created on Tue Dec 21 2021 # # Copyright (c) 2021 Lenders Cooperative, a division of Summit Technology Group, Inc. # """ Django settings for test_app project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ ...
4,181
1,489
# Copyright © 2020 Province of British Columbia # # 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 agr...
9,871
3,072
""" Module to contain Pywork decorators """ __author__ = 'sergey kharnam' import re import time import itertools import logging log = logging.getLogger(__name__)
165
55
from __future__ import unicode_literals import pytest from django.test import TestCase from rest_framework import status from rest_framework.authentication import BasicAuthentication from rest_framework.decorators import ( action, api_view, authentication_classes, detail_route, list_route, parser_classes, per...
10,449
2,857
## -*- coding: utf-8 -*- #(C) 2018 Muthiah Annamalai # This file is part of Open-Tamil project # You may use or distribute this file under terms of MIT license import codecs import json import tamil import sys import os #e.g. python morse_encode.py கலைஞர் CURRDIR = os.path.dirname(os.path.realpath(__file__)) def enco...
661
263
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: temp = head array = [] while temp: a...
1,355
401
""" Warning - this will reset all components back to a blank state before running the simulation Runs node1, electrumx1 and electrumsv1 and loads the default wallet on the daemon (so that newly submitted blocks will be synchronized by ElectrumSV reorged txid: 'a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a0...
3,029
1,011
# 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 ...
25,892
8,526
# pyRasp # Copyright (c) Tonino Tarsi 2020. Licensed under MIT. # requirement : # Python 3 # pip install pyyaml # pip install request # pip install f90nml from downloadGFSA import downloadGFSA from prepare_wps import prepare_wps from ungrib import ungrib from metgrid import metgrid from prepare_wrf import prepare_w...
469
167
import pandas as pd import ta from app.common import reshape_data from app.strategies.base_strategy import BaseStrategy pd.set_option("display.max_columns", None) pd.set_option("display.width", None) class EMABBAlligatorStrategy(BaseStrategy): BUY_SIGNAL = "buy_signal" SELL_SIGNAL = "sell_signal" def c...
1,572
593
# Python Basics # String concatenaton added_strings = str(32) + "_342" # Getting input input_from_user = input() # Basic print function print(input_from_user) # Mixing boolean and comparison operations if (4 < 5) and (5 < 6): print("True") # Basic if & if else flow if name == 'Alice': print('Hi, Alice.')...
1,336
472
DATABASE_OPTIONS = { 'database': 'klazor', 'user': 'root', 'password': '', 'charset': 'utf8mb4', } HOSTS = ['127.0.0.1', '67.209.115.211']
156
79
""" Django settings. Generated by 'django-admin startproject' using Django 2.2.4. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ #DEBUG = False DEBUG = True SERV...
818
302
from django import forms from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ('name', 'number', 'email', 'category', 'description')
204
54
# Copyright (c) 2017 Ansible, Inc. # All Rights Reserved. from django.urls import re_path from awx.api.views import ( AdHocCommandList, AdHocCommandDetail, AdHocCommandCancel, AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList, AdHocCommandNotification...
1,276
508
#test.py from time_tools import * # print(compareTimestamp(111,222)) time.showNowTime() # now time is XX:XX:XX
110
44
import arcade from arcade import FACE_RIGHT, FACE_DOWN, FACE_UP, FACE_LEFT class AnimatedWalkingSprite(arcade.Sprite): def __init__(self, scale: float = 1, image_x: float = 0, image_y: float = 0, center_x: float = 0, center_y: float = 0, *, stand_left, stand_righ...
3,265
1,043
from numpy.core.fromnumeric import transpose from sklearn import linear_model from scipy.special import logit from scipy import stats from copy import deepcopy from numpy import random, concatenate, quantile, matmul, transpose import logging class singleRegModel(): """ data struct for running a single regress...
2,089
665
import numpy as np import matplotlib.pyplot as plt from scipy import stats from sklearn.linear_model import ARDRegression, LinearRegression # Parameters of the example np.random.seed(0) n_samples, n_features = 100, 100 # Create Gaussian data X = np.random.randn(n_samples, n_features) # Create weights with a precision...
4,553
1,513
#!/usr/bin/python3 import os import json import re import ast import json from graphviz import Digraph import pandas as pd # color the graph import graph_tool.all as gt import copy import matplotlib.colors as mcolors import sys import utils from tompkins.ilp import schedule, jobs_when_where from collections import d...
7,516
2,712
from __future__ import absolute_import import unittest from testutils import ADMIN_CLIENT from testutils import TEARDOWN from library.user import User from library.project import Project from library.repository import Repository from library.repository import pull_harbor_image from library.repository import push_imag...
8,563
2,731
import datetime as dt import logging from babel import Locale, UnknownLocaleError from babel.dates import format_datetime, format_time, format_date import pytz from tzlocal import get_localzone from . import settings logger = logging.getLogger(__name__) class LocaleHelper: """Helpers for converting date & tim...
3,675
1,067
import os class Config(object): # FLASK GENERAL CONFIG PARAMETERS SECRET_KEY = os.getenv('DATABOARD_SECRET_KEY', 'abcdefghijkl') # abs max upload file size, to throw 413, before saving it WTF_CSRF_ENABLED = True LOG_FILENAME = None # if None, output to screen MAX_CONTENT_LENGTH = 1024 * 1024 ...
2,414
987
# !/usr/bin/env python # -- coding: utf-8 -- # @Author zengxiaohui # Datatime:8/31/2021 1:37 PM # @File:GlobalAvgPool2d import torch.nn as nn from python_developer_tools.cv.bases.activates.swish import h_swish class GlobalAvgPool2d(nn.Module): """ Fast implementation of global average pooling from TResNe...
1,193
443
"""Some utility functions""" # Authors: Eric Larson <larsoner@uw.edu> # # License: BSD (3-clause) import warnings import operator from copy import deepcopy import subprocess import importlib import os import os.path as op import inspect import sys import tempfile import ssl from shutil import rmtree import atexit imp...
28,531
8,510
import signal class KillableProcess(object): def __init__(self): self.interrupt = False signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) def _signal_handler(self, sign, frame): self.interrupt = True
295
89
def HAHA(): return 1,2,3 a = HAHA() print(a) print(a[0])
68
40
import torch import torch.overrides import linecache from typing import Type, Dict, List, Any, Union from .graph import Graph import copy # normal exec loses the source code, however we can patch # the linecache module to still recover it. # using exec_with_source will add it to our local cache # and then tools like T...
9,079
2,605
# # Copyright (c) 2016 Christoph Heiss <me@christoph-heiss.me> # # 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, copy, m...
8,949
3,506
from hover.utils.metrics import classification_accuracy import numpy as np def test_classification_accuracy(): true = np.array([1, 2, 3, 4, 5, 6, 7, 7]) pred = np.array([1, 2, 3, 4, 5, 6, 7, 8]) accl = classification_accuracy(true, pred) accr = classification_accuracy(pred, true) assert np.allclose...
366
156
#!/usr/bin/python # # This source file is part of appleseed. # Visit https://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2017-2018 Esteban Tovagliari, The appleseedhq Organization # # Permission is hereby granted, free of charge, to ...
27,504
8,327
ser = int(input()) mas = list(map(int, input().split())) mas.sort() print(*mas)
80
31
from django.utils.translation import gettext from wagtail.admin.rich_text.editors.draftail import features as draftail_features from wagtail.core import hooks from .richtext import KaTeXEntityElementHandler, katex_entity_decorator @hooks.register('register_rich_text_features') def register_katex_features(features):...
1,420
452
############################################################### # Autogenerated module. Please don't modify. # # Edit according file in protocol_generator/templates instead # ############################################################### from typing import Dict from ...structs.api.elect_preferred_le...
1,415
389
''' Copyright 2017 Dell Inc. or its subsidiaries. All Rights Reserved. This script tests arbitrary payload of the RackHD API 2.0 OS bootstrap workflows. The default case is running a minimum payload Windows OS install. Other Windows-type OS install cases can be specified by creating a payload file and specifiying it u...
8,991
2,654
from flask import Flask, render_template from flask_ask import Ask, statement import random app = Flask(__name__) ask = Ask(app, '/') @ask.intent('RandomNumber', convert={'lowerLimit': int, 'upperLimit': int}) def hello(lowerLimit, upperLimit): if lowerLimit == None: lowerLimit = 0 if upperLimit == None: upperL...
602
195
import torch import numpy as np import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from model.laplacian import LapLoss device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class EPE(nn.Module): def __init__(self): super(EPE, self).__init__() de...
9,686
3,729
import numpy as np import pybullet as p import itertools from robot import Robot class World(): def __init__(self): # create the physics simulator self.physicsClient = p.connect(p.GUI) p.setGravity(0,0,-9.81) self.max_communication_distance = 2.0 # We will int...
5,847
2,269
# Copyright (c) 2006-2012 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2012 Amazon.com, Inc. or its affiliates. # All Rights Reserved # # 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 wi...
31,437
8,366
''' Command line interface for the basis set exchange ''' import argparse import argcomplete from .. import version from .bse_handlers import bse_cli_handle_subcmd from .check import cli_check_normalize_args from .complete import (cli_case_insensitive_validator, cli_family_completer, cli_role_co...
9,677
2,750
""" 입력 예시 3 16 출력 예시 3 5 7 11 13 """ import math left, right = map(int, input().split()) array = [True for i in range(right+1)] array[1] = 0 for i in range(2, int(math.sqrt(right)) + 1): if array[i] == True: j = 2 while i * j <= right: array[i * j] = False j += 1 for i in...
376
174
# Copyright 2015 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...
42,452
15,512
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-04-26 09:14 import colorfield.fields from django.db import migrations, models import django.db.models.deletion import giscube.utils class Migration(migrations.Migration): initial = True dependencies = [ ('giscube', '0002_update'), ]...
2,698
812
backgroundurl = "https://storage.needpix.com/rsynced_images/colored-background.jpg" # <- Need to be a Image URL!!! lang = "en" # <- language code displayset = True # <- Display the Set of the Item raritytext = True # <- Display the Rarity of the Item typeconfig = { "BannerToken": True, "AthenaBackpack":...
910
345
import unittest import settings from healthvaultlib.helpers.connection import Connection class TestBase(unittest.TestCase): def setUp(self): self.connection = self.get_connection() def get_connection(self): conn = Connection(settings.HV_APPID, settings.HV_SERVICE_SERVER) conn...
592
183
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-06-09 03:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('extensions', '0011_auto_20170502_0908'), ] operations = [ migrations.AlterF...
484
176
''' multi-threading (python3 version) https://docs.python.org/3/library/threading.html ''' from time import clock import threading THREADS=2 lock = threading.Lock() A = 0 B = 0 C = 0 def test_globals(): global A, B, C for i in range(1024*1024): lock.acquire() A += 1 B += 2 C = A + B lock.release() def...
628
276
import numpy as np class Board: """ 0 - black 1 - white """ def __init__(self): board = [ [0, 1] * 4, [1, 0] * 4 ] * 4 players_board = [ [0, 1] * 4, # player 1 [1, 0] * 4 ] + [[0] * 8] * 4 + [ # 4 rows of nothing [0, 2] * 4, # player 2 [2, 0] * 4 ] se...
2,270
917
def get_season_things_price(thing, amount, price): if thing == 'wheel': wheel_price = price[thing]['month'] * amount return f'Стоимость составит {wheel_price}/месяц' else: other_thing_price_week = price[thing]['week'] * amount other_thing_price_month = price[thing]['month'] * a...
456
155
""" Zoe Game Engine Core Implementation =================================== Requirements ------------ [pygame](http://www.pygame.org/) """ # core packages # third-party packages import pygame # local package import layer __version__ = '0.0.0' #===================================================================...
5,261
1,419
# Generated by Django 3.0.6 on 2020-11-15 09:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Authentication', '0003_auto_20201113_2210'), ] operations = [ migrations.AlterField( model_name='profiles', name='Qu...
557
185
from django.urls import path, re_path from django.views.generic.base import TemplateView from .views import dashboard_cost, dashboard_energy, MotorDataListView app_name = 'dashboard' urlpatterns = [ path('', MotorDataListView.as_view(), name='dashboard_custom'), #path('', dashboard_custom, name='dashboar...
455
142
hrs = input("Enter Hours:") rate = input("Enter rate:") pay = float(hrs) * float(rate) print("Pay: " +str(pay))
111
44
# # This file is part of LiteX-Boards. # # Copyright (c) 2017-2019 Florent Kermarrec <florent@enjoy-digital.fr> # SPDX-License-Identifier: BSD-2-Clause from litex.build.generic_platform import * from litex.build.xilinx import XilinxPlatform, VivadoProgrammer # IOs -----------------------------------------------------...
18,742
8,687
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import math # In[2]: fileObj = open('../data/advent_of_code_input_day_three.txt', "r") #opens the file in read mode. items = fileObj. read(). splitlines() #puts the file into an array. # In[3]: #print (items) def split(line): return lis...
1,543
613
import os import traceback class InputHandler: IMAGES_PARENT_FOLDER = './images' def __init__(self): filesList = [] def listFiles(self,path=''): if path != '': self.IMAGES_PARENT_FOLDER = path try: self.listFiles = [os.path.join(self.IMAGES_PAREN...
670
221
#!/usr/bin/python import os import sys SITENAME = os.environ.get("BEPASTY_SITENAME", None) if SITENAME is None: print("\n\nEnvironment variable BEPASTY_SITENAME must be set.") sys.exit(1) SECRET_KEY = os.environ.get("BEPASTY_SECRET_KEY", None) if SECRET_KEY is None: print("\n\nEnvironment variable BEPAST...
1,281
541
from io import StringIO import re import tokenize import os from collections import deque, ChainMap from functools import lru_cache from enum import Enum import pysh from pysh.path import PathWrapper, Path from typing import List, Callable, Iterator, Tuple, NamedTuple, Deque, Union, Any TBangTransformer = Callable[ [...
13,786
4,483
# 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...
2,449
869
import os import tmdbsimple as tmdb import media import fresh_tomatoes as ft movies = [] if os.environ.get('TMDB_API', False): # Retrieve API KEY tmdb.API_KEY = os.environ['TMDB_API'] # TMDB Movie Ids movie_ids = [271110, 297761, 246655, 278154, 135397, 188927] # Get Configuration configurat...
4,743
1,486
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file './elements_ui.ui', # licensing of './elements_ui.ui' applies. # # Created: Wed Jun 16 14:29:03 2021 # by: pyside2-uic running on PySide2 5.13.2 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui...
8,798
2,525
def cube(number): return number*number*number digit = input(" the cube of which digit do you want >") result = cube(int(digit)) print(result)
148
48
try: from unittest.mock import patch except ImportError: # pragma: no cover from mock import patch from proofreader.runner import run, _run_command def test_it_will_return_1_exit_code_on_failure(bad_py_file): try: run(targets=[bad_py_file.strpath]) except SystemExit as exception: ass...
1,203
402
from tanim.utils.config_ops import digest_config from tanim.utils.iterables import list_update # Currently, this is only used by both Scene and Mobject. # Still, we abstract its functionality here, albeit purely nominally. # All actual implementation has to be handled by derived classes for now. class Container(obj...
1,266
354
from config import * def fetch_all_article(): try: cur = db.cursor() sql = "SELECT * FROM article WHERE article_status='N'" db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close() return result except Exception as...
5,076
1,644
#!/usr/bin/env python """Extract events from kafka and write them to hdfs """ import json from pyspark.sql import SparkSession, Row from pyspark.sql.functions import udf @udf('boolean') def is_purchase(event_as_json): event = json.loads(event_as_json) if event['event_type'] == 'purchase_sword': return...
1,231
394
import numpy as np from pysz import compress, decompress def test_compress_decompress(): a = np.linspace(0, 100, num=1000000).reshape((100, 100, 100)).astype(np.float32) tolerance = 0.0001 compressed = compress(a, tolerance=tolerance) recovered = decompress(compressed, a.shape, a.dtype) asse...
434
174
import json from sparkdq.outliers.params.OutlierSolverParams import OutlierSolverParams from sparkdq.outliers.OutlierSolver import OutlierSolver class KSigmaParams(OutlierSolverParams): def __init__(self, deviation=1.5): self.deviation = deviation def model(self): return OutlierSolver.kSigm...
447
141
from alerta.models.alert import Alert from alerta.webhooks import WebhookBase class SentryWebhook(WebhookBase): def incoming(self, query_string, payload): # For Sentry v9 # Defaults to value before Sentry v9 if 'request' in payload.get('event'): key = 'request' else:...
1,312
368