text stringlengths 1 927k |
|---|
from django import forms
from .models import Image,Profile,Comments
class NewsLetterForm(forms.Form):
your_name=forms.CharField(label='First Name',max_length=30)
email=forms.EmailField(label='Email')
class NewImageForm(forms.ModelForm):
class Meta:
model= Image
exclude =['editor','pub_... |
#Maral Dadvar
#09/01/2019
#This script filters the names with initialls.
import unicodedata
import os , glob
import rdflib
from rdflib import Namespace, URIRef, Graph , Literal , OWL, RDFS , RDF
from SPARQLWrapper import SPARQLWrapper2, XML , JSON , TURTLE
import re
import pprint
os.chdir('C:\\Users\\Maral\\Deskto... |
h,m = map(int, input().split())
mins = (24+h) * 60 + m
mins -= 45
mins %= 24*60
print(mins//60, mins%60) |
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import sklearn.datasets
import sklearn.linear_model
def plot_decision_boundary(model, X, y):
# Set min and max values and give it some padding
x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1
y_min, y_max = X[1, :].min() - 1, X[1, :].max(... |
# -*- coding: utf-8 -*-
"""
Main.py contains the functions to calculate the different quantities of materials
in each step of the process. Reffer to the diagram on Package-Overview for the
steps considered.
Support functions include Weibull functions for reliability and failure; also,
functions to modify baseline v... |
from bot import aria2, download_dict_lock, STOP_DUPLICATE_MIRROR
from bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper
from bot.helper.ext_utils.bot_utils import *
from .download_helper import DownloadHelper
from bot.helper.mirror_utils.status_utils.aria_download_status import AriaDownloadStatu... |
import sys
from configparser import ConfigParser
from .data import CMS_VERSION_MATRIX, DJANGO_VERSION_MATRIX
SECTION = "djangocms_installer"
def parse_config_file(parser, stdin_args):
"""Parse config file.
Returns a list of additional args.
"""
config_args = []
# Temporary switch required args... |
import rospy
from geometry_msgs.msg import Pose, Point
from std_msgs.msg import Bool
import numpy as np
import os
# This script creates a square trajectory for a robot to follow.
# Will output errors as well.
class CircleTrajectory(object):
def __init__(self, x_offset, y_offset, z_height, radius, theta_step):
... |
from .model import Model
class Services(Model):
pass |
import json
from shadowray.config.v2ray import SERVER_FILE
from shadowray.config.v2ray import SERVER_KEY_FROM_SUBSCRIBE, SERVER_KEY_FROM_ORIGINAL
class Server:
def __init__(self, filename=None):
self.__servers = json.loads('{"servers_subscribe": [] ,"servers_original": []}')
self.__filename = SER... |
import warnings
import numpy as np
from ...utils.colormaps import AVAILABLE_COLORMAPS
from ...utils.events import Event
from ...utils.translations import trans
from ..base import Layer
from ..intensity_mixin import IntensityVisualizationMixin
from ..utils.layer_utils import calc_data_range
from ._surface_constants im... |
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="family", parent_name="funnel.textfont", **kwargs):
super(FamilyValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
#add your custom command output handler class to this module
#the default handler , does nothing , just passes the raw output directly to STDOUT
class DefaultCommandOutputHandler:
def __init__(self,**args):
pass
def __call__(self, raw_cmd_output):
print_xml_stream(raw_cmd_... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
import logging
import torch
import numpy as np
from .shape_dependency import ChannelDependency, GroupDependency, InputChannelDependency
from .utils import get_module_by_name
# logging.basicConfig(level = logging.DEBUG)
_logger = logging.... |
from astropy.io import fits
a = fits.open('image0.fits')
image = a[0].data
print(image.shape) |
from django.contrib import admin
from .models import Course, CourseSemester, Department, Instructor
admin.site.register(Course)
admin.site.register(CourseSemester)
admin.site.register(Department)
admin.site.register(Instructor) |
import sys
import shapefile
longitude = float(sys.argv[1])
latitude = float(sys.argv[2])
outpath = sys.argv[3]
writer = shapefile.Writer(shapefile.POINT)
writer.field('label')
writer.point(longitude, latitude)
writer.record('singleton')
writer.save(outpath) |
import os,sys,struct,glob
import urllib.request
from binascii import hexlify, unhexlify
#don't change this mid brute force - can be different amount multiple computers - powers of two recommended for even distribution of workload 1 2 4 8 etc.
process_count=4
offset_override=0 #for gpu options, this allows st... |
import math
import unittest
from io import BytesIO
from urllib3 import HTTPResponse
from influxdb_client.client.flux_csv_parser import FluxCsvParser, FluxSerializationMode, FluxQueryException
from influxdb_client.client.flux_table import FluxStructureEncoder
class FluxCsvParserTest(unittest.TestCase):
def test... |
import FWCore.ParameterSet.Config as cms
from RecoLocalTracker.SiStripRecHitConverter.StripCPEfromTrackAngle_cfi import *
from RecoLocalTracker.SiStripRecHitConverter.SiStripRecHitMatcher_cfi import *
from RecoLocalTracker.SiPixelRecHits.PixelCPEParmError_cfi import *
from RecoTracker.TransientTrackingRecHit.Transien... |
from __future__ import print_function
import find_mxnet
import mxnet as mx
import argparse
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'symbol'))
import symbol_factory
parser = argparse.ArgumentParser(description='network visualization')
parser.add_argument('--network', type=str, defa... |
import sys
import os
from django.conf import settings
DEBUG = os.environ.get('DEBUG', 'on') == 'on'
SECRET_KEY = os.environ.get('SECRET_KEY', 'a^hi#2sv)yy%v(6fhlv(j@-5e%+7h*d%#g%+ru(hv-7rj08r7n'),
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',')
BASE_DIR = os.path.dirname(__file__)
settings.con... |
# EXAMPLE: Resampling an cubemap to the vertices of an depth scaled icosphere
#
# This example shows how to resample a cubemap to the vertices of an
# icosphere. We then scale the vertices according to provided depth
# information, which reshapes the mesh to the indoor scene it captures. We
# then show how to render ba... |
from locust import HttpLocust, TaskSet, task
import json, uuid, io, random, string
class UserBehavior(TaskSet):
def on_start(self):
global token, headers, getId, userId,company
#---------- Configurations
#user token
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiO... |
from datetime import datetime, timedelta
import discord
import asyncio
from discord.ext import commands
import pytimeparse
class Context(commands.Context):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.settings = self.bot.settings
self.permissions = self.bot.settings.permis... |
# -*- coding: utf-8 -*-
# 打卡脚修改自ZJU-nCov-Hitcarder的开源代码,感谢这位同学开源的代码
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import json
import re
import datetime
import time
import sys
class DaKa(object):
"""Hit card class
Attributes:
usernam... |
from configpp.soil import Config, Group, GroupMember, Transport, ClimberLocation
from voidpp_tools.mocks.file_system import FileSystem, mockfs
_data_filename = 'test1.json'
_data = {_data_filename: '{"a": 42}'}
def test_load_simple_not_found():
cfg = Config(_data_filename)
assert cfg.load() is False
@mockf... |
import torch as t
import torch.nn as nn
import torch.nn.functional as F
class MTRN(nn.Module):
def __init__(self, frame_count: int):
super().__init__()
self.frame_count = frame_count
self.fc1 = nn.Linear(256 * frame_count, 1024)
self.fc2 = nn.Linear(1024, 512)
self.fc3 ... |
#!/usr/bin/env python3
# encoding: utf-8
"""A snipMate snippet after parsing."""
from UltiSnips.snippet.definition.base import SnippetDefinition
from UltiSnips.snippet.parsing.snipmate import parse_and_instantiate
class SnipMateSnippetDefinition(SnippetDefinition):
"""See module doc."""
SNIPMATE_SNIPPET_P... |
"""
Copyright (C) 2020 Argonne, Hariharan Devarajan <hdevarajan@anl.gov>
This file is part of DLProfile
DLIO 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 published by the Free Softw... |
from .store_backend import (
StoreBackend,
InMemoryStoreBackend,
# FilesystemStoreBackend,
FixedLengthTupleFilesystemStoreBackend,
FixedLengthTupleS3StoreBackend,
)
from .store import (
WriteOnlyStore,
ReadWriteStore,
BasicInMemoryStore,
)
from .namespaced_read_write_store import (
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import copy
import inspect
import logging.config
import os
import sys
import warnings
from dataclasses import dataclass
from os.path import dirname, join, normpath, realpath
from traceback import print_exc, print_exception
from types... |
import os
import shutil
import pickle
import traceback
import json
import logging
import math
import time
import psutil
from time import sleep
from copy import deepcopy
from multiprocess import Process, Manager, cpu_count
from multiprocess.queues import Queue
from multiprocess.synchronize import Lock
from typing import... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
x = 1
y = 1
def foo():
x = 3
x = x + 1
print x
def bar():
global y
y = 3
y = y + 1
print y
foo()
bar()
print x
print y |
import re
import warnings
TYPE_REGEXP = r"(?:arrayof\s+)?\w+"
def parse_interface(interface_items):
parsed = []
for key, value in interface_items.iteritems():
if "(" in key:
# Item is a method
match = re.match(r"^\s*(%s)\s+(\S+)\s*\(\s*([^\)]*)\s*\)\s*$" % TYPE_REGEXP, key)
... |
#!/usr/bin/env python
# Copyright (c) 2014, Stanford University
# 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 code must retain the above copyright notice, this list ... |
import os
import re
import shutil
from subprocess import check_output, run, PIPE
import numpy as np
import torch
import logging
logger = logging.getLogger(__name__)
def get_gpu_memory_map():
result = check_output(
["nvidia-smi", "--query-gpu=memory.used", "--format=csv,nounits,noheader"]
)
return... |
import sys
import os
from os.path import expanduser
import pickle
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data
import torch.onnx
import re
import json
from PIL import Image, ImageDraw
import torch
import numpy as np
# Training script- trains a Pytorch model against the Google ... |
from django.urls import include, re_path,path
from .views import EffectUpdateView,EffectCreateView,EffectCreateInitView
from .views import StyleView,RenderImageView
from .views import ManageImageStylesView
app_name = 'image_styles'
urlpatterns = [
path('',ManageImageStylesView.as_view(),name='manage_image_styles'... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2018-01-12 04:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('videos', '0001_initial'),
]
operations = [
migrations.AddField(
... |
from sciwing.engine.engine import Engine |
import array
import binascii
import tempfile
a = array.array('i', range(5))
print('A1:', a)
# Write the array of numbers to a temporary file
output = tempfile.NamedTemporaryFile()
a.tofile(output.file) # must pass an *actual* file
output.flush()
# Read the raw data
with open(output.name, 'rb') as input:
raw_dat... |
# https://github.com/keleshev/schema
# Copyright (c) 2012 Vladimir Keleshev, <vladimir@keleshev.com>
#
# 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 l... |
EXAMPLES1 = (
('1122', 3),
('1111', 4),
('1234', 0),
('91212129', 9)
)
EXAMPLES2 = (
('1212', 6),
('1221', 0),
('123425', 4),
('123123', 12),
('12131415', 4)
)
def code1(string):
return sum(ord(x) - ord('0') for i, x in enumerate(string) if x == string[(i + 1) % len(string)])... |
import tkinter as tk
import tkinter.font as tkFont
from tkinter import ttk
import webbrowser
from config import Config
import ui.main_menu
class HelpPage(tk.Frame):
def __init__(self, parent, controller):
"""Rules of the game
"""
super().__init__(parent)
self.controller = contr... |
import math
def tfidf_calc(wordPerCat, numDocsWithTerm, totalDocs):
for i in wordPerCat:
for key, value in wordPerCat[i].items():
deted = int(numDocsWithTerm[key])
wordPerCat[i][key] = float(float(wordPerCat[i][key]) * (math.log(totalDocs/deted)))
return wordPerCat
def prior_pr... |
from django.test import TestCase
from django.urls import reverse
class TestUrls(TestCase):
def test_report(self):
self.assertEqual("/api/v1/report", reverse("report")) |
# sql/visitors.py
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""Visitor/traversal interface and library functions.
SQLAlchemy schema and expres... |
from GenObj import *
class GenBelongsTo(GenObj):
def __init__(self, name, stmtIndex):
super(GenBelongsTo, self).__init__(name)
self.stmtIndex = stmtIndex
def getStmtIndex(self):
return self.stmtIndex
def setStmtIndex(self, stmtIndex):
self.stmtIndex = stmtIndex |
import numpy as np
import pytest
from pandas import (
NA,
Categorical,
Series,
)
import pandas._testing as tm
@pytest.mark.parametrize(
"keep, expected",
[
("first", Series([False, False, False, False, True, True, False])),
("last", Series([False, True, True, False, False, False, ... |
#!/usr/bin/env python3
import os
import sys
import yaml
import argparse
import logging
import mysql.connector
logger = logging.getLogger(__name__)
def build_mysql_connection(rest_config_path):
with open(rest_config_path) as f:
cluster_config = yaml.load(f)
host = cluster_config["mysql"]["hostname"... |
#Tyler Sorensen
#University of Utah
#March 1, 2012
#dot_bdd.py
#This simply prints a .dot file for visualizing the bdd
#Only public function
def print_bdd(bdd, fileName):
"""
Generate a dot file with the bdd in it. Run the dot file through
dot and generate a ps file.
"""
#open the file
f1 = op... |
import numpy as np
import numpy.linalg as la
from MdlUtilities import Field, FieldList
import MdlUtilities as mdl
def get_osaCasing_fields():
OD = Field(2030)
ID = Field(2031)
Weight = Field(2032)
Density = Field(2039)
E = Field(2040)
osaCasing_fields = FieldList()
osaCasing_fields.append( ... |
import networkx
import numpy as np
from Library import mcl
from Library import Database, Util
try:
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import matplotlib.cm as cm
except ImportError:
print("Please install sklearn, matplotlib, and scipy to visualize embeddings.")
test = Tr... |
#!/usr/bin/python3
"""
Creando mi propio decorador
y entendiendolos
¿ Qué es un decorador ?
- Un decorador básicamente toma una función,
le añade alguna funcionalidad y la retorna.
"""
# Ejemplo:
def funcion_decorador(funcion):
def wrapper():
print("llamando a mi funcion")
funcion()
... |
import numbers
import tensorflow as tf
def all_diffs(a, b):
""" Returns a tensor of all combinations of a - b.
Args:
a (2D tensor): A batch of vectors shaped (B1, F).
b (2D tensor): A batch of vectors shaped (B2, F).
Returns:
The matrix of all pairwise differences between all vec... |
##
# File: CARDTargetFeatureProviderTests.py
# Author: J. Westbrook
# Date: 11-Jun-2021
# Version: 0.001
#
# Update:
#
#
##
"""
Tests for utilities managing CARD target data.
"""
__docformat__ = "google en"
__author__ = "John Westbrook"
__email__ = "jwest@rcsb.rutgers.edu"
__license__ = "Apache 2.0"
import log... |
import numpy as np
from sortedcontainers import SortedList
from scipy.stats import multivariate_normal
class NaiveBayes:
#def __init__(self):
# pass
def fit(self, X, Y):
self.X = X
self.Y = set(Y)
self.Classes = set(Y)
self.Prior = {}
self.G = {}
# smoo... |
from eversource_scraper import (selenium_scraper, mysql_inserter)
__version__ = "0.1.0" |
"""
This file offers the methods to automatically retrieve the graph Pantoea rwandensis.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02-... |
powsimp(exp(y) * exp(z)) |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
# Modifications copyright (C) 2020 Zi-Yi Dou
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compli... |
# --*-- coding: utf-8 --*--
# --------------------------------------------------------------------------------
# Description:
# search_spider负责将搜索结果扔进redis队列,提供给page_spider消费
# 两步爬虫分离,实现分布式,弹性扩展
# DATE:
# 2018/02/01
# BY:
# xiaoshicae
# --------------------------------------------------------... |
{
'targets': [
{
'target_name': 're2',
'type': 'static_library',
'include_dirs': [
'../deps/re2',
],
'direct_dependent_settings': {
'include_dirs': [
'../deps/re2',
],
},
'sources': [
'../deps/re2/re2/bitmap256.h',
'../dep... |
# encoding: utf-8
"""
An application for IPython.
All top-level applications should use the classes in this module for
handling configuration and creating componenets.
The job of an :class:`Application` is to create the master configuration
object and then create the configurable objects, passing the config to them.
... |
settings_1_9_0 = """
# Only for cross building, 'os_build/arch_build' is the system that runs Conan
os_build: [Windows, WindowsStore, Linux, Macos, FreeBSD, SunOS]
arch_build: [x86, x86_64, ppc64le, ppc64, armv6, armv7, armv7hf, armv8, sparc, sparcv9, mips, mips64, avr, armv7s, armv7k]
# Only for building cross compil... |
#
# 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... |
# _*_ coding: utf-8 _*_
from argparse import ArgumentParser
import torch
from torchtext import data, datasets
from vocab import LocalVectors
from models import *
from torch.optim import SGD
from torch.utils.data import DataLoader
from ignite.engine import Events, create_supervised_trainer, create_supervised_evaluat... |
"""Base class for all the objects in SymPy"""
from collections import defaultdict
from itertools import chain, zip_longest
from .assumptions import BasicMeta, ManagedProperties
from .cache import cacheit
from .sympify import _sympify, sympify, SympifyError
from .compatibility import iterable, ordered, Mapping
from .si... |
import os
from typing import Dict
from dbnd import as_task, band, task
from dbnd._core.commands import log_artifact, log_metric
from dbnd._core.current import get_databand_run
from dbnd._core.tracking.tracking_store_file import read_task_metrics
from dbnd.testing.helpers_pytest import assert_run_task
from test_dbnd.t... |
# Copyright 2020 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.
import os
import sys
import unittest
import PRESUBMIT
# append the path of src/ to sys.path to import PRESUBMIT_test_mocks
SRC_IOS_WEB_VIEW_PATH = os.path... |
BASE_DOWNLOAD_URL = 'http://download.geonames.org/export/dump/'
def full_url(filename):
return BASE_DOWNLOAD_URL + filename
filename_config = {
'admin1CodesASCII.txt': {
'url': full_url('admin1CodesASCII.txt'),
},
'admin2Codes.txt': {
'url': full_url('admin2Codes.txt'),
},
'a... |
import pandas as pd
import numpy as np
import scipy
from sklearn import linear_model, cluster
from collections import defaultdict, Iterable
from itertools import chain, combinations
import operator
import psycopg2
import sys
import json
conn = psycopg2.connect("dbname='postgres' user='pbailis' host='localhost'")
cur ... |
# 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... |
from services.game_service import GameService
from test.mocks.mock_objects import MockEndgameService
def test_play_works_with_no_hand(default_user_data):
service = GameService(default_user_data, MockEndgameService())
response = service.play()
assert response is not None
assert len(service.hand()) == 2... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import subprocess
from dbnd import parameter
from dbnd._core.parameter.validators import NonEmptyString
from dbnd._core.run.databand_run import DatabandRun
from dbnd._core.settings import EngineConfig
from targets.values.version_value import VersionStr
class ContainerEngineConfig(EngineConfig):
require_submit = ... |
def selectionSort(array, n):
for i in range(n):
minimum = i
for j in range(i + 1, n):
# to sort in descending order, change > to < in this line
# select the minimum element in each loop
if array[j] < array[minimum]:
minimum = j
... |
from django.core.management.base import BaseCommand
from ksiazkaadresowa.models import Person
class Command(BaseCommand):
help = 'Moj tekst pomocy'
def add_arguments(self, parser):
parser.add_argument(
'--file',
dest='file',
nargs='?',
help='Log File',
... |
from copy import deepcopy
import numpy as np
import json
import os
import gym
from baselines import logger
from baselines.her.ddpg import DDPG
from baselines.cher.her import make_sample_her_transitions
DEFAULT_ENV_PARAMS = {
'FetchReach-v0': {
'n_cycles': 10,
},
}
DEFAULT_PARAMS = {
# env
... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class W3m(AutotoolsPackage):
"""
w3m is a text-based web browser as well as a pager like `mo... |
# Copyright 2018 Jigsaw Operations 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 or agreed to i... |
# ---------- LEARN TO PROGRAM 7 ----------
# ---------- DICTIONARIES ----------
# While lists organize data based on sequential indexes
# Dictionaries instead use key / value pairs.
# A key / value pair could be
# fName : "Derek" where fName is the key and "Derek" is
# the value
# Create a Dictionary about me
derek... |
"""Test converting an image to a pyramid.
"""
import numpy as np
import napari
points = np.random.randint(100, size=(50_000, 2))
with napari.gui_qt():
viewer = napari.view_points(points, face_color='red') |
#Here we define "x" global variable and assign a value to it
x=10
y=200
print('the value of x global variable is {0}'.format(x))
#Here define function "MyFunction", it takes no paraments
def MyFunction():
global y # this is the same global variable "y"
x=2 #This is a local variable, unrelated to "x" global ... |
""" Define PNP-Stokes related problems """
from dolfin import *
from ..tools import *
from .params_physical import *
import ufl
parameters["allow_extrapolation"] = True
parameters["refinement_algorithm"] = "plaza_with_parent_facets"
__all__ = ["PNPS","PNPProblem","StokesProblem","StokesProblemEqualOrder",
... |
# Copyright 2016 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... |
import multiprocessing
import os
import shutil
from pathlib import Path
from loguru import logger
from make_prg import io_utils
from make_prg.denovo_paths_reader import DenovoPathsDB
from make_prg.prg_builder import PrgBuilderCollection, PrgBuilder, LeafNotFoundException
from make_prg.utils import output_files_alread... |
# -*- coding: utf-8 -*-
#
# 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
#... |
"""
2048 game
Move and merge squares using arrow keys
Get a 2048-value tile to win
Author: Sandro Tan
Date: Aug 2019
Version: 1.0
"""
import GUI_2048
import random
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
# Directions, DO NOT MODIFY
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# Offsets for computing tile in... |
# -*- coding: utf-8 -*-
import argparse
import os
import sys
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import collections as mc
import matplotlib.pyplot as plt
from epynet import Network
sys.path.insert(0, os.path.join('..'))
from utils.graph_utils import get_nx_graph, get_sensitiv... |
import pytest
from homework import tasks
from homework.models import AnswerCrossCheck
pytestmark = [pytest.mark.django_db]
def test_crosschecks_are_created(question_dispatcher):
question_dispatcher()
assert AnswerCrossCheck.objects.count() == 2
def test_question_method_does_the_same(question):
questi... |
"""
This file is licensed under the terms of the Apache License, Version 2.0. See the LICENSE file in the root of this
repository for complete details.
"""
# -----------------------------------------------------------------------
# FILTER MANIFEST
# -------------------------------------------... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
from frappe.model.document import Document
class POSClosingEntryTaxes(Document):
pass |
import _plotly_utils.basevalidators
class SideValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="side", parent_name="histogram2d.colorbar.title", **kwargs
):
super(SideValidator, self).__init__(
plotly_name=plotly_name,
parent_... |
import os
bind = '0.0.0.0:5000'
accesslog = 'app.log'
access_log_format = \
'%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
raw_env = [
'GRAPH_CLIENT_ID=' + os.getenv('GRAPH_CLIENT_ID'),
'GRAPH_CLIENT_SECRET=' + os.getenv('GRAPH_CLIENT_SECRET')
] |
import datetime
import itertools
import math
import sys
import threading
import time
from collections import defaultdict
from functools import wraps
from typing import Optional, Union, Callable
from jina.enums import ProgressBarStatus
from .logger import JinaLogger
from .. import __windows__
from ..helper import color... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.