content stringlengths 5 1.05M |
|---|
from pessoa import Pessoa
from base_dados import Base
class Adm(Pessoa):
def __init__(self, codigo, nome, idade):
super().__init__(nome, idade)
self.nome = nome
self.idade = idade
self.codigo = codigo
def getDados(self):
self.dados = Base()
self.visu = self.dados... |
# -*- coding: utf-8 -*-
"""
@author: alexyang
@contact: alex.yang0326@gmail.com
@file: rel_rnn.py
@time: 2018/4/6 10:53
@desc: learn a relation matching score function v(r, q) that measures the similarity between the question & the relation
"""
import os
import logging
import random
import numpy as np
import te... |
"""
vtelem - Test the websocket daemon's correctness.
"""
# built-in
import asyncio
import time
# third-party
import websockets
# module under test
from vtelem.daemon.websocket import WebsocketDaemon
from vtelem.mtu import get_free_tcp_port
async def consumer(websocket, message, _) -> None:
"""Simple echo cons... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-02-25 20:10:12
# @Author : ZubinGou (zebgou@gmail.com)
# @Link : https://github.com/ZubinGou
# @Version : $Id$
class Scene(object):
def enter(self):
pass
class Engine(object):
def __init__(self, Scene_map):
pass
def pla... |
print ("Hello Python World!")
print ("Hello Python Again")
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... |
# coding: utf-8
# # 20 Newsgroups text classification with pre-trained word embeddings
#
# In this notebook, we'll use pre-trained [GloVe word
# embeddings](http://nlp.stanford.edu/projects/glove/) for text
# classification using TensorFlow 2.0 / Keras. This notebook is
# largely based on the blog post [Using pre-tr... |
# students = ['小明','小红','小刚']
# students.append('3')
# del students[2]
# print(students)
# students = ['小明','小红','小刚']
#
# scores = {'小明':95,'小红':90,'小刚':90}
#
# print(len(students))
#
# print(len(scores))
# scores = {'小明':95,'小红':90,'小刚':90}
#
# print(scores['小明'])
# scores = {'小明':95,'小红':90,'小刚':90}
#
# scores['小... |
"""
Provides utilities for the sura_rename package
"""
import os.path
def prepend_path(file_list, path):
"""
Returns an iterable with each element replaced with a prepended path
"""
return (os.path.join(path, file) for file in file_list)
def get_ext_files(directory, ext):
"""
returns an itera... |
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
# reading both the data sets
trainDf = pd.read_csv("dataset/train.csv")
testDf = pd.read_csv("dataset/test.csv")
# checking lengths
trainingSetIndex = len(trainDf)
print(len(trainDf), len(testDf))
# data type check
print(trainDf.dtypes)
# n... |
import numpy as np
class Env:
def __init__(self, n_action, p):
self.n_action = n_action
self.p = p
def sample(self, action, n_sample):
return (np.random.uniform(0, 1, n_sample) < self.p[action]).astype(np.uint8)
def G1():
def _op(n_action):
p = np.random.uniform(0.02, 0.05... |
from functools import partial
import six
from ..utils.is_base_type import is_base_type
from ..utils.props import props
from .field import Field
from .objecttype import ObjectType, ObjectTypeMeta
class MutationMeta(ObjectTypeMeta):
def __new__(cls, name, bases, attrs):
# Also ensure initialization is on... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
"""
This module defines the SkipoleProject, SkiCall, PageData, SectionData classes
SkipoleProject being the core of the project which loads
the project from JSON files and responds to incoming calls by calling the user functions
SkiCall is the class of the skicall object which is created for each incoming
call and ... |
import numpy as np
def apply_offset(stream, offset=None, coffset=None):
if offset != None:
offsetarray = np.array(offset)
coeff = np.polyfit(
offsetarray[:, 0], offsetarray[:, 1], deg=len(offsetarray)-1)
# Make sure that constant shift (only one tuple provided is handled as of... |
def token(senten, word_tokenize):
results = []
for sentence in senten:
results.append(word_tokenize(sentence))
return results
def topic_model(reviews_lemmatized, gensim, np, MovieGroupProcess, int_val):
np.random.seed(0)
# initialize GSDMM
gsdmm = MovieGroupProcess(K=int_va... |
"""
View this repository on github: https://github.com/Jothin-kumar/Geometry-app
MIT License
Copyright (c) 2021 B.Jothin kumar
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... |
from __future__ import absolute_import, print_function
import logging
from collections import defaultdict
from sage.all import (
gcd,
vector,
matrix,
QQ,
Polyhedron,
cartesian_product,
Permutation,
Permutations,
)
from . import dual_root_primitive
from .disk_cache import disk_cache
__al... |
import discord
from discord.ext import commands
from sys import argv
class Links:
"""
Commands for easily linking to projects.
"""
def __init__(self, bot):
self.bot = bot
print('Addon "{}" loaded'.format(self.__class__.__name__))
@commands.command()
async def builds(se... |
email = input("Please enter your email id: ").strip()
user_name = email[:email.index("@")]
domain_name = email[email.index("@")+1:]
output = f"Your username is {user_name} and your domain name is {domain_name}"
print(output)
|
# prefix our test function names with test_
def sum_nums(x,y):
return x+y
def test_sum_nums():
assert sum_nums(2,3) == 5
|
#!/usr/bin/env python
# Copyright 2013,2016 The Font Bakery Authors.
#
# 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 ... |
""" use unittesting module as testing framework"""
import unittest
import json
from app.api.v1.models.auth import userModel
from app.api.v1.models.category import categoryModel
from app.api.v1.models.product import productModel
from app.api.v1.models.sales import salesModel
from .dummy_data import users, category, prod... |
import string
from pyawsstarter import LambdaBaseEnv
from .random_prefix_service import RandomPrefixService
from examplecommon import WordService
class WordsNotFoundException(Exception):
pass
class WordStep(LambdaBaseEnv):
_letters = string.ascii_lowercase
_number_letters = len(string.ascii_lowercase)
... |
"""
@author: Chandan Sharma
@GitHub: https://github.com/devchandansh/
"""
"""
================================================================
A Robot moves in a Plane starting from the origin point (0,0).
The robot can move toward UP, DOWN, LEFT, RIGHT.
The trace of Robot movement is as given following:
Assumed ... |
# -*- coding: utf-8 -*-
from website.citations.providers import CitationsProvider
from addons.zotero.serializer import ZoteroSerializer
class ZoteroCitationsProvider(CitationsProvider):
serializer = ZoteroSerializer
provider_name = 'zotero'
def _folder_to_dict(self, data):
return dict(
... |
# C2SMART Lab, NYU
# NCHRP 03-137
# @file HB_Ext_Online.py
# @author Fan Zuo
# @author Di Yang
# @date 2020-10-18
import pandas as pd
import numpy as np
from shapely.geometry import Polygon
import math
import time
import multiprocessing as mp
def main(dataset, hb_thr):
"""The main processing function.
... |
import os
import pickle
data_dir = os.path.dirname(os.path.realpath(__file__))
def get_file(name):
full_path = os.path.join(data_dir, name)
if not os.path.exists(full_path):
return None
else:
return full_path
def load_predict_model_from_pkl(filename):
''' The pickled models are assum... |
from urllib.parse import urlparse
from flask import session
from app.models import User
from app.models import TwoFactor
def is_two_factor_enabled() -> bool:
# 2단계 인증 정보 데이터베이스에서 검색하기
two_factor = TwoFactor.query.filter_by(
user_idx=session['user']['idx']
).first()
# 검색결과가 있다면
if two_fa... |
from functools import partial
from typing import Callable, Dict, Tuple
import jax
import jax.numpy as jnp
@partial(jax.jit, static_argnums=(0))
def marginal_likelihood(
prior_params: Tuple[Callable, Callable],
params: Dict,
Xtrain: jnp.ndarray,
Ytrain: jnp.ndarray,
) -> float:
# unpack params
... |
import _init_paths
import argparse
import yaml
import os.path as osp
from attrdict import AttrDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from datasets.mini_imageNet import MiniImageNet
from utils.samplers import CategoriesSampler
from m... |
n=int(input()) #2. Snake
s=[]
b=[]
matrix=[]
for j in range(n):
row=list(input())
matrix.append(row)
if 'S' in row:
s.append([j,row.index('S')])
if 'B' in row:
b.append([j,row.index('B')])
moves={'up':(-1,0),'down':(1,0),'left':(0,-1),'right':(0,1)}
food=0
while True:
move=input()
... |
__all__ = ["interpreter", "analysis"] |
import json
def shlex(command=None, shell=None):
shell = shell or '/bin/sh'
shlexed = [shell]
if command:
shlexed.extend(['-c', command])
return shlexed
|
import matplotlib.pyplot as plt
import time
from genetic.background_function import background_function
from vis.ScatterVisualizer import ScatterVisualizer
class Particle2DVis(ScatterVisualizer):
def __init__(
self,
n: float,
num_runs: int,
interactive: bool = True,
x_lim... |
import iniparse
from ram.osutils import TrySubmit
# hack to force iniparse to return empty string for non-present keys.
setattr(iniparse.config, 'Undefined', lambda name, namespace: '')
from . import SyncedDict
class _IniConfig(SyncedDict):
def __init__(self, dirname, section, readonly, delblank=False, createn... |
import json
import olefile
import pandas as pd
import time
import os
from .logstuff import get_logger
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
logger = get_logger('cache_json')
def write_json_cache(cach... |
from qtpy.QtCore import QObject, QLocale
from pymodaq.daq_utils.gui_utils.dock import DockArea
from pymodaq.daq_utils.managers.action_manager import ActionManager
from pymodaq.daq_utils.managers.parameter_manager import ParameterManager
from pyqtgraph.dockarea import DockArea
from qtpy import QtCore, QtWidgets
class ... |
from functools import reduce
# a dynamic programming solution
def calculate_largest_square_filled_first_approach(matrix):
"""
A method that calculates the largest square filled with only 1's of a given binary matrix (not space-optimized).
Problem description: https://practice.geeksforgeeks.org/problems/l... |
from __future__ import absolute_import
import os
import numpy as np
import pygame
import weakref
import carla
from carla import ColorConverter as cc
CARLA_OUT_PATH = os.environ.get("CARLA_OUT", os.path.expanduser("~/carla_out"))
if CARLA_OUT_PATH and not os.path.exists(CARLA_OUT_PATH):
os.makedirs(CARLA_OUT_PATH)
... |
"""URLs for Django api application
Contains api endpoints for requests. Using router for creating automatic
detail URLs.
"""
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from . import views as api_views
__author__ = 'Petr Hendrych'
__email__ = 'xhendr03@fit.vutbr.cz'
clas... |
import os
import logging
from cyvcf2 import VCF
from loqusdb.exceptions import VcfError
from loqusdb.vcf_tools.variant import get_variant_id
logger = logging.getLogger(__name__)
VALID_ENDINGS = ['.vcf', '.gz']
def get_file_handle(file_path):
"""Return cyvcf2 VCF object
Args:
file_path(str)
... |
from output.models.ms_data.attribute.att_d007_xsd.att_d007 import (
AttRef,
Char,
Doc,
No,
)
__all__ = [
"AttRef",
"Char",
"Doc",
"No",
]
|
from client import exception, listener, logger
from client.config import config as c
from discord.ext import commands, tasks
import discord
class event_listener(commands.Cog):
# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
name = 'event_listener'
STATUS = 0
# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
@tasks.loop(minutes=1)
async ... |
#!/usr/bin/env python3
"""Project Euler - Problem 40 Module"""
def problem41(limit):
"""Problem 41 - Champernowne's constant"""
i = 0
str_number = ''
while len(str_number) <= limit:
str_number += str(i)
i += 1
d = 1
result = 1
while d <= limit:
result *= int(str_nu... |
import numpy as np
# return -1 if x < 0, 1 if x > 0, random -1 or 1 if x ==0
def sign(x):
s = np.sign(x)
tmp = s[s == 0]
s[s==0] = np.random.choice([-1, 1], tmp.shape)
return s
if __name__ == "__main__":
x = np.random.choice([-1, 0, 1], [5, 5])
print(x)
print((sign(x)))
|
import xml.etree.ElementTree as ET
from CodegenDatatype import fromXMLCfgStr, toJavaDatatypeStr
from CodegenUtils import indent
class DataCodegen:
def __init__(self, parent):
self.parent = parent
def getIdentifier(self):
return self.parent.name
def getDeclaration(self):
... |
import os
import json
import numpy as np
import pandas as pd
from sklearn import metrics
import matplotlib.pyplot as plt
from matplotlib.pylab import rcParams
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_validate
from sklearn... |
from __future__ import absolute_import
import torch
from torch import nn
from torch.autograd import Variable
from ..evaluation_metrics import accuracy
class DeepLoss(nn.Module):
def __init__(self, margin=0):
super(DeepLoss, self).__init__()
self.triplet_criterion = nn.MarginRankingLoss(margin=mar... |
#!/usr/bin/python3
import sys
import re
from pathlib import Path
import fileinput
""" This script is intended to fix the issue with flash strings on ESP866 described """
""" in issue #8 (https://github.com/frankjoshua/rosserial_arduino_lib/issues/8) """
""" It can also be used on the raw output of the rosserial_ardui... |
#!/usr/bin/env python
from pathlib import Path
from typing import Tuple
def get_path(dir_path: Path,
dir_name: str = "movie",
counting_format: str = "%03d",
file_pattern: str = "") -> Tuple[Path, int, str, str]:
"""
Looks up all directories with matching dir_name
and... |
#!/usr/bin/env python
from main import main
main()
|
from django.http import HttpResponse
def dummy_view(request):
return HttpResponse('You ran a test.')
|
args_unmask = {
'no_cuda': False,
'cuda_device': '0',
'seed': 5,
'model': 'densenet121', # vgg16, resnet50, resnet101, densenet121
'dataset': 'unmask',
'class_set': 'cs5-2',
# training params
'val_ratio': 0.1,
'batch_size': 32,
'epochs': 30,
'optimizer': 'sgd', # can be sgd... |
"""
Copyright (c) 2017, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file LICENSE, distributed with this software.
Created on Oct 4, 2017
@author: jrm
"""
import sh
import sys
def main():
# Make sure instance is cleared
from enaml.application import Application... |
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium.webdriver.firefox.webdriver import WebDriver
from accounts.models import Account
class AuthenticationTest(StaticLiveServerTestCase):
DEFAULT_PASSWORD = "p4ssw0rd!"
@classmethod
def setUpClass(cls):
super().setU... |
#!/usr/bin/env python
# Copyright 2016 Andy Chu. 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
"""
bool_parse_test.py: Te... |
import resources
import sql.sql_deployment as sd
from sql.sql_parameters import SqlParameters
from helper import ServiceType
s = 'VM'
#res = resources.get_all_tks_resource_groups()
#params = SqlParameters()
#params.administrator_password = "})&B7Tq33n1f"
#p = sd.get_parameters(params)
#t = sd.get_template()
#reso... |
from dolfin import Mesh, cells, edges
import os
# FIXME
# We don't know how to deal with tight bbox intersecting the surface and so
# are forced to have the bbox larger. Would be nice to handle this.
def mesh_around_1d(mesh, size=1, scale=10, padding=0.05):
'''
From a 1d in xd (X > 1) mesh (in XML format) pro... |
import itertools
from cloud_info_provider.collectors import base
class ComputeCollector(base.BaseCollector):
def __init__(self, opts, providers):
super(ComputeCollector, self).__init__(opts, providers)
self.templates = ['compute']
def fetch(self):
info = {}
# Retrieve global... |
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions
import pandas as pd
from config import config
class BaseWatsonError(Exception):
pass
class WatsonConfigError(BaseWatsonError):
pass
clas... |
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, regularizers, initializers
from .blocks import conv_block, mlp_block
class OrthogonalRegularizer(regularizers.Regularizer):
"""Reference: https://keras.io/examples/vision/pointnet/#build-a-model"""
def __init__(self, num_feature... |
from memories import generate_memory
approved = "1"
idx, imagefile = generate_memory(approved)
print("result is", idx, "image", imagefile)
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_digits
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
digits = lo... |
import plotter_controller
import threading
import random
import time
import PIL.Image
import PIL.ImageDraw
import numpy as np
import sys
import step_file_data_provider
import math
class PlotterSimulator:
def __init__(self, step_time, phys_time, image_output_dir=None, save_stats=True):
self.image_time_step = 1 / 60
... |
import time
import pickle
from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from snake_env import SnakeEnv
from dqn_model import DQNAgent
# Code from https://gist.github.com/Jawdeyu/1d633c35238d13484deb2969ff40005d#file-dqn_run-py
def run(training_mode, pre... |
import datetime
import random
import discord
from discord.ext import commands, tasks
from discord_components import DiscordComponents
from discord_slash import SlashCommand
import functions
import json
token = your token
i = discord.Intents().all()
bot = commands.Bot(command_prefix='..', intents=i)
slash = SlashComma... |
"""Classes for handling telescope and eyepiece properties."""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams.update({'font.size': 14})
matplotlib.rcParams.update({'xtick.direction':'in'})
matplotlib.rcParams.update({'ytick.direction':'in'})
matplotlib.rcParams.update({'xtick.m... |
def interp(a, b, t, d=1) -> float:
return a + (b - a) * t**d
def inv_interp(a, b, t, d=1) -> float:
return a + (b - a) * (1 - (1 - t)**d)
def lerp_angle(a, b, t) -> float:
delta = (b - a) % 360
if delta > 180:
delta -= 360
return a + delta * t
def delta_angle(a, b):
delta = (b - a)... |
"""
Author: Will Hanstedt
Filename: TMmain.py
Project: Research for Irina Mazilu, Ph.D.
A file to run single iterations of temperature-dependent Cayley Tree simulations.
"""
import Cayley as cy
import Cayley.graphics as cg
def main():
generations = int(input("Number of generations: "))
links = int(input("Num... |
# coding: utf-8
from abc import ABCMeta, abstractmethod
class Strategy(object):
"""Strategy is an abstract base class providing an interface for
all subsequent (inherited) trading strategies.
The goal of a (derived) Strategy object is to output a list of signals,
which has the form of a time series in... |
import numpy as np
class Variable:
def __init__(self, data):
self.data = data
self.grad = None
class Function:
def __call__(self, input):
x = input.data
y = self.forward(x)
output = Variable(y)
self.input = input
return output
def forward(self, x):
... |
# Copyright 2019 The Forte 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 applicable ... |
# Generated by Django 3.2.5 on 2021-08-03 03:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0024_achievementcode_level'),
]
operations = [
migrations.AddField(
model_name='achievementcode',
name=... |
import unittest
from test.test_json import load_tests
unittest.main()
|
from flask_wtf import FlaskForm, Form
from wtforms import StringField, PasswordField, BooleanField, SubmitField, DateField, SelectField, SelectMultipleField, \
TextAreaField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from app.models import User,Artist, Venue, Event, ArtistToEvent
... |
"""
File: best_photoshop_award.py
----------------------------------
This file creates a photoshopped image
that is going to compete for the Best
Photoshop Award for SC001.
Please put all the images you will use in the image_contest folder
and make sure to choose the right folder when loading your images.
"""
from simp... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
SECRET_KEY = "TEST_SECRET_KEY"
INSTALLED_APPS = [
"drf_recaptcha",
]
DATABASES = {
"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "test.sqlite3"}
}
DRF_RECAPTCHA_SECRET_KEY = "TEST_DRF_RECAPTCHA_SECRET_KEY"
|
#!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import commands
"""Copy Special exercise
"""
#... |
import bottle
application = bottle.default_app()
@bottle.route('/')
def home():
return "apache and wsgi, sitting in a tree"
|
import streamlit as st
import pandas as pd
import sys
sys.path.insert(0, '../scripts')
from results_pickler import ResultPickler
def app():
# Load Saved Results Data
results = ResultPickler()
results.load_data(file_name='./data/satisfaction_results.pickle')
st.title("User Satisfaction analysis")
... |
# -*- encoding:utf8 -*-
from collections import OrderedDict
from collections import namedtuple
from math import log
from soynlp.tokenizer import MaxScoreTokenizer
from ._dictionary import Dictionary
default_profile= OrderedDict([
('cohesion_l', 0.5),
('droprate_l', 0.5),
('log_count_l... |
from direct.directnotify import DirectNotifyGlobal
from direct.distributed import DistributedObject
from otp.ai.MagicWordGlobal import *
lastClickedNametag = None
class MagicWordManager(DistributedObject.DistributedObject):
notify = DirectNotifyGlobal.directNotify.newCategory('MagicWordManager')
neverDisable =... |
from django.views.generic import View
from django.shortcuts import render, get_object_or_404
from django.http import Http404
from django.core.exceptions import PermissionDenied
from accounts.views import LoginRequiredMixin
from home.models import Text, Photo, Audio, Video, File, Sticker, Link
from operator import attrg... |
#!/usr/bin/env python3
x = 0
bool = True
while bool:
print(x)
x = x + 1
if x == 5:
bool = False
print(bool)
print("done")
|
import rdflib
import pytest
from project import graph_utils
my_graph = graph_utils.get_graph_info("travel")
def test_name():
assert my_graph[0] == "travel"
def test_nodes():
assert my_graph[1] == 131
def test_edges():
assert my_graph[2] == 277
def test_labels():
assert my_graph[3] == {
... |
"""
Objective
In this challenge, we're reinforcing what we've learned today. In case you've missed them, today's tutorials are on Conditional Probability and Combinations and Permutations.
Task
A bag contains 3 red marbles and 4 blue marbles. Then,2 marbles are drawn from the bag, at random, without replacement. If th... |
#!/usr/bin/env python3:
# _*_ coding: utf-8 _*_
'''
MIT License
Copyright (c) 2018 USAKU Takahashi
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 limitati... |
import pygame
pygame.init()
WIDTH = 700
HEIGHT = 700
FPS = 60
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (80, 175, 90)
BLUE = (60, 160, 200)
COLS = 10
ROWS = 6
win = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Breakout KD")
clock = pyga... |
print("ARACINIZ KM NE KADAR YAKIYOR ? ")
print("-------------------------------")
yapilan_km = int(input("Kaç Km Yol Yaptınız (KM): "))
yakilan_yakit = float(input("Km'de Araç Ne Kadar Yakıyor (TL) : "))
ödeme=yapilan_km*yakilan_yakit
print("Tüketilen Yakıt Bedeli {}'dir".format(ödeme))
|
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import livestream.routing
application = ProtocolTypeRouter({ # includes index by default
'websocket': AuthMiddlewareStack(
URLRouter(
livestream.routing.websocket_urlpatterns
)
... |
# coding: utf-8
"""
Social Graph API
Pho Networks REST API
OpenAPI spec version: 1.1.1
Contact: emre@phonetworks.org
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compli... |
from behave import *
use_step_matcher("parse")
@then("The URL is {url}")
def step_impl(context, url):
assert context.driver.current_url == url
@step("I open {url}")
def step_impl(context, url):
context.driver.get(url)
|
from dlutils.models.gans.softmax.softmax import SoftmaxGAN, update_fn
|
from __future__ import absolute_import
import argparse
import csv
import logging
import os
import random
import sys
from io import open
import pandas as pd
import numpy as np
import torch
import time
import collections
import torch.nn as nn
from collections import defaultdict
import gc
import itertools
from multiproce... |
from src.alerter.alert_code.alert_code import AlertCode
from src.alerter.alert_code.github_alert_code import GithubAlertCode
from src.alerter.alert_code.internal_alert_code import InternalAlertCode
from src.alerter.alert_code.system_alert_code import SystemAlertCode
|
from Tkinter import *
root = Tk()
labelframe = LabelFrame(root, text="This is a LabelFrame")
labelframe.pack(fill="both", expand="yes")
left = Label(labelframe, text="Inside the LabelFrame")
left.pack()
root.mainloop() |
# Generated by Django 2.0.7 on 2018-08-01 06:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('hsse_api', '0002_auto_20180801_0032'),
]
operations = [
migrations.RemoveF... |
from memory_profiler import profile
@profile
def load():
from udapi.core.document import Document
document = Document()
document.load_conllu('cs-ud-train-l.conllu')
for bundle in document:
for root in bundle:
for node in root.descendants:
form_lemma = node.form + no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.