content
stringlengths
0
894k
type
stringclasses
2 values
# coding: utf-8 # # Copyright 2019 The Oppia 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 requi...
python
from random import SystemRandom import pytest from cacheout import LFUCache parametrize = pytest.mark.parametrize random = SystemRandom() @pytest.fixture def cache(): _cache = LFUCache(maxsize=5) return _cache def assert_keys_evicted_in_order(cache, keys): """Assert that cache keys are evicted in th...
python
pessoaslist = [] dicionario = {} pessoastotal = 0 soma = media = 0 mulheres = [] acimamedia = [] while True: dicionario['Nome'] = str(input("Nome: ")) dicionario['Sexo'] = str(input("Sexo: [M/F] ")) dicionario['Idade'] = int(input("Idade: ")) resp = str(input("Continuar?: [S/N]")) pessoaslist.appe...
python
from ..utils import Object class MessageSchedulingStateSendAtDate(Object): """ The message will be sent at the specified date Attributes: ID (:obj:`str`): ``MessageSchedulingStateSendAtDate`` Args: send_date (:obj:`int`): Date the message will be sentThe date must be w...
python
'''Desarrollar un programa que cargue los datos de un triángulo. Implementar una clase con los métodos para inicializar los atributos, imprimir el valor del lado con un tamaño mayor y el tipo de triángulo que es (equilátero, isósceles o escaleno).''' import os class Triangulo(): def __init__(self, lado1, lado2...
python
import ldap import pandas import datetime.datetime from ldap_paged_search import LdapPagedSearch host = 'ldaps://example.com:636' username = 'domain\\username' password = 'password' baseDN = 'DC=example,DC=com' filter = "(&(objectCategory=computer))" #attributes = ['dn'] attributes = ['*'] #ldap.set_option(ldap.OPT_...
python
"""Custom pandas accessors.""" import numpy as np import plotly.graph_objects as go from vectorbt import defaults from vectorbt.root_accessors import register_dataframe_accessor from vectorbt.utils import checks from vectorbt.utils.widgets import CustomFigureWidget from vectorbt.generic.accessors import Generic_DFAcc...
python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: npu_utilization.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.prot...
python
#!/usr/bin/env python import fire from lib.dsv.commands.dsv_command import DSVCommand if __name__ == '__main__': fire.Fire(DSVCommand)
python
import predpy from predpy.predpy import * #from predpy.predpy import predpy from predpy.predpy import cleandata from predpy.predpy import galgraphs
python
# # Copyright 2020 Logical Clocks AB # # 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 ag...
python
from rest_framework import serializers from rest_framework.reverse import reverse from onadata.apps.fsforms.models import FieldSightXF from onadata.apps.logger.models import XForm from onadata.libs.utils.decorators import check_obj class XFormListSerializer(serializers.ModelSerializer): class Meta: mode...
python
import numpy as np from torch import nn, tensor import torch from torch.autograd import Variable class time_loss(nn.Module): def __init__(self, margin=0.1, dist_type = 'l2'): super(time_loss, self).__init__() self.margin = margin self.dist_type = dist_type if dist_type == 'l2': self.dist = nn.MS...
python
from types import FunctionType import pygame from pygame.locals import * from pygame.font import Font from pygameMenuPro.event import Event COLOR_BLACK = Color(0, 0, 0) COLOR_WHITE = Color(255, 255, 255) class InputManager: def __init__(self): self.last_checked_input = [] self.last_mouse_positio...
python
# Define player object class Player: def __init__(self, name, house): self.name = name self.house = house self.hasNumber = False # Method for setting users phonenumbers def setPhonenumber(self, phoneNumber): self.phoneNumber = phoneNumber self.hasNumber = True # 12...
python
# =============================================================================== # Copyright 2020-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.ap...
python
from data.station_number_data import StationNumberData from states_machine.state_context import State from states_machine.states.on_which_sum import OnWhichSum class StationNumber(State): def __init__(self): pass def income_handle(self) -> None: # TODO: # print(f"income_handl...
python
class Transformer: def transform(self, message): yield from map(self.map, (message,)) def map(self, message): raise NotImplementedError('Transformer is an abstract class.')
python
import socket import struct from struct import * import sys def ethernet_head(raw_data): dest, src, prototype = struct.unpack('! 6s 6s H', raw_data[:14]) dest_mac = get_mac_addr(dest) src_mac = get_mac_addr(src) proto = socket.htons(prototype) data = raw_data[14:] return dest_mac, src_mac, pro...
python
import unittest import random import numpy as np import pyquil from cirq import GridQubit, LineQubit, X, Y, Z, PauliSum, PauliString from openfermion import ( QubitOperator, IsingOperator, FermionOperator, get_interaction_operator, get_fermion_operator, jordan_wigner, qubit_operator_sparse,...
python
"""UseCase for updating a metric entry's properties.""" import logging from argparse import Namespace, ArgumentParser from typing import Final, Optional import jupiter.command.command as command from jupiter.domain.adate import ADate from jupiter.use_cases.metrics.entry.update import MetricEntryUpdateUseCase from jup...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ USD Opinion Editor widget implementations """ from __future__ import print_function, division, absolute_import __author__ = "Tomas Poveda" __license__ = "MIT" __maintainer__ = "Tomas Poveda" __email__ = "tpovedatd@gmail.com" from Qt.QtCore import * from Qt.QtWidgets...
python
# 000 # 999 # a=['one','two','three','four'] b=range(5) c=(9,-1,2) #one 0 9 #... #four 4 2 S = [4,5,3] def next_value(current, S): "[0,0,0] -> next one [1,0,0]" N = current[:] i = 0 N[i] += 1 while N[i]==S[i]: N[i] = 0 i += 1 if i==len(N): break N[i]...
python
# -*- coding: utf-8 -*- # # This file is part of the pyfixp project hosted at https://github.com/chipmuenk/pyfixp # # Copyright © Christian Muenker # Licensed under the terms of the MIT License # (see file LICENSE.txt in root directory for details) """ Store the version number here for setup.py and pyfixp.py """ __ve...
python
class Card(): def __init__(self, id: int, img: str, owner, position: int): """ Card defines a card. Args: id (int): card id (incremental int) img (str): path of the card img owner (int): card owner player, or None if in the deck/used position (int): when it is played, the position to vote removed...
python
from django.urls import path from .views import ( RideListView, RideDetailView, RideCreateView, RideUpdateView, RideDeleteView, OwnerRideListView, ShareCreateView, SharePickRideListView, ShareRideListView, ...
python
############################################################## # Fixing missmatches in parsing of doccano output # The script also does not claim to be a reusable solution, # instead it merely adapts the doccano output files to correspond # to the entity split style of LitBank. # Input: pandas dataframe, filename # Ou...
python
# -*- coding: utf-8 -*- # @Date : 2017-07-18 13:26:17 # @Author : lileilei ''' 导入测试接口等封装 ''' import xlrd def pasre_inter(filename):#导入接口 file=xlrd.open_workbook(filename) me=file.sheets()[0] nrows=me.nrows ncol=me.ncols project_name=[] model_name=[] interface_name=[] interface_url=[] interf...
python
# Create a function named same_name() that has two parameters named your_name and my_name. # If our names are identical, return True. Otherwise, return False. def same_name(your_name, my_name): if your_name == my_name: return True else: return False
python
import numpy as np import json def _reject_outliers(data, m=5.): d = np.abs(data - np.median(data)) mdev = np.median(d) s = d / mdev if mdev else 0. return data[s < m] def reject(input_): for line in input_: d = json.loads(line) print(_reject_outliers(np.array(d)).tolist())
python
# -*- coding: utf-8 -*- from django.template import loader from django.utils import formats from django.utils.text import Truncator import django_tables2 as tables from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from ..html import AttributeDict, Icon def merge_attrs...
python
""" Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC"....
python
import re import pprint from collections import Counter ihaveadream = open('ihaveadream.txt', 'r') read_dream = ihaveadream.read() split = read_dream.split() just_words = [re.sub('[^a-zA-Z]+','',i) for i in split] just_long_words = [] for word in just_words: word = word.lower() if len(word) > 3: j...
python
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options import time import os import sys from glob import glob import re import json import random import shutil import re import codecs dones = [x for x in open("done.txt",'r').read().split("\n...
python
from future.utils import with_metaclass from openpyxl_templates.exceptions import OpenpyxlTemplateException from openpyxl_templates.utils import OrderedType, Typed class TemplatedWorkbookNotSet(OpenpyxlTemplateException): def __init__(self, templated_sheet): super(TemplatedWorkbookNotSet, self).__init__(...
python
import hashlib, hmac, time def compute_signature(message, secret): message = message.encode('utf-8') timestamp = str(int(time.time()*100)).encode('ascii') hashdata = message + timestamp signature = hmac.new(secret.encode('ascii'), hashdata, hashlib.sha...
python
from django.conf import settings from django.utils.translation import ugettext_lazy as _ TEASERSWRAP_ALLOW_CHILDREN = getattr( settings, 'TEASERS_TEASERSWRAP_ALLOW_CHILDREN', True ) TEASERSWRAP_PLUGINS = getattr( settings, 'TEASERS_TEASERSWRAP_PLUGINS', [ 'TeaserPlugin', ] ) TEAS...
python
from .models_1d import * from .models_2d import * from .models_3d import * def M1D(config): if config.model_module == 'V2SD': model = V2StochasticDepth(n=config.channels, proba_final_layer=config.proba_final_layer, sdrop=config.sdrop, ...
python
"""Tests for the :mod:`campy.datastructures.sparsegrid` module."""
python
# -*- coding: utf-8 -*- # # GOM-Script-Version: 6.2.0-6 # Anja Cramer / RGZM # Timo Homburg / i3mainz # Laura Raddatz / i3mainz # Informationen von atos-Projektdateien (Messdaten: *.amp / *.session) # 2020/2021 import gom import xml, time, os, random import math import datetime ## Indicates if only properties for w...
python
# Generated by Django 2.2.2 on 2019-09-19 12:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('dcodex', '0001_initial'), ('dcodex_bible', '0001_initial'), ] operations = [ mi...
python
for i in range(0, 10, 2): print(f"i is now {i}")
python
# -- coding: utf-8 -- # Copyright 2019 FairwindsOps Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
python
import re import ast import discord from redbot.core import Config from redbot.core import commands from redbot.core import checks defaults = {"Prefixes": {}} class PrefixManager(commands.Cog): """Used to set franchise and role prefixes and give to members in those franchises or with those roles""" def __i...
python
#!/usr/bin/env python """ .. py:currentmodule:: FileFormat.Results.test_PhirhozElement .. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca> Tests for the module `PhirhozElement`. """ # Script information for the file. __author__ = "Hendrix Demers (hendrix.demers@mail.mcgill.ca)" __version__ = ""...
python
from json import loads from random import choice from .base_menti_question import BaseMentiQuestion QUOTES_PATH = 'quotes.json' def get_quotes(filename=QUOTES_PATH): with open(filename) as f: return f.read() return '' class MentiText(BaseMentiQuestion): max_text_len = 140 needed_attr = [] ...
python
# -*- coding: utf-8 -*- from .wiserapi import WiserBaseAPI, _convert_case class SetPoint: def __init__(self): self.time = None self.temperature = None class Schedule(WiserBaseAPI): """Represnts the /Schedule object in the Restful API""" def __init__(self, *args, **kwargs): # Def...
python
def lagrange(vec_x, vec_f, x=0): tam,res = len(vec_x),0 L = [0]*tam for i in range(tam): L[i] = 1 for j in range(tam): if j != i: L[i] = L[i] * (x - vec_x[j])/(vec_x[i] - vec_x[j]) for k in range (tam): res = res + vec_f[k]*L[k] print(res) x =...
python
import os import pandas as pd import numpy as np import shutil cwd = os.getcwd() sysname = os.path.basename(cwd) print(sysname) if os.path.isdir(cwd+'/lmbl/'): shutil.rmtree(cwd+'/lmbl/') os.mkdir('lmbl') coor = os.path.join(cwd+ '/coordinates/') lmbl = os.path.join(cwd+ '/lmbl/') os.chdir(lmbl) for filename in os....
python
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd """Servlet for Content Security Policy violation reporting. See http://www.html5rocks.com/en/tu...
python
import datetime from pathlib import Path from typing import Iterator, Any import pytest import google_takeout_parser.parse_json as prj @pytest.fixture(scope="function") def tmp_path_f( request: Any, tmp_path_factory: pytest.TempPathFactory ) -> Iterator[Path]: """ Create a new tempdir every time this run...
python
from __future__ import annotations from typing import TYPE_CHECKING import discord from discord.ext import typed_commands from .exceptions import NotGuildOwner, OnlyDirectMessage if TYPE_CHECKING: from discord.ext.commands import core def dm_only() -> core._CheckDecorator: def predicate(ctx: core._CT, /) ...
python
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Recipe for updating the go_deps asset.""" DEPS = [ 'checkout', 'infra', 'recipe_engine/context', 'recipe_engine/properties', 'recipe_engine/p...
python
import spacy import numpy as np import os, shutil, json, sys import json, argparse, logging from tqdm import tqdm import tensorflow as tf from collections import defaultdict from MultiHeadAttention import * class GAN: def __init__(self, input_shapes, embedding_size, question_padding): #input shapes is in ...
python
"""A Yelp-powered Restaurant Recommendation Program""" from abstractions import * from data import ALL_RESTAURANTS, CATEGORIES, USER_FILES, load_user_file from ucb import main, trace, interact from utils import distance, mean, zip, enumerate, sample from visualize import draw_map ################################## # ...
python
import subprocess import ansiconv import sys from django.conf import settings from django.http import StreamingHttpResponse from django.shortcuts import get_object_or_404 from django.views.generic import View from fabric_bolt.projects.models import Deployment from fabric_bolt.projects.signals import deployment_finish...
python
import json import asyncio import sys from joplin_api import JoplinApi from httpx import Response import pprint import difflib import logging with open('.token','r') as f: token = f.readline() joplin = JoplinApi(token) async def search(query): res = await joplin.search(query,field_restrictions='title') lo...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 30/11/2021 22:19 # @Author : Mr. Y # @Site : # @File : similarity_indicators.py # @Software: PyCharm import numpy as np np.seterr(divide='ignore',invalid='ignore') import time import os from utils import Initialize os.environ['KMP_DUPLICATE_LIB_OK'] = ...
python
""" """ try: from stage_check import Output except ImportError: import Output try: from stage_check import OutputAssetState except ImportError: import OutputAssetState def create_instance(): return OutputAssetStateText() class OutputAssetStateText(OutputAssetState.Base, Output.Text): """ "...
python
import re from django.urls import re_path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ re_path(r'^$',views.account,name='account'), re_path(r'^account/',views.account,name='account'), re_path(r'^home/',views.home,name='home'), re_path(r...
python
# coding: utf-8 # flake8: noqa E266 # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from flask_env import MetaFlaskEnv from celery.schedules import crontab class base_config(object, metaclass=MetaFlaskEnv): """Default configuration options.""" ENV_PREFIX = 'APP_' SITE_NAME = 'T...
python
You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: If the element is even, divide it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2]. If the eleme...
python
import pandas as pd import numpy as np from unittest import TestCase, mock from unittest.mock import MagicMock, PropertyMock from gtfs_kit.feed import Feed from representation.gtfs_metadata import GtfsMetadata from representation.gtfs_representation import GtfsRepresentation from usecase.process_stops_count_by_type_for...
python
from cryptography.utils import CryptographyDeprecationWarning import warnings warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning) from qc_qubosolv.solver import Solver
python
from sqlalchemy import create_engine engine = create_engine('sqlite:///todo.db?check_same_thread=False') from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Date from datetime import datetime Base = declarative_base() class task(Base): __tablename__ = 'task' ...
python
n=int(input()) res="" for i in range(1,n+1): a,b=map(int, input().split()) if a>=0: res+="Scenario #"+str(i)+":\n"+str((a+b)*(b-a+1)//2) elif a<0 and b>=0: res+="Scenario #"+str(i)+":\n"+str(b*(b+1)//2 + a*(abs(a)+1)//2) else: res+="Scenario #"+str(i)+":\n"+str((a+b)*(b-a+1)//2) ...
python
import torch import torch.nn as nn def FocalLoss(logits, labels, inverse_normed_freqs): labels = labels.type(torch.float32) probs = torch.sigmoid(logits) pt = (1 - labels) * (1 - probs) + labels * probs log_pt = torch.log(pt) floss = - (1 - pt)**2 * log_pt floss_weighted = floss * inverse_norm...
python
import sys import inspect import torch #from torch_geometric.utils import scatter_ from torch_scatter import scatter special_args = [ 'edge_index', 'edge_index_i', 'edge_index_j', 'size', 'size_i', 'size_j' ] __size_error_msg__ = ('All tensors which should get mapped to the same source ' 'or...
python
from requests import post,get from requests_oauthlib import OAuth1 from flask import request from os import path from json import dumps, loads from time import sleep dir_path = path.dirname(path.realpath(__file__)) def read_env(file=".env"): read_file = open(dir_path + "/" + file, "r") split_file = [r.strip()....
python
import gmaps2geojson writer = gmaps2geojson.Writer() writer.query("2131 7th Ave, Seattle, WA 98121", "900 Poplar Pl S, Seattle, WA 98144") writer.query("900 Poplar Pl S, Seattle, WA 98144", "219 Broadway E, Seattle, WA 98102") writer.save("example.geojson")
python
"""Этот модуль запускает работу. Работа должна быть асинхронной, модуль запускает и управляет потоками внутри(?)""" import asyncio import time import random from ss_server_handler import new_order_handler from PBM_main import TodaysOrders from controllers_handler import qr_code_alarm, oven_alarm from settings ...
python
import uuid from datetime import datetime from pydantic import BaseModel, EmailStr, Field class UserBase(BaseModel): id: uuid.UUID = Field(default_factory=uuid.uuid4) username: str email: EmailStr class Config: arbitrary_types_allowed = True class UserCreate(UserBase): register_date: d...
python
valores = [] for contador in range(0, 5): valor = int(input('Digite um valor: ')) if contador == 0 or valor > valores[-1]: valores.append(valor) print('Adicionado ao final da lista...') else: posicao = 0 while posicao < len(valores): if valor <= valores[posicao]: ...
python
import os,cStringIO class Image_Fonts(): def Fonts_Defaults(self): fontlist = [ '/usr/share/fonts/truetype/freefont/FreeSerif.ttf', '/usr/share/fonts/truetype/freefont/FreeSans.ttf', '/usr/share/fonts/truetype/freefont/FreeMono.ttf' ] fontpath = '.' ...
python
import itertools from django.http import HttpRequest, HttpResponse from django.core.exceptions import PermissionDenied from django.utils import timezone from django.utils.text import slugify from .jalali import Gregorian, datetime_to_str, mounth_number_to_name, en_to_fa_numbers # create unique slug. def unique_slug(t...
python
from hask.lang import build_instance from hask.lang import sig from hask.lang import H from hask.lang import t from hask.Control.Applicative import Applicative from hask.Control.Monad import Monad from .Foldable import Foldable from .Functor import Functor class Traversable(Foldable, Functor): """ Functors re...
python
from random import choice from xkcdpass import xkcd_password class XKCD: delimiters_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] delimiters_full = ["!", "$", "%", "^", "&", "*", "-", "_", "+", "=", ":", "|", "~", "?", "/", ".", ";"] + delimiters_numbers def __init__...
python
# -*- coding: utf-8 -*- ''' Created on : Thursday 18 Jun, 2020 : 00:47:36 Last Modified : Sunday 22 Aug, 2021 : 23:52:53 @author : Adapted by Rishabh Joshi from Original ASAP Pooling Code Institute : Carnegie Mellon University ''' import torch import numpy as np import torch.nn.functional as F from torch.nn...
python
# License: MIT # Author: Karl Stelzner import os import sys import torch from torch.utils.data import Dataset from torch.utils.data import DataLoader import numpy as np from numpy.random import random_integers from PIL import Image from torch.utils.data._utils.collate import default_collate import json def progres...
python
import random import numpy as np class Particle(): def __init__(self): self.position = np.array([(-1) ** (bool(random.getrandbits(1))) * random.random()*50, (-1)**(bool(random.getrandbits(1))) * random.random()*50]) self.pbest_position = self.position self.pbest_value = float('inf') ...
python
import sys import os import logging import shutil import inspect from . import config logger = logging.getLogger('carson') _init = None _debug = False def initLogging(debug=False): global _init, _debug if _init is not None: return _init = True _debug = debug formatter = logging.Format...
python
import sys from distutils.core import setup from setuptools import find_packages version = '0.1.1' install_requires = [ 'acme>=0.29.0', 'certbot>=1.1.0', 'azure-mgmt-resource', 'azure-mgmt-network', 'azure-mgmt-dns>=3.0.0', 'PyOpenSSL>=19.1.0', 'setuptools', # pkg_resources 'zope.int...
python
import json import jwt from fastapi import Depends, HTTPException, Path, Query from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from fastapi.security.utils import get_authorization_scheme_param from pydantic import BaseModel from starlette.requests import Request from starlette.status import HTTP_...
python
import time from itertools import chain from opentrons import instruments, labware, robot from opentrons.instruments import pipette_config def _sleep(seconds): if not robot.is_simulating(): time.sleep(seconds) def load_pipettes(protocol_data): pipettes = protocol_data.get('pipettes', {}) pipette...
python
#!/usr/bin/python import sys def int2bin(num, width): spec = '{fill}{align}{width}{type}'.format( fill='0', align='>', width=width, type='b') return format(num, spec) def hex2bin(hex, width): integer = int(hex, 16) return int2bin(integer, width) def sendBinary(send): binary = '# ' + '\t branch targ...
python
"""tests rio_tiler.sentinel2""" import os from unittest.mock import patch import pytest import rasterio from rio_tiler.errors import InvalidBandName from rio_tiler_pds.errors import InvalidMODISProduct from rio_tiler_pds.modis.aws import MODISASTRAEAReader MODIS_AST_BUCKET = os.path.join( os.path.dirname(__file...
python
import FWCore.ParameterSet.Config as cms from RecoTracker.DebugTools.TrackAlgoCompareUtil_cfi import *
python
# -*- coding: utf-8 -*- # @Time : 2020/1/23 10:10 # @Author : jwh5566 # @Email : jwh5566@aliyun.com # @File : test1.py # import sys # print('参数个数: ', len(sys.argv)) # print('参数列表: ', str(sys.argv)) # a = 10 # if a > 0: # print(a, "是一个正数") # print("总是打印这句话") # # a = -10 # if a > 0: # print(a, "是一个正数") # a = 10...
python
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy.selector import HtmlXPathSelector from ..items import NewsItem from datetime import datetime import pandas as pd import re class SabahSpider(CrawlSpider): name = "sabah" allowed_domains = ["sabah.c...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayOpenAppXwbsssQueryResponse(AlipayResponse): def __init__(self): super(AlipayOpenAppXwbsssQueryResponse, self).__init__() self._a = None @prop...
python
''' -------------------- standard_parsers.py -------------------- This module contains a set of commands initializing standard :py:class:`argparse.ArgumentParser` objects with standard sets of pre-defined options. The idea here is that I have a standard basic parser with set syntax but can also have a 'cluster parse...
python
import tensorflow as tf import tensorflow.contrib.slim as slim import numpy as np def conv(x, out_channel, kernel_size, stride=1, dilation=1): x = slim.conv2d(x, out_channel, kernel_size, stride, rate=dilation,activation_fn=None) return x def global_avg_pool2D(x): with tf.variable_scope(None, 'global_pool...
python
from functools import reduce from typing import Optional import numpy as np def find_common_elements(*indices: np.array) -> np.array: """ Returns array with unique elements common to *all* indices or the first index if it's the only one. """ common_elements = reduce(np.intersect1d, indices[1:], indices[0...
python
from rest_framework import viewsets, mixins from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from core.models import Skill from core.models import Location from core.models import Job # from core.models import Job from job import serializers from djang...
python
# Auto generated by generator.py. Delete this line if you make modification. from scrapy.spiders import Rule from scrapy.linkextractors import LinkExtractor XPATH = { 'name' : "//div[@class='clus']/h2[@class='nomargin title_sp']", 'price' : "//h2[@class='nomargin']/font", 'category' : "//div[@class='head_t...
python
from extractors import archive_extractor, ertflix_extractor, star_extractor, megatv_extractor from downloaders import m3u8_downloader, alpha_downloader import sys if __name__ == "__main__": url = sys.argv[1] if "ertflix.gr" in url: extractor = ertflix_extractor.ErtflixExtractor(url) stream_dat...
python
#!/usr/bin/env python2 # PYTHON_ARGCOMPLETE_OK import sys import agoat._config import agoat.run_disasms import agoat.indexer import agoat.diagnostic import agoat.keywordsearcher # set up command-line completion, if argcomplete module is installed try: import argcomplete import argparse parser = argparse...
python
import os import math import pygame class Lava(pygame.sprite.Sprite): def __init__(self, x, y, width, height): """ Create a platform sprite. Note that these platforms are designed to be very wide and not very tall. It is required that the width is greater than or equal to the heigh...
python
def pal(a): s=list(str(a)) i=1 w=[] while i<=len(s): w.append(s[-i]) i=i+1 if w==s: print("it is palimdrom") else: print("it is not palimdrom") string=input("enter the string :") pal(string)
python
from aoc import data from collections import Counter, defaultdict parser = int def part1(inputData, days=80): fish = Counter(inputData) for _ in range(days): newFish = fish.pop(0, 0) fish = Counter({k-1: v for k, v in fish.items()}) + Counter({6: newFish, 8:newFish}) return sum(fish.values...
python