content stringlengths 5 1.05M |
|---|
import os
import numpy
from setuptools import find_packages
from distutils.core import setup
from distutils.extension import Extension
# from numpy.distutils.core import Extension
from Cython.Build import cythonize
def readme():
with open('README.md') as readme_file:
return readme_file.read()
# os.envir... |
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext as _
from .models import NamedCondition
class UserConditionFilter(SimpleListFilter):
"""Filters using computed dynamic conditions from DB"""
title = _("Condition")
parameter_name = 'user_condition'
def l... |
#To test an individual's use of a certain mineral, a researcher injects small amount of a radioactive form of that mineral into the person's bloodstream.
#The mineral remaining in the bloodstream is measured each day for several days.
#Suppose the amount of the mineral remaining in the bloodstream (in milligram... |
# Copyright 2018 AT&T Intellectual Property. All other 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... |
import pytest
from nicks_intervals.Bound import Bound, PART_OF_LEFT, PART_OF_RIGHT
from nicks_intervals.Interval import Interval
import nicks_intervals._operators as ops
def test_iInterval_contains_value():
a = Interval.closed(1.0, 2.0)
assert a.contains_value(0.9) is False
assert a.contains_value(1.0) ... |
from . import seqm
|
"""
Defines the online collaborators manager
"""
import datetime
from google.appengine.api import memcache
from greenday_core.constants import EventKind
from greenday_core.eventbus import publish_appevent
from .utils import retry_until_truthy
class OnlineCollaboratorsManager(object):
"""
Tracks the... |
# 1st solution
# O(2^n) time | O(n) space
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
# Sorting is really helpful, se we can avoid over counting easily
candidates.sort()
result = []
self.combine_sum_2(candida... |
"""
Property class definition.
"""
from weaviate.exceptions import UnexpectedStatusCodeException, RequestsConnectionError
from weaviate.schema.validate_schema import check_property
from weaviate.util import _get_dict_from_object
from weaviate.connect import Connection
class Property:
"""
Property class used t... |
import json
from BitsianPythonClient.Common.PageRequest import PageRequest
from BitsianPythonClient.Common.constant import REST_END_POINT, ORDER, METHOD, CANCEL, responsedata, page
from BitsianPythonClient.GetResponse import getResponse as s
from BitsianPythonClient.Order.OrderResponse import OrderResponse
from Bitsia... |
import sys
from task_list.console import Console
from task_list.app import TaskList
from task_list.router import Router
def main():
task_list = TaskList(Console(sys.stdin, sys.stdout), Router())
task_list.run()
if __name__ == "__main__":
main()
|
from PySide2.QtCore import QCoreApplication
from PySide2.QtWidgets import QDesktopWidget, QMessageBox
from ..ventana2.Ui import VentanaInicio
class Events:
def __init__(self):
self.boton_salir_login.clicked.connect(QCoreApplication.instance().quit)
self.boton_salir_register.clicked.connect(QCoreA... |
import os
import json
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from eval.eval_bm25_coliee2021 import read_label_file #ranking_eval
from retrieval.bm25_aggregate_paragraphs import sort_write_trec_output
from preprocessing.coliee21_task2_bm25 import ranking_eval
from analysis.compa... |
from __future__ import division
import pandas as pd
def invoke(config):
results_df = pd.read_csv(config['input_file_path'])
calculate_f1_scores(results_df)
if config['detailed'] == False:
return
print ""
calculate_top_f1(results_df, 3)
print ""
calculate_top_f1(results_df, 5)
... |
# Copyright 2020 The Kale 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 applicable law or agreed to in wri... |
#!/usr/bin/env python
#
# 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; version 2 of the License
#
# Author: Octavian Purdila <tavi@cs.pub.ro>
#
from __future__ import print_function
import ar... |
from _pycryptonight import cn_fast_hash, cn_slow_hash
|
# -*- coding: utf-8 -*-
# Copyright (c) 2019, TU Wien, Department of Geodesy and Geoinformation (GEO).
# All rights reserved.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY... |
# © Copyright 2020 HP Development Company, L.P.
# SPDX-License-Identifier: MIT
from my_connect import my_connect
import requests
import psycopg2.sql as sql
import pandas
from datetime import datetime, timedelta
import pytz
import tempfile
import os
connection = my_connect()
cursor = connection.cursor()
TABLE = "nyt_... |
import pandas as pd
import sys
import os
def clean_currency_val(value):
if isinstance(value, str):
return float(value.replace('.', '').replace(',', '.').replace(' ', '').replace('"','').replace("'",''))
return float(value)
def clean_currency(data, beg_col, end_col):
for col in data.columns[beg_co... |
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
dp = [0 for _ in range(len(triangle) + 1)]
for r in triangle[::-1]:
for i in range(len(r)):
dp[i] = r[i] + min(dp[i], dp[i + 1])
return dp[0]
|
import unittest
from leetcode_python.src.algorithms.tree.maximum_depth import MaximumDepth
from leetcode_python.src.algorithms.tree.node import Node
class TestMaximumDepth(unittest.TestCase):
def test_max_depth(self):
root = Node(2, Node(1, Node(4, Node(9, Node(12), Node(19)))), Node(4, Node(13, Node(78... |
#!/usr/bin/env python
"""The setup script."""
import importlib
from setuptools import setup
readme = ''
changes = ''
setup_requires = []
install_requires = [
'requests==2.22.0',
'eth-abi==2.1.0',
'pysha3==1.0.2',
'ecdsa==0.15',
'secp256k1==0.13.2',
'protobuf==3.11.3'
]
# Get the requirements... |
#:25
import traceback
from common import profile
from util import unpack_pstr, pack_pstr
from common.emailaccount import EmailAccount, localprefs_key
from AccountManager import NETWORK_FLAG
from prefs import localprefprop
SMTP_UPGRADING = True
import smtplib, re
import logging
log = logging.getLogger('s... |
import pytest
from mixer.backend.django import mixer
pytestmark = pytest.mark.django_db
class TestVote:
def test_model(self):
country_obj1 = mixer.blend('countries.Country', name='Israel Test Data')
country_obj2 = mixer.blend('countries.Country', name='Russia Test Data')
country_obj3 = mi... |
def read_data():
with open ('input.txt') as f:
data = f.readlines()
return [d.strip() for d in data]
def write_data(data):
with open('output.txt','w') as f:
for d in data:
f.write(str(d)+'\n')
###
def parser(line):
from simpleeval import simple_eval
import simpleeval
import ast
import operator
s = s... |
from unittest import TestCase, main
from src.crawling import Browser, get_title_parsed, get_page_parsed, get_remove_hwa
driver_location = "../../../executable/web_drivers/chromedriver_mac64/chromedriver"
class TestCrawling(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def ... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 15:41:34 2019
/**
* 加密解密QQ消息的工具类. QQ消息的加密算法是一个16次的迭代过程,并且是反馈的,每一个加密单元是8字节,输出也是8字节,密钥是16字节
* 我们以prePlain表示前一个明文块,plain表示当前明文块,crypt表示当前明文块加密得到的密文块,preCrypt表示前一个密文块
* f表示加密算法,d表示解密算法 那么从plain得到crypt的过程是: crypt = f(plain ˆ preCrypt) ˆ
* prePlain 所以,从crypt得到pl... |
"""
# Copyright 2022 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
__author__ = 'wei'
class util:
def __init__(self):
self.comdict={}
'''
获取列表的长为m的组合
'''
def getcombination(self,l,m):
if l is None or (type(l) is not list and type(l) is not tuple):
return None
ll=len(l)
if ll == 0 or m==0:
return ()
i... |
# Generated by Django 3.2.7 on 2022-06-03 02:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20220326_0122'),
]
operations = [
migrations.RenameField(
model_name='animal',
old_name='type',
... |
"""The wrapper for the NationStates API that allows control of nations
@author Jacob Kerr"""
import requests
from bs4 import BeautifulSoup
from bs4.element import Tag
BASEURL = 'https://www.nationstates.net/cgi-bin/api.cgi'
"""The base url for all API requests"""
USERAGENT = 'github.com/jakejack13'
"""The UserAgent... |
import random
import time
password = ""
attempted_password = ""
list_of_char = 0123456789abcdefghijklmnopqrstuvwxyz
for letter in range(0, random,randint(10000,25000)):
password += list _of _char[random,randint(0,61)]
def timeit(func):
def wrapper(*args, **kwargs):
start = time.time()
result =... |
""" CIFAR10 Classification - Training Code."""
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torchvision import datasets, models, transforms
import numpy as np
import wandb
from tqdm import tqdm
from utils import parse_args
DATA_DIR = "/home/sanil/dee... |
from sympy.abc import x, y, z
from algebreb.expresiones.polinomios import polinomio_coeficientes_aleatorios
p1 = polinomio_coeficientes_aleatorios(2, [x, y], 'ZZ', 1, 14)
print(p1)
print(p1.total_degree())
p2 = polinomio_coeficientes_aleatorios(5, [x], 'ZZ', -10, 10)
print(p2)
print(p2.total_degree())
p3 = polinomio... |
import sys
import networkx as nx
import numpy as np
from math import lgamma
def write_gph(dag, idx2names, filename):
with open(filename, 'w') as f:
for edge in dag.edges():
f.write("{}, {}\n".format(idx2names[edge[0]], idx2names[edge[1]]))
def get_idx2names(line):
idx2names = {}
name... |
# Copyright 2021 Xanadu Quantum Technologies 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 law or agre... |
import streamlit as st
import app1
import style
import ca
import pix2pix
PAGES = {
"Deep Dream": app1 ,
"Style Transfer": style,
"Cartoonization" : ca ,
"Pix2Pix" : pix2pix
}
st.sidebar.title('SIP Project ')
selection = st.sidebar.radio("Go to", list(PAGES.keys()))
page = PAGES[selection]
page.app() |
try:
import sys
import string
import base64
import hashlib
from operator import itemgetter
from os.path import basename, isfile
from datetime import datetime
from django.db import models
from django.db.models import Q
from django.db import connection
from models import WaCont... |
#Code by Andrew DeVoss, viewed by Michael Naguib
import random
import copy
class Delinquent():
def __init__(self, biteString):
self.biteString = biteString
self.choice = biteString[len(biteString) - 1]
self.characteristics = biteString[:(len(biteString) - 1)]
self.score = 0
s... |
from selenium import webdriver
from bs4 import BeautifulSoup
from time import sleep
from file_io import *
import textwrap
import requests
from selenium.webdriver.common.keys import Keys
print('Thank you for using Simple Quora Backup')
print('This will backup your ANSWERS to a text file in the simplest form, ')
print(... |
from rest_framework import serializers
from api.models import User, Dept
class UserSerializers(serializers.ModelSerializer):
part_name = serializers.SerializerMethodField()
class Meta:
model = User # 定义关联的Model
fields = ('id', 'account', 'name', 'password', 'phone', 'email', 'dept', 'part_na... |
from embed.common import APIResponse
class Price(APIResponse):
"""
Handles all queries for Price
"""
def __init__(self, api_session):
super(Price, self).__init__()
self.base_url = f"{api_session.base_url}/api/{api_session.api_version}/"
self.token = api_session.token
s... |
import torch
from horcorr import HorCorrFunction
def profile():
batch = 8
height = 128
width = 256
n_windows = 64
dim = 128
device = torch.device('cuda:0')
inp0 = torch.empty((batch, dim, height, width + n_windows - 1), dtype=torch.float32, device=device)
inp1 = torch.empty((batch, di... |
from functools import partial
from string import ascii_letters, digits
from PyQt5.Qsci import QsciScintilla, QsciLexerCustom
from PyQt5.QtGui import QFontDatabase, QFont, QColor
from ...sieve import lex
from .styles import Style
class SieveLexer(QsciLexerCustom):
_TOKEN_STYLES = {
'COMMENT': Style.Comme... |
#!/usr/bin/env python
"""
--- Day 2: Corruption Checksum ---
As you walk through the door, a glowing humanoid shape yells in your direction. "You there! Your state appears to be idle. Come help us repair the corruption in this spreadsheet - if we take another millisecond, we'll have to display an hourglass cursor!"
T... |
"""
Improvements on Pyte.
"""
from __future__ import unicode_literals
from pyte.streams import Stream
from pyte.escape import NEL
from pyte import ctrl
from collections import defaultdict
__all__ = (
'BetterStream',
)
class BetterStream(Stream):
"""
Extension to the Pyte `Stream` class that also handles ... |
"""Regularni izrazi kao beskontekstni jezik.
Izgrađeni su od osnovnih (inicijalnih) regularnih izraza:
/0 prazan jezik
/1 jezik koji se sastoji samo od prazne riječi
x jezik koji se sastoji od jednoslovne riječi x
- specijalni znakovi zahtijevaju escaping pomoću /
pomoću operatora:
| ... |
# Copyright 2020 Red Hat
#
# 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 ... |
# Copyright 2022 @ReneFreingruber
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
from argparse import ArgumentParser
from chmTools.module import AppError, getExportedData, wrapMain
from dataclasses import dataclass, field
from functools import cached_property
import parse
import pandas as pd
from pathlib import Path
ENGLISH_TO_CZECH_DATASET = {
"random-s-100-angular": "100 000 náhodných ... |
from settings_base import *
PORT = 9083
SERVER_NAME = 'http://pitomba.org'
LOG_FILENAME = 'libra-app.log'
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
filename=LOG_FILENAME,
level=logging.WARNING)
|
from granite.utils.functional import fwd
properties = [
('binary_size', fwd),
]
|
'''
Created on Jun 10, 2014
@author: gollan
'''
import sys
from os.path import curdir, split
p = sys.path[0]
p = split(p)[0]
if not p:
p = curdir
sys.path.insert(1, p)
try:
import cPickle as pickle
except ImportError:
import pickle
from PyQt4 import QtGui
from gui.vumv_ui import Ui_VumV
class VumV(QtG... |
#!/usr/bin/env python
from __future__ import print_function
import logging
try:
from pathlib import PurePath
import subprocess
except ImportError:
from pathlib2 import PurePath
import subprocess32 as subprocess
import os
import sys
from typing import Optional, Iterable, List, Text
from poopbox.sync i... |
from unimodals.common_models import MLP, VGG16, Linear, MaxOut_MLP
from robustness.all_in_one import general_train, general_test
from get_data_robust import get_dataloader, get_dataloader_robust
from fusions.common_fusions import Concat
from training_structures.Simple_Late_Fusion import train, test
import torch
import ... |
from free_proxy import FreeProxy
import os
from proxyscrape import create_collector
from datetime import datetime
def get_now_str():
now = datetime.now()
return now.strftime("%Y-%m-%d")
from db_manager import DB
class ScrapeFreeProxies():
def __init__(self):
self.result_dir = os.path.join(os.get... |
runas_connection = automationassets.get_automation_connection("AzureRunAsConnection")
bt=get_automation_runas_token()
sub=str(runas_connection["SubscriptionId"])
headers = {'Authorization': 'Bearer ' + bt, 'Content-Type': 'application/json'}
crg=None
crf="azurerm"
cde=False
az2tfmess="# File generated by az2tf s... |
from laserforce.leaderboard import Leaderboard
from laserforce.objects import Player, Summary, GameType, LeaderboardPosition, LeaderboardType
from laserforce import helpers
from typing import List
import requests
# TODO: async
class Session:
def get_player(self, id) -> Player:
"""
Grabs stats from... |
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
class SentenceSentimentClassifier(nn.Module):
def __init__(self, idx2word, sentiment_categories, settings):
super(SentenceSentimentClassifier, self).__init__()
self.sentiment_categories = se... |
#!/usr/bin/env python
# coding: utf-8
import threading
import socket
from threading import Thread
import re
import time
import log_formatter as lf
import sys
import json
from math import *
import numpy as np
import os.path as path
import underworlds
from underworlds.helpers.geometry import get_bounding_box_for_node
... |
#
# Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates
#
# 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 ap... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 目的: 出力のプログラムを学ぶためのサンプルコード
# Hello!と表示する
print("Hello!") |
import numpy as np
import math
def UnpatchType(IndexType, domain, patchSize, patchOverlap, actualSize):
iCorner = [0, 0, 0]
dOverlap = np.round(np.multiply(patchSize, patchOverlap)) # only 2 elements
dNotOverlap = [patchSize[0] - dOverlap[0], patchSize[1] - dOverlap[1]]
paddedSize = [int(math.ceil((... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 20:24:50 2019
@author: GS-1854
"""
import cv2, os
def face_database(directory, user_name):
cascPath = 'haarcascade_frontalface_default.xml'
path = os.path.join(directory, user_name)
faceCascade = cv2.CascadeClassifier(cascPath)
mycamera ... |
class Solution:
def totalMoney(self, n: int) -> int:
acc = 0
whole = n // 7
mod = n % 7
for i in range(whole):
acc += 28 + 7*i
if whole == 0:
i = 0
for j in range(mod):
i += 1
acc += i
else:
... |
import os
import torch
import numpy as np
from perceiver_io.language_perceiver import LanguagePerceiver
from utils.bytes_tokenizer import BytesTokenizer
def pad(max_sequence_length: int, inputs, input_mask, pad_token):
input_len = inputs.shape[1]
assert input_len <= max_sequence_length
pad_len = max_seq... |
import torch
import torch.nn as nn
from dvmvs.utils import freeze_batchnorm
def down_conv_layer(input_channels, output_channels, kernel_size):
return nn.Sequential(
nn.Conv2d(
input_channels,
output_channels,
kernel_size,
padding=(kernel_size - 1) // 2,
... |
#!/usr/bin/env python3
from unicodedata import normalize
def remover_acentos(txt):
if isinstance(txt, str):
return normalize('NFKD', str(txt)).encode('ASCII', 'ignore').decode('ASCII').strip().lower()
else:
ret = []
for t in txt:
ret.append(normalize('NFKD', str(t)).encode(... |
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Hyper-parameters
input_size = 784 # 28x28
hidden_size = 500
num_classes = 10
n... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torchvision.transforms.functional import to_tensor, to_pil_image
from captcha.image import ImageCaptcha
from tqdm import tqdm
import random
import numpy as np
from collections import Order... |
from shapely.geometry import MultiPoint
def get_convex_hull_coordinates(gtfs):
"""
Parameters
----------
gtfs: gtfs.GTFS
Returns
-------
lons: list
of floats
lats: list
of floats
"""
lons, lats = _get_stop_lat_lons(gtfs)
lon_lats = list(zip(lons, lats))
... |
# Copyright 2008-2018 Univa 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
from datetime import datetime
from marquez_airflow import DAG
from airflow.operators.postgres_operator import PostgresOperator
from airflow.utils.dates import days_ago
default_args = {
'owner': 'datascience',
'depends_on_past': False,
'start_date': days_ago(1),
'email_on_failure': False,
'email_on_... |
from ai.activations import get_activation_function, threshold_activation
import json
import numpy as np
import settings
class Neural_Network(object):
"""
Implementation of a neural network.
"""
def __init__(self, weight_matrices):
self._weight_matrices = weight_matrices
@classmethod
d... |
from __future__ import unicode_literals
import logging
from django.utils import six
from django.utils.six.moves.urllib.parse import quote as urllib_quote, urlparse
from djblets.util.filesystem import is_exe_in_path
from reviewboard.diffviewer.parser import DiffParser, DiffParserError
from reviewboard.scmtools.core i... |
# -*- coding: utf-8 -*-
from mock import Mock
from unittest import TestCase
from alf.auth import BearerTokenAuth
class TestBearerTokenAuth(TestCase):
def setUp(self):
self.request = Mock()
self.request.headers = {}
self.auth = BearerTokenAuth('token')
def test_should_add_authorizat... |
__all__ = ["BorderStyle", "Style", "Styles"]
from Pyflai.style.style.BorderStyle import *
from Pyflai.style.style.Style import *
from Pyflai.style.style.Styles import *
|
from flask import render_template, redirect, url_for
from mlf_core_website.basic import bp
@bp.route('/')
def root():
return redirect((url_for('basic.index')))
@bp.route('/index')
def index():
return render_template('index.html')
@bp.route('/templates')
def dev():
return render_template('templates.ht... |
import json
def getJsonConfiguration(configurationPath):
configuration = {}
with open(configurationPath, "r") as f:
configurationStr = f.read()
configuration = json.loads(configurationStr)
return configuration
|
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
nx=41
ny=41
dataU=np.genfromtxt("solBurgersU.dat",delimiter=",")
dataV=np.genfromtxt("solBurgersV.dat",delimiter=",")
dataU=np.delete(dataU,-1,1)
dataV=np.delete(dataV,-1,1)
x=np.linspace(0,2,nx)
y=np.l... |
"""Document layouts for Bokeh widgets."""
# Standard impots
from abc import abstractmethod
# External imports
from bokeh.models import ColumnDataSource, callbacks, widgets
# Local package imports
from lhrhost.dashboard import DocumentModel
from lhrhost.util.interfaces import InterfaceClass
class Button(DocumentMod... |
from .player_state import PlayerState
from ..squares import Property, Street
import time
class Player(object):
'''
Holds the PlayerState and a player AI (an object
derived from PlayerAIBase).
'''
def __init__(self, ai, player_number, board):
'''
The 'constructor'.
'''
... |
__all__ = [
'Sparse',
'point_probe',
'Chunky',
]
from .chunky import (
Sparse,
point_probe
)
# compatibility aliases:
Chunky = Sparse
|
import threading
import time
g_num = 0
def work1(num):
global g_num
for i in range(num):
if mutex.acquire(True):
g_num += 1
mutex.release()
print('---in work1,g_num in %d---' % g_num)
def work2(num):
global g_num
for i in range(num):
if mutex.acquire(True... |
import config
def module_test_print(var_input, var_inmed, var_ouput):
for var in (var_input, var_inmed, var_ouput):
print('*'*10)
for key, value in var.items():
print('#', key)
print(value)
def UniformSample(users, dataset):
"""
the original impliment o... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Test_Data.csv')
X = dataset.iloc[:,4:6].values
y = dataset.iloc[:,8].values
# Encoding categorical data
# Encoding the Independent Variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = Labe... |
# Copyright 2021 The Feast 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
# -*- coding: UTF-8 -*-
#!/usr/bin/python
'''Spinning cube wxPython and PyOpenGL app'''
import wx
from wx.glcanvas import *
#import OpenGL
#from OpenGL import GLUT
#from OpenGL import GLU
#from OpenGL import GL
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from MenuCAIDViewer import Me... |
# 2049
#
# https://adventofcode.com/2018/day/12
import sys
import numpy as np
import re
from collections import Counter
import pprint
def getCount(arow, initial):
length = len(arow)
final = list(arow)
inputLength = len(initial)
sum = 0
for col in range(length):
if final[col] == '#':
... |
from datetime import timedelta
import requests
from django.test.utils import override_settings
from django.utils.timezone import now
from moneyed.classes import Money
from bluebottle.funding.tests.factories import FundingFactory, DonationFactory
from bluebottle.funding_pledge.tests.factories import PledgePaymentFacto... |
from django.contrib.gis.geos import Point
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "E08000029"
addresses_name = "local.2019-05-02/Version 1/Democracy_Club__02May2019soli.tsv"
stations_name = "local.20... |
"""This serves as a main function to run a worker."""
from qip.distributed.proto import *
from qip.distributed.proto.conversion import *
from qip.distributed.worker.worker_backends import SocketServerBackend
from qip.distributed.worker.worker_logger import WorkerLogger, PrintLogger
from qip.distributed.formatsock impor... |
import io
import pickle
import uuid
import hashlib
import sys
from pathlib import Path
from . import utils
class RestrictedUnpickler(pickle.Unpickler):
"""[An overriding of pickle loading to only allow ProtectedFile type]
"""
def find_class(self, module, name):
# Only allow safe classes from built... |
# from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from tethys_sdk.gizmos import SelectInput, RangeSlider
from django.contrib.auth.models import User
from django.http import JsonResponse
from .app import Earthobserver as App
from .gfsworkflow import run_gfs_workflow
from .o... |
#!/usr/bin/python2.7
# coding: utf-8
import xlrd
import os, glob
import re # exoressions régulières
# import numpy
import matplotlib.pyplot as plt
# from samba import strcasecmp_m
from operator import itemgetter # pour trier les années
CODE = 0; ANNEE = 1; SEXE = 2; AGE = 3; NB_MORTS = 4
def ajouterDonneesFichier( n... |
from PIL import Image # type: ignore
from ..windows import Window
from .base import Display
class WaveshareEpdDisplay(Display):
"""Waveshare EPD display - Renders an image onto a waveshare epd e-ink display.
Uses the epd library provided by waveshare to render an image to the display.
"""
def __in... |
import numpy as np
import math
import networkx as nx
import matplotlib.pyplot as plt
# This file is to initialize all the variables used in HyperType Model
####################################################################################################
#All Functions are below:
####################################... |
from datetime import datetime
from models.base.EntityBase import EntityBase
from infrastructure.json.BaseConverter import BaseConverter
@BaseConverter.register
class DataOperationJobExecutionIntegrationEventBase(EntityBase):
def __init__(self,
DataOperationJobExecutionIntegrationId: int = None,
... |
__author__ = 'ericpark'
class Card(object):
"""Represents a standard playing card.
Attributes:
suit: integer 0-3
rank: integer 1-13
"""
suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"]
rank_names = ["Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.