content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import numpy as np import pandas as pd import xarray as xr import cubepy from pyplan_engine.classes.evaluators.BaseEvaluator import BaseEvaluator from pyplan_engine.classes.evaluators.CubepyEvaluator import CubepyEvaluator from pyplan_engine.classes.evaluators.IPythonEvaluator import IPythonEvaluator from pyplan_engine...
nilq/baby-python
python
#! /usr/bin/env python # $Id: test_class.py 5174 2007-05-31 00:01:52Z wiemann $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Tests for the 'class' directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.Parser...
nilq/baby-python
python
# coding:utf-8 # 将图片以小分片的形式裁剪下来 import tkFileDialog import cv2 from configurationInjection import configInjection import os config = configInjection() config.loadConfiguration() rois = config.rois[0] flag = True videopath = tkFileDialog.askopenfilename(initialdir="/home/zb/myfile/cutSave") count = 0 cap = cv2.VideoC...
nilq/baby-python
python
# -*- coding: utf-8 -*- """form base classes for aloha-editor integration""" import floppyforms as forms from djaloha.widgets import AlohaInput from django.utils.encoding import smart_unicode class DjalohaForm(forms.Form): """Base class for form with aloha editor""" def __init__(self, model_class, lookup, ...
nilq/baby-python
python
"""Replays RocketLeagueReplays API module """ import requests BASE_URL = 'https://www.rocketleaguereplays.com/api/replays/?page=' def get_replays(page_num): """ Requests a page of replay data from the RocketLeagueReplaysAPI :param page_num: Page number to request :return: list of matches returned ...
nilq/baby-python
python
# -*- coding: utf-8 -*- import urwid PALETTE = [ ('red', 'dark red', ''), ('selectedred', 'dark red', 'yellow'), ('selected', '', 'yellow'), ] # Modify these as needed SIZES = {'small': (4, 3), 'medium': (6, 4), 'large': (8, 6)} card_size = 'large' class BaseCardWidget(urwid.WidgetWrap): def __init...
nilq/baby-python
python
# coding: utf-8 """ ELEMENTS API The version of the OpenAPI document: 2 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from elements_sdk.configuration import Configuration class TapeFile(object): """NOTE: This class is auto generated by OpenAPI ...
nilq/baby-python
python
from unittest import mock from django import forms from django.test import SimpleTestCase from django.utils.functional import lazy from phonenumber_field.formfields import PhoneNumberField ALGERIAN_PHONE_NUMBER = "+213799136332" class PhoneNumberFormFieldTest(SimpleTestCase): def test_error_message(self): ...
nilq/baby-python
python
from pkg.command.azcli_cmd import AzCliCommand from pkg.entity._az_cli import AzCli from pkg.executor._executor import Executor from pkg.executor.azcli.command._azcli_cmd_executor import AzCliCommandExecutor class AzCliExecutor(Executor): def __init__(self): pass def run_az_cli(self, cmd: AzCli): ...
nilq/baby-python
python
from logging import captureWarnings from operator import inv from typing import Container, Iterable, Union import uuid import time import math from datetime import datetime, timedelta, timezone from unittest import TestCase from unittest.mock import patch, MagicMock, ANY, call from botocore.exceptions import ClientErr...
nilq/baby-python
python
import datetime import dateutil.parser import pytz from django.conf import settings from django.db.models import F, Q from django.http import ( Http404, HttpResponseBadRequest, HttpResponseRedirect, JsonResponse, ) from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils imp...
nilq/baby-python
python
from invoke import task from os.path import join, exists from os import makedirs from shutil import copy, rmtree from subprocess import run from tasks.util.env import ( BIN_DIR, GLOBAL_BIN_DIR, KUBECTL_BIN, AZURE_RESOURCE_GROUP, AZURE_VM_SIZE, AKS_CLUSTER_NODE_COUNT, AKS_CLUSTER_NAME, ) fro...
nilq/baby-python
python
import sys class ModelSearchCriteria: def __init__(self, datatable_names: [str], column_names: [str], search_text: str ): self.datatable_names = datatable_names self.column_names = column_names self.search_text = search_text
nilq/baby-python
python
#!/usr/bin/python # -*- coding: utf_8 -*- """Access and query Twitter's API with the simplistic twitter package (`pip install twitter`). """ from __future__ import print_function from __future__ import unicode_literals import csv import os import time from twitter import OAuth from twitter import Twitter def setup...
nilq/baby-python
python
import jieba import jieba.analyse from gensim.test.utils import get_tmpfile import gensim.models.word2vec as word2vec from path import Path import argparse from utils import readlines,SeqSubSeq,toarry #文件位置需要改为自己的存放路径 #将文本分词 parser = argparse.ArgumentParser(description="precess tree file to a doc") parser.add_argume...
nilq/baby-python
python
"""functions for working with tensorboard""" from pathlib import Path import pandas as pd from tensorboard.backend.event_processing.event_accumulator import EventAccumulator def logdir2df(logdir): """convert tensorboard events files in a logs directory into a pandas DataFrame events files are created by Sum...
nilq/baby-python
python
import json import logging import os from datetime import datetime def coco_evaluation(dataset, predictions, output_dir, iteration=None): coco_results = [] for i, prediction in enumerate(predictions): img_info = dataset.get_img_info(i) prediction = prediction.resize((img_info['width'], img_inf...
nilq/baby-python
python
from snovault import upgrade_step @upgrade_step('suspension', '1', '2') def suspension_1_2(value, system): if 'biosample_ontology' in value: del value['biosample_ontology'] @upgrade_step('suspension', '2', '3') def suspension_2_3(value, system): if 'url' in value: value['urls'] = [value['url']] del value['ur...
nilq/baby-python
python
# -*- coding: utf-8 -*- from django.conf.urls import url from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase, override_settings from django.views.generic import CreateView, UpdateView, DeleteView, DetailView class CreateUserView(CreateView): ...
nilq/baby-python
python
""" This set of functions is for analyzing all the articles in the PLOS corpus. A Jupyter Notebook is provided with examples of analysis. It can: * compare the articles indexed in Solr, PMC, and article pages * spot-check individual JATS fields for irregularities * create summaries of articles by type, publ...
nilq/baby-python
python
import json import jk_json import jk_typing import jk_prettyprintobj from thaniya_common.cfg import CfgKeyValueDefinition from thaniya_common.cfg import AbstractCfgComponent from .BackupVolumeID import BackupVolumeID class _Magic(AbstractCfgComponent): MAGIC = "thaniya-volume-cfg" __VALID_KEYS = [ Cf...
nilq/baby-python
python
import os from threading import Thread from sh import tail from pymouse import PyMouse from datetime import datetime, timedelta import subprocess WAS_MOVED_SCATTER = 0 # in seconds SHORT_PRESS = .15 MEDIUM_PRESS = .4 LONG_PRESS = .6 VERY_LONG_PRESS = 1 SCROLL_SENSITIVITY = 10 MOVE_SENSITIVITY = .8 MOVE_SCALING = 1....
nilq/baby-python
python
#Write a Python program to add leading zeroes to a string. string = '5699' print() print(string.ljust(7, '0'))
nilq/baby-python
python
from django.apps import AppConfig class DbSearchConfig(AppConfig): name = 'db_search'
nilq/baby-python
python
import os import shutil import unittest import pandas as pd from python_tools.workflow_tools.qc.fingerprinting import ( read_csv, plot_genotyping_matrix ) class FingerprintingTestCase(unittest.TestCase): def setUp(self): """ Set some constants used for testing :return: "...
nilq/baby-python
python
#!/usr/bin/python3 # SPDX-License-Identifier: Apache-2.0 # Copyright © 2020 VMware, Inc. import os import sys import subprocess import time import shutil import configparser import pytest import collections import unittest networkd_unit_file_path = '/etc/systemd/network' network_config_manager_ci_path = '/run/networ...
nilq/baby-python
python
from project.appliances.appliance import Appliance class TV(Appliance): def __init__(self): self.cost = 1.5 super().__init__(self.cost)
nilq/baby-python
python
# Copyright 2020 The TensorFlow Quantum 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 req...
nilq/baby-python
python
from importlib import import_module from importlib import resources PLUGINS = dict() def register_plugin(func): """Decorator to register plug-ins""" name = func.__name__ PLUGINS[name] = func return func def __getattr__(name): """Return a named plugin""" try: return PLUGINS[name] e...
nilq/baby-python
python
# import os # os.environ["KIVY_WINDOW"] = "sdl2" # uncomment the above lines to run on raspberrypi like it runs on windows. import kivy kivy.require('1.9.1') from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.clock import Clock from time import sleep, time from random import randint from functo...
nilq/baby-python
python
import torch import unseal.transformers_util as tutil from unseal.hooks import HookedModel def test_load_model(): model, tokenizer, config = tutil.load_from_pretrained('gpt2') assert model is not None assert tokenizer is not None assert config is not None def test_load_model_with_dir(): model, tok...
nilq/baby-python
python
import cv2 from image_manipulation import binarize_image, grayscale_image class Camera(object): """ Class to take pictures. :param width_size: camera's image width :type width_size: int :param height_size: camera's image height :type height_size: int :param input_cam_device: p...
nilq/baby-python
python
#Passing a List def greet(names): for name in names: msg=f"Hello, {name.title()}" print(msg) username=['alice','beerus','cyrus'] greet(username)
nilq/baby-python
python
# coding:utf-8 # log utils """ 切记: 不要重复创造日志对象,否则会重复打印 """ # import os from logging import ( handlers, getLogger,) from logging import Formatter as LoggingFormatter from logging import StreamHandler as LoggingStreamHandler from logging import FileHandler as LoggingFileHandler from logging import ERROR as LOGG...
nilq/baby-python
python
# Adapted from https://github.com/openai/triton/blob/master/python/triton/ops/blocksparse/softmax.py import triton.language as tl import triton import torch from src.models.attention.blocksparse_utils import sparsify_broadcast_tensor def next_power_of_2(n): n -= 1 n |= n >> 1 n |= n >> 2 n |= n >> 4 ...
nilq/baby-python
python
import time import rich from hurry.filesize import size from tabulate import tabulate class Format: def __init__(self): pass @staticmethod def cli(**kwargs): """ Handle in coming CLI Output Style """ if "standard" in kwargs["style"]: return Format._defa...
nilq/baby-python
python
#!/usr/bin/env python2.7 import os import sys sys.path.insert(0, os.path.realpath(os.path.join(__file__, '../../../lib'))) import exatest from exatest.utils import chdir from exatest import ( useData, ) class TestParameterized(exatest.TestCase): @useData((x,) for x in range(10)) def test_pa...
nilq/baby-python
python
import sys, getopt import run def main(argv): path_database = '' path_cnn_trained = '' path_folder_retrieval = '' feature_extraction_method = '' distance = '' searching_method = '' number_of_images = 0 list_of_parameters = [] try: opts, args = getopt.getopt(argv,"h...
nilq/baby-python
python
import sys import torch sys.path.insert(0, "../") from linformer_pytorch import Linformer, Visualizer model = Linformer( input_size=512, channels=16, dim_k=128, dim_ff=32, nhead=4, depth=3, activation="relu", checkpoint_level="C0", parameter_shar...
nilq/baby-python
python
from typing import List class Solution: def searchInsert(self, nums: List[int], target: int) -> int: l, r = 0, len(nums) - 1 while l<=r: m = (l+r)//2 if nums[m]==target: return m elif nums[m]>target: r=m-1 ...
nilq/baby-python
python
import heapq import math import numpy as np import nltk.probability from nltk.classify import SklearnClassifier from sklearn.svm import SVC import re import sys sys.path.insert(0, '..') from definitions import * sys.path.insert(0, '../Wrapper/') from helper import * def get_svm_classifier(parameters): print "Loa...
nilq/baby-python
python
# 1-TASK. Matnlardan iborat ro'yxat qabul qilib, ro'yxatdagi har bir matnning birinchi # harfini katta harfga o'zgatiruvchi funksiya yozing. def katta_harf(ismlar): names = [] for i in range(len(ismlar)): ismlar[i] = ismlar[i].title() ismlar = ['ali', 'vali', 'hasan', 'husan'] katta_harf(ismlar) print(...
nilq/baby-python
python
import NNRequestHandler.Base import NNRequestHandler.User NN_REQUEST_CMD_USER_LOGIN = 1 class DispatchCenter(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(DispatchCenter, cls).__new__( cls, *args...
nilq/baby-python
python
import unittest from streamlink.plugins.canlitv import Canlitv, _m3u8_re class TestPluginCanlitv(unittest.TestCase): def test_m3u8_re(self): def test_re(text): m = _m3u8_re.search(text) self.assertTrue(m and len(m.group("url")) > 0) test_re('file: "test" ') test_r...
nilq/baby-python
python
""" Open Orchestrator Cloud Radio Access Network 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...
nilq/baby-python
python
from greent.rosetta import Rosetta import json from collections import defaultdict def setup(): rosetta = Rosetta() neodriver = rosetta.type_graph.driver; return neodriver def dumpem(dtype = 'gene'): driver = setup() cypher = f'MATCH (a:{dtype})-[r]-(b) return a,r,b' with driver.session() as s...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ /*************************************************************************** GeometryWrapper A QGIS plugin Converts geometry longitude from [-180,180] to [0,360] ------------------- begin : 2017-03-16 ...
nilq/baby-python
python
# Generated by Django 3.0.5 on 2020-04-06 15:06 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('shortner', '0002_auto_20200331_0717'), ] operations = [ migrations.AlterModelOptions( name='entry', options={'verbose_name_p...
nilq/baby-python
python
from numpy import diff def check_sorted(nu___): di_ = diff(nu___.ravel()) return (di_ <= 0).all() or (0 <= di_).all()
nilq/baby-python
python
'''VGG for CIFAR10. FC layers are removed. (c) YANG, Wei ''' import torch.nn as nn import torch.utils.model_zoo as model_zoo import math import torch __all__ = ['vgg19_bn_para'] class VGG(nn.Module): def __init__(self, features, gpu_num = 2, num_classes=1000, split_size=64): super(VGG, self).__init__()...
nilq/baby-python
python
# variants, kā importēt garākus nosaukumus import mape.helper as helper # importē konkrētu funkciju, tā it kā tā būtu lokāli definēta #from helper import ievadiSkaitli def main(): sk1 = helper.ievadiSkaitli() sk2 = helper.ievadiSkaitli() print("Ievadīto skaitļu summa ir", sk1 + sk2) helper.pievienotF...
nilq/baby-python
python
import six import time from collections import defaultdict import ujson as json import pandas as pd from oct.results.models import db, Result, Turret class ReportResults(object): """Represent a report containing all tests results :param int run_time: the run_time of the script :param int interval: the ...
nilq/baby-python
python
# Code generated by `typeddictgen`. DO NOT EDIT. """V1SubjectRulesReviewStatusDict generated type.""" from typing import TypedDict, List from kubernetes_typed.client import V1NonResourceRuleDict, V1ResourceRuleDict V1SubjectRulesReviewStatusDict = TypedDict( "V1SubjectRulesReviewStatusDict", { "evalua...
nilq/baby-python
python
# Copyright 2021 Xilinx 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 agreed to in writing,...
nilq/baby-python
python
import os from abc import abstractmethod from collections import defaultdict import PIL import cv2 import math import numpy as np import sldc import torch from PIL import Image from cytomine.models import Annotation from rasterio.features import rasterize from shapely import wkt from shapely.affinity import translate,...
nilq/baby-python
python
# # Copyright (c) 2019 UCT Prague. # # ec5cbec43ec8_initial_layout.py is part of Invenio Explicit ACLs # (see https://github.com/oarepo/invenio-explicit-acls). # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to d...
nilq/baby-python
python
from language_learner_env import secret_settings import learner app = learner.App(secret_settings) app.listen()
nilq/baby-python
python
from maya import cmds as mc from maya.api import OpenMaya as om from dcc.maya.libs import transformutils from . import transformmixin import logging logging.basicConfig() log = logging.getLogger(__name__) log.setLevel(logging.INFO) class ConstraintMixin(transformmixin.TransformMixin): """ Overload of Transf...
nilq/baby-python
python
# encoding=utf8 # This is temporary fix to import module from parent folder # It will be removed when package is published on PyPI import sys sys.path.append('../') # End of fix import numpy as np from NiaPy.task import StoppingTask, OptimizationType from NiaPy.algorithms import BasicStatistics from NiaPy.algorithms.b...
nilq/baby-python
python
# Copyright (c) 2014-2017, iocage # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted providing that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and th...
nilq/baby-python
python
"""Anvil is a tool for automating the rigging process in a given DCC.""" from six import itervalues import config import utils import colors import meta_data import log import version import interfaces import runtime import objects import grouping import node_types import sub_rig_templates import rig_templates class ...
nilq/baby-python
python
import numpy as np import pandas as pd import os from transformers import AutoModel from inference_schema.schema_decorators import input_schema, output_schema from inference_schema.parameter_types.pandas_parameter_type import PandasParameterType from inference_schema.parameter_types.numpy_parameter_type import NumpyP...
nilq/baby-python
python
#!/usr/bin/env python3 """ Copyright 2020 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BAS...
nilq/baby-python
python
#################################################################################################### # ------------------------------------------------------------------------------------------------ # # Functions for handling pool presence table analysis # -------------------------------------------------------------...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import cv2 import numpy as np import os def join_images(images): rows = len(images[0]) cols = len(images[0][0]) final_image = np.zeros((rows, cols, 1), np.uint8) print(len(images)) for img in images: for row in range(0, len(final_image)): ...
nilq/baby-python
python
_mod_txt = """ NEURON { POINT_PROCESS ExpSynMorphforge RANGE tau, e, i NONSPECIFIC_CURRENT i RANGE peak_conductance } UNITS { (nA) = (nanoamp) (mV) = (millivolt) (uS) = (microsiemens) } PARAMETER { tau = 0.1 (ms) <1e-9,1e9> e = 0 (mV) peak_conductance = -100000 () } ASSIGNED { v (mV) i (nA) ...
nilq/baby-python
python
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
nilq/baby-python
python
# Copyright 2018 Braxton Mckee # # 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...
nilq/baby-python
python
#!/usr/bin/env python """ read ntuple produced by Truth_JETMET... make some validation plots """ import ROOT ROOT.gROOT.SetBatch() from optparse import OptionParser def make_plots(file_name, post_fix): import AtlasStyle f1 = ROOT.TFile.Open(file_name) tree = f1.Get("physics") h_m4l = ROOT.TH1F("h_m4l...
nilq/baby-python
python
import numpy as np import matplotlib.pyplot as plt import pandas as pd import os cd=os.path.join('LinearRegression','Kidem_ve_Maas_VeriSeti.csv') dataset = pd.read_csv(cd) print(dataset.describe()) x=dataset.iloc[:,:-1].values y=dataset.iloc[:,1].values from sklearn.cross_validation import train_test_split x_train,...
nilq/baby-python
python
#__BEGIN_LICENSE__ # Copyright (c) 2015, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. # All rights reserved. # # The xGDS platform is licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance ...
nilq/baby-python
python
__author__ = 'Jeremy'
nilq/baby-python
python
#!/bin/false python3 # -*- coding: utf-8 -*- # # Copyright (C) 2020 The SymbiFlow Authors. # # Use of this source code is governed by a ISC-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/ISC # # SPDX-License-Identifier: ISC import os import shutil from BaseRunner import ...
nilq/baby-python
python
class Solution: def intToRoman(self, num): def get_representation(num): symbol_table={ 1:"I", 5:"V", 10:"X", 50:"L", 100:"C", 500:"D", 1000 :"M", } if num ...
nilq/baby-python
python
#py_gui.py "gui basics" from tkinter import * class Application(Frame): pass root = Tk() app = Application(master=root) app.mainloop()
nilq/baby-python
python
''' There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for yo...
nilq/baby-python
python
"""This acts as a kind of middleware - which has now been whittled down to only providing logging information""" import logging import platform from .constants import NameSpace from .config import CLIInputs, ParsedArgs from .utils import read_sdk_version logger = logging.getLogger("validate-cli-args") class Validat...
nilq/baby-python
python
# unet.py # from __future__ import division import torch.nn as nn import torch.nn.functional as F import torch from numpy.linalg import svd from numpy.random import normal from math import sqrt class UNet(nn.Module): def __init__(self, colordim = 1): super(UNet, self).__init__() self.conv1_1 = nn.Conv2d(colord...
nilq/baby-python
python
# First, we import a tool to allow text to pop up on a plot when the cursor # hovers over it. Also, we import a data structure used to store arguments # of what to plot in Bokeh. Finally, we will use numpy for this section as well! from bokeh.models import HoverTool, ColumnDataSource from bokeh.plotting import figur...
nilq/baby-python
python
from typing import Literal, Optional, Union class Trust_Region_Options: border_abstol: float = 1e-10 tol_step: float = 1.0e-10 tol_grad: float = 1.0e-6 abstol_fval: Optional[float] = None max_stall_iter: Optional[int] = None init_delta: float = 1.0 max_iter: int check_rel: float = 1.0e...
nilq/baby-python
python
import sqlite3 import os import MLBProjections.MLBProjections.DB.MLB as MLB import MLBProjections.MLBProjections.Environ as ENV from pprint import pprint ################################################################################ ################################################################################ ...
nilq/baby-python
python
# # Functional Python: The Lambda Lambada (Recursion) # Python Techdegree # # Created by Dulio Denis on 3/22/19. # Copyright (c) 2019 ddApps. All rights reserved. # ------------------------------------------------ # Recursion Challenge # ------------------------------------------------ # Challenge Task 1 of 1 # ...
nilq/baby-python
python
#!/usr/bin/env python import os import random import requests import subprocess import argparse import datetime import time import sys """Based off https://github.com/fogleman/primitive/blob/master/bot/main.py """ with open(os.path.expanduser('~/.flickr_api_key'), 'r') as key_file: FLICKR_API_KEY = key_file.read...
nilq/baby-python
python
import multiprocessing as mp import time def foo_pool(taskQ, x): print(x) taskQ.put(x) return x*x result_list = [] def log_result(result): # This is called whenever foo_pool(i) returns a result. # result_list is modified only by the main process, not the pool workers. result_list.append(result...
nilq/baby-python
python
# Crie um script Python que leia o nome de uma pessoa e mostre uma mensagem de boas-vindas de acordo com o valor digitado msg = 'Olá Mundo!' print(msg)
nilq/baby-python
python
import ldap import json import socket from urllib.parse import urlparse def create_from_env(): import os auth = LdapAuth(os.environ.get('LDAP_ADDRESS')) auth.base_dn = os.environ.get('LDAP_BASE_DN') auth.bind_dn = os.environ.get('LDAP_BIND_DN') auth.bind_pass = os.environ.get('LDAP_BIND_PASS') ...
nilq/baby-python
python
# %% coding=utf-8 import pandas as pd from atm import ATM from sklearn.model_selection import train_test_split beauty_data = pd.read_csv('/data/face/df_input.csv') select_cols = ['Image', 'label', '0_10_x', '0_10_y', '0_11_x', '0_11_y', '0_12_x', '0_12_y', '0_13_x', '0_13_y', '0_14_x', '0_14_y', '0_15_x...
nilq/baby-python
python
from .descriptor import DescriptorType from .object_type import ObjectDict __all__ = ["ObjectDict", "DescriptorType"]
nilq/baby-python
python
from typing import List class Solution: # 141, 逆波兰表达式求值, Medium def evalRPN(self, tokens: List[str]) -> int: stack = [] for token in tokens: if token == "+": oprand2 = stack.pop() oprand1 = stack.pop() stack.append(oprand1 +...
nilq/baby-python
python
# we are here to get weighted-5-node-subgraph, # given edge-count/bi-edge-count/strong-tie-count/weak-tie-count only to distinguish # to leverage on weighte 4 node subgraphs(edge_count, biedge_count, strong_count, weak_count, subNo) # next to share not edge import re,sys,random, os def subg(edges,s4,lf,sf,sfv,ror): ...
nilq/baby-python
python
#!/usr/bin/env python from distutils.core import setup setup(name="Eng Phys Office Space Tools", description="A set of scripts to work with the Eng Phys office space committee", version="0.1dev", author="Tim van Boxtel", author_email="vanboxtj@mcmaster.ca", py_modules=['parse-grad-studen...
nilq/baby-python
python
import tweepy #https://github.com/tweepy/tweepy import csv import pandas as pd # Used for progress bar import time import sys #Twitter API credentials consumer_key = "NBNgPGCBeGv80PcsYU3QWU94d" consumer_secret = "lvAaoSInlF9mPonoMMldFq5ZE96oAAl30TLh6ynVwK2tauvOQC" access_key = "1311728151265832961-AaFHXfZtozEgfoVZoFnN...
nilq/baby-python
python
#Pygments Tk Text from http://code.google.com/p/pygments-tk-text/ #Original Developer: Jonathon Eunice: jonathan.eunice@gmail.com __author__ = 'Robert Cope' __original__author__ = 'Jonathan Eunice'
nilq/baby-python
python
import random def generatePassword(pwlength): alphabet = "abcdefghijklmnopqrstuvwxyz" passwords = [] for i in pwlength: password = "" for j in range(i): next_letter_index = random.randrange(len(alphabet)) password = password + alphabet[next...
nilq/baby-python
python
GAME_SIZE = 4 SCORE_TO_WIN1 = 512 SCORE_TO_WIN2 = 1024 SCORE_TO_WIN3 = 2048 SCORE_TO_WIN0 = 256 from game2048.game import Game from game2048.agents import ExpectiMaxAgent # save the dataset f1 = open("dataset_256_3.txt", "w") f2 = open("dataset_512_3.txt", "w") f3 = open("dataset_1024_3.txt", "w") # for i in range(1...
nilq/baby-python
python
""" #################################################################################################### # Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved. # Filename : embedding.py # Abstract : torch.nn.Embedding function encapsulation. # Current Versi...
nilq/baby-python
python
from tweepy import Stream from stream_tweets import StockListener import get_old_tweets import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) def getTweets(stock_name): twitter_stream = Stream(get_old_tweets.auth, StockListener(stock_name)) twitter_stream.filter(track=[...
nilq/baby-python
python
from painter.config import NAME, PATH, SHELVES from templates import app # Painter base PAINTER = app.App(NAME, PATH, SHELVES)
nilq/baby-python
python
"""Various lower-level functions to support the computation of steady states""" import warnings import numpy as np import scipy.optimize as opt from numbers import Real from functools import partial from ...utilities import misc, solvers def instantiate_steady_state_mutable_kwargs(dissolve, block_kwargs, solver_kwa...
nilq/baby-python
python
from django.db import models from .book import Book from .language import Language class BookLanguage(models.Model): id = models.AutoField( primary_key=True, editable=False) book = models.ForeignKey( Book, db_column='book_id', blank=False, null=False, on_delet...
nilq/baby-python
python