text stringlengths 2 999k |
|---|
class Solution:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return len(set(zip(s,t)))==len(set(s))==len(set(t))
|
"""Google Cloud Speech API sample application using the REST API for batch
processing."""
import argparse
import base64
import json
from googleapiclient import discovery
import httplib2
from oauth2client.client import GoogleCredentials
DISCOVERY_URL = ('https://{api}.googleapis.com/$discovery/rest?'
... |
import xlsxwriter
import os
import re
import pandas as pd
from bs4 import BeautifulSoup
import urllib3
import matplotlib.pyplot as plt
#import requests
#import glob
#import numpy as np
#import xml.etree.ElementTree as ET
#import urllib.request
#from collections import Counter
#from bioservices import UniProt
#import ... |
import networkx as nxvisited
import re
import networkx.classes.function as function
import networkx.algorithms.connectivity.cuts as cuts
import networkx as nx
import pandas as pd
def get_dist(ref_s, ref_t, max_dist):
s = ref_s.split("_")[-1]
t = ref_t.split("_")[-1]
return min(abs(int(s) - int(t)), abs(ab... |
from google.cloud import firestore
db = firestore.Client()
def get_url_from_query(slug):
"""An end user sends a url ex: dannyrosen.net/word where 'word' is a slug. The app queries the link collection for the document containing the slug and returns the url"""
links = db.collection(u'links')
query_ref = l... |
import os
import os.path
import csv
import operator
import itertools
import makepaths
import taz_files
import od_matrix_analysis
from pyOTPA import trip_analysis
TAG_GRAPH = "REPLACE_GRAPH_NAME"
TAG_RUN_NAME = "REPLACE_RUN_NAME"
TAG_RESULTS_BASE_PATH = "REPLACE_RESULTS_BASE_PATH"
TAG_GRAPHS_PATH = "REPLACE_GRAPHS_PAT... |
from sklearn.model_selection import *
import wandb
import nltk
from nltk.stem.porter import *
from torch.nn import *
from torch.optim import *
import numpy as np
import pandas as pd
import torch
import torchvision
import random
from tqdm import *
from torch.utils.data import Dataset, DataLoader
stemmer = PorterStemmer(... |
import pyodbc
from typing import Dict, List, Any, Union, Hashable, Tuple
import yaml
import db_configuration
class DatabaseConnectionHelper(object):
def __init__(self, db_local):
"""
Initializes the class
:param db_local:
:return
"""
self.db_local = db_local
... |
# Copyright 2020 The FedLearner 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... |
# 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 torch
from torch.utils import data
import numpy as np
from functools import reduce
from egg.zoo.objects_game.util import compute_binomia... |
# Find the Most Competitive Subsequence: https://leetcode.com/problems/find-the-most-competitive-subsequence/
# Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.
# An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) ele... |
class TrieNode:
def __init__(self, isLeaf):
self.isLeaf = isLeaf
self.next = {}
def insert(self, val, isLeaf):
self.next[val] = TrieNode(isLeaf)
return self.next[val]
class Trie:
def __init__(self):
self.root = TrieNode(self, isLeaf)
def add_word(self, new_word):
i = ... |
import os
import pandas as pd
import torch
import sys
sys.path.insert(0, "/nfs/Meta-Aug/")
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
from transformers import get_linear_schedule_with_warmup
from transformers.optimization import AdamW
from transformers import BertModel
from transformer... |
#!/usr/bin/env python3 -u
# 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.
"""
Translate raw text with a trained model. Batches data on-the-fly.
"""
from collections import namedtuple
import ... |
# Generated by Django 3.1.3 on 2020-11-23 04:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('instagram', '0013_auto_20201123_0707'),
]
operations = [
migrations.RenameField(
model_name='profile',
old_name='profile_ima... |
# -*- coding: utf-8 -*-
"""Package configuration.
Copyright (c) 2016-2019 Cisco and/or its affiliates.
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 limit... |
from json import JSONEncoder
import json
from iip import Serializer
import MyConnMachineIn
class MyConnMachineInSerializer(Serializer):
"""JSON transport serializer for MyConnMachineIn.
Generated by: EASy-Producer."""
class MyConnMachineInEncoder(JSONEncoder):
"""JSON encoder class for MyCo... |
"""SCons.Node
The Node package for the SCons software construction utility.
This is, in many ways, the heart of SCons.
A Node is where we encapsulate all of the dependency information about
any thing that SCons can build, or about any thing which SCons can use
to build some other thing. The canonical "thing," of co... |
print('''Crie um programa onde o usuário possa digitar cinco
valores numéricos e cadastre-os em uma lista,
já na posição correta de inserção(sem usar o sort()).
No final, mostre a lista ordenada na tela.''')
li = []
for c in range(1, 6, 1):
no = 1
valor = int(input(f'Digite o {c}º valor: '))
if c == 1:
... |
"""
General helper functions aiding in the boostrapping of this library.
"""
# pylint: disable = redefined-outer-name, too-few-public-methods
import argparse
import logging
import os
import sys
from pathlib import Path
from typing import List, Type
import moderngl
from moderngl_window.context.base import... |
"""
Components/Spinner
==================
.. rubric:: Circular progress indicator in Google's Material Design.
Usage
-----
.. code-block:: python
from kivy.lang import Builder
from kivymd.app import MDApp
KV = '''
Screen:
MDSpinner:
size_hint: None, None
size: dp(4... |
from my_app import db
class Console(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
year = db.Column(db.Integer)
price = db.Column(db.Float(asdecimal=True))
status = db.Column(db.String(100))
numberGames = db.Column(db.Integer)
def __init__(sel... |
""" This module contains algorithms for the sparsification, i.e. edge filtering, of networks. The methods are described in detail in the publication
` Structure-Preserving Sparsification of Social Networks` at http://arxiv.org/abs/1505.00564
"""
__author__ = "Gerd Lindner"
from _NetworKit import ChibaNishizekiTriang... |
# All content Copyright (C) 2018 Genomics plc
from wecall.bamutils.read_sequence import FORWARD_GOOD_READ
from wecall.genomics.reference_chromosome import DEFAULT_CHROM
from wecall.genomics.variant import Variant
from wecall_test_drivers.base_test import BaseTest
from wecall_test_drivers.svc_driver import SVCDriver
c... |
"""
Menu-driven login system
Contribution - Griatch 2011
This is an alternative login system for Evennia, using the
contrib.menusystem module. As opposed to the default system it doesn't
use emails for authentication and also don't auto-creates a Character
with the same name as the Player (instead assuming some sort... |
# test ellipses in slices
class foo:
def __getitem__(self,id):
print id
a = foo()
print a[...]
|
from scannerpy import Database
db = Database(workers=['ocean.pdl.local.cmu.edu:15559', 'crissy.pdl.local.cmu.edu:15559'])
|
from django.contrib.gis import admin
from .models import Ways
admin.site.register(Ways, admin.OSMGeoAdmin)
|
# Generated by Django 2.0 on 2019-04-17 13:02
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import swapper
class Migration(migrations.Migration):
initial = True
dependencies = [
swapper.dependency('dataframe_store', 'Label'),
]
op... |
# Copyright 2016-2017 Capital One Services, 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 ... |
import subprocess
import fnmatch
import os
try:
import netifaces
def network_interface_should_exist(name):
if name not in netifaces.interfaces():
raise Exception('Network interface {} not found.'.format(name))
def network_interface_should_be_up(name):
proc = subprocess.Popen([... |
'''
This group of tasks deals with the life cycle of any terraform deployment.
'''
import invoke
import glob
import os
import os.path
import sys
def iac_path(context):
'''
Returns the path of the deployment code inside this repository.
:param context: PyInvoke context
:return: path of the deployment code
'... |
import sys
sys.path.append('../implementations/')
from implementations.cars import cars
print(cars)
cars.reverse() # reverse order list
print(cars) |
"""Generate fine-grained dependencies for AST nodes, for use in the daemon mode.
Dependencies are stored in a map from *triggers* to *sets of affected locations*.
A trigger is a string that represents a program property that has changed, such
as the signature of a specific function. Triggers are written as '<...>' (a... |
import os,sys
import csv
lib_path = os.path.abspath(os.path.join('../../client'))
sys.path.append(lib_path)
from config import *
import random
from random import randint
class MicroBenchmark:
def __init__(self, lock_type = SHARED_LOCK, max_lock_id = 100000, server_number = 10, threads_per_server = 2):
self... |
import unittest
import pandas as pd
import numpy as np
from ..timeseries import TimeSeries
class TimeSeriesTestCase(unittest.TestCase):
times = pd.date_range('20130101', '20130110')
pd_series1 = pd.Series(range(10), index=times)
pd_series2 = pd.Series(range(5, 15), index=times)
pd_series3 = pd.Serie... |
""" A submodel that uses Dynamic Flux Balance Analysis (dFBA) to model a set of reactions
:Author: Yin Hoon Chew <yinhoon.chew@mssm.edu>
:Author: Arthur Goldberg <Arthur.Goldberg@mssm.edu>
:Date: 2020-07-29
:Copyright: 2016-2020, Karr Lab
:License: MIT
"""
import collections
import conv_opt
import copy
import enum
im... |
# Copyright (c) 2013 Ondrej Kipila <ok100 at openmailbox dot org>
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar. See the COPYING file for more details.
"""Metadata-related code."""
import os... |
class Node:
"""Create a Node object"""
def __init__(self, val, next=None):
"""Constructor for the Node object"""
self.val = val
self._next = next
def __repr__(self):
return '{val}'.format(val=self.val)
def __str__(self):
return self.__repr__
|
#/usr/bin/env python
# -*- coding: utf-8 -*-
def insertionsort(IN): # fonksiyon oluştutduk
for i in range(1, len(IN)): # dizinin uzunluğu kadar döngüye soktuk
key = IN[i] # anahtar olarak yani bakılacak sayı olarak dizinin 0 değil 1. indexsini aldık
j = i - 1 # j dediğimiz şey 0. index oldu her ... |
# -*- coding: utf-8 -*-
# pylint: disable=E1101,E1103,W0232
from datetime import datetime, timedelta, time
from pandas.compat import range, lrange, lzip, u, zip, PY3
import operator
import re
import nose
import warnings
import os
import numpy as np
from pandas import (period_range, date_range, Categorical, Series,
... |
import numpy as np
import pandas as pd
from sklearn.metrics import (make_scorer, f1_score, precision_score,
recall_score, confusion_matrix)
from sklearn.model_selection import RandomizedSearchCV
def randomized_hyperparameter_search(X_train, y_train, X_val, y_val,
... |
from django.contrib import admin
from consent.models import PersonalDetail, EducationDetail, CGPA, \
UserConsent, UserDataFields, ConsentDeadline, FieldOrder
admin.site.register(PersonalDetail)
admin.site.register(EducationDetail)
admin.site.register(CGPA)
admin.site.register(UserConsent)
admin.site.register(UserData... |
from django.db import models
from django.core.cache import cache
from django.utils.translation import ugettext_lazy as _
from mezzanine.core.models import Slugged
try:
from mptt.models import MPTTModel, TreeForeignKey
class BaseBlockCategory(MPTTModel, Slugged):
"""Base Category (MPTT tree).
... |
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_library.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. A... |
"""LISC setup script."""
import os
from setuptools import setup, find_packages
# Get the current version number from inside the module
with open(os.path.join('lisc', 'version.py')) as version_file:
exec(version_file.read())
# Load the long description from the README
with open('README.rst') as readme_file:
l... |
import concurrent.futures
import pandas as pd
from equities import static as STATIC
from solaris.api import Client as SolarisClient
from pytrends.request import TrendReq as GoogleTrendClient
import yfinance as YahooFinanceClient
__version__ = STATIC.__version__
__author__ = STATIC.__author__
class Client(object):
... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Building()
result.template = "object/building/poi/shared_tatooine_tuskenbantha_medium.iff"
result.attribute_templ... |
# Copyright 2017 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 numpy as np
from . import core
class Conv2D(core.Layer):
def __init__(self, filter_shape, strides=1, padding="SAME",
filter_init=lambda shp: np.random.normal(scale = 0.1, size = shp),
l2reg_lambda=0.0, channels_first=True):
""" 2 Dimensional convolutional layer, ex... |
# Copyright 2020, The TensorFlow 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 t... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# Packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init import * # noqa
# -----------------------------------------... |
""" Transformer in Transformer (TNT) in PyTorch
A PyTorch implement of TNT as described in
'Transformer in Transformer' - https://arxiv.org/abs/2103.00112
The official mindspore code is released and available at
https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT
"""
import math
import torch
i... |
/usr/local/python3/lib/python3.7/posixpath.py |
import os
import argparse
from .shared import glob_paths_dirs
from . import read_stdin_text
def main():
parser = argparse.ArgumentParser(description='prints file extension statistics')
parser.add_argument("path", nargs="*", help="paths")
parser.add_argument('-s', '--short', action='store_true')
args =... |
# -*- coding: utf-8 -*-
## @file testsuite/resources/pyModScript.py
## @date feb. 2017
## @author PhRG - opticalp.fr
##
## Test the python module
#
# Copyright (c) 2017 Ph. Renaud-Goud / Opticalp
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated doc... |
# Copyright (c) 2015, VMRaid Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import vmraid
import sys
from six.moves import html_parser as HTMLParser
import smtplib, quopri, json
from vmraid import msgprint, _, safe_decode, safe_encode, enqueue
from vmraid... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
from model.util import ls, Options
def set_theme(console, command):
"""Controls the logic surrounding the set_theme.sh fakescript
in the game
:param console: The console object that is responsible for the fake console
:param command: The command that has been entered
"""
if command.split("/")... |
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Output, Input, State
from apps import chorus_dt
from apps import odrive
from apps import osfi
from app import app
from utils.organization_chart import oc
from utils.texts impor... |
#eval(expression, globals=None, locals=None)
eval('print("ABC")')
a = 100
eval('print(a)', globals(), locals())
|
from src.utils import reader_util
from src.content.translation import Translation
# import load_from_file, load_json_from_file, load_kvp_from_file
class AppData:
arabic = reader_util.load_from_file("content/arabic/quran-uthmani.txt", "ar")
translation_yusuf_ali = Translation("Yusuf Ali", "en", "content/trans... |
from sqlobject import *
from sqlobject.tests.dbtest import *
class EmptyClass(SQLObject):
pass
def test_empty():
if not supports('emptyTable'):
return
setupClass(EmptyClass)
e1 = EmptyClass()
e2 = EmptyClass()
assert e1 != e2
assert e1.id != e2.id
assert e1 in list(EmptyClass.... |
from kelvin.fci import fci
from kelvin.ccsd import ccsd
from kelvin.ueg_system import ueg_system
import numpy
import time
T = 0.5
mu = 7.0
L = 1.942
norb = 33
cut = 30.0
damp = 0.0
mi = 50
ti = time.time()
ueg = ueg_system(T,L,cut,mu=mu,norb=norb,orbtype='u')
print('Norb: {}'.format(len(ueg.basis.basis)))
print('L: {:... |
import copy
from services.switcher_service import SwitcherService
from payloads.home import MODAL_REQUEST, APP_HOME
from utils.slack_payload_util import populate_selection
from utils.switcher_util import get_environment_keyval
def on_home_opened(client, event, logger):
try:
client.views_publish(
user_id =... |
# -*- coding: utf-8 -*-
from multiprocessing import Pool
class ResultSet(object):
def __init__(self, function_name, function_result):
"""ResultSet initialization, standarises output
Args:
function_name (string): The name of the function
function_result (list): Results
... |
import socket
import json
import time
from matplotlib import pyplot as plt
from robot import Robot
from path import Path
from pid import PIDAngle
from datetime import datetime
def restartRobot():
data = conn.recv(1024)
recData = json.loads(data.decode('utf-8'))
robot.setCoord(recData['robot0']['x'],recData['robot0... |
#!/usr/bin/env python2.7
"""A test case update script.
This script is a utility to update LLVM 'llc' based test cases with new
FileCheck patterns. It can either update all of the tests in the file or
a single test function.
"""
import argparse
import os # Used to advertise this file's name ("autogenerated_no... |
#!/usr/bin/env python3
#
# Copyright 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Print the status of factory-related repositories.
This is used to generate the file containing the status of each repositorie... |
import unittest
import numpy as np
from eventsearch.signals import SingleSignal, SmoothedSignal
from eventsearch.utils import Smoother
from .utils import TemporaryFolder
class TestSingleSingal(unittest.TestCase):
def test_create_object(self):
t = np.linspace(0, 5, 10)
y = t ** 2
test = ... |
"""Device handler for centralite ias sensors."""
from zigpy.profiles import zha
from zigpy.quirks import CustomDevice
from zigpy.zcl.clusters.general import Basic, Identify, Ota, PollControl
from zigpy.zcl.clusters.measurement import TemperatureMeasurement
from zigpy.zcl.clusters.security import IasZone
from . import ... |
#aggregation script
from distributed import wait
import pandas as pd
import geopandas as gpd
from panoptes_client import Panoptes
from shapely.geometry import box, Point
import json
import numpy as np
import os
from datetime import datetime
import utils
import extract
import start_cluster
def download_data(everglades_... |
'''
For a web developer, it is very important to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
1. The area of the rectangular web page you designed must equal t... |
import graphene
from netbox.graphql.fields import ObjectField, ObjectListField
from .types import *
class VirtualizationQuery(graphene.ObjectType):
cluster = ObjectField(ClusterType)
clusters = ObjectListField(ClusterType)
cluster_group = ObjectField(ClusterGroupType)
cluster_groups = ObjectListFiel... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mempool persistence.
By default, bitcoind will dump mempool on shutdown and
then reload it on sta... |
r"""Metric space in which the Hamiltonian dynamic is embedded.
An important particular case (and the most used in practice) of metric for the
position space in the Euclidean metric. It is defined by a definite positive
matrix :math:`M` with fixed value so that the kinetic energy of the hamiltonian
dynamic is independe... |
# Copyright (C) 2015-2016 Regents of the University of California
#
# 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 app... |
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['GCN']
class GCN(nn.Module):
""" Graph Convolutional Networks,
see reference below for more information
Kipf, T.N. and Welling, M., 2016.
Semi-supervised classification with graph convolutional networks.
arXiv pr... |
"""
Django settings for xfz project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
from . i... |
import random
def choose():
words=['rainbow','computer','science','programming','mathematics','player','condition','reverse','water','board']
pick=random.choice(words)
return pick
def jumble(word):
jumbled="".join(random.sample(word,len(word)))
return jumbled
def thank(p1n,p2n,p1,p2):
print(p... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 6 18:48:32 2021
@author: Arpita
"""
import cv2
# Load our input image
image = cv2.imread("C:\Users\lenovo\Pictures\user_image\000183_0.jpg")
cv2.waitKey()
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#filename = 'output.jpg'
cv2.imwrite('C:\\Users\\lenovo\... |
import unittest
import cpmpy as cp
from cpmpy.expressions import *
from cpmpy.expressions.core import Operator
class TestSum(unittest.TestCase):
def setUp(self):
self.iv = cp.intvar(0, 10)
def test_add_int(self):
expr = self.iv + 4
self.assertIsInstance(expr, Operator)
self.a... |
import pandas as pd
import numpy as np
import nltk
import os
# TODO load a pre-trained model (gloVe word vectors):
import gensim.downloader as api
info = api.info() # show info about available models/datasets
model = api.load("glove-twitter-25") # download the model and return as object ready for use
model.most_sim... |
import sqlite3
class database_object():
def __init__(self):
self.path_to_db = 'db/predictions.db'
def create_connection(self):
self.conn = sqlite3.connect(self.path_to_db, check_same_thread=False)
def create_table(self):
self.create_connection()
c = self.conn.cursor()
... |
import os
import torch
import argparse
import torch.nn as nn
from pathlib import Path
import torch.onnx as onnx
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from azureml.core.run import Run
############################... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This file is part of the Wapiti project (http://wapiti.sourceforge.net)
# Copyright (C) 2009-2018 Nicolas Surribas
#
# Original authors :
# Anthony DUBOCAGE
# Guillaume TRANCHANT
# Gregory FONTAINE
#
# This program is free software; you can redistribute it and/or modify
... |
# --------------------------------------------------------
# SimMIM
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu
# Modified by Zhenda Xie
# --------------------------------------------------------
import os
import sys
import logging
import functools
from... |
from ipdb import set_trace as st
import os
import time
import random
import numpy as np
from loguru import logger
import torch
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed) # type: ignore
... |
# -*- coding: utf-8 -*-
from sqlalchemy import String, Column, Float
from zvt.contract import Mixin
class KdataCommon(Mixin):
provider = Column(String(length=32))
code = Column(String(length=32))
name = Column(String(length=32))
# Enum constraint is not extendable
# level = Column(Enum(IntervalLe... |
_base_ = ['../../../../_base_/datasets/coco_wholebody_hand.py']
log_level = 'INFO'
load_from = None
resume_from = None
dist_params = dict(backend='nccl')
workflow = [('train', 1)]
checkpoint_config = dict(interval=10)
evaluation = dict(
interval=10, metric=['PCK', 'AUC', 'EPE'], key_indicator='AUC')
optimizer = di... |
import pandas as pd
import folium
from flask import Flask,render_template
def find_top_confirmed(n = 15):
corona_df=pd.read_csv("covid-19-dataset-2.csv")
by_country = corona_df.groupby('Country').sum()[['Confirmed', 'Deaths', 'Recovered', 'Active']]
cdf = by_country.nlargest(n, 'Confirmed')[['... |
import sys
try:
from pathlib import Path
except ImportError:
# noinspection PyUnresolvedReferences
from pathlib2 import Path
__version__ = "1.0.8"
__vendor_site__ = (Path(__file__).parent / "_vendor").as_posix()
if __vendor_site__ not in sys.path:
sys.path.insert(0, __vendor_site__)
|
import json
import matplotlib.pyplot as plt
with open('output.json', 'r') as f:
result = json.load(f)
# plotting = {}
indexs = []
losses = []
val_losses = []
accuracies = []
for k, v in result.items():
name = k.replace(".pth", "").split('-')
index = int(name[0][2:])
loss = float(name[1].replace("los... |
import pandas as pd
import json
from sklearn import preprocessing
import numpy as np
dummy_data = json.dumps({
"indexKeys": ["feeling", "jogging", "exercise", "meditate", "paint", "read", "code", "games", "socialize", "socialMedia", "goodSleep", "badSleep", "moderateSleep", "netflix", "smoke", "junkFood"],
"re... |
from . import main
from werkzeug.security import generate_password_hash
from flask import render_template,flash, redirect, url_for, request
from flask_login import login_user, current_user, logout_user, login_required
from .forms import *
from ..models import *
from ..requests import *
from .. import db, photos
@main.... |
# -*- coding: utf-8 -*-
from ....Methods.Simulation.Input import InputError
def run(self):
"""Run the Structural module"""
if self.parent is None:
raise InputError(
"ERROR: The Structural object must be in a Simulation object to run"
)
if self.parent.parent is None:
ra... |
DATA = [
## Google
'72.14.199.0/25',
'209.85.238.0/25',
## Yahoo! Japan
'124.83.159.146/31',
'124.83.159.148/30',
'124.83.159.152/29',
'124.83.159.160/28',
'124.83.159.176/29',
'124.83.159.184/31',
## DeNA
'202.238.103.126',
'202.213.221.97',
## F-route
'60... |
""" discover and run doctests in modules and test files."""
import bdb
import inspect
import platform
import sys
import traceback
import warnings
from contextlib import contextmanager
from typing import Dict
from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple
from ty... |
from collections import Counter
from django.test.html import HTMLParseError, parse_html
from .shortcodes import find_all_shortcodes
class HTMLAnalyzer:
def __init__(self):
self.total = 0
self.invalid = 0
self.tags_total = Counter()
self.attributes_total = Counter()
self.s... |
# Generated by Django 3.1.2 on 2020-12-14 20:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20201214_1547'),
]
operations = [
migrations.AlterField(
model_name='stats',
name='toi',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.