content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import datetime
from random import randint
from telegram.chat import Chat
from telegram.message import Message
from telegram.user import User
class MockBot:
last_message = {}
def send_message(self, chat_id, text, **kwargs):
self.last_message[chat_id] = text
def sendMessage(self, *args, **kwargs... | python |
def pairs(k, arr):
result = 0
arr = sorted(arr)
j = 1
for i in range(len(arr)-1):
while j<len(arr):
if arr[j] - arr[i] == k:
result += 1
j += 1
elif arr[j] - arr[i] > k:
break
elif arr[j] - arr[i] < k:... | python |
# MINLP written by GAMS Convert at 04/21/18 13:54:23
#
# Equation counts
# Total E G L N X C B
# 19 18 1 0 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... | python |
from org.mowl.Parsers import TaxonomyWithRelsParser as Parser
from org.semanticweb.owlapi.model import OWLOntology
from mowl.graph.edge import Edge
import sys
from mowl.graph.graph import GraphGenModel
class TaxonomyWithRelsParser(GraphGenModel):
r'''
This class will project the ontology considering the fo... | python |
import numpy as np
import matplotlib.pyplot as plt
from de_expl import de_expl
from es_expl import es_expl
from gwo_expl import gwo_expl
from hho_expl import hho_expl
from mfo_expl import mfo_expl
from pso_expl import pso_expl
from p5_base import plot_progress, plot_objs
fevals = 10000
#de_x, de_y, de_hist, de_res,... | python |
# Create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI',
}
# Careate a basic set of states and some cities in them
cities = {
'CA': 'San Farncisco',
'MI': 'Detroit',
'FL': 'JAcksonsville',
}
# Add so... | python |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from modules.execution.models import *
class Project(models.Model):
PROJECT_TYPES = (
("internal", "internal"),
("public", "public")
)
name = models.CharField(max_length=100, unique=... | python |
from datasets.parties.all import df_regions_votes_and_parties
from datasets.regions.province import df_community_and_provice | python |
# Link - https://www.hackerrank.com/challenges/designer-door-mat/problem
inp = input().split()
N = int(inp[0])
M = int(inp[1])
for i in range(1, N, 2):
print((i * ".|.").center(M, "-"))
print("WELCOME".center(M,"-"))
for i in range(N-2, -1, -2):
print((i * ".|.").center(M, "-"))
| python |
#
# 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 us... | python |
import time
import uuid
import six
from mazepa.queue import Queue
from mazepa.job import Job, AllJobsIndicator
class Scheduler:
def __init__(self, queue_name=None, completion_queue_name=None,
queue_region=None, threads=1):
self.queue = Queue(queue_name=queue_name,
completion_qu... | python |
"""Main module which implements the components of graph-based autoconstraint model.
"""
import torch
from sketchgraphs.pipeline.graph_model import target, scopes_from_offsets
from sketchgraphs_models.graph.model import EdgePartnerNetwork, numerical_features, message_passing
from sketchgraphs_models import nn as sg_n... | python |
# Ensures the validity of blocks inside a blockchain
# Copyright (c) 2022 gparap
from Blockchain import Blockchain
class Validator:
def __init__(self, blockchain: Blockchain):
self.blockchain = blockchain
# the previous hash of the current block must match the hash of the previous block
def valid... | python |
from pdb import set_trace as T
import numpy as np
from itertools import chain
from neural_mmo.forge.blade import core
from neural_mmo.forge.blade.lib import material
from random import randint
import os
numsent = 0
class Map:
'''Map object representing a list of tiles
Also tracks a sparse list of tile up... | python |
# encoding: cinje
: from .template import page
: from .letterscountsbar import letterscountsbar
: from .namelist import namelist
: def browsetemplate title, ctx, letterscountslist, names=None
: using page title, ctx, lang="en"
<div class="row">
: if letterscountslist is not None
: use ... | python |
# [그리디] 거스름돈
#========== input ===========
# n : 거스름돈 금액
#========== output ==========
# result : 금액에 해당되는 최소의 동전 개수
# 풀이 : 가장 큰 동전부터, 거스를 수 있을 만큼 거슬러 주기
n = int(input())
result = 0
coin_list = [500, 100, 50, 10]
for coin in coin_list:
result += n//coin
n %= coin
print(result)
| python |
from collections import namedtuple
from copy import copy
from datetime import *
from geojson import Feature, Point, FeatureCollection, LineString
from geojson.mapping import to_mapping
from typing import List, Dict
import functools
import os
import struct
import pyall
from hyo2.mate.lib.scan import Scan, A_NONE, A_PAR... | python |
import argparse
import sys
class ContactsCLI():
"""Parse command line arguments for contacts program"""
def __init__(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument(
'-f',
'--filter',
default=None,
type=str,
h... | python |
from client import Client
import pprint
"""
MAIN INSTANCE (petition)
"""
tenant_id = ""
client_id = ""
client_secret = ""
dynamics_resource = ""
CRM_resource = ""
refresh_token = ""
token = ""
petition = Client(client_id=client_id, client_secret=client_secret, token=token)
"""
API ENDPOINTS EXAMPLES
"contacts", "acco... | python |
# */
# * 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... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from itertools import combinations, permutations
import logging
import networkx as nx
import numpy as np
import pandas as pd
# +
# generate a random adjacency matrix
# traces: Number or Domino Traces
# If traces>1 the output will be a data frame of list
# nodes: Number ... | python |
# AUTOGENERATED FILE - DO NOT MODIFY!
# This file generated by Djinni from foo_client_interface.djinni
from djinni.support import MultiSet # default imported in all files
from djinni.exception import CPyException # default imported in all files
from djinni.pycffi_marshal import CPyPrimitive, CPyRecord
from PyCFFIlib_c... | python |
import numpy as np
a = np.array([[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]])
print(np.cumsum(a)) # 1 次元 array に変換してから累積和を計算
'''
[ 0 1 3 6 10 15 21 28 36 45 55 66]
'''
print(np.cumsum(a, axis=0)) # 縦方向に累積和を計算
'''
[[ 0 1 2 3]
[ 4 6 8 10]
[12 15 18 21]]
'''
print(np.cumsum(a, axi... | python |
import pytest
try:
import simplejson as json
except ImportError:
import json
from click.testing import CliRunner
from diderypy.cli import main
from diderypy.lib import generating as gen
def parsOutput(data):
return list(filter(None, data.split('\n')))
def testValidConfigFile():
runner = CliRunner()... | python |
import time
import heapq
def curr_time():
return round(time.time() * 1000)
class GameEventPQueue:
''' singleton event queue for the game, event listeners handle different game event types
game events are scheduled in a pqueue for certain events can be handled before others
uses minpqueue since... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This contains a 128x128 px thumbnail in PNG format
# Taken from http://www.zwahlendesign.ch/en/node/20
# openoffice_icons/openoffice_icons_linux/openoffice11.png
# License: Freeware
import base64
iconstr = """\
iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAAG0OVFdAAAABGdBTUEAANbY1E9Y... | python |
import os
from my_lib import Object, Object2, Object3
def is_unique(s):
s = list(s)
s.sort()
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
return 0
else:
return 1
if __name__ == "__main__":
print(is_unique(input()))
| python |
def get_names():
names = []
while True:
name = input("Enter players name: ")
if name != 'done':
print(f'{name} added to the list of players')
names.append(name)
continue
else:
break
return names
def get_player_scores(players):
for... | python |
#! /usr/bin/env python
from eclib.elgamal import *
key_length = 20
params, pk, sk = keygen(key_length)
delta = 1e-2
print('========== ElGamal parameter ==========')
print(f'key length = {key_length} bit')
print(f'p = {params.p}')
print(f'q = {params.q}')
print(f'g = {params.g}')
print(f'h = {pk}')
print(f's = {sk}')... | python |
import numpy as np
import cv2
import os
from src.types.parent_slide import SlideImage
class FluorescenceSlide(SlideImage):
def __init__(self, img, **kwargs):
"""
Arguments:
img (ndarray): uint16 array of shape (h,w,3)
"""
self.img = img
self.height, self.width, ... | python |
from typing import List, Optional, Type
from ape.types import AddressType
from .base import abstractdataclass, abstractmethod
from .providers import ProviderAPI, ReceiptAPI, TransactionAPI
@abstractdataclass
class AddressAPI:
_provider: Optional[ProviderAPI] = None
@property
def provider(self) -> Provi... | python |
""" capture_faces.py
Author: Gonçalo S. Martins
This script implements the basic face detection and extraction features
needed for this work. The main section of the script illustrates its usage
in extracting faces from pre-recorded videos.
This script was tested using Python 3.5 and OpenCV 3.1.
Video capture code i... | python |
#!/usr/bin/python3
"""
Made by Facundo Diaz - Tomas De Castro - Tadeo Grach for Holberton School 2021 """
""" IMPORTS EXTERN MODULES """
import time
from datetime import datetime
import os
""" IMPORTS FILES """
import persistence
import entities
import mail
import info
import percent
""" In case url 1 is not worki... | python |
#Based on https://github.com/alexandrebarachant/muse-lsl/blob/master/notebooks/N170%20with%20Muse.ipynb
import sys
from collections import OrderedDict
from mne import create_info, concatenate_raws
from mne.io import RawArray
from mne.channels import read_montage
import pandas as pd
import numpy as np
from glob impor... | python |
#https://www.hackerrank.com/challenges/mark-and-toys/problem?isFullScreen=true
def maximumToys(prices, k):
# Write your code here
prices.sort()
count = 0
sum = 0
i = 0
while sum < k:
sum += prices[i]
i += 1
count += 1
return count - 1
| python |
import hassapi as hass
import datetime
import re
"""
Class Phone_Manager handles sending call to voice notfyng service
"""
__NOTIFY__ = "notify/"
SUB_TTS = [("[\*\-\[\]_\(\)\{\~\|\}\s]+", " ")]
class Phone_Manager(hass.Hass):
def initialize(self):
self.dict_lingua = {
"it-IT": "it-IT-Standar... | python |
"""
Export biomedical data from a relational database to an Avro file.
An Avro file stores the data schema as a JSON blob and the data in a
binary format
See https://avro.apache.org for details
In this case, the Avro file is called a PFB
(Portable Format for Bioinformatics) file because the data in the Avro file
con... | python |
from urlparse import urljoin
from kivy.properties import StringProperty
from kivy.uix.screenmanager import Screen
from kivy.utils import platform
from pytt.tools import Tool, RectangleTool
from pytt.pasteimage import PasteImageScreen, get_png_from_clipboard
class DMScreen(Screen):
mapfile = StringProperty('')
... | python |
import adv.adv_test
from core.advbase import *
import marth
def module():
return Marth
class Marth(marth.Marth):
comment = 'dodge*2 to miss s2p3 then dodge*2 back to attack'
def s2_proc(self, e):
if self.stance == 0:
self.stance = 1
Selfbuff('s21',0.1,10).on()
... | python |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\fame\fame_commands.py
# Compiled at: 2020-06-01 23:01:55
# Size of source mod 2**32: 8751 bytes
from... | python |
from django.apps import AppConfig
class ReportConfig(AppConfig):
name = "reports"
verbose_name = "Django Model Reports"
def ready(self):
from .base import reports
reports.discover()
| python |
#!/usr/bin/env python
import rospy
import numpy as np
import cv2
from subprocess import call
import sys
from std_msgs.msg import String
import cv2.cv as cv
import os
class martin_aimas_interface:
def __init__(self):
self.speechRecognitionFlag = True
self.subSpeech = rospy.Subscriber('/recognizer/output', String,... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 22 00:29:48 2018
@author: Hiba Lubbad
"""
animals = { 'a': ['horse'], 'b': ['baboon'], 'c': ['giraffe']}
animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')
def howmany(di):
count = 0
for i in di.values():
... | python |
# Get the data from:
# https://archive.ics.uci.edu/ml/datasets/Airfoil+Self-Noise
from __future__ import print_function, division
from future.utils import iteritems
from builtins import range, input
import os
# Note: you may need to update your version of future
# sudo pip install -U future
# just in case we need it... | python |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import inspect
from abc import ABC, abstractmethod
from typing import Dict, Generator, List, Type, TypeVar
from libcst impor... | python |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import tensorflow as tf
from itl.layers.core import Layer
from itl import logging
# from itl.decorators import deprecated_alias
__all__ = [
'UpSampling2dLayer',
'DownSampling2dLayer',
]
class UpSampling2dLayer(Layer):
"""The :class:`UpSampling2dLayer` class ... | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Author : xuqiang
@License : (C) Copyright 2020-, H3C
@Contact : xu.qiang@h3c.com
@Software: f8s
@File : config.py
@Time : 20200211
@Desc :
'''
#k8s cfg
K8S_CFG = "/root/f8s/kubeconfig.yaml"
FISCO_HOME = '/root/fisco_network'
NFS = "1... | python |
import cfm_api_utils
token = get_token()
print token
| python |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2009- Spyder Project Contributors
#
# Distributed under the terms of the MIT License
# (see spyder/__init__.py for details)
# --------------------------------------------------------------------------... | python |
class Person:
def __init__(self, firstName, lastName, idNumber):
self.firstName = firstName #initialization of first number ,last number as done in the constructor
self.lastName = lastName
self.idNumber = idNumber
def printPerson(self):
print("Name:", self.lastName + ",", self.firstName)# #printout stat... | python |
'''
Copyright (c) 2021, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
'''
import torch
# from transformers import MT5ForConditionalGeneration, MT5Config, MT5EncoderModel, MT5Tok... | python |
# 167. Two Sum II - Input array is sorted - LeetCode
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
left = 1... | python |
import logging
def column_headers(header_row):
logging.info(f"Validating header row, headers: {header_row}")
header_list = header_row.split(",")
try:
valid = True
if header_list[0] != "code":
logging.info(f"got in code: {header_list[0]}")
valid = False
if ... | python |
import json
from config import TEXT_LANGUAGE
from game.roles.villager import Villager
from game.roles.werewolf import Werewolf
from game.roles.guard import Guard
from game.roles.seer import Seer
from game.roles.lycan import Lycan
from game.roles.betrayer import Betrayer
from game.roles.superwolf import Superwolf
from ... | python |
t = c = i= 0
menor = ''
while True:
n = str(input('Nome: ')).capitalize()
p = float(input('Preço: R$ '))
t += p
if i == 0:
m = p
menor = n
i += 1
if p > 1000:
c += 1
if p < m:
menor = n
op = ' '
while op not in 'sn':
op = str(input('Quer co... | python |
# -*- coding: utf-8 -*-
"""
Some generic laguage level utilities for internal use.
"""
import collections
import functools
import sys
import warnings
from typing import (
AbstractSet,
Any,
Callable,
Hashable,
Iterable,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Seque... | python |
""" --- The Angles of a Triangle --- Elementary
You are given the lengths for each side on a triangle.
You need to find all three angles for this triangle. If the given side
lengths cannot form a triangle (or form a degenerated triangle),
then you must return all angles as 0 (zero). The angles should be
represented as... | python |
# -*- coding: utf-8 -*-
""" doScan.py
The core interface that takes minimal text description of scan and does IPC with hardware system
This is the common entry into the hardware interface and uses a minimal text desc file containing three
blocks: [Major], [Minor], [Interface]. This routine can be called independently... | python |
import logging
from django.core.management.base import BaseCommand, CommandError
from plyara import Plyara
from rules.models import YaraRule
# Configure Logging
logging.basicConfig(level=logging.INFO)
class Command(BaseCommand):
help = 'Recalculate the logic hashes of the entire rule corpus'
def handle(se... | python |
import pandas as pd
import numpy as np
class ExternalData():
def __init__(self, csv, mol_names, exclude=[]):
self.csv = csv
self.mol_names = mol_names
self.exclude = exclude
def fit(self, molecules):
return molecules
def fit_transform(self, molecules, labels):
... | python |
import mailroom_stuff.Front_End
if __name__ == '__main__':
mailroom_stuff.Front_End.main()
| python |
from flask_script import Manager,Shell,Server
from app import create_app ,db
from app.models import User
from flask_migrate import Migrate, MigrateCommand
app=create_app('production')
manager = Manager(app)
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)
manager.add_command('Server',Server)
@mana... | python |
#!/usr/bin/env python
import socket
import sys
import os
sys.path.append('./src')
from multi_detector import MultiDetector
libpath = "../lib/linux/libnyumaya.so"
hotword_graph="../models/Hotword/marvin_big_0.3.tflite"
hotword_labels="../models/Hotword/marvin_labels.txt"
action_graph="../models/Command/on_off_big_0... | python |
#!/usr/bin/env python
""" This code implements a ceiling-marker based localization system.
The core of the code is filling out the marker_locators
which allow for the specification of the position and orientation
of the markers on the ceiling of the room """
import rospy
from ar_pose.msg import ARMarkers
... | python |
import os
from typing import Any, Dict, Optional
import httpx
import pytest
from fastapi import status
from tortoise import Tortoise
from chapter6.tortoise_relationship.app import app
from chapter6.tortoise_relationship.models import (
CommentDB,
CommentTortoise,
PostDB,
PostTortoise,
)
DATABASE_FIL... | python |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='Test Project fro machine learning',
author='Vipin',
license='MIT',
)
| python |
# Generated by Django 2.1 on 2020-01-10 00:07
from django.db import migrations
import pyuploadcare.dj.models
class Migration(migrations.Migration):
dependencies = [
('rate', '0002_auto_20200109_1306'),
]
operations = [
migrations.AddField(
model_name='profile',
n... | python |
from .music import * | python |
# -*- coding: UTF-8 -*-
import torbjorn as tbn
from .an2cn import An2Cn
from .cn2an import Cn2An
ac = An2Cn()
ca = Cn2An()
an = 9876543298765432
cn = "九千八百七十六万五千四百三十二亿九千八百七十六万五千四百三十二"
@tbn.run_time
def run_cn2an_ten_thousand_times():
for _ in range(10000):
result = ca.cn2an(cn)
assert result ==... | python |
import warnings
from ..utility.strcmpi import *
from ..utility.debug_message import *
from .fileparts import *
def _open_file(filename, defaultExt, permission, fileDataFcn, verbose=False):
"""
Opens a given file and executes the specified function over its data
Parameters
---------... | python |
numbers = ["886"]
def parse_phone_number(phone_number):
# 国内号码不按照国际号码方式处理,直接返回手机号,这样亿美才能发送成功
if phone_number.startswith("+86"):
return phone_number[3:]
real_phone_number = None
for number in numbers:
p = "+" + number
if phone_number.startswith(p + "0"):
real_phone... | python |
# common conversion point stacking
# import modules
import sys
from geographiclib.geodesic import Geodesic as geo
import numpy as np
# from matplotlib.mlab import griddata
import scipy
import scipy.ndimage
from scipy import interpolate
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import num... | python |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\sims\aging\aging_data.py
# Compiled at: 2019-04-30 00:16:35
# Size of source mod 2**32: 7516 bytes
f... | python |
"""Tests for web app requests"""
from unittest import TestCase
import sodar_taskflow
from apis.irods_utils import init_irods, cleanup_irods_data
class AppTestBase(TestCase):
"""Base test class for web app"""
def setUp(self):
# Init iRODS connection
self.irods = init_irods(test_mode=True)
... | python |
from django.db import models
from django.urls import reverse
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('Date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = mode... | python |
#!/usr/bin/env python2
"""
os_path_test.py: Tests for os_path.py
"""
from __future__ import print_function
import unittest
from pylib import os_path # module under test
class OsPathTest(unittest.TestCase):
def testBasename(self):
self.assertEqual('bar', os_path.basename('foo/bar'))
if __name__ == '__main_... | python |
from abc import ABCMeta
class OgreMeshSerializerListener(metaclass=ABCMeta):
"""
This class allows users to hook into the mesh loading process and
modify references within the mesh as they are loading. Material and
skeletal references can be processed using this interface which allows
f... | python |
import os
import dill
import numpy as np
from math import pi, exp, atan, sqrt, acos
def angle(x, y):
"""calculates the angle of (x,y) with respect to (0,0)
:param x: x choordinate
:param y: y choordinate
:returns: the angle"""
at = atan(y/x)
if(x < 0): return at+pi
elif(y < 0): return at+2*pi
return at
de... | python |
# -*- coding: utf-8 -*-
# Copyright (C) 2016 Adrien Vergé
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This pro... | python |
# Copyright (C) 2014 Universidad Politecnica de Madrid
#
# 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 la... | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/david/projects/luxcorerender/LuxCore/src/pyluxcoretools/pyluxcoretools/pyluxcoremenu/menuwindow.ui',
# licensing of '/home/david/projects/luxcorerender/LuxCore/src/pyluxcoretools/pyluxcoretools/pyluxcoremenu/menuwindow.ui' applies.
#
#... | python |
from bflib.items.base import Item
from core import flags
from bfgame.factories.recipes import listing
from core.gameobject import GameObject
class ItemFactory(object):
name = "item"
type_map = Item
def __init__(self, game):
self.game = game
def create_new(self, base_item):
recipe = l... | python |
num = [1,2,3,4]
evens = list(filter(lambda x: x % 2 == 0, num))
print(evens)
| python |
from aclarknet.aclarknet.models import Client
from aclarknet.aclarknet.models import Service
from aclarknet.aclarknet.models import TeamMember
from aclarknet.aclarknet.models import Testimonial
from django.contrib import admin
class ClientAdmin(admin.ModelAdmin):
pass
class ServiceAdmin(admin.ModelAdmin):
p... | python |
import unittest
from pydantic import ValidationError
from mobile_handset_price_model.prediction.model import MobileHandsetPriceModel
from mobile_handset_price_model.prediction.schemas import MobileHandsetPriceModelInput, \
MobileHandsetPriceModelOutput, PriceEnum
class ModelTests(unittest.TestCase):
def tes... | python |
# stdlib
import itertools
from urllib import quote
from unittest import TestCase
import logging
import mock
import json
from utils.splunk.splunk import SplunkSavedSearch, SplunkInstanceConfig, SavedSearches
from utils.splunk.splunk_helper import SplunkHelper
class FakeInstanceConfig(object):
def __init__(self):... | python |
# -*- coding: utf-8 -*-
import logging
import os
from logging.handlers import RotatingFileHandler
from platform import uname
from plexapi.config import PlexConfig, reset_base_headers
from plexapi.utils import SecretsFilter
from uuid import getnode
# Load User Defined Config
DEFAULT_CONFIG_PATH = os.path.expanduser('~/... | python |
import sys
from cx_Freeze import setup, Executable
product_name = "Triangulation"
exe = Executable(
script = "main.py",
base = "Win32GUI",
targetName = "Triangulation.exe",
icon = "icon.ico",
shortcutName = "Triangulation",
shortcutDir = "ProgramMenuFolder"
)
build_exe_options = {"packag... | python |
import sys
sys.path.append('/home/george2/Raise/ProgramRepair/CodeSeer/projects/src/main/python')
from CodeJam.Y12R5P1.kelvinlau.A import *
def func_87caa8d11eaf4a20affa21f893f4cbfc(infile):
n = int(infile.readline())
l = map(int, infile.readline().split())
return l
def func_38404980cd9d4ebb8816600eb7513... | python |
# -*- coding: utf-8 -*-
from app.api import HTTPStatus, Resource, api
from app.auth import auth
@api.response(code=HTTPStatus.UNAUTHORIZED.value, description="Unauthorized access")
class BaseController(Resource):
method_decorators = [auth.login_required]
| python |
# https://www.youtube.com/watch?v=XNKeayZW4dY
from __future__ import absolute_import, division, print_function
import os
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.preprocessing import LabelEncoder
from tensorflow import keras
from tensorflow.keras import layers
print('You ... | python |
"""
Kaggle Challenge:
Modded version from
"http://www.kaggle.com/c/acquire-valued-shoppers-challenge/"
'Reduce the data and generate features' by Triskelion
"""
from datetime import datetime, date
from collections import defaultdict
data_dir = "../data/"
loc_offers = data_dir + "offers.csv"
loc_transactions = da... | python |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import generics
from rest_framework import status, mixins, viewsets
from rest_framework.decorators import api_view
from rest_framework.decorators import action
#Serializers
from cride.maps.serializers import StopMo... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import VERSION as DJANGO_VERSION
from django.db import migrations
def add_image_permissions_to_admin_groups(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')... | python |
#!/usr/bin/python -u
# -*- coding: latin-1 -*-
#
# Curious numbers in Z3
#
# From Martin Henz' collection of puzzles
# http://www.comp.nus.edu.sg/~henz/projects/puzzles/arith/#curious
# """
# Curious Numbers from "Amusements in Mathematics, Dudeney", number 114.
#
# The number 48 has this peculiarity, that if you add... | python |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class UserTestCase(IntegrationT... | python |
#Curso #7 Templates tags
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app = Flask(__name__, template_folder = 'prueba_template')
#para darle una carpeta en especifico
@app.route('/')
def index():
name = 'Sergio'
return render_template('index.html', nombre = name)
@app.route('... | python |
from output.models.ms_data.wildcards.wild_h003_xsd.wild_h003 import (
Bar,
Foo,
)
__all__ = [
"Bar",
"Foo",
]
| python |
import torch.nn as nn
import functools
import torch.nn.functional as F
import torch
from core.dataset.architecture.mobilespace import *
class MBSpaceController(nn.Module):
def __init__(self, n_conditions=1, n_unit=N_UNITS,
depths=DEPTHS, kernel_sizes=KERNEL_SIZES, expand_ratios=EXPAND_RATIOS,
... | python |
# Copyright (c) 2019 GalaxyLearning 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 appli... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.