text
string
size
int64
token_count
int64
import os import sys import slackweb from pywell.entry_points import run_from_cli DESCRIPTION = 'Send notification to Slack.' ARG_DEFINITIONS = { 'SLACK_WEBHOOK': 'Web hook URL for Slack.', 'SLACK_CHANNEL': 'Slack channel to send to.', 'TEXT': 'Text to send.' } REQUIRED_ARGS = [ 'SLACK_WEBHOOK', '...
597
247
from os import path, makedirs, walk ,remove, scandir, unlink from numpy import inf from torch import save as t_save from lib.utils import sort_human, BOLD, CLR class EarlyStopping: def __init__(self, log_path, patience=7, model=None, verbose=False, exp_tag=""): """Early stops the training if validation ...
4,203
1,248
from ldapauthenticator.ldapauthenticator import LDAPAuthenticator __all__ = [LDAPAuthenticator]
97
33
""" This file tests the TC100 error: >> Missing 'from __future__ import annotations' import The idea is that we should raise one of these errors if a file contains any type-checking imports and one is missing. One thing to note: futures imports should always be at the top of a file, so we only need to check one ...
2,207
821
#!/bin/env python2 import matplotlib as mpl mpl.use('pgf') pgf_with_pgflatex = { "pgf.texsystem": "pdflatex", "pgf.rcfonts": False, "pgf.preamble": [ r"\usepackage[utf8x]{inputenc}", r"\usepackage[T1]{fontenc}", # r"\usepackage{cmbright}", ] } mpl.rcParams.update(pgf_wit...
6,628
2,844
# Copyright (c) 2018 The Regents of the University of Michigan # and the University of Pennsylvania # # 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 li...
5,272
1,692
la = [] for x in range(5): la.append(lambda x: (lambda q: q + x)(x)) print la[3](1)
91
44
from ctypes import * rust = cdll.LoadLibrary("./target/debug/libhello_rust.dylib") answer = rust.times2(64) print('rust.times2(64)', rust.times2(64))
153
62
from deck_of_cards import * def check(card1, card2): if card1.number == card2.number: check = True #Add special cards elif card1.suit == card2.suit: check = True else: check = False return check def turn(myCard, myHand, opponentsHand, deck): cardplayed = False w...
2,323
745
from instamarket import settings ON_SERVER=settings.ON_SERVER ON_HEROKU=settings.ON_HEROKU ON_MAGGIE=settings.ON_MAGGIE REMOTE_MEDIA=settings.REMOTE_MEDIA ON_SERVER=settings.ON_SERVER DEBUG=settings.DEBUG BASE_DIR=settings.BASE_DIR COMING_SOON=settings.COMING_SOON MYSQL=settings.MYSQL TIME_ZONE=settings.TIME_ZONE STA...
674
288
import functools def memoise(func): @functools.wraps(func) def wrapper(*args, **kwargs): if not wrapper.hasResult: wrapper.result = func(*args, **kwargs) wrapper.hasResult = True return wrapper.result wrapper.result = None wrapper.hasResult = False return wr...
326
94
# Pytest fixtures to get different DLKit configs during tests # Implemented from documentation here: # https://docs.pytest.org/en/latest/unittest.html import pytest @pytest.fixture(scope="class", params=['TEST_SERVICE', 'TEST_SERVICE_FUNCTIONAL']) def dlkit_service_config(request): request.cls....
348
111
#!/venv/bin python """ DESCRIPTION: This file contains wrappers and variations on DataLoader. """ # Libraries import os from random import shuffle import torch import numpy as np from torch.utils.data import Dataset from resquiggle_utils import parse_resquiggle, window_resquiggle from torch import nn class Combined...
1,432
457
from setuptools import setup, find_packages import os version = "0.0.1" if "VERSION" in os.environ: version = os.environ["VERSION"] setup( name="high-res-stereo", version=version, description="high-res-stereo", author="Jariullah Safi", author_email="safijari@isu.edu", packages=find_packag...
405
144
#!/usr/bin/env python3 """ Image viewer based on Tkinter and integrated to the database. """ ##########################################################IMPORTS import argparse import os import tkinter import tkinter.messagebox import tkinter.filedialog import tkinter.font import PIL import PIL.Image import PIL.ImageTk i...
7,169
2,437
import datetime as suan def al(text): try: zaman=suan.datetime.now() saat=zaman.strftime("%H") dakika=zaman.strftime("%M") saniye=zaman.strftime("%S") gun=zaman.strftime("%A") ay=zaman.strftime("%B") yil=zaman.strftime("%Y") if gun=="Monday...
1,882
655
# Copyright 2019 The Texar 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 ...
10,467
3,046
import json import pandas as pd import time import matplotlib.pyplot as plt ylabels = [ "CPU Utilization (%)", "Disk I/O Utilization (%)", "Process CPU Threads In Use", "Network Traffic (bytes)", "System Memory Utilization (%)", "Process Memory Available (non-swap) (MB)", "Process Memory In...
4,110
1,460
"""Serial objects are responsible for: * Maintaining specific catalogues of Format and Protocol parsers * Serializing and deserializing Python objects to and from dictionary equivalents Eventually, the second item will need to support more complex types, such as user-defined enumerations. For now, the following f...
3,045
1,041
import requests import atexit from apscheduler.schedulers.background import BackgroundScheduler from bs4 import BeautifulSoup class lodeStoneScraper: def __init__(self): self.__URL = 'https://na.finalfantasyxiv.com/lodestone/worldstatus/' self.__statistics = {} self.update_page() ...
3,893
1,047
TOKEN_PREALTA_CLIENTE = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InJhdWx0ckBnbWFpbC5jb20iLCJleHAiOjQ3MzM1MTA0MDAsIm93bmVyX25hbWUiOiJSYXVsIEVucmlxdWUgVG9ycmVzIFJleWVzIiwidHlwZSI6ImVtYWlsX2NvbmZpcm1hdGlvbl9uZXdfY2xpZW50In0.R-nXh1nXvlBABfEdV1g81mdIzJqMFLvFV7FAP7PQRCM' TOKEN_PREALTA_CLIENTE_CADUCO = 'eyJ0eXAiOiJ...
1,078
847
from sqlalchemy import Column, Integer, String from app.db.base_class import Base class SearchTerm(Base): id = Column(Integer, primary_key=True, index=True) term = Column(String, nullable=False, comment="Término de búsqueda para filtros", unique=True, index=True)
275
89
""" It converts Strings in the format # to deactivate commands just comment them out by putting a # to the beginning of the line # optional commands can be deactivated by putting a # to the lines' beginning and activated by removing # from the beginning # replace 'example.com' with the hostname or ip address of the se...
2,565
784
from rest_framework import serializers from .models import Event, Notification class EventSerializer(serializers.ModelSerializer): class Meta: model = Event exclude = ('id', 'moved_to', 'received_timestamp',) class EventExcludeIDSerializer(serializers.ModelSerializer): class Meta: mode...
618
161
# -*- coding: utf-8 -*- # This plugins is licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php # Authors: Kenji Hosoda <hosoda@s-cubism.jp> from gluon import * class TableCheckbox(FORM): def __init__(self, id_getter=lambda row: row.id, tablecheckbox_var='tablech...
3,458
1,017
# -*- encoding: utf-8 -*- """ Created by eniocc at 11/10/2020 """ import ctypes from py_dss_interface.models import Bridge from py_dss_interface.models.Base import Base from py_dss_interface.models.Sensors.SensorsS import SensorsS from py_dss_interface.models.Text.Text import Text class SensorsV(Base): """ ...
2,781
918
from __future__ import absolute_import # import models into model package from netapp.santricity.models.v2.access_volume_ex import AccessVolumeEx from netapp.santricity.models.v2.add_batch_cg_members_request import AddBatchCGMembersRequest from netapp.santricity.models.v2.add_consistency_group_member_request impo...
25,967
8,409
""" WSGI config for test_project project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os import sys from django.core.wsgi import get_wsgi_application # This allows easy...
629
210
# Generated by Django 2.1.1 on 2020-04-05 06:12 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Response', fields=[ ('id', models.AutoField...
747
226
SRM_TO_HEX = { "0": "#FFFFFF", "1": "#F3F993", "2": "#F5F75C", "3": "#F6F513", "4": "#EAE615", "5": "#E0D01B", "6": "#D5BC26", "7": "#CDAA37", "8": "#C1963C", "9": "#BE8C3A", "10": "#BE823A", "11": "#C17A37", "12": "#BF7138", "13": "#BC6733", "14": "#B26033", ...
1,534
888
from ctypes.util import find_library as _find_library print(_find_library('sndfile')) print('test fine')
107
35
from incense import utils def test_find_differing_config_keys(loader): assert utils.find_differing_config_keys(loader.find_by_ids([1, 2])) == {"epochs"} assert utils.find_differing_config_keys(loader.find_by_ids([1, 3])) == {"optimizer"} assert utils.find_differing_config_keys(loader.find_by_ids([2, 3])) ...
561
220
#!/usr/bin/env python3 """VUnit run script.""" from pathlib import Path from vunit import VUnit prj = VUnit.from_argv() lib = prj.add_library("lib") root = Path(__file__).parent lib.add_source_files(root / "src" / "*.vhd") lib.add_source_files(root / "test" / "*.vhd") prj.main()
285
115
""" Test functions for regular module. """ import pytest import numpy as np from sklearn.linear_model import LinearRegression, LogisticRegression from sklearn.base import clone import tensorflow as tf from tensorflow.keras import Sequential, Model from tensorflow.keras.layers import Dense from tensorflow.keras.optimiz...
6,420
2,755
import unittest from multienv.config import Config from multienv.env_var import EnvVar from multienv.exceptions import InvalidYamlFileException, \ EnvVarContainerBuildNotFoundException class EnvVarTestCase(unittest.TestCase): def test_get_containers_to_rebuild_with_existent_env_var(self): config = Co...
1,810
563
from mythic_payloadtype_container.MythicCommandBase import * import json from uuid import uuid4 from os import path from mythic_payloadtype_container.MythicRPC import * import base64 import donut class AssemblyInjectArguments(TaskArguments): def __init__(self, command_line): super().__init__(command_line)...
3,097
856
''' Created on 4 Feb 2022 @author: ucacsjj ''' import random from enum import Enum import numpy as np from gym import Env, spaces from .robot_states_and_actions import * # This environment affords a much lower level control of the robot than the # battery environment. It is partially inspired by the AI Gymn Frozen...
6,211
1,959
import boto3 import json import urllib.request import os from . import reflect def publish(name, payload): if os.environ.get("NODE_ENV") == "testing": try: dump = json.dumps({"name": name, "payload": payload}) data = bytes(dump.encode()) handler = urllib.request.urlope...
753
230
import os import numpy as np from scipy.misc import imread, imresize def load_image_labels(dataset_path=''): labels = {} with open(os.path.join(dataset_path, 'image_class_labels.txt')) as f: for line in f: pieces = line.strip().split() image_id = pieces[0] class_i...
1,927
648
#!/usr/bin/env python # Copyright (c) 2021 Samsung Electronics Co., Ltd. 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...
1,964
597
# coding:utf-8 # Copyright (c) 2020 PaddlePaddle 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 requ...
6,857
2,034
# ------ [ API ] ------ API = '/api' # ---------- [ BLOCKCHAIN ] ---------- API_BLOCKCHAIN = f'{API}/blockchain' API_BLOCKCHAIN_LENGTH = f'{API_BLOCKCHAIN}/length' API_BLOCKCHAIN_BLOCKS = f'{API_BLOCKCHAIN}/blocks' # ---------- [ BROADCASTS ] ---------- API_BROADCASTS = f'{API}/broadcasts' API_BROADCASTS_NEW_BLOCK =...
929
441
import logging import logging.config import socket import os from autumn.core.utils.runs import read_run_id from autumn.core.project import Project, get_project def get_project_from_run_id(run_id: str) -> Project: app_name, region_name, _, _ = read_run_id(run_id) return get_project(app_name, region_name) d...
1,748
543
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Xinlei Chen # -------------------------------------------------------- from __future__ import absolute_import from __future__ i...
6,433
2,121
# Compute the distance between all the points on a sphere and a # plane. # import pyvista as pv sphere = pv.Sphere() plane = pv.Plane() _ = sphere.compute_implicit_distance(plane, inplace=True) dist = sphere['implicit_distance'] type(dist) # Expected: ## <class 'numpy.ndarray'> # # Plot these distances as a heatmap # p...
573
213
# -*- coding: utf-8 -*- # 系统模块 import sys # 数据处理模块 import pandas as pd # 引入外部模块 # 整理数据 from predict_prepare import Predict_Prepare as Prepare # 获取价格预测结果 from predict_predict import Predict_Predict as Predict class Predict_Lead: def __init__(self): pass # 其他包调用的函数 def predict_result(self): ...
1,953
979
import pygame from aerforge.color import * from aerforge.error import * class Text: def __init__(self, window, text, font_size = 24, font_file = None, font_name = "arial", bold = False, italic = False, underline = False, color = Color(240, 240, 240), x = 0, y = 0, parent = None, add_to_objects = True): ...
4,255
1,476
default_app_config = 'webapp.apps.WebAppConfig'
47
17
from distutils.core import setup setup( name='als', packages=['als'], version='0.0.2', description='Python library for Alternating Least Squares (ALS)', author='Rui Vieira', author_email='ruidevieira@googlemail.com', url='https://github.com/ruivieira/python-als', download_url='https://g...
500
169
# coding=utf-8 # National Oceanic and Atmospheric Administration (NOAA) # Alaskan Fisheries Science Center (AFSC) # Resource Assessment and Conservation Engineering (RACE) # Midwater Assessment and Conservation Engineering (MACE) # THIS SOFTWARE AND ITS DOCUMENTATION ARE CONSIDERED TO BE IN THE PUBLI...
8,274
2,368
import numpy as np import argparse import sys import os dir_name = os.path.dirname(os.path.realpath(__file__)) npy_data = np.load(os.path.join(dir_name, sys.argv[1])) npy_data = npy_data.astype(np.float32) npy_data = npy_data.reshape((-1,)) npy_data.tofile(os.path.join(dir_name, sys.argv[1].split(".")[0] + ".f32"))
318
139
#!/usr/bin/env python3 import os import sys from shutil import copyfile, move import argparse from glob import glob sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from Metronome import distributed_execution def generate_astar_configs(domain_paths, domain_type): config_list = [] ...
15,448
4,743
from View import telaRelatorio, telaNovoProjeto, telaAbrirProjeto, telaCadastro, telaConfigura, telaConexao, telaEditarControle, telaPopUp from View.Painel import painelSensores, painelControladores, painelConexao from View.Conexao import telaConAnalogAnalog, telaConAnalogDigit, telaConDigitAnalog, telaConDigitDigit ...
1,671
709
#tables or h5py libname="h5py" #tables" #libname="tables" def setlib(name): global libname libname = name
109
46
#!/usr/bin/env python # -*- coding: utf-8 -*- """ setup_project.py -- GIS Project Setup Utility Garin Wally; May 2014/May 2016 This script creates a project folder-environment for GIS projects as follows: <project_name>/ data/ raw/ <project_name>.gdb design/ fonts/ images/ ...
2,914
984
import os from pathlib import Path import pytest from dismantle.package import DirectoryPackageFormat, PackageFormat def test_inherits() -> None: assert issubclass(DirectoryPackageFormat, PackageFormat) is True def test_grasp_exists(datadir: Path) -> None: src = datadir.join('directory_src') assert Dire...
1,816
582
from functools import wraps from django.contrib import messages from django.shortcuts import get_object_or_404, redirect from access.cbac import default_cbac_required from core.models import Event from .views.admin_menu_items import labour_admin_menu_items def labour_admin_required(view_func): @wraps(view_func...
1,394
436
import tensorflow as tf import numpy as np a = np.arange(15) out = a.reshape(5, 3) c = np.arange(15) / 2 y_onehot = c.reshape(5, 3) out_tensor = tf.convert_to_tensor(out, dtype=tf.float32) y_onehot_tensor = tf.convert_to_tensor(y_onehot, dtype=tf.float32) # y_onehot = tf.one_hot(y_onehot_tensor, depth=3) # one-hot...
411
191
if __name__ == "__main__": pages = [5, 4, 3, 2, 1, 4, 3, 5, 4, 3, 2, 1, 5] faults = {3: 0, 4: 0} for frames in faults: memory = [] for page in pages: out = None if page not in memory: if len(memory) == frames: out =...
632
234
a={'a':'hello','b':'1','c':'jayalatha','d':[1,2]} d={} val=list(a.values()) val.sort(key=len) print(val) for i in val: for j in a: if(i==a[j]): d.update({j:a[j]}) print(d)
247
109
from django.urls import path, include from django.contrib.auth.decorators import login_required from papermerge.core.views import documents as doc_views from papermerge.core.views import access as access_views from papermerge.core.views import api as api_views document_patterns = [ path( '<int:id>/previe...
2,419
807
import abc #inteface Component creamos la funcion buscador que es la que buscara alguna PaginaWeb en el SitioWeb class ISitioWebComponent(metaclass=abc.ABCMeta): @abc.abstractmethod def buscador(self): pass # Concrete Component class SitioWebConcreteComponent(ISitioWebComponent): def __init__(s...
4,773
1,484
# # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # # Author: Pengcheng He (penhe@microsoft.com) # Date: 05/15/2019 # import os import numpy as np import math import sys from torch.utils.data import Sampler __all__=['BatchSampler', 'Distribut...
2,003
712
# -*- coding: utf-8 -*- """ Created on Wed Nov 04 17:37:37 2015 @author: Kevin """
85
49
# pytest --html=tests/report/test-report.html # above command runs tests and test reports generates in tests/report location. # nosetests --with-coverage --cover-html # clean all the .pyc files # find . -name \*.pyc -delete # nosetests --with-coverage --cover-html # pytest --cov=contentstack_utils # pytest -v --cov=co...
2,336
677
#!/usr/bin/env python3 ''' Use the python built-in sort for comparison against other implementations.''' import sys def merge(a, b): sorted = [] while len(a) > 0 and len(b) > 0: if a[0] < b[0]: sorted.append(a.pop(0)) else: sorted.append(b.pop(0)) if len(a) > ...
584
212
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "core_library", "core_resx", "core_xunit_test") core_resx( name = "core_resource", src = ":src/Moq/Properties/Resources.resx", identifier = "Moq.Properties.Resources.resources", ) core_library( name = "Moq.dll", srcs = glob(["src/Moq/**/*.cs"]), ...
1,160
424
#!/usr/bin/env python # # soaplib - Copyright (C) Soaplib contributors. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any late...
8,160
2,683
from decimal import Decimal import numpy def strategy(history, memory): """ Nice Patient Comparative Tit for Tat (NPCTT): 1. Nice: Never initiate defection, else face the wrath of the Grudge. 2. Patient: Respond to defection with defection, unless it was in possibly response to my ...
2,097
669
from django.contrib.auth.models import User from mock import MagicMock from onadata.apps.main.tests.test_base import TestBase from onadata.apps.logger.models import Instance, XForm from onadata.apps.api.permissions import MetaDataObjectPermissions class TestPermissions(TestBase): def setUp(self): self.vi...
1,202
336
import moeda preco = float(input("Digite o preço: R$")) por100 = float(input("Digite a porcentagem: ")) formatar = str(input("Deseja formatar como moeda [S/N]? ")).upper() if "S" in formatar: formatado = True else: formatado = False print(f"\nA metade de {moeda.moeda(preco)} é {moeda.metade(preco, formatado)...
610
258
from django.urls import path, include from .views import CompanyAPIView # urlpatterns = [ # path("",include(router.urls)), # ]
132
41
from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from djangosaml2.conf import get_config from djangosaml2.utils import available_idps from saml2.attribute_converter import ac_factory from saml2.mdstore import InMemoryMetaData, MetaDataFile from saml2.mdstore import name as get_idp_...
2,681
769
import logging # configure logging before initializing further modules logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(name)s - %(message)s") logging.getLogger("urllib3.connectionpool").setLevel(logging.INFO) import argparse import json import flask import flask_compress from werkzeug.m...
3,846
1,292
# Time: O(n^2) # Space: O(n) # Given an array of unique integers, each integer is strictly greater than 1. # We make a binary tree using these integers and each number may be used for # any number of times. # Each non-leaf node's value should be equal to the product of the values of # it's children. # How many binary...
1,274
517
# -*- coding: utf-8 -*- from jtr.load.embeddings.embeddings import Embeddings, load_embeddings from jtr.load.embeddings.word_to_vec import load_word2vec, get_word2vec_vocabulary from jtr.load.embeddings.glove import load_glove from jtr.load.embeddings.vocabulary import Vocabulary __all__ = [ 'Embeddings', 'lo...
424
184
############################################################################## # Copyright (c) 2016 Max Breitenfeldt and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is avai...
9,466
2,882
# Blurring and Sharpening Images # Import Computer Vision package - cv2 import cv2 # Import Numerical Python package - numpy as np import numpy as np # Read the image using imread built-in function image = cv2.imread('image_6.jpg') # Display original image using imshow built-in function cv2.imshow("Orig...
1,513
551
from flask import Flask, request, jsonify, abort, render_template, redirect, session, url_for import MySQLdb.cursors import hashlib import html import json import math import os import pathlib import random import re import string import urllib import sys from werkzeug.contrib.profiler import ProfilerMiddleware, MergeS...
10,887
3,683
from django.apps import AppConfig class TodoConfig(AppConfig): name = 'todo'
80
28
def run(): animal = str(input('¿Cuál es tu animal favorito? ')) if animal.lower() == 'tortuga' or animal.lower() == 'tortugas': print('También me gustan las tortugas.') else: print('Ese animal es genial, pero prefiero las tortugas.') if __name__ == '__main__': run()
299
107
from enum import Enum class Registration(Enum): ID_SERVIDOR_PORTAL = 1 NOME = 2 CPF = 3 MATRICULA = 4 DESCRICAO_CARGO = 5 CLASSE_CARGO = 6 REFERENCIA_CARGO = 7 PADRAO_CARGO = 8 NIVEL_CARGO = 9 SIGLA_FUNCAO = 10 NIVEL_FUNCAO = 11 FUNCAO = 12 CODIGO_ATIVIDADE = 13 ...
1,153
677
from leapp.actors import Actor from leapp.models import InstalledRedHatSignedRPM from leapp.libraries.common.rpms import has_package from leapp.reporting import Report, create_report from leapp import reporting from leapp.tags import ChecksPhaseTag, IPUWorkflowTag class CheckAcpid(Actor): """ Check if acpid i...
1,269
349
from crypto_config import (ConfigParser, ParsingError, Crypt) import re class CryptoConfigParser(ConfigParser): def __init__(self, *args, **kwargs): key = kwargs.pop('crypt_key', None) if key != None: self.crypt_key = key else: self.crypt_key = None Config...
831
273
import os.path import scipy.io as sio import numpy as np # for algebraic operations, matrices import keras.models from keras.models import Sequential from keras.layers.core import Dense, Activation, Flatten, Dropout # , Layer, Flatten # from keras.layers import containers from keras.models import model_from_json,Mode...
9,888
3,929
class reversor: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value def __lt__(self, other): """ Inverted it to be able to sort in descending order. """ return self.value >= other.value if __name__ == '__...
856
349
from twarc import Twarc2, expansions import json # Replace your bearer token below client = Twarc2(bearer_token="XXXXX") def main(): # The followers function gets followers for specified user followers = client.followers(user="twitterdev") for page in followers: result = expansions.flatten(page) ...
501
149
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Yue-Wen FANG' __maintainer__ = "Yue-Wen FANG" __email__ = 'fyuewen@gmail.com' __license__ = 'Apache License 2.0' __creation_date__= 'Dec. 25, 2018' """ This example shows the functionality of positional arguments and keyword ONLY arguments. The positional a...
1,091
387
""" A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. Given the root to a binary tree, count the number of unival subtrees. For example, the following tree has 5 unival subtrees: 0 / \ 1 0 / \ 1 0 / \ 1 1 """ class Node...
1,999
744
import sublime import sublime_plugin import urllib import urllib2 import threading import re from dyna_snip_helpers import get_snippet_list, inc_snippet_object COMMENT_MARKER_JAVA = '//' COMMENT_MARKER_PYTHON = "#" class PrefixrCommand(sublime_plugin.TextCommand): def run(self, edit): self.edit = edit ...
2,327
736
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # 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 limitation the rights # to us...
2,735
843
#!/usr/bin/env python3 # encoding: utf-8 """Easily create ../app.db and import ../lemuria.json""" import asyncio from db_tools import init_db from db_tools import import_world asyncio.run(init_db()) asyncio.run(import_world('../atlemuria.txt', '../proplemuria.txt'))
269
100
import numpy as np import random import matplotlib.pyplot as plt from load_data import loadLabel,loadImage def der_activation_function(x,type): if type==1: return 1 - np.power(np.tanh(x), 2) elif type==2: return (1/(1+np.exp(-x)))*(1-1/(1+np.exp(-x))) else: x[x<=0]=0.25 x[x>...
2,517
1,039
from dataclasses import dataclass from bindings.gmd.cylindrical_cstype import CylindricalCstype __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class CylindricalCs(CylindricalCstype): """gml:CylindricalCS is a three-dimensional coordinate system consisting of a polar coordinate system extended by a s...
586
182
import pandas as pd from collections import Counter def import_lexique_as_df(path=r".\lexique3832.xlsx"): """importe le lexique :param path: lexique3832.xlsx chemin du fichier :return pd.dataframe """ df = pd.read_excel(path) df.iloc[:, 0] = df.iloc[:, 0].fillna(value="nan") # transforme Na...
4,800
1,816
## This code is written by Davide Albanese, <albanese@fbk.eu>. ## (C) 2011 mlpy Developers. ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at y...
25,517
8,639
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.urls import reverse from .forms import UserSignupForm, CreatePollForm, UserUpdateForm fro...
9,695
2,771
import re class AlphabetPosition: alphabet = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, ...
1,355
446
# Iterations: Definite Loops ''' Use the 'for' word there is a iteration variable like 'i' or 'friend' ''' # for i in [5, 4, 3, 2, 1] : # print(i) # print('Blastoff!') # friends = ['matheus', 'wataru', 'mogli'] # for friend in friends : # print('happy new year:', friend) # print('Done!')
300
121
from utils import (load_data, data_to_series_features, apply_weight, is_minimum) from algorithm import (initialize_weights, individual_to_key, pop_to_weights, select, reconstruct_population) from sklearn.metrics import mean_squared_error, mean_absolute_error from tensorflow.ker...
5,008
1,632