repo_name
stringlengths 7
111
| __id__
int64 16.6k
19,705B
| blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
151
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_url
stringlengths 26
130
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
42
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 14.6k
687M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 12
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
10.2M
⌀ | gha_stargazers_count
int32 0
178k
⌀ | gha_forks_count
int32 0
88.9k
⌀ | gha_open_issues_count
int32 0
2.72k
⌀ | gha_language
stringlengths 1
16
⌀ | gha_archived
bool 1
class | gha_disabled
bool 1
class | content
stringlengths 10
2.95M
| src_encoding
stringclasses 5
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 10
2.95M
| extension
stringclasses 19
values | num_repo_files
int64 1
202k
| filename
stringlengths 4
112
| num_lang_files
int64 1
202k
| alphanum_fraction
float64 0.26
0.89
| alpha_fraction
float64 0.2
0.89
| hex_fraction
float64 0
0.09
| num_lines
int32 1
93.6k
| avg_line_length
float64 4.57
103
| max_line_length
int64 7
931
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
agodoriru/black_hat_python_code | 14,946,486,235,381 | 38fca40a3c245c5ef44e11625615db5a71af6905 | 1516cb356262b0b0ae364a7ea8e16c406bd37f64 | /CP5/REQUEST.py | 9a4d6bd82461f8a531324e1e61042ee1bf05d7b9 | []
| no_license | https://github.com/agodoriru/black_hat_python_code | d47b0729e8dc26d56a803994d4ab1670f0f1d559 | ebddc5a05567a2c25925b6f83fba3da33f5dc1dd | refs/heads/master | 2021-08-22T22:59:36.963045 | 2017-12-01T15:01:24 | 2017-12-01T15:01:24 | 109,213,254 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding:utf-8 -*-
import urllib2
url=""
headers={}
headers['User-agent']="Googlebot"
request=urllib2.Request(url,headers=headers)
response=urllib2.urlopen(request)
print response.read()
response.close() | UTF-8 | Python | false | false | 212 | py | 15 | REQUEST.py | 11 | 0.731132 | 0.712264 | 0 | 14 | 14.214286 | 44 |
kotbegemot/text-analyst | 9,534,827,425,275 | 9fb092a3cd64bb044032c05d68d2d4c0f9524bc4 | f5211410938b863b4b3d37e158eac74a3d676220 | /tests/test_fraud_detect.py | 80c0b5ddf3d891b15a76074e5cc1a3fc9037442d | [
"MIT"
]
| permissive | https://github.com/kotbegemot/text-analyst | 643bbb92e2581cac4bf43efe4a3f2ff7f3cf7964 | e91e6a80f4bd672f7119f38dfd67a940de312332 | refs/heads/master | 2018-02-06T17:28:38.086163 | 2016-09-20T09:45:45 | 2016-09-20T09:45:45 | 68,591,710 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from unittest import TestCase
from text_processing.word import detect_fraud
class FraudTestCase(TestCase):
def test_fraud_in_start_one_symbol(self):
is_fraud, word = detect_fraud('aвокадо')
self.assertTrue(is_fraud)
self.assertEqual('авокадо', word)
def test_fraud_in_start_few_symbols(self):
is_fraud, word = detect_fraud('apтишок')
self.assertTrue(is_fraud)
self.assertEqual('артишок', word)
def test_fraud_in_end_one_symbol(self):
is_fraud, word = detect_fraud('почтa')
self.assertTrue(is_fraud)
self.assertEqual('почта', word)
def test_fraud_in_end_few_symbols(self):
is_fraud, word = detect_fraud('пожap')
self.assertTrue(is_fraud)
self.assertEqual('пожар', word)
def test_fraud_in_middle_one_symbol(self):
is_fraud, word = detect_fraud('печeнька')
self.assertTrue(is_fraud)
self.assertEqual('печенька', word)
def test_fraud_in_middle_few_symbols(self):
is_fraud, word = detect_fraud('мизepишко')
self.assertTrue(is_fraud)
self.assertEqual('мизеришко', word)
def test_fraud_in_middle_twice(self):
is_fraud, word = detect_fraud('пeчeнька')
self.assertTrue(is_fraud)
self.assertEqual('печенька', word)
def test_fraud_in_middle_few_times_few_symbols(self):
is_fraud, word = detect_fraud('сбopнаярoссиипoфутболу')
self.assertTrue(is_fraud)
self.assertEqual('сборнаяроссиипофутболу', word)
def test_fraud_in_all_parts_of_word(self):
is_fraud, word = detect_fraud('cбopнаярoссиипoфутболуecт123-256_328печeнькy')
self.assertTrue(is_fraud)
self.assertEqual('сборнаяроссиипофутболуест123-256_328печеньку', word)
def test_good_latin(self):
is_fraud, word = detect_fraud('laserjet')
self.assertFalse(is_fraud)
self.assertEqual('laserjet', word)
def test_good_latin_and_cyrilic_1(self):
is_fraud, word = detect_fraud('cam-модуль')
self.assertFalse(is_fraud)
self.assertEqual('cam-модуль', word)
def test_good_latin_and_cyrilic_2(self):
is_fraud, word = detect_fraud('camмодуль')
self.assertFalse(is_fraud)
self.assertEqual('camмодуль', word)
def test_good_num_and_latin(self):
is_fraud, word = detect_fraud('rbc30set')
self.assertFalse(is_fraud)
self.assertEqual('rbc30set', word)
def test_good_num_and_cyrilic(self):
is_fraud, word = detect_fraud('30-летний')
self.assertFalse(is_fraud)
self.assertEqual('30-летний', word)
def test_good_num_and_cyrilic(self):
is_fraud, word = detect_fraud('30летний')
self.assertFalse(is_fraud)
self.assertEqual('30летний', word)
def test_fraud_cyrilic_and_latin(self):
is_fraud, word = detect_fraud('почкa')
self.assertTrue(is_fraud)
self.assertEqual('почка', word)
| UTF-8 | Python | false | false | 3,202 | py | 11 | test_fraud_detect.py | 9 | 0.647079 | 0.636272 | 0 | 85 | 33.835294 | 85 |
DimaSapsay/py_dates | 11,510,512,383,633 | 48279b0325a03241b3e0f0cc84fec7325ebf69e0 | 12652411eef24a5f0631ea3082717bf4f1080a23 | /dates.py | b089886419faede687b9addfd5e666adaddf4dbf | []
| no_license | https://github.com/DimaSapsay/py_dates | 7d99d33c30285b981b3de69b844161015534b07e | 76ffef86c5ede047d5b2e23093e3df17d0a53e0a | refs/heads/master | 2020-09-21T13:39:34.557301 | 2019-11-29T08:41:22 | 2019-11-29T08:41:22 | 224,804,930 | 0 | 0 | null | true | 2019-11-29T07:57:29 | 2019-11-29T07:57:28 | 2019-11-29T04:32:32 | 2019-11-29T04:32:29 | 1 | 0 | 0 | 0 | null | false | false | """
You have two dates in the format DD.MM.YYYY.
Calculate the difference between these dates in days.
"""
import datetime
def dates_between(date1, date2) -> int:
"""Calculate the difference"""
date1 = datetime.datetime.strptime(str(date1), '%d.%m.%Y')
date2 = datetime.datetime.strptime(date2, '%d.%m.%Y')
return (date2 - date1).days
| UTF-8 | Python | false | false | 354 | py | 1 | dates.py | 1 | 0.677966 | 0.655367 | 0 | 13 | 26.230769 | 62 |
Nicholas-t/Cryptio_btc_block_bg_checker | 824,633,752,145 | 7be6e0618b3c8d203f793af3028aa3d11786e48e | 9262ac708b94d7546bca3c36da9735f70f0293e9 | /bitcoin_block_bg_checker/main.py | f2f9e42e1aefc27a07f68f1710fbf1a8e936eeea | []
| no_license | https://github.com/Nicholas-t/Cryptio_btc_block_bg_checker | c6cd546d2999c7cc64c66b5e44f510757fda5590 | 6e7a1ec62100559a4490d6aa5034d77f6a36c141 | refs/heads/master | 2022-02-09T03:41:58.130967 | 2019-07-30T09:11:27 | 2019-07-30T09:11:27 | 197,717,062 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 9 10:57:21 2019
@author: Admin
"""
from bitcoin_block_bg_checker.complete import *
from bitcoin_block_bg_checker.handshake import handshake
from bitcoin_block_bg_checker.blockchain import blockexplorer as blk
import binascii
import codecs
VERSION = 70015
limit = 3
i = 0
def double_sha256(b):
first_round = hashlib.sha256(b).digest()
second_round = hashlib.sha256(first_round).digest()
return second_round
def flip_byte_order(string):
flipped = "".join(reversed([string[i:i+2] for i in range(0, len(string), 2)]))
return codecs.encode(flipped,"utf-8")
class GetHeadersMessage:
command = b"getheaders"
def __init__(self, locator, hashstop=0):
self.locator = locator
self.hashstop = hashstop
def to_bytes(self):
msg = self.locator.to_bytes()
msg += int_to_bytes(self.hashstop, 32)
return msg
class BlockLocator:
def __init__(self, hashes, version):
self.hashes = hashes
self.version = version
def to_bytes(self):
msg = int_to_bytes(self.version, 4)
msg += int_to_var_int(len(self.hashes))
for hash_ in self.hashes:
msg += int_to_bytes(hash_, 32)
return msg
def construct_block_locator(all_hashes):
locator_hashes = []
height = len(all_hashes) - 1
step = 1
while height >= 0:
# every iteration adds header at `height` and decrements `step`
header = all_hashes[height]
locator_hashes.append(header)
height -= step
# `step` starts doubling after the 11th hash
if len(locator_hashes) > 10:
step *= 2
# make sure we have the genesis hash
if not locator_hashes.index(block):
locator_hashes.append(block)
return BlockLocator(hashes=locator_hashes, version=VERSION)
def send_getheaders(sock):
locator = construct_block_locator(header_hashes)
getheaders = GetHeadersMessage(locator)
packet = Packet(getheaders.command, getheaders.to_bytes())
sock.send(packet.to_bytes())
class HeadersMessage:
command = b"headers"
def __init__(self, count, headers):
self.count = count
self.headers = headers
@classmethod
def from_bytes(cls, b):
s = io.BytesIO(b)
count = read_var_int(s)
headers = []
for _ in range(count):
header = BlockHeader.from_stream(s)
headers.append(header)
return cls(count, headers)
def __repr__(self):
return f"<HeadersMessage #{len(self.headers)}>"
class BlockHeader:
def __init__(
self, version, prev_block, merkle_root, timestamp, bits, nonce, txn_count
):
self.version = version
self.prev_block = prev_block
self.merkle_root = merkle_root
self.timestamp = timestamp
self.bits = bits
self.nonce = nonce
self.txn_count = txn_count
@classmethod
def from_stream(cls, s):
version = read_int(s, 4)
prev_block = read_int(s, 32)
merkle_root = read_int(s, 32)
timestamp = read_int(s, 4)
bits = s.read(4)
nonce = s.read(4)
txn_count = read_var_int(s)
return cls(version, prev_block, merkle_root, timestamp, bits, nonce, txn_count)
def to_bytes(self):
result = int_to_bytes(self.version, 4)
result += int_to_bytes(self.prev_block, 32)
result += int_to_bytes(self.merkle_root, 32)
result += int_to_bytes(self.timestamp, 4)
result += self.bits
result += self.nonce
return result
def hash(self):
s = self.to_bytes()
sha = double_sha256(s)
return sha[::-1] # little endian
def pow(self):
s = self.to_bytes()
sha = double_sha256(s)
return bytes_to_int(sha)
def target(self):
# last byte is exponent
exponent = self.bits[-1]
# the first three bytes are the coefficient in little endian
coefficient = bytes_to_int(self.bits[:-1])
# the formula is:
# coefficient * 2**(8*(exponent-3))
return coefficient * 2 ** (8 * (exponent - 3))
def check_pow(self):
return self.pow() < self.target()
def pretty(self):
hx = hex(self.pow())[2:] # remove "0x" prefix
sigfigs = len(hx)
padding = "0" * (64 - sigfigs)
return padding + hx
def __str__(self):
headers = ["BlockHeader", ""]
attrs = [
"version",
"prev_block",
"merkle_root",
"timestamp",
"bits",
"nonce",
"txn_count",
]
rows = [[attr, fmt(getattr(self, attr))] for attr in attrs]
rows = [["hash", self.pretty()]] + rows
# import pdb; pdb.set_trace()
return tabulate(rows, headers, tablefmt="grid")
def save_header_hashes(block_headers):
for header in block_headers:
# we add it to the header_hashes if prev_block is our current tip
if header.prev_block == header_hashes[-1]:
header_hashes.append(header.pow())
else:
raise RuntimeError("received out-of-order block")
class Block(BlockHeader):
def __init__(
self, version, prev_block, merkle_root, timestamp, bits, nonce, txn_count, txns
):
super().__init__(
version, prev_block, merkle_root, timestamp, bits, nonce, txn_count
)
self.txns = txns
@classmethod
def from_stream(cls, s):
version = read_int(s, 4)
prev_block = read_int(s, 32)
merkle_root = read_int(s, 32)
timestamp = read_int(s, 4)
bits = s.read(4)
nonce = s.read(4)
txn_count = read_var_int(s)
txns = [Tx.from_stream(s) for _ in range(txn_count)]
return cls(
version, prev_block, merkle_root, timestamp, bits, nonce, txn_count, txns
)
def __repr__(self):
return f"<Block {self.pretty()} >"
class InventoryItem:
def __init__(self, type_, hash_):
self.type = type_
self.hash = hash_
@classmethod
def from_stream(cls, s):
type_ = bytes_to_int(s.read(4))
hash_ = s.read(32)
return cls(type_, hash_)
def to_bytes(self):
msg = b""
msg += int_to_bytes(self.type, 4)
msg += self.hash
return msg
def __repr__(self):
return f"<InvItem {inv_map[self.type]} {self.hash}>"
class GetData:
command = b"getdata"
def __init__(self, items=None):
if items is None:
self.items = []
else:
self.items = items
def to_bytes(self):
msg = int_to_var_int(len(self.items))
for item in self.items:
msg += item.to_bytes()
return msg
def __repr__(self):
return f"<Getdata {repr(self.inv)}>"
def request_blocks(sock):
items = [InventoryItem(2, int_to_bytes(hash_, 32))
for hash_ in header_hashes]
getdata = GetData(items=items)
packet = Packet(getdata.command, getdata.to_bytes())
sock.send(packet.to_bytes())
def handle_headers_packet(packet, sock):
headers_message = HeadersMessage.from_bytes(packet.payload)
block_headers = headers_message.headers
print(f"{len(block_headers)} new headers")
save_header_hashes(block_headers)
print(f"We now have {len(header_hashes)} headers")
request_blocks(sock)
def handle_block_packet(packet, sock):
block = Block.from_stream(io.BytesIO(packet.payload))
for txn in block.txns:
print(txn)
yield txn
def handle_packet(packet, sock, target_unspent_tx):
global i
command_to_handler = {
b"headers": handle_headers_packet,
b"block": handle_block_packet,
}
handler = command_to_handler.get(packet.command)
if handler:
i = 0
print(f'handling "{packet.command}"')
if packet.command == b"block":
for txn in handler(packet, sock):
for ins in txn.tx_ins:
if ins.prev_tx in target_unspent_tx:
return txn
else:
handler(packet, sock)
return None
else:
print(f'discarding "{packet.command}"')
if packet.command == b'inv':
i+=1
if i >= limit :
return -1
return None
class Tx:
def __init__(self, version, tx_ins, tx_outs, locktime, testnet=False):
self.version = version
self.tx_ins = tx_ins
self.tx_outs = tx_outs
self.locktime = locktime
self.testnet = testnet
def get_raw(self):
raw = b''
raw+= binascii.hexlify(int_to_bytes(self.version,4))
raw+= binascii.hexlify(int_to_bytes(len(self.tx_ins),4))
for t in self.tx_ins:
raw+= t.get_raw()
raw+= binascii.hexlify(int_to_bytes(len(self.tx_outs),4))
for t in self.tx_outs:
raw+= t.get_raw()
raw+= binascii.hexlify(int_to_bytes(self.locktime,4))
return raw
def get_hash(self):
try:
return codecs.encode(double_sha256(binascii.unhexlify(self.get_raw()))[::-1], "hex_codec")
except:
return "Failed to calculate hash"
@classmethod
def from_stream(cls, s):
"""Takes a byte stream and from_streams the transaction at the start
return a Tx object
"""
# s.read(n) will return n bytes
# version has 4 bytes, little-endian, interpret as int
version = bytes_to_int(s.read(4))
# num_inputs is a varint, use read_var_int(s)
num_inputs = read_var_int(s)
# each input needs parsing
inputs = []
for _ in range(num_inputs):
inputs.append(TxIn.from_stream(s))
# num_outputs is a varint, use read_var_int(s)
num_outputs = read_var_int(s)
# each output needs parsing
outputs = []
for _ in range(num_outputs):
outputs.append(TxOut.from_stream(s))
# locktime is 4 bytes, little-endian
locktime = bytes_to_int(s.read(4))
# return an instance of the class (cls(...))
return cls(version, inputs, outputs, locktime)
def __repr__(self):
try :
t = blk.get_tx(self.get_hash())
print(t.address, " successfully found")
exit()
except:
return "<Tx new \n ntx_ins: {} \n tx_outs: {}> \n".format(
",".join([repr(t) for t in self.tx_ins]),
",".join([repr(t) for t in self.tx_outs]))
class TxIn:
def __init__(self, prev_tx, prev_index, script_sig, sequence):
self.prev_tx = prev_tx.hex()
self.prev_index = prev_index
self.script_sig = script_sig # TODO from_stream it
self.sequence = sequence
def get_raw(self):
raw= b''
raw+= flip_byte_order(self.prev_tx)
raw+= binascii.hexlify(int_to_bytes(self.prev_index,4))
raw+= codecs.encode('{0:x}'.format(len(self.script_sig)),"utf-8")
raw+= binascii.hexlify(self.script_sig)
raw+= codecs.encode('{0:x}'.format(self.sequence),"utf-8")
return raw
def __repr__(self):
return "<TxIn {}>".format(self.prev_tx)
@classmethod
def from_stream(cls, s):
"""Takes a byte stream and from_streams the tx_input at the start
return a TxIn object
"""
# s.read(n) will return n bytes
# prev_tx is 32 bytes, little endian
prev_tx = s.read(32)[::-1]
# prev_index is 4 bytes, little endian, interpret as int
prev_index = bytes_to_int(s.read(4))
# script_sig is a variable field (length followed by the data)
# get the length by using read_var_int(s)
script_sig_length = read_var_int(s)
script_sig = s.read(script_sig_length)
# sequence is 4 bytes, little-endian, interpret as int
sequence = bytes_to_int(s.read(4))
# return an instance of the class (cls(...))
return cls(prev_tx, prev_index, script_sig, sequence)
class TxOut:
def __init__(self, amount, script_pubkey):
self.amount = amount
self.script_pubkey = script_pubkey # TODO from_stream it
def get_raw(self):
raw = b''
raw+= binascii.hexlify(int_to_bytes(self.amount,8))
raw+= codecs.encode('{0:x}'.format(len(self.script_pubkey)),"utf-8")
raw+= binascii.hexlify(self.script_pubkey)
return raw
def __repr__(self):
return "<Amount {}>".format(self.amount)
@classmethod
def from_stream(cls, s):
"""Takes a byte stream and from_streams the tx_output at the start
return a TxOut object
"""
# s.read(n) will return n bytes
# amount is 8 bytes, little endian, interpret as int
amount = bytes_to_int(s.read(8))
# script_pubkey is a variable field (length followed by the data)
# get the length by using read_var_int(s)
script_pubkey_length = read_var_int(s)
script_pubkey = s.read(script_pubkey_length)
# return an instance of the class (cls(...))
return cls(amount, script_pubkey)
header_hashes = []
block = 0
def block_search(address, block_hash, target_unspent_tx = -1):
global block
block = int(block_hash, 16)
global header_hashes
header_hashes = [block]
sock = handshake(address, log=False)
# comment this line out and we don't get any headers
send_getheaders(sock)
while True:
packet = Packet.from_socket(sock)
temp = handle_packet(packet, sock, target_unspent_tx)
if isinstance(temp,Tx):
print("new_transaction detected from unspent transaction {}".format(target_unspent_tx))
return temp
if temp == -1:
break
return None
def recent_hash():
return blk.get_latest_block().hash
| UTF-8 | Python | false | false | 14,030 | py | 8 | main.py | 7 | 0.573628 | 0.564006 | 0 | 462 | 29.367965 | 102 |
Ro9ueAdmin/django-orchestra | 16,226,386,481,136 | c438baa8e2ed4a595949145a6dbc91f44913964b | be4b394066275072f995a6fa90fd0e9adb68371d | /orchestra/contrib/saas/services/owncloud.py | 2f850f071c38837b55f1215f61f4ff7ea583ae1e | [
"BSD-3-Clause"
]
| permissive | https://github.com/Ro9ueAdmin/django-orchestra | dc35345c2fb01a3520784d1dddb33f42da8e0918 | 49c84f13a8f92427b01231615136549fb5be3a78 | refs/heads/master | 2021-06-19T16:15:35.235999 | 2017-06-16T13:33:41 | 2017-06-16T13:33:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django import forms
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from .. import settings
from .options import SoftwareService
class OwnCloudService(SoftwareService):
name = 'owncloud'
verbose_name = "ownCloud"
icon = 'orchestra/icons/apps/ownCloud.png'
site_domain = settings.SAAS_OWNCLOUD_DOMAIN
| UTF-8 | Python | false | false | 371 | py | 529 | owncloud.py | 443 | 0.770889 | 0.770889 | 0 | 13 | 27.538462 | 55 |
jqnv/python_challenges_Bertelsmann_Technology_Scholarship | 7,679,401,530,855 | 4fa0ec247c116334cb8f5b87e04e904cb728bc3e | 6e4ad02763e234f2d1982de64163f4054e30912d | /passwd_to_csv.py | 5f27f204c8cb3f4706db5ea1e04fdbd9ebe24c02 | []
| no_license | https://github.com/jqnv/python_challenges_Bertelsmann_Technology_Scholarship | d8852bc58490621acf7cb84557b1ce80c0f73e8e | cf8505dd5e31e57142bb24bdb982b501cef74af1 | refs/heads/master | 2023-03-15T08:41:07.685075 | 2021-03-12T04:38:12 | 2021-03-12T04:38:12 | 323,754,667 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | # For this exercise, create a function, passwd_to_csv, that takes two filenames as arguments: the first is a
# passwd-style file to read from, and the second is the name of a file in which to write the output.The new file’s
# contents are the username (index 0) and the user ID (index 2).Note that a record may contain a comment,
# in which case it will not have anything at index 2; you should take that into consideration when writing
# the file.The output file should use TAB characters to separate the elements.
# To run the file at the command line Prompt>python passwd_to_csv.py in_file.csv out_file.csv
import csv
from sys import argv
# Function to read username and userID from a csv file
# Creating a new csv file with just the info required
def passwd_to_csv():
# Get the name of input and output files
f_in=argv[1]
f_out=argv[2]
# Read input file line by line storing every element in the data list
with open(f_in, mode="r") as f_input:
for line in f_input:
data = line.split(":")
text=line.strip()
# Ignoring any line without a colon separating strings
if len(text)>2 and text.find(":")!=-1:
# Writing username and userID to a new file separated by a tab character
with open(f_out,mode="a",newline='') as f_output:
o=csv.writer(f_output)
o.writerow([data[0],"\t",data[2]])
if __name__ == '__main__':
passwd_to_csv()
| UTF-8 | Python | false | false | 1,491 | py | 65 | passwd_to_csv.py | 56 | 0.657488 | 0.651444 | 0 | 36 | 40.361111 | 114 |
julianMendozaGg/ProyectoFinal | 14,705,968,044,811 | 5e60b853b36f9bd224ea8ed1151f1b526e6d22c1 | d28972e2560a322ce97059d02f40d52f17d2fe34 | /PintarNiveles/Abstraction.py | a1a2087c9404d90cb0310ce910de43a800cf0e63 | []
| no_license | https://github.com/julianMendozaGg/ProyectoFinal | e9ced3e7bb691594e757a4c6ee0340f8ed5fbb7a | ed34480f8bbe2b807062ab398d25dd3ee99a4fb7 | refs/heads/master | 2022-12-02T06:48:18.016735 | 2020-08-17T03:16:42 | 2020-08-17T03:16:42 | 284,527,547 | 0 | 1 | null | false | 2020-08-17T03:16:43 | 2020-08-02T19:29:04 | 2020-08-13T20:59:46 | 2020-08-17T03:16:42 | 1,869 | 0 | 1 | 0 | Python | false | false | from CreadorDeNiveles.Creador import *
import pygame as p
class Abstraction():
def __init__(self, ventana):
self.ventana = ventana
def entregarlvl1(self):
lvl1 = ConcreteImplementation1(self.ventana)
return lvl1.pintarNivel()
def entregarlvl2(self): pass
def entregarlvl3(self): pass
class Implementation():
def __init__(self, ventana):
self.VERDE = (15, 255, 8)
self.ROJO = (255, 0, 0)
self.ventana = ventana
self.X = 50
self.Y = 50
self.rectangles = []
self.positions = []
def pintarNivel(self): pass
class ConcreteImplementation1(Implementation):
def __init__(self, ventana):
super().__init__(ventana)
def pintarNivel(self):
creat = CreadorNivelFacil()
prod = creat.diseñarNivel().crear()
for i in range(len(prod)):
for j in range(len(prod)):
if prod[i][j] == "0":
p.draw.rect(self.ventana, self.VERDE,
(self.X, self.Y, 80, 80))
self.rectangles.append(p.Rect(self.X,self.Y,80,80))
elif prod[i][j] == "1":
p.draw.rect(self.ventana, self.ROJO,
(self.X, self.Y, 80, 80))
self.positions.append((self.X, self.Y))
self.X = self.X + 80
self.Y = self.Y + 80
self.X = 50
| UTF-8 | Python | false | false | 1,503 | py | 13 | Abstraction.py | 13 | 0.500666 | 0.472703 | 0 | 52 | 26.884615 | 71 |
janusnic/django-cropduster | 14,998,025,806,681 | 286c3fffe8d0e7d9ffcd0bf8c601783a222f3f17 | 43a417e36ed6bacd0f59a1e0fa3492afdd5ae032 | /cropduster3/models.py | c0f0632c1351beba6bdb3b1619ef6033262d3509 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
]
| permissive | https://github.com/janusnic/django-cropduster | 19e8dfdec3b8fcb6b43a991d1c0ace7ea21872ad | cc3eba654c35b7b278facf81085eb11b54e615aa | refs/heads/master | 2021-01-09T07:03:38.596733 | 2015-05-05T13:45:28 | 2015-05-05T13:45:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import re
import shutil
import time
import uuid
import os
import datetime
import hashlib
import itertools
import urllib
from PIL import Image as pil
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor
from django.conf import settings
from django.db.models.signals import post_save
from . import utils
from . import settings as cropduster_settings
try:
from caching.base import CachingMixin, CachingManager
except ImportError:
class CachingMixin(object):
pass
CachingManager = models.Manager
assert not settings.CROPDUSTER_UPLOAD_PATH.startswith('/')
nearest_int = lambda a: int(round(a))
to_retina_path = lambda p: '%s@2x%s' % os.path.splitext(p)
class SizeSet(CachingMixin, models.Model):
objects = CachingManager()
class Meta:
app_label = cropduster_settings.CROPDUSTER_APP_LABEL
db_table = '%s_sizeset' % cropduster_settings.CROPDUSTER_DB_PREFIX
name = models.CharField(max_length=255, db_index=True)
slug = models.SlugField(max_length=50, null=False, unique=True)
def __unicode__(self):
return u"%s" % self.name
def get_size_by_ratio(self):
""" Shorthand to get all the unique ratios for display in the admin,
rather than show every possible thumbnail
"""
size_query = Size.objects.filter(size_set__id=self.id)
size_query.query.group_by = ["aspect_ratio"]
try:
return size_query
except ValueError:
return None
class Size(CachingMixin, models.Model):
objects = CachingManager()
class Meta:
app_label = cropduster_settings.CROPDUSTER_APP_LABEL
db_table = '%s_size' % cropduster_settings.CROPDUSTER_DB_PREFIX
# An Size not associated with a set is a 'one off'
size_set = models.ForeignKey(SizeSet, null=True)
date_modified = models.DateTimeField(auto_now=True, null=True)
name = models.CharField(max_length=255, db_index=True)
slug = models.SlugField(max_length=50, null=False)
height = models.PositiveIntegerField(null=True, blank=True)
width = models.PositiveIntegerField(null=True, blank=True)
aspect_ratio = models.FloatField(null=True, blank=True)
auto_crop = models.BooleanField(default=False)
retina = models.BooleanField(default=False)
def get_height(self):
"""
Return calculated height, if possible.
@return: Height
@rtype: positive int
"""
if self.height is None and self.width and self.aspect_ratio:
return nearest_int(self.width / self.aspect_ratio)
return self.height
def get_width(self):
"""
Returns calculate width, if possible.
@return: Width
@rtype: positive int
"""
if self.width is None and self.height and self.aspect_ratio:
return nearest_int(self.height * self.aspect_ratio)
return self.width
def get_aspect_ratio(self):
"""
Returns calculated aspect ratio, if possible.
@return: Aspect Ratio
@rtype: float
"""
if self.aspect_ratio is None and self.height and self.width:
return round(self.width / float(self.height), 2)
return self.aspect_ratio
def get_dimensions(self):
"""
Returns all calculated dimensions for the size.
@return: width, height, aspect ratio
@rtype: (int > 0, int > 0, float > 0)
"""
return (self.get_width(), self.get_height(), self.get_aspect_ratio())
def calc_dimensions(self, width, height):
"""
From a given set of dimensions, calculates the rendered size.
@param width: Starting width
@type width: Positive int
@param height: Starting height
@type height: Positive int
@return: rendered width, rendered height
@rtype: (Width, Height)
"""
w, h, a = self.get_dimensions()
# Explicit dimension give explicit answers
if w and h:
return w, h, a
# Empty sizes are basically useless.
if not (w or h):
return width, height, None
aspect_ratio = round(width / float(height), 2)
if w:
h = nearest_int(w / aspect_ratio)
else:
w = nearest_int(h * aspect_ratio)
return w, h, round(w / float(h), 2)
def __unicode__(self):
return u"%s: %sx%s" % (self.name, self.width, self.height)
def save(self, *args, **kwargs):
if self.slug is None:
self.slug = uuid.uuid4().hex
w, h, a = self.get_dimensions()
self.width = w
self.height = h
self.aspect_ratio = a
super(Size, self).save(*args, **kwargs)
class Crop(CachingMixin, models.Model):
class Meta:
app_label = cropduster_settings.CROPDUSTER_APP_LABEL
db_table = '%s_crop' % cropduster_settings.CROPDUSTER_DB_PREFIX
objects = CachingManager()
crop_x = models.PositiveIntegerField(default=0, blank=True, null=True)
crop_y = models.PositiveIntegerField(default=0, blank=True, null=True)
crop_w = models.PositiveIntegerField(default=0, blank=True, null=True)
crop_h = models.PositiveIntegerField(default=0, blank=True, null=True)
def __unicode__(self):
return u"Crop: (%i, %i),(%i, %i) " % (
self.crop_x,
self.crop_y,
self.crop_x + self.crop_w,
self.crop_y + self.crop_h,
)
class ImageMetadata(CachingMixin, models.Model):
objects = CachingManager()
class Meta:
app_label = cropduster_settings.CROPDUSTER_APP_LABEL
db_table = '%s_image_meta' % cropduster_settings.CROPDUSTER_DB_PREFIX
# Attribution details.
attribution = models.CharField(max_length=255, blank=True, null=True)
attribution_link = models.URLField(max_length=255, blank=True, null=True)
caption = models.CharField(max_length=255, blank=True, null=True)
class Image(CachingMixin, models.Model):
objects = CachingManager()
class Meta:
app_label = cropduster_settings.CROPDUSTER_APP_LABEL
db_table = '%s_image' % cropduster_settings.CROPDUSTER_DB_PREFIX
verbose_name = "Image"
verbose_name_plural = "Image"
# Original image if this is generated from another image.
original = models.ForeignKey('self',
related_name='derived',
null=True)
image = models.ImageField(
upload_to=lambda obj, filename: obj.cropduster_upload_to(filename),
width_field='width',
height_field='height',
max_length=255)
# An image doesn't need to have a size associated with it, only
# if we want to transform it.
size = models.ForeignKey(Size, null=True)
crop = models.OneToOneField(Crop, null=True)
# Image can have 0:N size-sets
size_sets = models.ManyToManyField(SizeSet, null=True)
# Single set of attributions
metadata = models.ForeignKey(ImageMetadata, null=True, blank=True)
date_modified = models.DateTimeField(auto_now=True, null=True)
width = models.PositiveIntegerField(null=True)
height = models.PositiveIntegerField(null=True)
@staticmethod
def cropduster_upload_to(filename, fmt="%Y/%m/%d"):
if fmt:
now = datetime.date.today()
fmt = now.strftime(fmt)
else:
fmt = ''
return os.path.join(settings.CROPDUSTER_UPLOAD_PATH, fmt, filename)
@property
def retina_path(self):
"""
Returns the path to the retina image if it exists.
"""
return to_retina_path(self.image.path)
@property
def aspect_ratio(self):
if self.width and self.height:
return round(self.width / float(self.height), 2)
return None
@property
def is_original(self):
return self.original is None
def add_size_set(self, size_set=None, **kwargs):
"""
Adds a size set to the current image. If the sizeset
is provided, will add that otherwise it will query
all size sets that match the **kwarg criteria
@return: Newly created derived images from size set.
@rtype: [Image1, ...]
"""
if size_set is None:
size_set = SizeSet.objects.get(**kwargs)
self.size_sets.add(size_set)
# Do not duplicate images which are already in the
# derived set.
d_ids = set(d.size.id for d in self.derived.all())
# Create new derived images from the size set
return [self.new_derived_image(size=size)
for size in size_set.size_set.all()
if size.id not in d_ids]
def get_metadata(self):
if self.metadata is None:
if self.original is not None:
metadata = self.original.get_metadata()
else:
metadata = ImageMetadata()
self.metadata = metadata
return self.metadata
def new_derived_image(self, **kwargs):
"""
Creates a new derived image from the current image.
@return: new Image
@rtype: Image
"""
return Image(original=self, metadata=self.get_metadata(), **kwargs)
def set_manual_size(self, **kwargs):
"""
Sets a manual size on the image.
@return: New Size object, unsaved
@rtype: @{Size}
"""
# If we don't have a size or we have a size from a size set,
# we need to create a new Size object.
if self.size is None or self.size.size_set is not None:
self.size = Size(**kwargs)
else:
# Otherwise, update the values
for k, v in kwargs.iteritems():
setattr(self.size, k, v)
return self.size
def _save_to_tmp(self, image):
"""
Saves an image to a tempfile.
@param image: Image to save.
@type image:
@return: Temporary path where the image is saved.
@rtype: /path/to/file
"""
path = self._get_tmp_img_path()
return utils.save_image(image, path)
def render(self, force=False):
"""
Renders an image according to its Crop and its Size. If the size also
specifies a retina image, it will attempt to render that as well. If a
crop is set, it is applied to the image before any resizing happens.
By default, render will throw an error if an attempt is made to render
an original image.
NOTE: While render will create a new image, it will be stored it in a
temp file until the object is saved when it will overwrite the
previously stored image. There are a couple of reasons for this:
1. If there's any sort of error, the previous image is preserved,
making re-renderings of images safe.
2. We have to resave the image anyways since 'width' and 'height' have
likely changed.
3. If for some reason we want to 'rollback' a change, we don't have
to do anything special.
The temporary images are saved in CROPDUSTER_TMP_DIR if available, or
falls back to the directory the image currently resides in.
@param force: If force is True, render will allow overwriting the
original image.
@type force: bool.
"""
if not force and self.is_original:
raise ValidationError("Cannot render over an original image. "\
"Use render(force=True) to override.")
if not (self.crop or self.size):
# Nothing to do.
return
# We really only want to do rescalings on derived images, but
# we don't prevent people from it.
if self.original:
image_path = self.original.image.path
else:
image_path = self.image.path
if self.crop:
image = utils.create_cropped_image(image_path,
self.crop.crop_x,
self.crop.crop_y,
self.crop.crop_w,
self.crop.crop_h)
else:
image = pil.open(image_path)
# If we are resizing the image.
if self.size:
size = self.size
orig_width, orig_height = image.size
width, height = size.calc_dimensions(orig_width, orig_height)[:2]
if size.retina:
# If we are supposed to build a retina, make sure the
# dimensions are large enough. No stretching allowed!
self._new_retina = None
if orig_width >= (width * 2) and orig_height >= (height * 2):
retina = utils.rescale(utils.copy_image(image),
width * 2, height * 2, size.auto_crop)
self._new_retina, _fmt = self._save_to_tmp(retina)
# Calculate the main image
image = utils.rescale(image, width, height, size.auto_crop)
# Save the image in a temporary place
self._new_image, self._new_image_format = self._save_to_tmp(image)
def _get_tmp_img_path(self):
"""
Returns a temporary image path. We should probably be using the
Storage objects, but this works for now.
Tries to it in CROPDUSTER_TMP_DIR if set, falls back to the current
directory of the image.
@return: Temporary image location.
@rtype: "/path/to/file"
"""
dest_path = self.get_dest_img_path()
if hasattr(settings, 'CROPDUSTER_TMP_DIR'):
tmp_path = settings.CROPDUSTER_TMP_DIR
else:
tmp_path = os.path.dirname(dest_path)
ext = os.path.splitext(dest_path)[1]
return os.path.join(tmp_path, uuid.uuid4().hex + ext)
def get_dest_img_path(self):
"""
Figures out where to place save a new image for this Image.
@return: path to image location
@rtype: "/path/to/image"
"""
# If we have a path already, reuse it.
if self.image:
return self.image.path
return self.get_dest_img_from_base(self.original.image.path)
def get_dest_img_name(self):
if self.image:
return self.image.name
return self.get_dest_img_from_base(self.original.image.name)
def get_dest_img_from_base(self, base):
# Calculate it from the size slug if possible.
if self.size:
slug = self.size.slug
elif self.crop:
slug = os.path.splitext(os.path.basename(base))[0]
else:
# Guess we have to return the original path
return base
path, ext = os.path.splitext(base)
return os.path.join(path, slug) + ext
def has_size(self, size_slug):
return self.derived.filter(size__slug=size_slug).count() > 0
def set_crop(self, x, y, width, height):
"""
Sets the crop size for an image. It should be noted that the crop
object is NOT saved by default, so should be saved manually.
Adds a crop from top-left (x,y) to bottom-right (x+width, y+width).
@return: The unsaved crop object.
@rtype: {Crop}
"""
if self.crop is None:
self.crop = Crop()
self.crop.crop_x = x
self.crop.crop_y = y
self.crop.crop_w = width
self.crop.crop_h = height
return self.crop
def __unicode__(self):
return self.get_absolute_url() if self.image else u""
def get_absolute_url(self, date_hash=True):
"""
Gets the absolute url for an image.
@param date_hash: If True, adds a GET param hex hash indicating
the update date for the image.
@type date_hash: bool
@return: Absolute path to the url
@rtype: basestring
"""
path = self.image.url
if date_hash:
unix_time = int(time.mktime(self.date_modified.timetuple()))
path += '?' + format(unix_time, 'x')
# Django's filepath_to_uri passes '()' in the safe kwarg to
# urllib.quote, which is problematic when used in inline
# background-image:url() styles.
# This regex replaces '(' and ')' with '%28' and '%29', respectively
url = unicode(path)
return re.sub(r'([\(\)])', lambda m: urllib.quote(m.group(1)), url)
def get_thumbnail(self, slug, size_set=None):
"""
Returns the derived image for the Image or None if it does not exist.
@param slug: Name of the image slug.
@type slug: basestring
@param size_set: Size Set object to filter by, if available.
@type size_set: SizeSet.
@return: Image or None
@rtype: Image or None
"""
try:
if size_set:
return self.derived.get(size__size_set=size_set, size__slug=slug)
else:
return self.derived.filter(size__slug=slug)[0]
except IndexError:
return None
except Image.DoesNotExist:
return None
def __init__(self, *args, **kwargs):
if 'metadata' not in kwargs and 'metadata_id' not in kwargs:
kwargs['metadata'] = ImageMetadata()
return super(Image, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
# Make sure our original image is saved
if self.original and not self.original.pk:
self.original.save()
# Make sure we've saved our metadata
metadata = self.get_metadata()
if not metadata.id:
metadata.save()
# Bug #8892, not updating the 'metadata_id' field.
self.metadata = metadata
# Do we have a new image? If so, we need to move it over.
if getattr(self, '_new_image', None) is not None:
name = self.get_dest_img_name()
if getattr(settings, 'CROPDUSTER_NORMALIZE_EXT', False):
if not name.endswith(self._new_image_format.lower()):
rest, _ext = os.path.splitext(name)
name = rest + '.' + self._new_image_format.lower()
# Since we only store relative paths in here, but want to get
# the correct absolute path, we have to set the image name first
# before we set the image directly (which will)
self.image.name = name
os.rename(self._new_image, self.image.path)
self.image = name
# I'm not a fan of all this state, but it needs to be saved
# somewhere.
del self._new_image
del self._new_image_format
# Check for a new retina
if hasattr(self, '_new_retina'):
retina_path = self.retina_path
if self._new_retina is None:
if os.path.exists(retina_path):
# If the reina is now invalid, remove the previous one.
os.unlink(retina_path)
else:
os.rename(self._new_retina, retina_path)
del self._new_retina
return super(Image, self).save(*args, **kwargs)
@property
def descendants(self):
"""
Gets all descendants for the current image, starting at the highest
levels and recursing down.
@returns set of descendants
@rtype <Image1, ...>
"""
stack = [self]
while stack:
original = stack.pop()
children = original.derived.all()
for c in children:
c.original = original
yield c
stack.extend(children)
@property
def ancestors(self):
"""
Returns the set of ancestors associated with an Image
"""
current = self
while current.original:
yield current.original
current = current.original
def delete(self, remove_images=True, *args, **kwargs):
"""
Deletes an image, attempting to clean up foreign keys as well.
@param remove_images: If True, performs a bulk delete and then
deletes all derived images. It does not,
however, remove the directories.
@type remove_images: bool
"""
# Delete manual image sizes.
if self.size is not None and self.size.size_set is None:
self.size.delete()
# All crops are unique to the image.
if self.crop is not None:
self.crop.delete()
return super(Image, self).delete(*args, **kwargs)
class CropDusterReverseProxyDescriptor(ReverseSingleRelatedObjectDescriptor):
def __set__(self, instance, value):
if value is not None and not isinstance(value, self.field.rel.to):
# ok, are we a direct subclass?
mro = self.field.rel.to.__mro__
if len(mro) > 1 and type(value) == mro[1]:
# Convert to the appropriate proxy object
value.__class__ = self.field.rel.to
super(CropDusterReverseProxyDescriptor, self).__set__(instance, value)
PROXY_COUNT = itertools.count(1)
class CropDusterField(models.ForeignKey):
dynamic_path = False
def __init__(self, upload_to=None, dynamic_path=False, *args, **kwargs):
if upload_to is None:
if not args and 'to' not in kwargs:
args = (Image,)
super(CropDusterField, self).__init__(*args, **kwargs)
return
# Figure out what we are inheriting from.
if args and issubclass(args[0], Image):
base_cls = args[0]
args = tuple(args[1:])
elif 'to' in kwargs and issubclass(kwargs.get('to'), Image):
base_cls = kwargs.get('to')
else:
base_cls = Image
if callable(upload_to) and dynamic_path:
# we have a function and we want it to dynamically change
# based on the instance
self.dynamic_path = True
if isinstance(upload_to, basestring):
upload_path = upload_to
def upload_to(object, filename):
return Image.cropduster_upload_to(filename, upload_path)
elif callable(upload_to):
old_upload_to = upload_to
def upload_to(self, filename, instance=None):
new_path = old_upload_to(filename, instance)
return os.path.join(settings.CROPDUSTER_UPLOAD_PATH, new_path)
else:
raise TypeError("'upload_to' needs to be either a callable or string")
# We have to create a unique class name for each custom proxy image otherwise
# django likes to alias them together.
ProxyImage = type('ProxyImage%i' % next(PROXY_COUNT),
(base_cls,),
{'Meta': type('Meta', (), {'proxy':True}),
'cropduster_upload_to': upload_to,
'__module__': Image.__module__})
return super(CropDusterField, self).__init__(ProxyImage, *args, **kwargs)
def contribute_to_class(self, cls, name):
super(CropDusterField, self).contribute_to_class(cls, name)
setattr(cls, self.name, CropDusterReverseProxyDescriptor(self))
if self.dynamic_path:
def post_signal(sender, instance, created, *args, **kwargs):
cdf = getattr(instance, name, None)
if cdf is not None:
dynamic_path_save(instance, cdf)
post_save.connect(post_signal, sender=cls, weak=False)
def dynamic_path_save(instance, cdf):
# Ok, try to move the fields.
if cdf is None:
# No image to check, move along.
return
# Check to see if the paths are the same
old_name = cdf.image.name
basename = os.path.basename(old_name)
new_name = cdf.cropduster_upload_to(basename, instance=instance)
if new_name == old_name:
# Nothing to move, move along
return
old_to_new = {}
old_path = cdf.image.path
images = [cdf]
cdf.image.name = new_name
old_to_new[old_path] = cdf.image.path
# Iterate through all derived images, updating the paths
for derived in cdf.descendants:
old_path = derived.image.path
old_retina_path = derived.retina_path
# Update the name to the new one
derived.image.name = derived.get_dest_img_from_base(derived.original.image.name)
old_to_new[old_path] = derived.image.path
# Only add the retina if it exists.
if os.path.exists(old_retina_path) and derived.size.retina:
old_to_new[old_retina_path] = derived.retina_path
images.append(derived)
# Filter out paths which haven't changed.
old_to_new = dict((k,v) for k,v in old_to_new.iteritems() if k != v)
# Copy the images... this is not cheap
for old_path, new_path in old_to_new.iteritems():
# Create the directory, if needed
dirname = os.path.dirname(new_path)
if not os.path.isdir(dirname):
if os.path.exists(dirname):
raise ValidationError("Cannot create new directory '%s'" % dirname)
os.makedirs(dirname)
# Copy the file, should blow up for all manner of things.
shutil.copy(old_path, new_path)
# Check existance
if not os.path.exists(new_path):
raise ValidationError("Could not copy image %s to %s" % (old_path, new_path))
# Save the images
for image in images:
image.save()
# Ok, we've made every reasonable attempt to preserve data... delete!
old_dirs = set()
for old_path in old_to_new:
os.unlink(old_path)
old_dirs.add( os.path.dirname(old_path) )
# Files are deleted, delete empty directories, except the upload path...
# that would be bad
for path in reversed(sorted(old_dirs, key=lambda d: d.count('/'))):
if not os.listdir(path) and path not in settings.MEDIA_ROOT:
os.rmdir(path)
class ImageRegistry(object):
"""
Registers cropduster Images to a hash to make it reasonable to lookup
image directly from the admin.
"""
hashes = {}
@classmethod
def add(cls, model, field_name, Image):
model_hash = hashlib.md5('%s:%s' % (model, field_name)).hexdigest()
cls.hashes[model_hash] = Image
return model_hash
@classmethod
def get(cls, image_hash):
return cls.hashes.get(image_hash, Image)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^cropduster3\.models\.CropDusterField"])
| UTF-8 | Python | false | false | 26,928 | py | 33 | models.py | 24 | 0.591689 | 0.589164 | 0 | 809 | 32.285538 | 89 |
jnxyp/PyPractice | 11,493,332,484,595 | 498c206d57f5d85a1ee041ed7dbf4772eb37173d | 5114fd1f7c3be8ea0c0b92ff8addb16cc1287b8c | /src/recycle_bin/PolynomialTransformation.py | be57b7b0123336be6161fd7dd0f954818370beb3 | []
| no_license | https://github.com/jnxyp/PyPractice | 8690d261a8eaed2f7e19bef4a7fc3c4092765569 | 38afc7fe2523b13db0aa8f6e19d47a7c4451e63d | refs/heads/master | 2021-08-28T16:18:35.184871 | 2017-12-12T18:09:11 | 2017-12-12T18:09:11 | 114,022,941 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
'''
Created on 2017-9-19
@author: jn_xyp
'''
from sympy import *
exp_str = input('Expression:')
x,y = symbols('x y')
exp = expand(exp_str.replace('y=','').replace('^', '**'))
deg = str(exp)
deg = deg.split('+')[0].split('-')
deg = deg[0].split('**')[-1]
print('Parent Function:y=x^' + deg) | UTF-8 | Python | false | false | 319 | py | 82 | PolynomialTransformation.py | 28 | 0.554859 | 0.520376 | 0 | 19 | 15.842105 | 57 |
Ragz875/PythonLearning | 3,805,341,053,980 | 89b4ab1679baa2c5049f624e776f922aeaec317e | 9307b1c233cd5f4838fdb67f4d9ad848a01ce4f9 | /Strings/WordSearch.py | 190063dbc471784b4cc7f977d15e14cfb1a0eb5d | []
| no_license | https://github.com/Ragz875/PythonLearning | 5443f9fe57cb268d97f03d019a5942de5afe9b0c | 3a142c279f999e55b7ba7c13549444eefb70de44 | refs/heads/master | 2023-06-09T03:59:49.810708 | 2021-06-21T17:38:52 | 2021-06-21T17:38:52 | 379,012,027 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | def dirsearch(grid,row,col,word,dir):
if word[0] != grid[row][col]:
return False
# loop trough all directions
for x,y in dir:
#print(f' Direction search {x},{y}')
flag=True
rowd= row + x
cold= col + y
# print(f' Direction search {rowd},{cold}')
# loop through all characters , first char already taken care
for charind in range(1,len(word)):
if ( 0 <= rowd < len(grid) and
0 <= cold < len(grid[0]) \
and grid[rowd][cold] == word[charind]):
rowd+=x
cold+=y
#print('Char : ', word[char], 'Location :', rowd,' ' ,cold, 'len(grid) :',len(grid),'len(grid[0]) :',len(grid[0]))
else:
flag=False
break
# after all 8 direct search check the flag
if flag:
return True
return False
def patternsearch(grid,word,dir):
print('in Pattern search')
for row in range(len(grid)):
for col in range(len(grid[row])):
if dirsearch(grid,row,col,word,dir):
print(f'Word : {word} found at location :',row ,' ' ,col)
# print('called seperate',dirsearch(grid, row, col, word, dir))
if __name__=='__main__' :
dir=[[-1,0],[1,0],[1,1],[1,-1],[-1,-1],[-1,1],[0,1],[0,-1]]
print('Your Main starts here')
grid = ["GEEKSFORGEEKS","GEEKSQUIZGEEK","IDEQAPRACTICE"]
word='GEEKS'
patternsearch(grid,word,dir)
| UTF-8 | Python | false | false | 1,497 | py | 108 | WordSearch.py | 106 | 0.516366 | 0.500334 | 0 | 42 | 34.47619 | 130 |
jailukanna/DeepLearning-Module-3 | 4,930,622,466,718 | c5bc309da4b95d73f09b8fbe9d44dea9a6e0b6b9 | 7e34fd5e1802a1bf3674fb3710b416968c51df94 | /Computer Vision/INTRODUCTION/IMPLEMENTATION AND RESULTS OF RCNN/keras_rcnn/layers/object_detection/__init__.py | 8df714534def3224c0a5e874f24b8cb1f437ed7e | [
"BSD-3-Clause",
"BSD-2-Clause"
]
| permissive | https://github.com/jailukanna/DeepLearning-Module-3 | 6c5de53d2550398e8e1f1525601c7be57078a276 | 868f51dfa130b405d5426e170ec4bd45bcb62f87 | refs/heads/main | 2023-03-23T14:18:28.388159 | 2021-03-18T13:41:42 | 2021-03-18T13:41:42 | 347,349,705 | 0 | 0 | null | true | 2021-03-13T11:18:18 | 2021-03-13T11:18:18 | 2021-03-13T09:59:23 | 2021-03-13T10:54:35 | 0 | 0 | 0 | 0 | null | false | false | # -*- coding: utf-8 -*-
from ._anchor import Anchor
from ._object_proposal import ObjectProposal
from ._proposal_target import ProposalTarget
| UTF-8 | Python | false | false | 152 | py | 22 | __init__.py | 8 | 0.710526 | 0.703947 | 0 | 7 | 19.714286 | 44 |
joaopmt/competitive-programming | 17,291,538,338,436 | d2e14e3ca9b28793aa8afaa6b03030c73fadee5a | b682c1191c6e7833d3884a8f474279f8a013889e | /programming-challenges/mc821/11-01/stones.py | e327abb0f360ae47533cb1b617a3e1cc6b782ef5 | []
| no_license | https://github.com/joaopmt/competitive-programming | 5969c9428918ba67768648211e5c5f8c6fce9c82 | 0bf8c9a9a852d674b368cf08833903f04b0ed2a8 | refs/heads/master | 2020-04-21T15:47:32.236011 | 2020-04-05T00:52:37 | 2020-04-05T00:52:37 | 169,679,947 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | t = int(input())
for t_ in range(t):
a, b, c = [int(x) for x in input().split()]
count = 0
while b >= 1 and c >= 2:
b -= 1
c -= 2
count += 3
while a >= 1 and b >= 2:
a -= 1
b -= 2
count += 3
print(count)
| UTF-8 | Python | false | false | 273 | py | 161 | stones.py | 119 | 0.380952 | 0.340659 | 0 | 14 | 18.5 | 47 |
gdugas/gtrac | 618,475,335,636 | d49696b6e763c7529cb731e714d45868dd5adb28 | f3cb31ac51d3cb2111edc6cc81cdf8e210e9c137 | /gtrac/ganglia/models.py | 9eeccd13cb2855f29a6f545e9261c86c320609ae | []
| no_license | https://github.com/gdugas/gtrac | e588c3badb5058ea94f4f62b2a1afeec4c70b6a8 | 19527c5d04f1585c0d11dad024fe7db9945cf55b | refs/heads/master | 2020-05-17T10:55:48.086441 | 2014-02-10T16:20:33 | 2014-02-10T16:20:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Metric(object):
TYPES = {
'string': str,
'int8' : int,
'int16' : int,
'int32' : int,
'uint8' : int,
'uint16' : int,
'uint32' : int,
'float' : float,
'double' : float
}
class TypeException(Exception):
pass
def __init__(self, host, name, value, type, units,
tn, tmax, dmax, slope, source,
extras={}):
self.host = host
self.name = name
self.type = type
self.units = units
if not type in self.TYPES:
raise Metric.TypeException(type)
self.value = self.to_python(value)
self.tn = tn
self.tmax = tmax
self.dmax = dmax
self.slope = slope
self.source = source
self.extras = {}
def to_python(self, value):
return self.TYPES[self.type.lower()](value)
def __cmp__(self, other):
value = other
if isinstance(other, Metric):
value = other.value
if self.value < value:
return -1
elif self.value == value:
return 0
elif self.value > value:
return 1
else:
return -1
def __unicode__(self):
return "%s %s" % (str(self.value), self.units)
def __str__(self):
return "%s %s" % (str(self.value), self.units)
class Host(object):
def __init__(self, cluster, name, ip, reported, tn, tmax, dmax, gmond_started,
location=None):
self.cluster = cluster
self.name = name
self.ip = ip
self.tn = tn
self.tmax = tmax
self.dmax = dmax
self.location = location
self.reported = reported
self.gmond_started = gmond_started
self._metrics = {}
def __contains__(self, metric):
return metric in self._metrics
def __iter__(self):
return iter(self._metrics)
def __getitem__(self, metricname):
return self._metrics[metricname]
def __setitem__(self, metricname, metric):
self._metrics[metricname] = metric
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Cluster(object):
def __init__(self, grid, name, localtime,
owner=None,
url=None,
latlong=None):
self.grid = grid
self.name = name
self.localtime = localtime
self.owner = owner
self.url = url
self.latlong = latlong
self._hosts = {}
def __contains__(self, host):
return host in self._hosts
def __iter__(self):
return iter(self._hosts)
def __getitem__(self, hostname):
return self._hosts[hostname]
def __setitem__(self, hostname, host):
self._hosts[hostname] = host
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Grid(object):
def __init__(self, name, localtime, authority=None):
self.name = name
self.authority = authority
self.localtime = localtime
self._clusters = {}
def __contains__(self, cluster):
return cluster in self._clusters
def __iter__(self):
return iter(self._clusters)
def __getitem__(self, clustername):
return self._clusters[clustername]
def __setitem__(self, clustername, cluster):
self._clusters[clustername] = cluster
def __unicode__(self):
return self.name
def __str__(self):
return self.name
| UTF-8 | Python | false | false | 3,755 | py | 9 | models.py | 9 | 0.503862 | 0.500133 | 0 | 155 | 23.206452 | 82 |
Poogles/vulcanpy | 15,384,572,888,792 | c9762712ca50bbc21b0394c5855453a0399500fd | 4e028bde5f983ef32d9b06b9d315468d5de686f6 | /vulcan.py | 11c100aa51b3c100667875e3699c25bc3b0a16dd | [
"MIT"
]
| permissive | https://github.com/Poogles/vulcanpy | f8712e176a90f8f0417a0cf60df56d1395ca2bd1 | 555cabe2fedfa4841baa59701b1ee8da0f373534 | refs/heads/master | 2020-05-18T11:42:18.485564 | 2015-06-25T13:54:50 | 2015-06-25T13:54:50 | 38,051,887 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import requests
import json
class Vulcan:
def __init__(self, endpoint):
self.endpoint = endpoint
def get_hosts(self):
"""
GET /v2/hosts
"""
resp = requests.get(self.endpoint +
"/v2/hosts")
return resp.json()
def upsert_host(self, hostname):
"""
POST 'application/json' /v2/hosts
"""
payload = {"Host": {"Name": hostname,
"Settings": {}}}
print(payload)
resp = requests.post(self.endpoint +
"/v2/hosts", data=json.dumps(payload))
return resp.json()
def delete_host(self, hostname):
"""
DELETE /v2/hosts/<name>
"""
resp = requests.delete(self.endpoint +
"/v2/hosts/{}".format(hostname))
return resp.json()
def get_backends(self):
"""
GET /v2/backends
"""
resp = requests.get(self.endpoint +
"/v2/backends")
return resp.json()
def upsert_backend(self, be_id, timeout_read=5, keepalive=30, idle_cons=12):
"""
POST 'application/json' /v2/backends
"""
payload = {"Backend": {"Id": be_id,
"Type": "http",
"Settings": {"Timeouts": {"Read": "{}s".format(timeout_read),
"Dial": "5s",
"TLSHandshake": "10s"},
"KeepAlive": {"Period": "{}s".format(keepalive),
"MaxIdleConnsPerHost": idle_cons}}}}
resp = requests.post(self.endpoint +
"/v2/backends",
data=json.dumps(payload))
return resp.json()
def delete_backend(self, backend):
"""
DELETE /v2/backends/<id>
"""
resp = requests.delete(self.endpoint +
"/v2/backends/{}".format(backend))
return resp.json()
def get_servers(self, backend):
"""
GET /v2/backends/<id>/servers
"""
resp = requests.get(self.endpoint +
"/v2/backends/{}/servers".format(backend))
return resp.json()
def get_server(self, backend, server):
"""
GET /v2/backends/<backend>/servers/<server>
"""
resp = requests.get(self.endpoint +
"/v2/backends/{}/servers/{}".format(backend,
server))
return resp.json()
def upsert_server(self, backend, server, server_url):
"""
POST /v1/upstreams/<id>/endpoints
"""
payload = {"Server": {"Id": server, "URL": server_url}}
resp = requests.post(self.endpoint +
"/v2/backends/{}/servers".format(backend),
data=json.dumps(payload))
return resp.json()
def delete_server(self, backend, server):
"""
DELETE /v2/backends/<id>/servers/<server-id>
"""
resp = requests.delete(self.endpoint +
"/v2/backends/{}/servers/{}".format(backend,
server))
return resp.json()
def get_frontends(self):
"""
GET /v2/frontends
"""
resp = requests.get(self.endpoint + "/v2/frontends")
return resp.json()
def get_frontend(self, fe_id):
"""
GET /v2/frontends/<frontend-id>
"""
resp = requests.get(self.endpoint +
"/v2/frontends/{}".format(fe_id))
return resp.json()
def upsert_frontend(self, fe_id, be_id, route="Path(`\/`)"):
"""
POST 'application/json' /v2/frontends
"""
payload = {"Frontend": {"Id": fe_id,
"Route": route,
"Type": "http",
"BackendId": be_id}}
resp = requests.post(self.endpoint +
"/v2/frontends",
data=json.dumps(payload))
return resp.json()
def delete_frontend(self, frontend_id):
"""
DELETE /v2/frontends/<frontend-id>
"""
resp = requests.delete(self.endpoint +
"/v2/frontends/{}".format(frontend_id))
return resp.json()
| UTF-8 | Python | false | false | 4,656 | py | 1 | vulcan.py | 1 | 0.434278 | 0.426546 | 0 | 155 | 29.03871 | 94 |
uveio/pystats | 16,303,695,869,953 | cc0ea32dc6e9bee04e165f74ef5f168d4e71551d | 2085069caa9f5e893213f3b6a364a2761be81bfb | /forkcore.py | 0b43218896f491ad5a6c29b853ed1079f8d27f85 | []
| no_license | https://github.com/uveio/pystats | 4668593963cd2ed8bc7940eb687028dfe9b80a80 | c6a47507103ed294c3f060fc131d0763ddcc0b9d | refs/heads/master | 2017-12-05T02:26:04.716436 | 2016-03-23T07:47:26 | 2016-03-23T07:47:26 | 83,382,344 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
import os
import threading
import select
import socket
class Forkcore(object):
def __init__(self, time_worker, qps_worker, port=3333):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("", port))
s.listen(5000)
self.s = s
self.connections = {}
self.incomplete_line = {}
self.unread_line = ''
self.left_line = ''
self.time_worker = time_worker
self.qps_worker = qps_worker
self.process()
def process(self, child_process_num=1):
pid = os.getpid()
for _ in range(0, child_process_num):
if pid == os.getpid():
if os.fork():
pass
else:
self.thread()
def thread(self, thread_num=1):
for _ in range(0, thread_num):
t = threading.Thread(target=self.epoll)
t.setDaemon(1)
t.start()
t.join()
def epoll(self):
self.epoll = select.epoll()
self.epoll.register(self.s.fileno(), select.EPOLLIN|select.EPOLLET)
while True:
epoll_list = self.epoll.poll()
for fd,events in epoll_list:
if fd == self.s.fileno():
conn,addr = self.s.accept()
self.epoll.register(conn.fileno(), select.EPOLLIN|select.EPOLLET)
self.connections[conn.fileno()] = conn
conn.setblocking(0)
else:
conn = self.connections[fd]
self.worker(conn)
def worker_process(self, line):
if line.find('qps') != -1:
self.qps_worker(line)
if line.find('time') != -1:
self.time_worker(line)
def worker(self, conn):
while True:
try:
msg = conn.recv(1024)
if msg == '':
self.epoll.unregister(conn.fileno())
self.connections.pop(conn.fileno())
conn.close()
if self.incomplete_line.has_key(conn.fileno()) and self.incomplete_line[conn.fileno()]:
pos = msg.find('\n')
self.unread_line = msg[:pos]
msg = msg[pos+1:]
self.left_line = self.incomplete_line[conn.fileno()] + self.unread_line
pos = msg.rfind('\n')
self.incomplete_line[conn.fileno()] = msg[pos+1:]
msg = msg[:pos]
lines = msg.split('\n')
for line in lines:
if line[:3] == 'uve':
self.worker_process(line)
if self.left_line:
if self.left_line[:3] == 'uve':
self.worker_process(self.left_line)
self.left_line = ''
except Exception:
break
| UTF-8 | Python | false | false | 3,019 | py | 7 | forkcore.py | 6 | 0.473998 | 0.465717 | 0 | 88 | 33.306818 | 103 |
Clombardi91/GardenSocial | 11,098,195,537,622 | 2af30800fec4a346cf66bf0ec5a52a7efbc4c4f4 | 8098b2a5368b5561b89cd9e261b86582b28d16fb | /garden/forms.py | c144bb580f64ccebf3928ebf9332e2a0666c9bf8 | []
| no_license | https://github.com/Clombardi91/GardenSocial | adf40177cad65b0af1eb06f490602105e0212709 | fe00b6462cab94d3d06703e63b09ccfd8b77b87c | refs/heads/master | 2023-06-24T18:35:51.302103 | 2021-07-12T15:50:39 | 2021-07-12T15:50:39 | 372,952,867 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
state = forms.CharField(max_length=30, required=False, help_text='*Required.')
zip_code = forms.CharField(max_length=30, required=False, help_text='*Required to asign correct growing region.')
email = forms.EmailField(max_length=254, help_text='*Required. Inform a valid email address.')
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'state', 'zip_code', 'email', 'password1', 'password2', ) | UTF-8 | Python | false | false | 788 | py | 12 | forms.py | 7 | 0.717005 | 0.700508 | 0 | 16 | 48.3125 | 117 |
nixawk/hello-python3 | 2,190,433,369,402 | abeff738aa6b844076a92bab8a504a3eb14d1214 | e415e4cdab3d1cd04a4aa587f7ddc59e71977972 | /builtin/algorithm/recursion-Binary Search.py | 67ee3ac4d22cb9943465c78fcdc2a05ece65f80b | []
| no_license | https://github.com/nixawk/hello-python3 | 8c3ebba577b39f545d4a67f3da9b8bb6122d12ea | e0680eb49d260c5e3f06f9690c558f95a851f87c | refs/heads/master | 2022-03-31T23:02:30.225702 | 2019-12-02T10:15:55 | 2019-12-02T10:15:55 | 84,066,942 | 5 | 7 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/python
# -*- coding: utf-8 -*-
# In this section, we describe a classic recursive algorithm, binary search,
# that is used to efficiently locate a target value within a sorted sequence
# of n elements. This is among the most important of computer algorithms,
# and it is the reason that we so often store data in sorted data in sorted
# order.
# When the sequence is unsorted, the standard approach to search for a target
# value is to use a loop to examine every element, until either finding the
# target or exhausting the data set. This is known as the sequential search
# algorithm. This algorithm runs in O(n) time (i.e., linear time) since every
# element is inspected in the worst case.
# When the sequemce is sorted and indexable, there is a much more efficient
# algorithm.
# mid = (low + high)/2
# We consider three cases:
# If the target equals data[mid], then we have found the item we are
# looking for, and the search terminates successfully.
# If target < data[mid], then we recur on the first half of the sequence,
# that is, on the interval of indices from low to mid -1.
# If target > data[mid], then we recur on the second half of the sequence,
# that is, on the interval of indices from mid + 1 to high.
# An unsuccessful search occurs if low > high, as the interval [low, high] is
# empty.
def binary_search(data, target, low, high):
if low > high:
return Falsse
mid = (low + high) // 2
if target == data[mid]:
print(mid, data[mid], sep=', ')
return True
elif target < data[mid]:
return binary_search(data, target, low, mid - 1)
else:
return binary_search(data, target, mid + 1, high)
if __name__ == '__main__':
seq = ['asm', 'c', 'cpp', 'perl', 'python', 'ruby', 'go', 'shell', 'rust']
binary_search(seq, 'python', 0, len(seq))
| UTF-8 | Python | false | false | 1,871 | py | 360 | recursion-Binary Search.py | 355 | 0.67023 | 0.665954 | 0 | 51 | 35.686275 | 78 |
arnav13081994/python-deepdive | 2,018,634,667,111 | de42833d5e68b21cfc8338a5bb6df662a5416bfe | 81dc2411ea6e9b59e80aad01a30e11ab8d581fff | /python-problems/parse_ranges.py | e8341383fab68cff9e09caf0dcce28c8244f4a25 | []
| no_license | https://github.com/arnav13081994/python-deepdive | fb9445e3b5536af34093e993772fa0569df520a1 | 7b906291d044f4ca7387de6e1833a61c9583c966 | refs/heads/master | 2023-07-07T14:05:08.688553 | 2021-08-16T02:45:33 | 2021-08-16T02:45:33 | 254,629,266 | 1 | 0 | null | true | 2020-04-10T12:29:16 | 2020-04-10T12:29:15 | 2020-04-09T20:05:41 | 2020-04-08T04:46:07 | 2,397 | 0 | 0 | 0 | null | false | false | """
Edit the parse_ranges function so that it accepts a string containing ranges of numbers and returns a generator of
the actual numbers contained in the ranges. The range numbers are inclusive.
>>> parse_ranges('0-0,4-8,20-21,43-45')
[0, 4, 5, 6, 7, 8, 20, 21, 43, 44, 45]
"""
# TODO Try to use th ecsv module instead of a.split to see if you can lazy loop and split the input string.
def parse_ranges(a):
csv_reader = csv.reader([a])
"""Return a list of numbers corresponding to number ranges in a string"""
for row in csv_reader:
for group in row:
start, sep, end = group.partition('-')
if end.startswith('>') or not sep:
yield int(start)
else:
yield from range(int(start), int(end)+1)
def parse_ranges_a(a):
"""Return a list of numbers corresponding to number ranges in a string"""
for group in a.split(','):
start, sep, end = group.partition('-')
if end.startswith('>') or not sep:
yield int(start)
else:
yield from range(int(start), int(end)+1)
if __name__ == "__main__":
import csv
from time import perf_counter
a = '0-0,4-8,20-21,43-45,'
# Create a very long random string
b = a * 2000000
b = b[:-1]
t0 = perf_counter()
q = parse_ranges_a(b)
while True:
try:
next(q)
except Exception as e:
t1 = perf_counter()
print("Time Taken:", (t1-t0)/len(b))
break
t0 = perf_counter()
q = parse_ranges(b)
while True:
try:
next(q)
except Exception as e:
t1 = perf_counter()
print("Time Taken by with csv:", (t1-t0)/len(b))
break
| UTF-8 | Python | false | false | 1,765 | py | 49 | parse_ranges.py | 47 | 0.556941 | 0.524079 | 0 | 64 | 26.484375 | 114 |
infinit/elle | 1,743,756,773,094 | 097483a42400d9cf48c7a1543a18e939a0051952 | f53891174b71e3b52497b3ab56b30ca7056ef1b7 | /drake/src/drake/deprecation.py | 90ea8d2bb7b9317c457a18a8e7df12cbd3461890 | [
"Apache-2.0",
"AGPL-3.0-only"
]
| permissive | https://github.com/infinit/elle | 050e0a3825a585add8899cf8dd8e25b0531c67ce | 1a8f3df18500a9854a514cbaf9824784293ca17a | refs/heads/master | 2023-09-04T01:15:06.820585 | 2022-09-17T08:43:45 | 2022-09-17T08:43:45 | 51,672,792 | 533 | 51 | Apache-2.0 | false | 2023-05-22T21:35:50 | 2016-02-14T00:38:23 | 2023-02-13T18:20:59 | 2023-05-22T21:35:49 | 346,505 | 467 | 43 | 2 | C++ | false | false | # Copyright (C) 2009-2019, Quentin "mefyl" Hocquet
#
# This software is provided "as is" without warranty of any kind,
# either expressed or implied, including but not limited to the
# implied warranties of fitness for a particular purpose.
#
# See the LICENSE file for more information.
import warnings
import functools
def deprecated(func):
'''This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used.'''
@functools.wraps(func)
def f(*args, **kwargs):
warnings.warn(
'Call to deprecated function {}.'.format(func.__name__),
category=DeprecationWarning,
stacklevel=2)
return func(*args, **kwargs)
return f
| UTF-8 | Python | false | false | 734 | py | 1,521 | deprecation.py | 1,274 | 0.715259 | 0.702997 | 0 | 23 | 30.913043 | 65 |
AbhijithNK94/Python-Basics | 11,716,670,793,570 | 07443346e776f1ffcc67108cc7bad208c6f626a0 | 9b2973f6a69c9234a27d016a2f33e40f28c6e867 | /Collections/Strings.py | 8686aae7c70655f9fa165ead5769d8c9a8db04c3 | []
| no_license | https://github.com/AbhijithNK94/Python-Basics | 8274c4f81a617316ed66bd1efac5644523e690e6 | 09f4a066d4dc31c54ae5186f32fd4ed0cea84908 | refs/heads/main | 2023-06-05T19:15:04.170480 | 2021-06-17T14:20:44 | 2021-06-17T14:20:44 | 360,181,557 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # ####String slicing using character position
# a="hello world"
# print(a[4])
# print(a[1:4])
# print(a[1:8:2]) ##[starting pos : Ending pos : Step size]
# print(a[::2])
# print(a[0:6:1])
# print(a[0:len(a):2])
# print(a[-1])
# print(a[-3:-1])
# print(a[::-1]) ## Character reversing
# ##Deleting the string
#
# ##Concatenation (adding the strings)
# b=" world"
# a=a+b
# print(a)
# ##Iteration
# for i in b:
# print(i)
# ##Membership operator(Output of membership operator will be true or false)
# print("l" in "hello")
# print('hl' in "hello")
# ##lower case and upper case
# print("HELLO".lower())
# print("heLLo".upper())
# ##Split (Output will always be list)
# print("Hello world".split())##Space is a default splitter
# print("Hello,world".split(","))
# print("Hello/World".split("/"))
# ##Join
# print("".join(["hey","morning"]))##join without space
# print(" ".join(["hey","morning"]))##join with space
# print(",".join(["hey","morning"]))
# ###REVERSING
# a="ernakulam"
# print(reversed(a))##only shows the memory allocation of the reversed string
# s=list(reversed(a))
# print(s)
# #or
# s=print(a[::-1])
# #Sort
# a=["zbc","acs","dfg"]
# b=sorted(a)
# print(b)
# print(a)
# a.sort()
# print(a)
# #find(Finds the position of a string in a string by identifying the position of its 1st char
# print("how are you".find('ow'))
# print("how are you".find('are'))
# ##REPLACE (replaces an existing string)
# print("how are you".replace('how','where'))
# ##Capitalize (makes the first character of a string uppercase and the remaining lower)
# print("welcome to experTz Lab".capitalize())
# ##CENTER (Makes the string to the center)
# print("welcome to experTz Lab".center(50,"*"))
# ##Counts the number of the defined character in the string
# a="Welcome to Expertz Lab"
# print(a.count("o"))
# print(a.count("om"))
# ##Starts with and ends with
# print(a.startswith("W"))
# print(a.startswith("w"))
# print(a.endswith("b"))
# ##INDEX(finds position)
# print(a.index("c"))
# ##print words in alphabetical order
# a="Hi world how are you"
# b=a.lower()
# c=b.split()
# print(c)
# d=sorted(c)
# print(d)
# for i in d:
# print(i)
#
# ## STRIP (removes white space or mentioned char from both side(left start and right end))
# a=" Hi world how are you"
# print(a)
# print(len(a))
# s=a.strip()
# print(len(s))
# print(s)
# f=a.strip("u")
# print(f)
# ##lstrip and rstrip (removes white space or mentioned char from left side)
# a="uHi world how are you"
# s=a.lstrip("u")
# print(s)
# a="uHi world how are youuuu"
# s=a.rstrip("u")
# print(s)
#
#
# ###
# a = [1,"python",[2,'4']]
# # a += [2]
# # print(a)
# a.extend([2,3])
# print(a)
# a.append('5')
# print(a) | UTF-8 | Python | false | false | 2,773 | py | 27 | Strings.py | 24 | 0.606563 | 0.596827 | 0 | 103 | 24.941748 | 94 |
sgherro/AWM-Project-Gestione-Acetaia | 8,005,819,089,715 | a0ffc06e79b402eb508340fdd0011ec18dc20ca8 | 3423dd8c22365ae0c2f3bee158ddd76fc859c393 | /honningbrew/operations/serializers.py | a1dfa348f3ccdf757f6ab411f60ec8e1e0cde343 | []
| no_license | https://github.com/sgherro/AWM-Project-Gestione-Acetaia | b00ad530e9117d12009d11ba19a9102ed1bf5126 | d6f9ec6d9d3300945c0b202cb5ecd018fc2eaf06 | refs/heads/main | 2023-03-06T03:03:00.653342 | 2021-02-20T10:12:07 | 2021-02-20T10:12:07 | 311,261,107 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from rest_framework import serializers
from . import models
class SetSerializer(serializers.ModelSerializer):
class Meta:
model = models.Set
fields = '__all__'
class BarrelSerializer(serializers.ModelSerializer):
class Meta:
model = models.Barrel
fields = '__all__'
class RabboccoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Rabbocco
fields = '__all__'
class AddMostoSerializer(serializers.ModelSerializer):
class Meta:
model = models.AddMosto
fields = '__all__'
class MisurationSerializer(serializers.ModelSerializer):
class Meta:
model = models.Misuration
fields = '__all__'
class TasteSerializer(serializers.ModelSerializer):
class Meta:
model = models.Taste
fields = '__all__'
class OperationSerializer(serializers.ModelSerializer):
class Meta:
model = models.Operation
fields = '__all__'
| UTF-8 | Python | false | false | 974 | py | 29 | serializers.py | 23 | 0.655031 | 0.655031 | 0 | 37 | 25.027027 | 56 |
tinylcy/LeetCode | 12,704,513,264,216 | 4d7ed144fecb835ff447149de3f93554e81e0f1d | 883da09a86aedc629a57cf4131ff84993340f9e1 | /Distributed System/braft/experiment/ex4.py | 7ec9b019a89d3afb7ed7d8a68b52761e3e8321e7 | []
| no_license | https://github.com/tinylcy/LeetCode | ed21b7231bd0ac81536494025a9f0a1cfe1110db | a78c88a0dbeb1067cdf848deb27840f6ea47dc22 | refs/heads/master | 2020-04-12T08:07:54.255282 | 2018-06-09T11:45:24 | 2018-06-09T11:45:24 | 38,624,416 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
x1 = np.linspace(6, 30, 25)
x2 = np.linspace(4, 30, 27)
y1 = [157, 158, 159, 158, 159, 160, 163, 160, 155, 150, 149, 144, 139, 127, 126, 111, 113, 92, 82, 78, 75, 73, 73, 72,
69]
y2 = [118, 106, 78, 72, 62, 55, 47, 43, 39, 37, 35, 30, 27, 26, 21, 22, 20, 21, 18, 17, 17, 15, 14, 14, 12, 12, 12]
y3 = np.repeat(7, 27)
# Set global title.
fig = plt.figure()
st = fig.suptitle("", fontsize="x-large")
# Set tick direction.
matplotlib.rcParams['xtick.direction'] = 'in'
matplotlib.rcParams['ytick.direction'] = 'in'
plt.plot(x1, y1, 'r.-', label='BRaft')
plt.xlabel('Number of nodes (.)')
plt.ylabel('Throughput (tps)')
plt.legend()
plt.plot(x2, y2, 'g.--', label='PBFT')
plt.legend()
plt.plot(x2, y3, 'b.:', label='PoW')
plt.legend()
plt.show()
| UTF-8 | Python | false | false | 822 | py | 301 | ex4.py | 250 | 0.620438 | 0.441606 | 0 | 32 | 24.6875 | 118 |
kuromatia/AnaClaraBot | 16,071,767,641,014 | 188d2df0d098a70590465bb199dea9c905910998 | d49f7d3823c3ae926338e0112058d9a536da2595 | /patch/current_time/get_datetime.py | 9d4e2a2f825eb859f96cb5d494e4894f884a94b1 | []
| no_license | https://github.com/kuromatia/AnaClaraBot | 96ab8d143378ec70b1b58bcbaf96399ef57e3712 | 352c64be208f35d95fb6873fe021df3edbf8159f | refs/heads/master | 2020-07-06T22:18:44.530976 | 2019-08-31T14:03:28 | 2019-08-31T14:03:28 | 203,155,802 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #! /usr/bin/env python
# coding: utf-8
import re
import datetime
import os
def main():
today = datetime.datetime.today().strftime("%m月%d日%H時%M分")
if re.search("^0", today):
today = today[1:]
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "current_time.txt"), "w") as f:
f.write("現在"+today+"です。")
if __name__ == '__main__':
main()
| UTF-8 | Python | false | false | 405 | py | 12 | get_datetime.py | 8 | 0.583979 | 0.576227 | 0 | 18 | 20.5 | 102 |
joshkel/sentry-on-heroku | 12,154,757,460,914 | 891fe76071fd344c150abc56a6285cb133983dfe | 2b1574719aab94e69e08afd012f2b8ec6e821b09 | /sentry.conf.py | 748859cc3964359759406a1fb3233d3d2e2aa857 | []
| no_license | https://github.com/joshkel/sentry-on-heroku | cff37b750ea59557846e07109de25f8b4fb21f04 | 0d3b056db75283cd84223e55c92fa4df26c03d60 | refs/heads/master | 2021-01-18T03:17:02.358234 | 2015-09-12T19:49:46 | 2015-09-12T19:49:46 | 39,282,671 | 0 | 2 | null | true | 2015-07-18T01:41:40 | 2015-07-18T01:41:40 | 2015-07-18T01:41:40 | 2015-06-28T12:57:37 | 323 | 0 | 0 | 0 | Python | null | null | import logging
import os
import sys
import urlparse
from sentry.conf.server import *
ROOT = os.path.dirname(__file__)
sys.path.append(ROOT)
import dj_database_url
DATABASES = {'default': dj_database_url.config()}
from gevent import monkey
monkey.patch_all()
# Sentry configuration
# --------------------
SENTRY_KEY = os.environ.get('SENTRY_KEY')
SECRET_KEY = os.environ.get('SECRET_KEY')
# Set this to false to require authentication
SENTRY_PUBLIC = False
SENTRY_WEB_HOST = '0.0.0.0'
SENTRY_WEB_PORT = int(os.environ.get('PORT', 9000))
SENTRY_WEB_OPTIONS = {
'workers': 3,
'worker_class': 'gevent',
}
SENTRY_URL_PREFIX = os.environ.get('SENTRY_URL_PREFIX', '')
# Caching
# -------
SENTRY_CACHE = 'sentry.cache.django.DjangoCache'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
# Email configuration
# -------------------
if 'SENDGRID_USERNAME' in os.environ:
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = os.environ.get('SENDGRID_USERNAME')
EMAIL_HOST_PASSWORD = os.environ.get('SENDGRID_PASSWORD')
elif 'MANDRILL_USERNAME' in os.environ:
EMAIL_HOST = 'smtp.mandrillapp.com'
EMAIL_HOST_USER = os.environ.get('MANDRILL_USERNAME')
EMAIL_HOST_PASSWORD = os.environ.get('MANDRILL_APIKEY')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# Disable the default admins (for email)
ADMINS = ()
# Set Sentry's ADMINS to a raw list of email addresses
SENTRY_ADMINS = os.environ.get('ADMINS', '').split(',')
# The threshold level to restrict emails to.
SENTRY_MAIL_LEVEL = logging.WARNING
# The prefix to apply to outgoing emails.
EMAIL_SUBJECT_PREFIX = '[Sentry] '
# The reply-to email address for outgoing mail.
SERVER_EMAIL = os.environ.get('SERVER_EMAIL', 'root@localhost')
DEFAULT_FROM_EMAIL = os.environ.get(
'DEFAULT_FROM_EMAIL',
'webmaster@localhost'
)
SENTRY_ADMIN_EMAIL = os.environ.get('SENTRY_ADMIN_EMAIL')
# Security
# --------
INSTALLED_APPS += ('djangosecure',)
MIDDLEWARE_CLASSES += ('djangosecure.middleware.SecurityMiddleware',)
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Whether to use HTTPOnly flag on the session cookie. If this is set to `True`,
# client-side JavaScript will not to be able to access the session cookie.
SESSION_COOKIE_HTTPONLY = True
# Whether to use a secure cookie for the session cookie. If this is set to
# `True`, the cookie will be marked as "secure," which means browsers may
# ensure that the cookie is only sent under an HTTPS connection.
SESSION_COOKIE_SECURE = True
# If set to `True`, causes `SecurityMiddleware` to set the
# `X-Content-Type-Options: nosniff` header on all responses that do not already
# have that header.
SECURE_CONTENT_TYPE_NOSNIFF = True
# If set to `True`, causes `SecurityMiddleware` to set the
# `X-XSS-Protection: 1; mode=block` header on all responses that do not already
# have that header.
SECURE_BROWSER_XSS_FILTER = True
# If set to `True`, causes `SecurityMiddleware` to set the `X-Frame-Options:
# DENY` header on all responses that do not already have that header
SECURE_FRAME_DENY = True
# If set to a non-zero integer value, causes `SecurityMiddleware` to set the
# HTTP Strict Transport Security header on all responses that do not already
# have that header.
SECURE_HSTS_SECONDS = 31536000
# If `True`, causes `SecurityMiddleware` to add the ``includeSubDomains`` tag
# to the HTTP Strict Transport Security header.
#
# Has no effect unless ``SECURE_HSTS_SECONDS`` is set to a non-zero value.
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
# If set to True, causes `SecurityMiddleware` to redirect all non-HTTPS
# requests to HTTPS
SECURE_SSL_REDIRECT = True
# Bcrypt
# ------
INSTALLED_APPS += ('django_bcrypt',)
# Enables bcrypt password migration on a ``check_password()`` call.
#
# The hash is also migrated when ``BCRYPT_ROUNDS`` changes.
BCRYPT_MIGRATE = True
# Redis
# -----
SENTRY_TSDB = 'sentry.tsdb.redis.RedisTSDB'
redis_url = urlparse.urlparse(os.environ.get('REDISCLOUD_URL'))
SENTRY_TSDB_OPTIONS = {
'hosts': {
0: {
'host': redis_url.hostname,
'port': redis_url.port,
'password': redis_url.password
}
}
}
# Social Auth
# -----------
SOCIAL_AUTH_CREATE_USERS = 'SOCIAL_AUTH_CREATE_USERS' in os.environ
# Twitter
# -------
TWITTER_CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY')
TWITTER_CONSUMER_SECRET = os.environ.get('TWITTER_CONSUMER_SECRET')
# Facebook
# --------
FACEBOOK_APP_ID = os.environ.get('FACEBOOK_APP_ID')
FACEBOOK_API_SECRET = os.environ.get('FACEBOOK_API_SECRET')
# Google
# ------
GOOGLE_OAUTH2_CLIENT_ID = os.environ.get('GOOGLE_OAUTH2_CLIENT_ID')
GOOGLE_OAUTH2_CLIENT_SECRET = os.environ.get('GOOGLE_OAUTH2_CLIENT_SECRET')
# GitHub
# ------
GITHUB_APP_ID = os.environ.get('GITHUB_APP_ID')
GITHUB_API_SECRET = os.environ.get('GITHUB_API_SECRET')
GITHUB_EXTENDED_PERMISSIONS = ['repo']
# Bitbucket
# ---------
BITBUCKET_CONSUMER_KEY = os.environ.get('BITBUCKET_CONSUMER_KEY')
BITBUCKET_CONSUMER_SECRET = os.environ.get('BITBUCKET_CONSUMER_SECRET')
| UTF-8 | Python | false | false | 5,086 | py | 2 | sentry.conf.py | 1 | 0.700551 | 0.695438 | 0 | 197 | 24.817259 | 79 |
catboost/catboost | 13,005,161,007,401 | 67ce62e8d3adedee75cd89cad05ec08a85fc5dd9 | 010279e2ba272d09e9d2c4e903722e5faba2cf7a | /contrib/python/scipy/py3/scipy/linalg/decomp_schur.py | edb70fc14ac657e1891d0f000219737fbddcd547 | [
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Qhull",
"BSD-3-Clause",
"BSL-1.0",
"Apache-2.0",
"BSD-2-Clause"
]
| permissive | https://github.com/catboost/catboost | 854c1a1f439a96f1ae6b48e16644be20aa04dba2 | f5042e35b945aded77b23470ead62d7eacefde92 | refs/heads/master | 2023-09-01T12:14:14.174108 | 2023-09-01T10:01:01 | 2023-09-01T10:22:12 | 97,556,265 | 8,012 | 1,425 | Apache-2.0 | false | 2023-09-11T03:32:32 | 2017-07-18T05:29:04 | 2023-09-10T21:09:54 | 2023-09-11T03:32:31 | 1,618,563 | 7,340 | 1,141 | 516 | Python | false | false | """Schur decomposition functions."""
import numpy
from numpy import asarray_chkfinite, single, asarray, array
from numpy.linalg import norm
# Local imports.
from .misc import LinAlgError, _datacopied
from .lapack import get_lapack_funcs
from .decomp import eigvals
__all__ = ['schur', 'rsf2csf']
_double_precision = ['i', 'l', 'd']
def schur(a, output='real', lwork=None, overwrite_a=False, sort=None,
check_finite=True):
"""
Compute Schur decomposition of a matrix.
The Schur decomposition is::
A = Z T Z^H
where Z is unitary and T is either upper-triangular, or for real
Schur decomposition (output='real'), quasi-upper triangular. In
the quasi-triangular form, 2x2 blocks describing complex-valued
eigenvalue pairs may extrude from the diagonal.
Parameters
----------
a : (M, M) array_like
Matrix to decompose
output : {'real', 'complex'}, optional
Construct the real or complex Schur decomposition (for real matrices).
lwork : int, optional
Work array size. If None or -1, it is automatically computed.
overwrite_a : bool, optional
Whether to overwrite data in a (may improve performance).
sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
Specifies whether the upper eigenvalues should be sorted. A callable
may be passed that, given a eigenvalue, returns a boolean denoting
whether the eigenvalue should be sorted to the top-left (True).
Alternatively, string parameters may be used::
'lhp' Left-hand plane (x.real < 0.0)
'rhp' Right-hand plane (x.real > 0.0)
'iuc' Inside the unit circle (x*x.conjugate() <= 1.0)
'ouc' Outside the unit circle (x*x.conjugate() > 1.0)
Defaults to None (no sorting).
check_finite : bool, optional
Whether to check that the input matrix contains only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Returns
-------
T : (M, M) ndarray
Schur form of A. It is real-valued for the real Schur decomposition.
Z : (M, M) ndarray
An unitary Schur transformation matrix for A.
It is real-valued for the real Schur decomposition.
sdim : int
If and only if sorting was requested, a third return value will
contain the number of eigenvalues satisfying the sort condition.
Raises
------
LinAlgError
Error raised under three conditions:
1. The algorithm failed due to a failure of the QR algorithm to
compute all eigenvalues.
2. If eigenvalue sorting was requested, the eigenvalues could not be
reordered due to a failure to separate eigenvalues, usually because
of poor conditioning.
3. If eigenvalue sorting was requested, roundoff errors caused the
leading eigenvalues to no longer satisfy the sorting condition.
See also
--------
rsf2csf : Convert real Schur form to complex Schur form
Examples
--------
>>> from scipy.linalg import schur, eigvals
>>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]])
>>> T, Z = schur(A)
>>> T
array([[ 2.65896708, 1.42440458, -1.92933439],
[ 0. , -0.32948354, -0.49063704],
[ 0. , 1.31178921, -0.32948354]])
>>> Z
array([[0.72711591, -0.60156188, 0.33079564],
[0.52839428, 0.79801892, 0.28976765],
[0.43829436, 0.03590414, -0.89811411]])
>>> T2, Z2 = schur(A, output='complex')
>>> T2
array([[ 2.65896708, -1.22839825+1.32378589j, 0.42590089+1.51937378j],
[ 0. , -0.32948354+0.80225456j, -0.59877807+0.56192146j],
[ 0. , 0. , -0.32948354-0.80225456j]])
>>> eigvals(T2)
array([2.65896708, -0.32948354+0.80225456j, -0.32948354-0.80225456j])
An arbitrary custom eig-sorting condition, having positive imaginary part,
which is satisfied by only one eigenvalue
>>> T3, Z3, sdim = schur(A, output='complex', sort=lambda x: x.imag > 0)
>>> sdim
1
"""
if output not in ['real', 'complex', 'r', 'c']:
raise ValueError("argument must be 'real', or 'complex'")
if check_finite:
a1 = asarray_chkfinite(a)
else:
a1 = asarray(a)
if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):
raise ValueError('expected square matrix')
typ = a1.dtype.char
if output in ['complex', 'c'] and typ not in ['F', 'D']:
if typ in _double_precision:
a1 = a1.astype('D')
typ = 'D'
else:
a1 = a1.astype('F')
typ = 'F'
overwrite_a = overwrite_a or (_datacopied(a1, a))
gees, = get_lapack_funcs(('gees',), (a1,))
if lwork is None or lwork == -1:
# get optimal work array
result = gees(lambda x: None, a1, lwork=-1)
lwork = result[-2][0].real.astype(numpy.int_)
if sort is None:
sort_t = 0
sfunction = lambda x: None
else:
sort_t = 1
if callable(sort):
sfunction = sort
elif sort == 'lhp':
sfunction = lambda x: (x.real < 0.0)
elif sort == 'rhp':
sfunction = lambda x: (x.real >= 0.0)
elif sort == 'iuc':
sfunction = lambda x: (abs(x) <= 1.0)
elif sort == 'ouc':
sfunction = lambda x: (abs(x) > 1.0)
else:
raise ValueError("'sort' parameter must either be 'None', or a "
"callable, or one of ('lhp','rhp','iuc','ouc')")
result = gees(sfunction, a1, lwork=lwork, overwrite_a=overwrite_a,
sort_t=sort_t)
info = result[-1]
if info < 0:
raise ValueError('illegal value in {}-th argument of internal gees'
''.format(-info))
elif info == a1.shape[0] + 1:
raise LinAlgError('Eigenvalues could not be separated for reordering.')
elif info == a1.shape[0] + 2:
raise LinAlgError('Leading eigenvalues do not satisfy sort condition.')
elif info > 0:
raise LinAlgError("Schur form not found. Possibly ill-conditioned.")
if sort_t == 0:
return result[0], result[-3]
else:
return result[0], result[-3], result[1]
eps = numpy.finfo(float).eps
feps = numpy.finfo(single).eps
_array_kind = {'b': 0, 'h': 0, 'B': 0, 'i': 0, 'l': 0,
'f': 0, 'd': 0, 'F': 1, 'D': 1}
_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1}
_array_type = [['f', 'd'], ['F', 'D']]
def _commonType(*arrays):
kind = 0
precision = 0
for a in arrays:
t = a.dtype.char
kind = max(kind, _array_kind[t])
precision = max(precision, _array_precision[t])
return _array_type[kind][precision]
def _castCopy(type, *arrays):
cast_arrays = ()
for a in arrays:
if a.dtype.char == type:
cast_arrays = cast_arrays + (a.copy(),)
else:
cast_arrays = cast_arrays + (a.astype(type),)
if len(cast_arrays) == 1:
return cast_arrays[0]
else:
return cast_arrays
def rsf2csf(T, Z, check_finite=True):
"""
Convert real Schur form to complex Schur form.
Convert a quasi-diagonal real-valued Schur form to the upper-triangular
complex-valued Schur form.
Parameters
----------
T : (M, M) array_like
Real Schur form of the original array
Z : (M, M) array_like
Schur transformation matrix
check_finite : bool, optional
Whether to check that the input arrays contain only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Returns
-------
T : (M, M) ndarray
Complex Schur form of the original array
Z : (M, M) ndarray
Schur transformation matrix corresponding to the complex form
See Also
--------
schur : Schur decomposition of an array
Examples
--------
>>> from scipy.linalg import schur, rsf2csf
>>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]])
>>> T, Z = schur(A)
>>> T
array([[ 2.65896708, 1.42440458, -1.92933439],
[ 0. , -0.32948354, -0.49063704],
[ 0. , 1.31178921, -0.32948354]])
>>> Z
array([[0.72711591, -0.60156188, 0.33079564],
[0.52839428, 0.79801892, 0.28976765],
[0.43829436, 0.03590414, -0.89811411]])
>>> T2 , Z2 = rsf2csf(T, Z)
>>> T2
array([[2.65896708+0.j, -1.64592781+0.743164187j, -1.21516887+1.00660462j],
[0.+0.j , -0.32948354+8.02254558e-01j, -0.82115218-2.77555756e-17j],
[0.+0.j , 0.+0.j, -0.32948354-0.802254558j]])
>>> Z2
array([[0.72711591+0.j, 0.28220393-0.31385693j, 0.51319638-0.17258824j],
[0.52839428+0.j, 0.24720268+0.41635578j, -0.68079517-0.15118243j],
[0.43829436+0.j, -0.76618703+0.01873251j, -0.03063006+0.46857912j]])
"""
if check_finite:
Z, T = map(asarray_chkfinite, (Z, T))
else:
Z, T = map(asarray, (Z, T))
for ind, X in enumerate([Z, T]):
if X.ndim != 2 or X.shape[0] != X.shape[1]:
raise ValueError("Input '{}' must be square.".format('ZT'[ind]))
if T.shape[0] != Z.shape[0]:
raise ValueError("Input array shapes must match: Z: {} vs. T: {}"
"".format(Z.shape, T.shape))
N = T.shape[0]
t = _commonType(Z, T, array([3.0], 'F'))
Z, T = _castCopy(t, Z, T)
for m in range(N-1, 0, -1):
if abs(T[m, m-1]) > eps*(abs(T[m-1, m-1]) + abs(T[m, m])):
mu = eigvals(T[m-1:m+1, m-1:m+1]) - T[m, m]
r = norm([mu[0], T[m, m-1]])
c = mu[0] / r
s = T[m, m-1] / r
G = array([[c.conj(), s], [-s, c]], dtype=t)
T[m-1:m+1, m-1:] = G.dot(T[m-1:m+1, m-1:])
T[:m+1, m-1:m+1] = T[:m+1, m-1:m+1].dot(G.conj().T)
Z[:, m-1:m+1] = Z[:, m-1:m+1].dot(G.conj().T)
T[m, m-1] = 0.0
return T, Z
| UTF-8 | Python | false | false | 10,216 | py | 16,030 | decomp_schur.py | 8,629 | 0.563136 | 0.480521 | 0 | 292 | 33.986301 | 79 |
qmnguyenw/python_py4e | 18,322,330,498,094 | 2a796ab13e24d6323dfcc526f5f6b7452717b1f6 | 8e24e8bba2dd476f9fe612226d24891ef81429b7 | /geeksforgeeks/python/python_all/4_11.py | c6084c6b110fbc4462255ce5eb2367f75d58f75e | []
| no_license | https://github.com/qmnguyenw/python_py4e | fb56c6dc91c49149031a11ca52c9037dc80d5dcf | 84f37412bd43a3b357a17df9ff8811eba16bba6e | refs/heads/master | 2023-06-01T07:58:13.996965 | 2021-06-15T08:39:26 | 2021-06-15T08:39:26 | 349,059,725 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | Python – Test if any set element exists in List
Given a set and list, the task is to write a python program to check if any
set element exists in the list.
**Examples:**
> **Input :** test_dict1 = test_set = {6, 4, 2, 7, 9, 1}, test_list = [6, 8,
> 10]
>
> **Output :** True
>
> **Explanation :** 6 occurs in list from set.
>
>
>
>
>
>
>
> **Input :** test_dict1 = test_set = {16, 4, 2, 7, 9, 1}, test_list = [6, 8,
> 10]
>
> **Output :** False
>
> **Explanation :** No set element exists in list.
**Method #1 : Using** **any()**
In this, we iterate for all the elements of the set and check if any occurs in
the list. The _any()_ , returns true for any element matching condition.
## Python3
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Test if any set element exists in List
# Using any()
# initializing set
test_set = {6, 4, 2, 7, 9, 1}
# printing original set
print("The original set is : " + str(test_set))
# initializing list
test_list = [6, 8, 10]
# any() checking for any set element in check list
res = any(ele in test_set for ele in test_list)
# printing result
print("Any set element is in list ? : " + str(res))
---
__
__
**Output:**
The original set is : {1, 2, 4, 6, 7, 9}
Any set element is in list ? : True
**Method #2 : Using** **& operator**
In this, we check for any element by using and operation between set and list,
if any element matches, the result is True.
## Python3
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Test if any set element exists in List
# Using & operator
# initializing set
test_set = {6, 4, 2, 7, 9, 1}
# printing original set
print("The original set is : " + str(test_set))
# initializing list
test_list = [6, 8, 10]
# & operator checks for any common element
res = bool(test_set & set(test_list))
# printing result
print("Any set element is in list ? : " + str(res))
---
__
__
**Output:**
The original set is : {1, 2, 4, 6, 7, 9}
Any set element is in list ? : True
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
| UTF-8 | Python | false | false | 2,580 | py | 5,210 | 4_11.py | 5,192 | 0.565555 | 0.541505 | 0 | 174 | 12.816092 | 78 |
Jeevankv/LearnPython | 13,967,233,648,463 | 15b5df3f5cb67403b3f05e9c519e556d47e4ed17 | 9ce6a0eaba9f82d536ca4348a1594f90f5d67638 | /zSpeak.py | 6be31acb80e7b8d4db921a9eca046aa001bac486 | []
| no_license | https://github.com/Jeevankv/LearnPython | 028d57ac7b6b68d129e9769541ae509df8ef204d | 504b96795b6ccd107f0b176adc142246f9a26094 | refs/heads/master | 2022-12-21T15:53:27.669206 | 2020-09-01T10:36:38 | 2020-09-01T10:36:38 | 279,399,567 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
def speak(str):
from win32com.client import Dispatch
speak = Dispatch('SAPI.spVoice')
speak.Speak(str)
speak("hello world")
import pyttsx3
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voices',voices[0].id)
def speak2(str):
engine.say(str)
engine.runAndWait()
speak2("Iam jeevan from J S S Academy of Technical education- Bangalore") | UTF-8 | Python | false | false | 426 | py | 73 | zSpeak.py | 63 | 0.678404 | 0.659624 | 0 | 20 | 19.2 | 73 |
stojan211287/ThirdOrderCorrelations | 10,050,223,494,035 | b38293eb30257a1b6877e2af6eb7c443d419eeed | 59152347b5c4fab8ff05f94a6643c0eea4b4b56a | /estimate_third_cumulant.py | 627eed2aa407b36b861888398e2738255cdc16e0 | []
| no_license | https://github.com/stojan211287/ThirdOrderCorrelations | 787e856121df5466b0eb941dc8236582fe0c3864 | 75410055979aa0bd5fe617ceca1e8fde340274d7 | refs/heads/master | 2018-01-11T05:34:54.017759 | 2016-02-26T13:43:11 | 2016-02-26T13:43:11 | 51,293,594 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
import time
import random
#estimate cumulant k^{r,s,t} at indices i, j, k
def estimate(data1, data2, data3):
n = len(data1)
estimate = 0.
no_dist = 0
no_all_eq = 0
no_two_eq = 0
diagonala = 0.
suma = 0.
for i in range(n):
for j in range(n):
for k in range(n):
if i == j == k:
no_all_eq += 1
#diagonala += data1[i]*data2[j]*data3[k]
estimate += data1[i]*data2[j]*data3[k]
elif i != j and i != k and j != k :
no_dist += 1
estimate += 2.*data1[i]*data2[j]*data3[k]/((n-1.)*(n-2.))
else :
no_two_eq += 1
#suma -= 1.*data1[i]*data2[j]*data3[k]/(n-1.)
#estimate += 2.*data1[i]*data2[j]*data3[k]/((n-1.)*(n-2.))
estimate -= 1.*data1[i]*data2[j]*data3[k]/(n-1.)
return estimate/n, no_all_eq, no_two_eq#, no_dist, suma, diagonala
def comb_est(x, y, z):
N = len(x)
a = 0
b = max(np.concatenate((x, y, z)))
s = 0
d = 0
cx = [0]*(b+1)
cy = [0]*(b+1)
cz = [0]*(b+1)
for i in range(N):
cx[x[i]] = cx[x[i]] + 1
cy[y[i]] = cy[y[i]] + 1
cz[z[i]] = cz[z[i]] + 1
d = d + x[i]*y[i]*z[i]
for i in range(b+1):
for j in range(b+1):
for k in range(b+1):
s = s + 2.*cx[i]*i*cy[j]*j*cz[k]*k/((N-1.)*(N-2.))
s = s - d*2./((N-1.)*(N-2.)) + d #add the diagonal back with the correct coefficient : the first is for the counting happening in the triple loop with the wrong coefficient
#subtract the correlation (two same indices) with the correct coefficient
cov = np.cov(x*y, z)[0,1] #has diagonal
cov += np.cov(x*z, y)[0,1]
cov += np.cov(y*z, x)[0,1]
cov = N*cov - 3*d #take out diagonal (three times)
#add the non-diagonal, non distinct with the correct coefficient
s = s + 2.*cov/((N-2.)) + cov
#finally, normalize s and return it
return s/N
def theo_cum(rates, B, i, j, k):
N = len(B[0, :])
term = np.sum(rates*B[i, :]*B[j, :]*B[k, :]) #add the 3-cherry
term += np.sum(rates*B[k, :]*np.dot(B[i, :]*B[j, :], B - np.eye(N))) #add the second tree shape for 3rd cumulant
term += np.sum(rates*B[j, :]*np.dot(B[i, :]*B[k, :], B - np.eye(N))) #add the second tree shape for 3rd cumulant
term += np.sum(rates*B[i, :]*np.dot(B[j, :]*B[k, :], B - np.eye(N))) #add the second tree shape for 3rd cumulant
return term
'''
N = 100
a = 0
b = 20
x = np.random.randint(a, b, N)
y = np.random.randint(a, b, N)
z = np.random.randint(a, b, N)
start = time.time()
cum, no1, no2, no3 = estimate(x,y,z)
end = time.time()
print cum
print "Time for size "+str(N)+" is "+str(end-start)+"."
start_comb = time.time()
s = comb_est(x,y,z)
end_comb = time.time()
print 'Second (combinatorial) : ', s
print 'Time (combinatorial) : '+str(end_comb - start_comb)
'''
| UTF-8 | Python | false | false | 2,737 | py | 9 | estimate_third_cumulant.py | 9 | 0.553891 | 0.522835 | 0 | 114 | 22.991228 | 173 |
jz2327/sample_mapreduce_AWS | 19,215,683,682,829 | 7243ff6a232869f02d0cf226f816f4133fa6e5d1 | 5b968bd30bde7eafd90810757e46df7f22df6063 | /task2-e/reduce.py | ce76b6aa3521b7de190d641b5315e276db3dfc95 | []
| no_license | https://github.com/jz2327/sample_mapreduce_AWS | d8ba3703c6a5febb94d513c2123002856a47b3ac | dd0bcfc9e18b6f3a5128ecbf1609bfe582c18020 | refs/heads/master | 2021-01-01T03:50:39.842511 | 2016-04-29T04:37:40 | 2016-04-29T04:37:40 | 57,354,556 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/python
from operator import itemgetter
import sys
current_key = None
count_sum = 0
datetime_list = []
count_date = 0
# input comes from STDIN (stream data that goes to the program)
for line in sys.stdin:
key, values = line.strip().split('\t')
datetime = values.strip().split(',')[0]
count = values.strip().split(',')[1]
try:
count = int(count)
except ValueError:
continue
if key == current_key:
count_sum += count
if datetime not in datetime_list:
datetime_list.append(datetime)
count_date += 1
else:
if current_key:
# output goes to STDOUT (stream data that the program writes)
print "%s\t%d,%.2f" %(current_key, count_sum, float(count_sum)/count_date)
current_key = key
count_sum = count
datetime_list = [datetime]
count_date = 1
print "%s\t%d,%.2f" %(current_key, count_sum, float(count_sum)/count_date)
| UTF-8 | Python | false | false | 985 | py | 15 | reduce.py | 15 | 0.590863 | 0.582741 | 0 | 37 | 25.621622 | 86 |
jabrouwer82/DataVizYelp | 16,080,357,588,396 | b963a98d89edbe2a9fed1ae5606a6e951909e48a | 9668f5bba20f46d55fef640286030e06ff032540 | /python/word_counts.py | c644867b115aea4f35f185bc7d8e22060c4deba3 | []
| no_license | https://github.com/jabrouwer82/DataVizYelp | 3f29654ff8cc8334a1a63e1d162e80d76374f176 | 407cc3bf33cfcc6c74e3089322ed6ec3bf11594d | refs/heads/master | 2020-04-01T09:47:33.913886 | 2014-12-16T03:12:25 | 2014-12-16T03:12:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #! /bin/python3
import getopt
import json
import nltk
import operator
import os
import random
import sys
from datetime import datetime
from nltk.corpus import stopwords
num_training = 0
opts = getopt.getopt(sys.argv[1:], 'i:d:n:s:', ['input_dir=', 'dev='])
input_dir = './'
for opt, arg in opts[0]:
if opt in ('-i', '--input_dir'):
input_dir = arg
elif opt in ('-d', '--dev'):
num_training = int(arg)
word_counts = [{}, {}, {}, {}, {}, {}]
num_reviews = 1125458
update_freq = num_reviews / 30
count = 0
start = datetime.now()
feature_set = []
# Contents of the feature_set should be in the form ({feature_name: feature_val}, label)
print 'Parsing reviews json into frequency distributions.'
raw_reviews = open(os.path.join(input_dir, "yelp_academic_dataset_review.json"))
# Parses a review object
for raw_review in raw_reviews:
count += 1
if count % update_freq == 0:
print 'Parsing review number:', count
review_json = json.loads(raw_review)
stars = int(review_json['stars'])
text = review_json['text'].lower()
if num_training > 0:
if count < num_training:
tokens = nltk.tokenize.word_tokenize(text)
for token in tokens:
word_counts[stars][token] = word_counts[stars].get(token, 0) + 1
else:
break
else:
tokens = nltk.tokenize.word_tokenize(text)
for token in tokens:
word_counts[stars][token] = word_counts[stars].get(token, 0) + 1
print 'There are', len(word_counts[1]), 'unique words in 1 star reviews'
print 'There are', len(word_counts[2]), 'unique words in 2 star reviews'
print 'There are', len(word_counts[3]), 'unique words in 3 star reviews'
print 'There are', len(word_counts[4]), 'unique words in 4 star reviews'
print 'There are', len(word_counts[5]), 'unique words in 5 star reviews'
| UTF-8 | Python | false | false | 1,794 | py | 109 | word_counts.py | 14 | 0.665552 | 0.648272 | 0 | 61 | 28.393443 | 88 |
pengwang01/yumanxiang | 18,872,086,324,265 | 3deb6122a20e4afd1422f5eff11d8f324c3eb27b | 51a7fe1406e773eb42c7b873f169e31684b141a4 | /ymx/apps.py | d9e5b939dabd02da9e93c039ffb89dad41e95952 | []
| no_license | https://github.com/pengwang01/yumanxiang | b33a327b825cfdbe4161cee870ac740373ac1d4b | 9a853129a0ccde0506ddbab5406d18d113218a40 | refs/heads/master | 2021-01-02T23:52:08.257850 | 2017-08-11T13:58:43 | 2017-08-11T13:58:43 | 99,512,806 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.apps import AppConfig
class YmxConfig(AppConfig):
name = 'ymx'
| UTF-8 | Python | false | false | 81 | py | 5 | apps.py | 4 | 0.728395 | 0.728395 | 0 | 5 | 15.2 | 33 |
fatihzkaratana/intranet | 2,224,793,068,788 | 9cd4e2faee28a31065e4f810583dd861520d3aff | 3d6b991ae1de688ebac24f80260d8caf5a429402 | /backend/intranet/middleware.py | 8b0e8a7c10df5996200c1043b55a38e1cfa80bd4 | [
"Apache-2.0"
]
| permissive | https://github.com/fatihzkaratana/intranet | 192dc7141a44ac45495846abf15a1ae0141dc803 | 161d8b6df0157c3d32472458642bf1f6c5723061 | refs/heads/master | 2020-07-10T14:37:54.178281 | 2014-12-29T10:39:46 | 2014-12-29T10:39:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
from django.conf import settings
from django.http import HttpResponse
from django.utils.importlib import import_module
from django.contrib.sessions.middleware import SessionMiddleware
class TokenSessionMiddleware(SessionMiddleware):
def process_request(self, request):
engine = import_module(settings.SESSION_ENGINE)
session_key = request.META.get(settings.SESSION_HEADER_NAME, None)
if not session_key:
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
request.session = engine.SessionStore(session_key)
COORS_ALLOWED_ORIGINS = getattr(settings, 'COORS_ALLOWED_ORIGINS', '*')
COORS_ALLOWED_METHODS = getattr(settings, 'COORS_ALLOWED_METHODS',
['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE', 'PATCH'])
COORS_ALLOWED_HEADERS = getattr(settings, 'COORS_ALLOWED_HEADERS',
['Content-Type', 'X-Requested-With',
'X-Session-Token', 'Accept-Encoding'])
COORS_ALLOWED_CREDENTIALS = getattr(settings, 'COORS_ALLOWED_CREDENTIALS', True)
class CoorsMiddleware(object):
def _populate_response(self, response):
response['Access-Control-Allow-Origin'] = COORS_ALLOWED_ORIGINS
response['Access-Control-Allow-Methods'] = ",".join(COORS_ALLOWED_METHODS)
response['Access-Control-Allow-Headers'] = ",".join(COORS_ALLOWED_HEADERS)
if COORS_ALLOWED_CREDENTIALS:
response['Access-Control-Allow-Credentials'] = 'true'
def process_request(self, request):
if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
response = HttpResponse()
self._populate_response(response)
return response
return None
def process_response(self, request, response):
self._populate_response(response)
return response
| UTF-8 | Python | false | false | 1,893 | py | 137 | middleware.py | 65 | 0.666138 | 0.66561 | 0 | 45 | 41.066667 | 85 |
CodingDojoInc/online-python-aug-2016 | 6,571,299,991,587 | ee33b14ae0ca4762637a867665aab9083acda98a | baed12b233efec74d6a39ec238b210948e58b68c | /KevinBrooks/Assignments/Week1/crawler.py | 03c60924e0947f1439a4ce8b0ae4ae111820c7b9 | []
| no_license | https://github.com/CodingDojoInc/online-python-aug-2016 | 53ed2e373b09981d6778eb49972004d8cfdf8df2 | 8745e0ca311b7beefa3903e6431679a90354a884 | refs/heads/master | 2016-09-13T11:17:37.054217 | 2016-09-08T20:41:29 | 2016-09-08T20:41:29 | 64,510,699 | 5 | 22 | null | false | 2016-09-27T23:29:57 | 2016-07-29T21:10:56 | 2016-09-06T16:54:48 | 2016-09-27T22:15:52 | 49,223 | 3 | 15 | 4 | Python | null | null | # import the urlopen function from the urllib2 module
from urllib2 import urlopen
# import the BeautifulSoup function from the bs4 module
from bs4 import BeautifulSoup
# import pprint to print things out in a pretty way
import pprint
# choose the url to crawl
url = 'http://www.codingdojo.com'
# get the result back with the BeautifulSoup crawler
soup = BeautifulSoup(urlopen(url))
#print soup # print soup to see the result!!
# your code here to find all the links from the result
# and complete the challenges below
links_list = []
links_dictionary = {}
for a in soup.body.findAll("a"):
links_list.append(a["href"])
for item in links_list:
if (links_dictionary.has_key(item)):
links_dictionary[item] = int(links_dictionary[item]) + 1
else:
links_dictionary[item] = 1
for key, value in links_dictionary.iteritems():
print key + ":" + str(value)
| UTF-8 | Python | false | false | 886 | py | 636 | crawler.py | 348 | 0.718962 | 0.71219 | 0 | 28 | 29.642857 | 58 |
UTSDataArena/examples | 19,404,662,272,556 | cabc05e7543513a94598a16bc5ed27a452a50d42 | 4ca82dad17a4ba59264a97b3e73726be9b501ec0 | /Tutorials/exportTut/loadGeom.py | bc2aee15dbdd97eb547fb318c59177ea2110491d | [
"BSD-2-Clause"
]
| permissive | https://github.com/UTSDataArena/examples | 48ba5ea044b5e57e0ce8f8ff4a2799ee5d61cbf6 | 0e326207a7ba6d9d86b1327d3d90c811ab6bdf9a | refs/heads/master | 2020-05-21T19:59:32.798995 | 2017-09-14T00:14:09 | 2017-09-14T00:14:09 | 61,348,259 | 2 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | from cyclops import *
from omega import *
from daHEngine import LoaderTools
LoaderTools.registerDAPlyLoader()
scene = getSceneManager()
scene.setBackgroundColor(Color(0.1,0.1,0.1,1))
fileToLoad = "mtcars.ply"
def addModel(fileToLoad, faceScreen=False):
# Load a static model
mdlModel = ModelInfo()
mdlModel.name = fileToLoad
mdlModel.path = fileToLoad
mdlModel.optimize=False # optimising takes a LONG time..
if faceScreen:
mdlModel.readerWriterOptions = "shiftVerts faceScreen"
return mdlModel
# Let the tetrahdeons face the screen for demo purposes
scene.loadModel(addModel(fileToLoad,faceScreen=True))
model = StaticObject.create(fileToLoad)
model.setName(fileToLoad)
model.getMaterial().setAdditive(True)
scene.loadModel(addModel("axes.ply"))
axes = StaticObject.create("axes.ply")
axes.setName("axes.ply")
model.addChild(axes)
#create a camera controller
camManipController = ManipulatorController.create()
#set its manipulator
manipulator = NodeTrackerManipulator.create()
camManipController.setManipulator(manipulator, None)
#set the node to track
manipulator.setTrackedNode(model)
#pass down events
def onEvent():
e = getEvent()
camManipController.onEvent(e)
setEventFunction(onEvent)
| UTF-8 | Python | false | false | 1,227 | py | 111 | loadGeom.py | 43 | 0.788101 | 0.782396 | 0 | 48 | 24.5625 | 57 |
fullgore/aclook | 1,700,807,089,810 | 07fcb9daf31c971f90e226d3aef44dea8aca9783 | 5aa4b37ccde948ecbbd5a54f31d19e0139ae2aee | /app/application.py | 153c8919414ef95d96dd560f15585b06f8b6034c | [
"MIT"
]
| permissive | https://github.com/fullgore/aclook | 2cdc41f2228d0b31512316d145809b81e380c958 | af27e5aff45719420cc4120b98ba3566b8668349 | refs/heads/master | 2022-04-24T05:27:12.958420 | 2020-04-14T09:48:45 | 2020-04-14T09:48:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
import logging
from flask import Flask
from flask.logging import default_handler
from aclook import appSC
CONFIG_MAPPER = {
'development': 'config.DevelopmentConfig',
'testing': 'config.TestingConfig',
'production': 'config.ProductionConfig',
}
def configure_loggers(app):
loggers = app.config.get("LOGGERS")
for logger_name, logger_value in loggers.items():
root_logger = logging.getLogger(logger_name)
root_logger.addHandler(default_handler)
root_logger.setLevel(logger_value)
def register_services(app):
appSC.bird_socket.provided_by(app.config['BIRD_SOCKET'])
appSC.bird_timeout.provided_by(app.config['BIRD_TIMEOUT'])
def create_app():
flask_env = os.getenv('FLASK_ENV', 'development')
app = Flask(__name__)
app.config.from_object(CONFIG_MAPPER.get(flask_env, 'development'))
configure_loggers(app)
import aclook
aclook.init_app(app)
register_services(app)
import modules
modules.init_app(app)
return app
| UTF-8 | Python | false | false | 1,027 | py | 22 | application.py | 18 | 0.697176 | 0.697176 | 0 | 45 | 21.822222 | 71 |
Thawster/AllTheWorldsAStage | 1,717,986,949,829 | 7f6e4f0b2b165b31cf1358adfee110458620fa0a | 5397221dc8d872722fa2697e149efa18430cbcc9 | /workforce/admin.py | f1f6ec0163d898d7ec8f4ebc86e1c138f205410d | []
| no_license | https://github.com/Thawster/AllTheWorldsAStage | f0c0c603366a4282311ea3b7bc4fc5fe9c3b2b06 | 2136ed26c2012c67ca33c7de2b0edfe4c4b8c3a2 | refs/heads/master | 2021-02-27T00:42:08.054226 | 2020-03-07T07:18:15 | 2020-03-07T07:18:15 | 245,564,374 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.contrib import admin
from workforce.models import Clown
class ClownAdmin(admin.ModelAdmin):
list_display = ('name', 'age', 'description', 'slug', )
admin.site.register(Clown, ClownAdmin)
| UTF-8 | Python | false | false | 207 | py | 13 | admin.py | 7 | 0.73913 | 0.73913 | 0 | 9 | 22 | 59 |
itrevex/adds | 7,327,214,230,917 | 0e3b1e0c8eda201c817787d9a0679fa26d83dd18 | a8099487b8a94950f5be025c353efe9357ece4bf | /src/dxf/dxf.py | 5298e544957c47bdf51622ba2b602f3b536e0fe7 | []
| no_license | https://github.com/itrevex/adds | 3cc5094ee557f83f9934961c49bbaaba8e97db64 | 0568385a8553bad85cf95c0d8655e01305c2b302 | refs/heads/master | 2022-01-20T13:44:27.790242 | 2019-06-03T05:10:38 | 2019-06-03T05:10:38 | 189,927,168 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import ezdxf
from ezdxf.addons import dimstyles, LinearDimension
from common.constants import Constants
from common.utils import Utils
from common.messages import Messages
from common.message_codes import MessageCodes
from .vport import VPort
SHOW_DIMENSIONS = False
class DxfDraw:
def __init__(self, app_data):
self.dwg = ezdxf.new('R2010') # create a new DXF R2010 drawing, official DXF version name: 'AC1024'
self.msp = self.dwg.modelspace() # add new entities to the model space
self.app_data = app_data
self.addLayersToModelSpace()
self.addStylesToModelSpace()
self.setHeaderAttribs()
#setup dimstyles
# dimstyles.setup(self.dwg)
pass
def makeDxf(self, entities, number_of_beams):
self.drawEntities(entities)
#setup viewports
VPort(self.dwg, number_of_beams)
output_path = self.app_data.getOutPutFile()
try:
self.dwg.saveas(output_path)
Messages.i("")
Messages.i(MessageCodes.INFO_DXF_GENERATED%output_path)
except PermissionError:
Messages.showError(MessageCodes.ERROR_OPEN_DXF)
Messages.continuePrompt(MessageCodes.INFO_CONTINUE_PROMPT)
def getFileName(self):
return Utils.dateTimeString() +"-detail.dxf"
def addDxfLine(self, line):
# add a LINE entity
layer = self.getLayer(line.layer)
self.msp.add_line(line.pt1, line.pt2,
dxfattribs={'layer': layer})
def addDxfCircle(self, circle):
# add a Circle entity
layer = self.getLayer(circle.layer)
self.msp.add_circle(circle.centre, circle.radius,
dxfattribs={'layer': layer})
def addDxfText(self, text):
# add a Text entity
# self.msp .add_circle(center, radius, dxfattribs={'layer': layer})
layer = self.getLayer(text.layer)
self.msp.add_text(text.text, dxfattribs={'style': text.style,
'height': text.height, 'layer': layer }).set_pos(text.pos, align=text.align)
def addDxfHatch(self, hatch):
'''
hatch has a list of the polyline path.
Path should be closed
'''
layer = self.getLayer(hatch.layer)
color = self.getLayerColor(hatch.layer)
dxf_hatch = self.msp.add_hatch(color=color, dxfattribs={'layer': layer})
with dxf_hatch.edit_boundary() as boundary:
boundary.add_polyline_path(hatch.path, is_closed=1)
def addDimEntity(self, dim):
'''
add dimesion
'''
if SHOW_DIMENSIONS:
layer = self.getLayer(dim.layer)
Messages.d("dxf.py", dim.points, dim.starting_point, dim.angle)
dimline = LinearDimension(dim.starting_point,
dim.points, dim.angle, layer=layer)
dimline.render(self.msp)
def getLayer(self, layer_name='0'):
try:
return self.layers[layer_name][Constants.LAYER_NAME]
except KeyError:
return '0'
def getLayerColor(self, layer_name='0'):
try:
return self.layers[layer_name][Constants.LAYER_COLOR]
except KeyError:
return '7'
def availableLineTypes(self):
# iteration
print('available line types:')
for linetype in self.dwg.linetypes:
print('{}: {}'.format(linetype.dxf.name, linetype.dxf.description))
def printLayers(self):
print(self.app_data.getLayers())
def getLayerAttributes(self, layer):
name = layer[Constants.LAYER_NAME]
lineType = layer[Constants.LAYER_LINE_TYPE]
color = layer[Constants.LAYER_COLOR]
layerAttributes = { Constants.LAYER_LINE_TYPE: lineType,
Constants.LAYER_COLOR: color}
return name, layerAttributes
def addStylesToModelSpace(self):
self.styles = self.app_data.getTextStyles()
for name, attribs in self.styles.items():
try:
self.dwg.styles.new(name=name, dxfattribs=attribs)
except ezdxf.lldxf.const.DXFTableEntryError:
#log error already exists
pass
def addLayersToModelSpace(self):
self.layers = self.app_data.getLayers()
for layer in self.layers.values():
name, attribs = self.getLayerAttributes(layer)
try:
self.dwg.layers.new(name=name, dxfattribs=attribs)
except ezdxf.lldxf.const.DXFTableEntryError:
#log error already exists
pass
def setHeaderAttribs(self):
headerAttribs = self.app_data.getHeaderAttribs()
for attrib in headerAttribs.values():
attribName = attrib[Constants.HEADER_ATTRIB_NAME]
attribValue = attrib[Constants.HEADER_ATTRIB_VALUE]
self.dwg.header.__setitem__(attribName, attribValue)
def drawEntities(self, entities):
if (entities == None):
return
for entity in entities:
#check to see if entity is line
if entity.type == Constants.ENTITY_LINE:
self.addDxfLine(entity)
pass
elif entity.type == Constants.ENTITY_CIRCLE:
#draw circle
self.addDxfCircle(entity)
pass
elif entity.type == Constants.ENTITY_TEXT:
#draw text
self.addDxfText(entity)
pass
elif entity.type == Constants.ENTITY_HATCH:
#draw hatch
self.addDxfHatch(entity)
pass
elif entity.type == Constants.ENTITY_DIMENSION:
#draw dimension
self.addDimEntity(entity)
pass | UTF-8 | Python | false | false | 5,790 | py | 62 | dxf.py | 43 | 0.597064 | 0.593782 | 0 | 168 | 33.470238 | 108 |
martini0117/SeparabilityMembranes | 764,504,226,018 | 1552e6e4ac288ca575367ce040b6787bd6832469 | 1c54040e0180ad99de167c9dda891b70d927d0c2 | /kidney/ShowBoundingBox.py | 1b5dd5ea395881744aa55ef9436ea06336434a8c | []
| no_license | https://github.com/martini0117/SeparabilityMembranes | c7d16d22626905dec698017cb59197cf4b63f80c | f867b50a818d75686b1bffc8260c67d23a745ad2 | refs/heads/main | 2023-03-20T21:04:37.799392 | 2021-03-09T07:57:53 | 2021-03-09T07:57:53 | 338,274,085 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import sys; sys.path.append('/Users/shomakitamiya/Documents/python/snake3D/src/Toolbox')
import sys; sys.path.append('/Users/shomakitamiya/Documents/python/snake3D/src/ellipsoid_fit')
import math
import matplotlib
import geomdl.visualization.VisMPL as VisMPL
import matplotlib.pyplot as plt
import numpy as np
from geomdl import BSpline
from geomdl.fitting import approximate_surface
from geomdl.knotvector import generate
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
from skimage.segmentation import flood_fill
import nibabel as nib
import cv2
from sklearn.cluster import KMeans
import Toolbox as tb
import ellipsoid_fit as ef
from skimage.filters import threshold_otsu
from mpl_toolkits.mplot3d import Axes3D
import ellipsoid_fit as ef
vis = True
# human = ''
human = '_h'
# cases = range(150,160)
# cases = range(150,190)
cases = [152]
data_path = '/Users/shomakitamiya/Documents/python/snake3D/data/kits19/data/'
window_center = 0
window_width = 300
for case in cases:
case_str = tb.get_full_case_id(case)
print(case_str)
nii0=nib.load(data_path + case_str + '/imaging.nii.gz')
img = nii0.get_data()
img = tb.window_function(img,window_center,window_width)
bounding_box = np.load('/Users/shomakitamiya/Documents/python/snake3D/data/SliceLabel/all/' + str(case) + '/bounding_box' + human + '.npy')
bb = np.zeros(img.shape,dtype=np.uint8)
for i in range(bb.shape[0]):
if i < bounding_box[0,0] or bounding_box[0,1] < i:
continue
X_indices, Y_indices = np.indices(bb.shape[1:])
bb[i,:,:] = np.where(
np.logical_and(
np.logical_and(
X_indices >= bounding_box[1,0],
X_indices <= bounding_box[1,1]
),
np.logical_and(
Y_indices >= bounding_box[2,0],
Y_indices <= bounding_box[2,1]
)
),
1,0)
x_range = slice(bounding_box[0,0],bounding_box[0,1])
y_range = slice(bounding_box[1,0],bounding_box[1,1])
z_range = slice(bounding_box[2,0],bounding_box[2,1])
clip = img[x_range,y_range,z_range]
clip_binary = np.zeros(clip.shape,dtype=np.bool)
# thresh = threshold_otsu(clip[i,:,:])
thresh = 180
for i in range(clip.shape[0]):
clip_binary[i,:,:] = thresh < clip[i,:,:]
points = np.zeros((np.sum(clip_binary),3))
count = 0
for i in range(clip.shape[0]):
for j in range(clip.shape[1]):
for k in range(clip.shape[2]):
if clip_binary[i,j,k]:
points[count,:] = np.array([i,j,k]) + bounding_box[:,0] + 0.0001 * np.random.rand(3)
count += 1
center, rotation, radius = ef.ellipsoid_fit(points)
# center = np.array(center) + bounding_box[:,0]
print(center)
print(rotation)
print(radius)
np.save('/Users/shomakitamiya/Documents/python/snake3D/data/SliceLabel/all/' + str(case) + '/bb_center' + human +'.npy',center)
np.save('/Users/shomakitamiya/Documents/python/snake3D/data/SliceLabel/all/' + str(case) + '/bb_rotation' + human +'.npy',rotation)
np.save('/Users/shomakitamiya/Documents/python/snake3D/data/SliceLabel/all/' + str(case) + '/bb_radius' + human +'.npy',radius)
np.save('/Users/shomakitamiya/Documents/python/snake3D/data/SliceLabel/all/' + str(case) + '/bb_points' + human +'.npy',points)
if vis:
con, bb = tb.get_contour_pts_img(bb)
tb.show_image_collection(tb.draw_segmentation_u(img,bb,mark_val=255,color=[255,255,255]))
tb.show_image_collection(clip)
tb.show_image_collection(clip_binary.astype(np.uint8) * 255)
psize = 20
app_points = np.array([[radius[0]*math.cos(u)*math.cos(v), radius[1]*math.cos(v)*math.sin(u),radius[2]*math.sin(v)]
for u in np.linspace(0,2*math.pi,num=psize)
for v in np.linspace(-math.pi/2+0.01,math.pi/2-0.01,num=psize)])
for i in range(len(app_points)):
app_points[i] = np.dot(app_points[i],rotation)
app_points += center
fig = plt.figure()
ax = Axes3D(fig)
ax.plot(points[:,0],points[:,1],points[:,2],marker="o",linestyle='None')
ax.plot(app_points[:,0],app_points[:,1],app_points[:,2],marker="o",linestyle='None')
plt.show()
surf = tb.make_nearest_surf(center,radius,rotation,points)
tb.surf_render(surf) | UTF-8 | Python | false | false | 4,724 | py | 99 | ShowBoundingBox.py | 93 | 0.588273 | 0.562024 | 0 | 127 | 36.204724 | 143 |
Fenykepy/phiroom | 9,448,928,082,529 | 7613715732446e2a8e7404c82214f5b591fafdc9 | 7b08198d079b17317211249764b0b0a063b0ecf8 | /src/api/phiroom/serializers.py | de11c99b56990cb7d9de7d3bb9527039e302abda | []
| no_license | https://github.com/Fenykepy/phiroom | 5bc04c6a503f86e2fd12ccafa7370922871e9f6c | ed2e458dfb6247d7fe487f4795a855a5275cfe5f | refs/heads/master | 2020-04-12T08:13:15.614372 | 2017-03-06T12:08:20 | 2017-03-06T12:08:20 | 19,888,777 | 1 | 0 | null | false | 2014-08-19T07:04:15 | 2014-05-17T14:43:18 | 2014-08-18T17:05:18 | 2014-08-18T21:39:36 | 129,795 | 1 | 1 | 1 | Python | null | null | from rest_framework import serializers
class CSRFTokenSerializer(serializers.Serializer):
token = serializers.CharField()
| UTF-8 | Python | false | false | 128 | py | 291 | serializers.py | 237 | 0.8125 | 0.8125 | 0 | 4 | 30.75 | 50 |
Maxim-ua/shop | 3,839,700,774,721 | 1c656ee0826226d4c0c8e1447f7ce118e062fd2e | 1dd51ba5d7515ab3e5c16c507f57f98f0e30b2c5 | /catalog/migrations/0004_auto_20160119_1544.py | c8cd4eb0ca842f7d548576f49f46927a98ca98e0 | []
| no_license | https://github.com/Maxim-ua/shop | 5e54df9f60a160315c268e481fefbc71c30e7372 | 419c2970d50b5388510b2305c3ad0d5b674c6232 | refs/heads/master | 2019-07-17T22:37:01.352120 | 2017-04-23T17:33:55 | 2017-04-23T17:33:55 | 72,571,369 | 0 | 0 | null | false | 2016-12-03T16:11:53 | 2016-11-01T19:55:58 | 2016-11-01T20:09:59 | 2016-12-03T16:11:53 | 656 | 0 | 0 | 0 | CSS | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('catalog', '0003_auto_20160112_1648'),
]
operations = [
migrations.AddField(
model_name='product',
name='discount',
field=models.DecimalField(default=0, verbose_name=b'\xd0\xa1\xd0\xba\xd0\xb8\xd0\xb4\xd0\xba\xd0\xb0 (%)', max_digits=8, decimal_places=2),
preserve_default=True,
),
migrations.AlterField(
model_name='product',
name='new_sale',
field=models.CharField(max_length=1, verbose_name=b'\xd0\xa2\xd0\xb8\xd0\xbf \xd0\xba\xd0\xb0\xd1\x82\xd0\xb5\xd0\xb3\xd0\xbe\xd1\x80\xd0\xb8\xd0\xb8', choices=[(b'N', b'\xd0\x9d\xd0\xbe\xd0\xb2\xd0\xb8\xd0\xbd\xd0\xba\xd0\xb0'), (b'S', b'\xd0\xa0\xd0\xb0\xd1\x81\xd0\xbf\xd1\x80\xd0\xbe\xd0\xb4\xd0\xb0\xd0\xb6\xd0\xb0'), (b'T', b'\xd0\xa2\xd0\xb5\xd0\xba\xd1\x83\xd1\x89\xd0\xb0\xd1\x8f \xd0\xba\xd0\xbe\xd0\xbb\xd0\xbb\xd0\xb5\xd0\xba\xd1\x86\xd0\xb8\xd1\x8f')]),
),
] | UTF-8 | Python | false | false | 1,122 | py | 46 | 0004_auto_20160119_1544.py | 29 | 0.623886 | 0.522282 | 0.090909 | 25 | 43.92 | 478 |
Mrsbutton13/rage-quit | 9,259,949,490,615 | 433621214721f780b4c35f7b554f4c2e48c8fff7 | 3aea98766d1f1d493088f0ccae480e57c2d6a284 | /app/models/gameComment.py | b394e478ef912c278d60c44501f918afe361e9b2 | []
| no_license | https://github.com/Mrsbutton13/rage-quit | 079b07fda573913a8ccab37247b41258a4880009 | aaced86bfa3448eee9a6268dc0d3c157da9d1e33 | refs/heads/main | 2023-05-10T13:41:53.727635 | 2021-06-19T01:05:16 | 2021-06-19T01:05:16 | 352,738,288 | 1 | 0 | null | false | 2021-04-23T01:57:30 | 2021-03-29T18:03:37 | 2021-04-22T03:46:15 | 2021-04-23T01:57:30 | 3,803 | 1 | 0 | 0 | Python | false | false | from .db import db
class GameComment(db.Model):
__tablename__ = 'gameComments'
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.Text)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
game_id = db.Column(db.Integer, db.ForeignKey('games.id'), nullable=False)
def to_dict(self):
return {
'id': self.id,
'user_id': self.user_id,
'game_id': self.game_id,
'body': self.body
} | UTF-8 | Python | false | false | 463 | py | 90 | gameComment.py | 68 | 0.62635 | 0.62635 | 0 | 20 | 22.2 | 76 |
nonepkg/nonebot-plugin-todo | 6,313,601,972,775 | 85bf0918c2f9338dfe2ea3ed23d45f7bf92bbfc2 | 95c1206c157d94bc2ad56f1ffc4a9e43124174c4 | /nonebot_plugin_todo/__init__.py | ff92d36c6d422c6bde2ffb2e06a55f962851594c | [
"MIT",
"Python-2.0"
]
| permissive | https://github.com/nonepkg/nonebot-plugin-todo | 3a67ce4deaf0d1c9f7ee34a55b2a9e8ad2ae7450 | a5a7424ee36590dfb67ecb8169bab0129d3ac2b0 | refs/heads/master | 2023-04-04T03:14:56.736347 | 2021-04-17T14:49:03 | 2021-04-17T14:49:03 | 357,260,968 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | from nonebot.plugin import on_shell_command, require
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import (
unescape,
Bot,
Event,
Message,
PrivateMessageEvent,
GroupMessageEvent,
)
from nonebot import get_bots
from .parser import todo_parser, handle_scheduler
scheduler = require("nonebot_plugin_apscheduler").scheduler
# 注册 shell_like 事件响应器
todo = on_shell_command("todo", parser=todo_parser, priority=5)
# 每分钟进行一次检测
@scheduler.scheduled_job("cron", minute="*", id="todo")
async def _():
bots = get_bots()
args = handle_scheduler()
for bot in bots.values():
for job in args.jobs:
await bot.send_msg(
user_id=job["user_id"],
group_id=job["group_id"],
message=Message(job["message"]),
)
@todo.handle()
async def _(bot: Bot, event: Event, state: T_State):
args = state["args"]
args.user_id = event.user_id if isinstance(event, PrivateMessageEvent) else None
args.group_id = event.group_id if isinstance(event, GroupMessageEvent) else None
args.is_admin = (
event.sender.role in ["admin", "owner"]
if isinstance(event, GroupMessageEvent)
else False
)
if hasattr(args, "message"):
args.message = unescape(args.message)
if hasattr(args, "handle"):
args = args.handle(args)
if args.message:
await bot.send_msg(
user_id=args.user_id,
group_id=args.group_id,
message=Message(args.message),
)
| UTF-8 | Python | false | false | 1,608 | py | 7 | __init__.py | 4 | 0.616751 | 0.616117 | 0 | 57 | 26.649123 | 84 |
bpn21/django-backend--crud-and-auth | 412,316,898,949 | d5c82f89bf7e242d6b075137c2fbeeebeef12b8e | 75dab02a690413bb05f1130229bccb2a78a70b7d | /my_project/book/views.py | 7e06d66c23c5065bcc4265dd34e9bda1b3852dde | []
| no_license | https://github.com/bpn21/django-backend--crud-and-auth | 04801a7eca3a4b3b28d479134175205d05961eaa | 023050a945f8bc9d9b0a356d0ba61a9a04e7b6c3 | refs/heads/master | 2023-01-13T05:19:08.958938 | 2020-11-10T16:40:09 | 2020-11-10T16:40:09 | 307,263,626 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from rest_framework import viewsets
from . import models
from . import serializers
from .serializers import ProductSerializer,CategorySerializer
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
class ProductViewSet(viewsets.ModelViewSet):
queryset = models.Product.objects.all()
serializer_class = serializers.ProductSerializer
class CategoryViewSet(viewsets.ModelViewSet):
queryset = models.Category.objects.all()
serializer_class = serializers.CategorySerializer
class CustomAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'user_id': user.pk,
'email': user.email
})
class HelloView(APIView):
def get(self, request):
content = {'message': 'Hello, World!'}
return Response(content)
# class ProductList(generics.ListCreateAPIView):
# queryset = Product.objects.all()
# serializer_class = ProductSerializer
# permission_classes = (permissions.AllowAny,)
# class Create(generics.CreateAPIView):
# model = Product
# queryset = Product.objects.all()
# serializer_class = ProductSerializer
# permission_classes = (permissions.AllowAny,)
# class Update(generics.RetrieveUpdateDestroyAPIView):
# model = Product
# queryset = Product.objects.all()
# serializer_class = ProductSerializer
# permission_classes = (permissions.AllowAny,)
# # template_name = 'update_product.html'
# # fields = '__all__'
# class Remove(DeleteView):
# model = Product
# template_name = 'remove_product.html'
# success_url = 'home'
# class List(ListView):
# model = Product
# template_name = 'home.html'
# class Detail(DetailView):
# model = Product
# template_name = 'product_detail.html'
| UTF-8 | Python | false | false | 2,423 | py | 15 | views.py | 11 | 0.688816 | 0.688816 | 0 | 88 | 26.5 | 84 |
linhvo/umbelapi | 5,523,327,944,301 | fc8b2d748ee0af02ec3866e092cc197e42a044d5 | aeb991b6e714046ae1827b350256c30b38690786 | /core/api/profile.py | 27cef7e1b186119b1739a738498d608d00c9df14 | []
| no_license | https://github.com/linhvo/umbelapi | c47d9166ac18c0f5ff160cefbf671a16a4908655 | 50bfde474696ef598b97c1024ee9130620d9356f | refs/heads/master | 2021-01-22T04:40:31.886554 | 2015-04-20T02:33:32 | 2015-04-20T02:33:32 | 33,888,163 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from rest_framework import viewsets, serializers, mixins
from core.models import Profile
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('id', 'created', 'last_mod')
class UserProfileViewSet(mixins.RetrieveModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet):
model=Profile
queryset = Profile.objects.all()
serializer_class = UserProfileSerializer | UTF-8 | Python | false | false | 489 | py | 15 | profile.py | 11 | 0.683027 | 0.683027 | 0 | 15 | 31.666667 | 57 |
MarvinTeichmann/TorchLab | 14,001,593,395,178 | 0eae20738eb68e861c9924e822f1880fe094a5c2 | 8b941c71ad2919e223b716fbafaca382695ae3dd | /torchlab/loss/__init__.py | 8dec2bbf3a0d3a10bb2d22da69fa5f0fbc11ee03 | [
"MIT"
]
| permissive | https://github.com/MarvinTeichmann/TorchLab | 1f79b4f6afc36e202d9a12328962fdad18312855 | b02cbbb0f8ad2115df86a1c09120ec8131b91be1 | refs/heads/master | 2023-08-10T21:25:11.442958 | 2023-08-02T03:24:43 | 2023-08-02T03:24:43 | 205,008,475 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from . import loss
from .loss import *
| UTF-8 | Python | false | false | 39 | py | 76 | __init__.py | 68 | 0.717949 | 0.717949 | 0 | 2 | 18.5 | 19 |
sh-ebrahimi/Edge_Cache_Sim | 13,700,945,720,270 | 5a355f20fcb20ccd05a30dc46d18ced9e65c7eed | 6f65c2819a507e86d0ebc0490393ff5d3861391e | /codes/node.py | 4fdcf55f28adb7d8a6d259055692b95890cc3ea9 | []
| no_license | https://github.com/sh-ebrahimi/Edge_Cache_Sim | 04a0425ef54abdbb03636cb39cf6c0857e824bf0 | 36223b856a47afb43ed7705537142e87ad10dd38 | refs/heads/master | 2022-05-29T16:13:56.084383 | 2022-05-14T05:40:40 | 2022-05-14T05:40:40 | 156,227,040 | 18 | 7 | null | false | 2018-11-21T06:36:03 | 2018-11-05T14:02:30 | 2018-11-10T15:14:49 | 2018-11-21T06:36:02 | 1,641 | 0 | 1 | 0 | Python | false | null | import random
from packet import DataPacket , InterestPacket
from globals import time , timeComparator, getTime , addTime , logging
from decorators import debug
class Node:
name = ""
memorySize = None
totalPower = None
residualPower = None
processingPowerUnit = None
transmissionPowerUnit = None
ArchitectureLevel = None
cacheHit = None
cacheMiss = None
residualCacheSize = None
numberOfInterestPacket = None
numberOfDataPacket = None
inputLoad = None
facesFlags = None # key is interest name and value is face flag
inputFaces = None # key is interest name and value is face queue
outputFaces = None
fib = None # key is interest name and value is face name
pit = None # { interest name : { 'inface' : "1" , 'outface' : "3" , 'freshness' : "400" }}
cs = None # { name : { 'packet' : "dklsfj" , 'size' : "kldf" , 'hit ratio' : "adlfk" ,'lastAccess' = "dskflj" , 'ref' = "points to memory"}}
def __init__(self, name, memorySize, totalPower, processingPowerUnit, transmissionPowerUnit, arch):
self.name = name
self.memorySize = int(memorySize)
self.residualCacheSize = self.memorySize
self.totalPower = int(totalPower)
self.residualPower = int(totalPower)
self.processingPowerUnit = int(processingPowerUnit)
self.transmissionPowerUnit = int(transmissionPowerUnit)
self.ArchitectureLevel = arch
self.cacheHit = 0
self.cacheMiss = 0
self.numberOfInterestPacket = 0
self.numberOfDataPacket = 0
self.inputLoad = 0
self.inputFaces = {}
self.outputFaces = {}
self.facesFlags = {}
self.fib = {}
self.pit = {}
self.cs = {}
self.cacheMemory = [False] * self.memorySize
def initialFib(self, *array):
for i in range(1, len(array), 2):
self.fib[array[i]] = array[i + 1]
@debug
def forwardInterestPacket(self, interestPacket, faceName):
self.residualPower -= 1
interestName = interestPacket.name
outgoingFaceName = self.fib[interestName]
if self.cs.__contains__(interestName) and interestPacket.freshness < self.getFreshness(self.cs[interestName]['packet']):
logging.debug(self.name + ": sending interest packet " + interestPacket.name + " back from cs (CACHE HIT!)")
print (self.name + ": sending interest packet " + interestPacket.name + " " + str(self.getFreshness(self.cs[interestName]['packet'])) + " back from cs (CACHE HIT!)")
self.sendOut(self.cs[interestName]['packet'], faceName)
self.cs[interestName]['lastAccess'] = time.timeInSeconds
self.cs[interestName]['hitRatio'] += 1
self.cacheHit += 1
# we must forward interest
elif self.pit.__contains__(interestName):
containsEntryFlag = False
table = self.pit[interestName]
self.cacheMiss += 1
for array in table:
if array[0] == faceName and array[1] == outgoingFaceName:
containsEntryFlag = True
if not containsEntryFlag:
table.append([faceName, outgoingFaceName, interestPacket.freshness])
# it is forward
logging.debug(self.name + ": forward interest packet " + interestPacket.name + " to " + outgoingFaceName)
print (self.name + ": forward interest packet " + interestPacket.name + " to " + outgoingFaceName + " pit contains")
self.sendOut(interestPacket, outgoingFaceName)
else:
# it is forward
self.cacheMiss += 1
logging.debug(self.name + ": forward interest packet " + interestPacket.name + " to " + outgoingFaceName)
print (
self.name + ": forward interest packet " + interestPacket.name + " to " + outgoingFaceName + " pit doesn't contain")
self.sendOut(interestPacket, outgoingFaceName)
self.pit[interestName] = []
self.pit[interestName].append([faceName, outgoingFaceName, interestPacket.freshness])
@debug
def forwardInterestPacketNoCache(self, interestPacket, faceName):
self.residualPower -= 1
interestName = interestPacket.name
outgoingFaceName = self.fib[interestName]
# we must forward interest
if self.pit.__contains__(interestName):
containsEntryFlag = False
table = self.pit[interestName]
self.cacheMiss += 1
for array in table:
if array[0] == faceName and array[1] == outgoingFaceName:
containsEntryFlag = True
if not containsEntryFlag:
table.append([faceName, outgoingFaceName, interestPacket.freshness])
# it is forward
logging.debug(self.name + ": forward interest packet " + interestName + " to " + outgoingFaceName)
print (
self.name + ": forward interest packet " + interestName + " to " + outgoingFaceName + " pit contains")
self.sendOut(interestPacket, outgoingFaceName)
else:
# it is forward
self.cacheMiss += 1
logging.debug(self.name + ": forward interest packet " + interestName + " to " + outgoingFaceName)
print (
self.name + ": forward interest packet " + interestName + " to " + outgoingFaceName + " pit doesn't contain")
self.sendOut(interestPacket, outgoingFaceName)
self.pit[interestName] = []
self.pit[interestName].append([faceName, outgoingFaceName, interestPacket.freshness])
@debug
def forwardInterestPacketPathCache(self, interestPacket, faceName):
self.residualPower -= 1
interestName = interestPacket.name
outgoingFaceName = self.fib[interestName]
if self.cs.__contains__(interestName) and interestPacket.freshness < self.getFreshness(
self.cs[interestName]['packet']):
logging.debug(self.name + ": sending interest packet " + interestPacket.name + " back from cs (CACHE HIT!)")
print (self.name + ": sending interest packet " + interestPacket.name + " " + str(
self.getFreshness(self.cs[interestName]['packet'])) + " back from cs (CACHE HIT!)")
self.sendOut(self.cs[interestName]['packet'], faceName)
self.cs[interestName]['lastAccess'] = time.timeInSeconds
self.cs[interestName]['hitRatio'] += 1
self.cacheHit += 1
# we must forward interest
elif self.pit.__contains__(interestName):
containsEntryFlag = False
table = self.pit[interestName]
self.cacheMiss += 1
for array in table:
if array[0] == faceName and array[1] == outgoingFaceName:
containsEntryFlag = True
if not containsEntryFlag:
table.append([faceName, outgoingFaceName, interestPacket.freshness])
# it is forward
logging.debug(
self.name + ": forward interest packet " + interestPacket.name + " to " + outgoingFaceName)
print (self.name + ": forward interest packet " + interestPacket.name + " to " + outgoingFaceName + " pit contains")
interestPacket.pathCache+= self.residualCacheSize
self.sendOut(interestPacket, outgoingFaceName)
else:
# it is forward
self.cacheMiss += 1
logging.debug(self.name + ": forward interest packet " + interestPacket.name + " to " + outgoingFaceName)
print (self.name + ": forward interest packet " + interestPacket.name + " to " + outgoingFaceName + " pit doesn't contain")
interestPacket.pathCache += self.residualCacheSize
self.sendOut(interestPacket, outgoingFaceName)
self.pit[interestName] = []
self.pit[interestName].append([faceName, outgoingFaceName, interestPacket.freshness])
@debug
def forwardDataPacket(self, dataPacket, faceName):
self.residualPower -= 1
interestName = dataPacket.name
if self.pit.__contains__(interestName):
table = self.pit[interestName]
ntable = []
for array in table:
if array[1] == faceName and self.getFreshness(dataPacket) > array[2]:
logging.debug(self.name + ": data packet " + dataPacket.name + " forwarded to " + array[0])
self.sendOut(dataPacket, array[0])
else:
ntable.append(array)
if ntable == []:
self.pit.pop(interestName)
else:
self.pit[interestName] = ntable
self.cacheManagementByFrequency(dataPacket)
@debug
def forwardDataPacketNoCache(self, dataPacket, faceName):
self.residualPower -= 1
interestName = dataPacket.name
if self.pit.__contains__(interestName):
table = self.pit[interestName]
ntable = []
for array in table:
if array[1] == faceName and self.getFreshness(dataPacket) > array[2]:
logging.debug(self.name + ": data packet " + dataPacket.name + " forwarded to " + array[0])
self.sendOut(dataPacket, array[0])
else:
ntable.append(array)
if ntable == []:
self.pit.pop(interestName)
else:
self.pit[interestName] = ntable
@debug
def forwardDataPacketHalfCache(self, dataPacket, faceName):
self.residualPower -= 1
interestName = dataPacket.name
if self.pit.__contains__(interestName):
table = self.pit[interestName]
ntable = []
for array in table:
if array[1] == faceName and self.getFreshness(dataPacket) > array[2]:
logging.debug(self.name + ": data packet " + dataPacket.name + " forwarded to " + array[0])
self.sendOut(dataPacket, array[0])
else:
ntable.append(array)
if ntable == []:
self.pit.pop(interestName)
else:
self.pit[interestName] = ntable
rand = random.randint(0, 1)
if rand == 1:
self.cacheManagementByFrequency(dataPacket)
@debug
def forwardDataPacketPcasting(self, dataPacket, faceName):
self.residualPower -= 1
interestName = dataPacket.name
if self.pit.__contains__(interestName):
table = self.pit[interestName]
ntable = []
for array in table:
if array[1] == faceName and self.getFreshness(dataPacket) > array[2]:
logging.debug(self.name + ": data packet " + dataPacket.name + " forwarded to " + array[0])
self.sendOut(dataPacket, array[0])
else:
ntable.append(array)
if ntable == []:
self.pit.pop(interestName)
else:
self.pit[interestName] = ntable
print self.name , " pacasting "
fu = (float(self.residualPower)/self.totalPower + float(self.residualCacheSize)/self.memorySize + self.getFreshness(dataPacket))/3
probability = int(fu * 100)
rand = random.randint(0 , 100)
print "residualPower/totalPower: " , float(self.residualPower)/self.totalPower , " residualCacheSize/memorySize: " , float(self.residualCacheSize)/self.memorySize , " Freshness: " , self.getFreshness(dataPacket)
print "fu: " , fu , "probability: " , probability , " rand: " , rand
if rand < probability:
self.cacheManagementByFrequency(dataPacket)
@debug
def forwardDataPacketPathCache(self, dataPacket, faceName):
self.residualPower -= 1
interestName = dataPacket.name
if self.pit.__contains__(interestName):
table = self.pit[interestName]
ntable = []
for array in table:
if array[1] == faceName and self.getFreshness(dataPacket) > array[2]:
logging.debug(self.name + ": data packet " + dataPacket.name + " forwarded to " + array[0])
self.sendOut(dataPacket, array[0])
else:
ntable.append(array)
if ntable == []:
self.pit.pop(interestName)
else:
self.pit[interestName] = ntable
fu = float(self.residualCacheSize)/dataPacket.pathCache
probability = int ( fu * 100)
rand = random.randint(0, 100)
print "fu: " , fu , " probability: " , probability , " rand: " , rand , " dataPacket.pathCache: " , dataPacket.pathCache
if rand < probability:
self.cacheManagementByFrequency(dataPacket)
@debug
def sendOut (self , packet , faceName): # forward functions use this function
self.residualPower -= 1
queue = self.outputFaces[faceName]
queue.append(packet)
self.facesFlags[faceName] = True
logging.debug( self.name+ ": packet "+ packet.name+ " sent out to "+ faceName)
if packet.__class__ is InterestPacket:
self.numberOfInterestPacket+=1
else:
self.numberOfDataPacket+=1
@debug
def processOutgoingpackets (self):
for faceName , face in self.outputFaces.items():
if not self.facesFlags[faceName]:
face.append("0")
self.facesFlags[faceName] = True
logging.debug(self.name + " ++ " + faceName + " " + str(face))
@debug
def cacheManagement(self, packet):
self.residualPower -= 1
interestName = packet.name
if self.cs.__contains__(interestName):
if self.cs[interestName]['freshness'] + 50 < packet.freshness:
print self.name, " : data exists in cache but expired"
self.cacheReplace(packet)
else:
neededSize = packet.size
ref = self.findEmptySpace(neededSize)
print "cache management ", ref, neededSize
print self.cacheMemory
if ref != -1:
print self.name, ": have enough memory for data packet ", packet.name
self.cs[interestName] = {}
self.cs[interestName]['packet'] = packet
self.cs[interestName]['freshness'] = packet.freshness
self.cs[interestName]['size'] = packet.size
self.cs[interestName]['hitRatio'] = 0
self.cs[interestName]['lastAccess'] = 0
self.cs[interestName]['ref'] = ref
self.fillSpace(neededSize, ref)
else:
print self.name, ": not enough space for data packet ", packet.name, " so calling cache replace "
self.cacheReplace(packet)
@debug
def cacheManagementByFrequency(self, dataPacket):
self.residualPower -= 1
interestName = dataPacket.name
if self.cs.__contains__(interestName):
csPacket = self.cs[interestName]['packet']
if time.timeInSeconds - csPacket.generatedTime > csPacket.frequency or self.getFreshness(
csPacket) < self.getFreshness(dataPacket):
print self.name, " : data exists in cache but expired or old"
print "expiration: time.timeInSeconds - csPacket.generatedTime > csPacket.frequency", time.timeInSeconds - csPacket.generatedTime, csPacket.frequency
print "old: self.getFreshness(csPacket) < self.getFreshness(dataPacket)", self.getFreshness(
csPacket), self.getFreshness(dataPacket)
self.cacheReplace(dataPacket)
else:
neededSize = dataPacket.size
ref = self.findEmptySpace(neededSize)
print "cache management ", ref, neededSize
# print self.cacheMemory
if ref != -1:
print self.name, ": have enough memory for data packet ", dataPacket.name
self.cs[interestName] = {}
self.cs[interestName]['packet'] = dataPacket
self.cs[interestName]['size'] = dataPacket.size
self.cs[interestName]['hitRatio'] = 0
self.cs[interestName]['lastAccess'] = 0
self.cs[interestName]['ref'] = ref
self.fillSpace(neededSize, ref)
else:
print self.name, ": not enough space for data packet ", dataPacket.name, " so calling cache replace "
self.cacheReplace(dataPacket)
@debug
def cacheReplace(self, dataPacket):
self.residualPower -= 1
interestName = dataPacket.name
if self.cs.__contains__(interestName):
self.cs[interestName]['packet'] = dataPacket
oldSize = self.cs[interestName]['size']
self.cs[interestName]['size'] = dataPacket.size
self.cs[interestName]['hitRatio'] = 0
self.cs[interestName]['lastAccess'] = 0
oldRef = self.cs[interestName]['ref']
print self.name, " : packet ", interestName, " is renewing "
self.emptySpace(oldSize, oldRef)
newRef = self.findEmptySpace(self.cs[interestName]['size'])
if newRef != -1:
self.cs[interestName]['ref'] = newRef
self.fillSpace(self.cs[interestName]['size'], newRef)
print self.name, " : packet ", interestName, " is new "
else:
print(self.name, " : packet ", interestName, " couldn't find space :(")
else:
print self.name, " : finding space for new packet ", interestName
minLastAccess = time.timeInSeconds
minInterest = None
neededSize = dataPacket.size
newRef = -1
while newRef == -1:
for name, data in self.cs.items():
print (name + str(data['lastAccess']) + str(minLastAccess))
if data['lastAccess'] < minLastAccess:
minLastAccess = data['lastAccess']
minInterest = name
if minInterest != None:
self.emptySpace(self.cs[minInterest]['size'], self.cs[minInterest]['ref'])
print self.name, " packet ", self.cs[minInterest]['packet'].name, " removed"
self.cs.pop(minInterest)
minLastAccess = time.timeInSeconds
newRef = self.findEmptySpace(neededSize)
print self.name, " : new ref ", newRef, " found for ", dataPacket.name
def emptySpace(self, size, ref):
for x in range(ref, ref + size / 8):
self.cacheMemory[x] = False
self.residualCacheSize+= size/8
def fillSpace(self, size, ref):
for x in range(ref, ref + size / 8):
self.cacheMemory[x] = True
self.residualCacheSize-=size/8
def findEmptySpace(self, neededSize):
self.residualPower -= 1
neededSize /= 8
maxSize = self.memorySize + 1
maxRef = -1
ref = 0
acc = 0
for x in range(0, self.memorySize):
if not self.cacheMemory[x]:
acc += 1
if acc == 1:
ref = x
if x == self.memorySize - 1 and acc < maxSize and acc >= neededSize:
maxRef = ref
maxSize = acc
elif acc < maxSize and acc >= neededSize:
maxRef = ref
maxSize = acc
acc = 0
return maxRef
def getFreshness(self, dataPacket):
freshness = 1 - (float(time.timeInSeconds - dataPacket.generatedTime) / dataPacket.frequency)
return freshness | UTF-8 | Python | false | false | 20,059 | py | 20 | node.py | 9 | 0.575652 | 0.570118 | 0 | 446 | 43.977578 | 219 |
maiahillel/ColorConverter | 7,000,796,736,761 | 2413708be343b70137711e3e41310aef93402331 | 4e9c279b2f5bf360b9676809f2c10b6fc993d9bf | /VideoWidget.py | 5e12c8aaed5f2c6c701bf7ba53eb8a6ab84ec0d6 | []
| no_license | https://github.com/maiahillel/ColorConverter | f3546423d499c49716806637fa611fe17014c9ad | ad347827b97eb94f03b63a9bbf445ad0ec5accdf | refs/heads/master | 2021-01-21T13:43:48.439843 | 2016-05-21T08:48:12 | 2016-05-21T08:48:12 | 49,712,341 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # coding=utf8
# Copyright (C) 2011 Saúl Ibarra Corretgé <saghul@gmail.com>
#
# Some inspiration taken from: http://www.morethantechnical.com/2009/03/05/qt-opencv-combined-for-face-detecting-qwidgets/
import ColorConverter
import sys
sys.path.append('/usr/lib/pymodules/python2.7/')
sys.path.append('/usr/lib/python2.7/dist-packages')
sys.path.append('/usr/lib/pyshared/python2.7/')
sys.path.append('/usr/local/lib/python2.7/site-packages/')
import numpy
import cv2 as cv
from PyQt4.QtCore import *
import IplQImage
from PyQt4.QtGui import *
class VideoWidget(QWidget):
""" A class for rendering video coming from OpenCV """
def __init__(self, color_deficit, parent=None):
QWidget.__init__(self)
self.capture = cv.VideoCapture(0)
# Take one frame to query height
ret, frame = self.capture.read()
self.color_converter = ColorConverter.ColorConverter(color_deficit)
image = self.color_converter.convert(frame)
self.setMinimumSize(800, 600)
self.setMaximumSize(self.minimumSize())
self._frame = None
self._image = self._build_image(image)
# Paint every 50 ms
self._timer = QTimer(self)
self._timer.timeout.connect(self.queryFrame)
self._timer.start(50)
def _build_image(self, frame):
self._frame = frame
# if frame.origin == cv.IPL_ORIGIN_TL:
# cv.Copy(frame, self._frame)
# else:
# cv.Flip(frame, self._frame, 0)
return IplQImage.IplQImage(numpy.fliplr(self._frame))
def paintEvent(self, event):
painter = QPainter(self)
painter.drawImage(QPoint(0, 0), self._image)
def queryFrame(self):
ret, frame = self.capture.read()
image = self.color_converter.convert(frame)
self._image = self._build_image(image)
self.update()
def set_to_d(self):
self.color_converter.set_deficit('d')
def set_to_p(self):
self.color_converter.set_deficit('p')
def set_to_t(self):
self.color_converter.set_deficit('t')
def set_key(self, key, zoom):
self.color_converter.set_key(key, zoom)
| UTF-8 | Python | false | false | 2,162 | py | 12 | VideoWidget.py | 11 | 0.64537 | 0.627778 | 0 | 72 | 29 | 122 |
Kirill888/odc-tools | 7,980,049,264,485 | ccd9fb63d8dffe57625c2c996e82908747cef1fb | 27a87acc82d6ab6ba84e90a76c510d3c1cb5c0ca | /apps/dc_tools/tests/test_azure_to_dc.py | 6573127688429ab43563f704f5ab40d110eadf7b | [
"Apache-2.0"
]
| permissive | https://github.com/Kirill888/odc-tools | 8540315794d0f4836d12d12d24fb83746ca0b9dc | 2477849cc92bf32c087805beb8043e6524515da7 | refs/heads/develop | 2023-07-19T06:46:31.907368 | 2021-09-15T03:23:41 | 2021-09-15T03:34:11 | 385,593,169 | 0 | 0 | Apache-2.0 | true | 2021-08-20T08:31:26 | 2021-07-13T12:17:41 | 2021-08-19T02:14:23 | 2021-08-20T08:24:49 | 3,528 | 0 | 0 | 1 | Python | false | false | # Tests using the Click framework the azure-to-dc CLI tool | UTF-8 | Python | false | false | 58 | py | 129 | test_azure_to_dc.py | 90 | 0.793103 | 0.793103 | 0 | 1 | 58 | 58 |
WarmongeringBeaver/hera_sim | 16,801,912,084,174 | 4c203ce81ed1fb14984d60f5165553e03c97f1bd | 5f93984387d7326695d4df88321b29cc477059ba | /hera_sim/components.py | cdb1bdee164842a445ca09af7543589046949cb4 | [
"MIT"
]
| permissive | https://github.com/WarmongeringBeaver/hera_sim | 640434d4e3482f53c2bdd19b54b7369502da44d6 | 7e8b317a4fed5c75c273405a1d123a84073793b4 | refs/heads/main | 2023-07-15T19:30:40.898909 | 2021-08-23T14:19:08 | 2021-08-23T14:19:08 | 375,382,892 | 0 | 0 | NOASSERTION | true | 2021-07-27T20:01:20 | 2021-06-09T14:24:27 | 2021-07-26T07:28:40 | 2021-07-27T20:01:18 | 57,929 | 0 | 0 | 0 | Python | false | false | """A module providing discoverability features for hera_sim."""
from __future__ import annotations
import re
from abc import abstractmethod, ABCMeta
from copy import deepcopy
from .defaults import defaults
from typing import Dict, Optional, Tuple, Type
from types import new_class
from collections import defaultdict
_available_components = {}
class SimulationComponent(metaclass=ABCMeta):
"""Base class for defining simulation component models.
This class serves two main purposes:
- Provide a simple interface for discovering simulation
component models (see :meth:`~list_discoverable_components`").
- Ensure that each subclass can create abstract methods.
The :meth:`~component`: class decorator provides a simple way of
accomplishing the above, while also providing some useful extra
features.
Attributes
----------
is_multiplicative
Specifies whether the model ``cls`` is a multiplicative
effect. This parameter lets the :class:`~hera_sim.simulate.Simulator`:
class determine how to apply the effect simulated by
``cls``. Default setting is False (i.e. the model is
assumed to be additive unless specified otherwise).
"""
#: Whether this systematic multiplies existing visibilities
is_multiplicative: bool = False
_alias: Tuple[str] = tuple()
def __init_subclass__(cls, is_abstract: bool = False):
"""Provide some useful augmentations to subclasses.
Parameters
----------
is_abstract
Specifies whether the subclass ``cls`` is an abstract
class or not. Classes that are not abstract are
registered in the ``_models`` dictionary. This
is the feature that provides a neat interface for
automatic discoverability of component models. Default
behavior is to register the subclass.
Notes
-----
This subclass initialization routine also automatically
updates the ``__call__`` docstring for the subclass with
the parameters from the ``__init__`` docstring if both
methods are documented in the numpy style. This decision was
made because the convention for defining a new component
model is to have optional parameters be specified on class
instantiation, but with the option to override the
parameters when the class instance is called. In lieu of
repeating the optional parameters with their defaults, all
component model signatures consist of only required
parameters and variable keyword arguments.
For an example of how to use the ``component`` decorator,
please refer to the following tutorial notebook:
< ADD APPROPRIATE LINK HERE >
"""
super().__init_subclass__()
cls._update_call_docstring()
if not is_abstract:
for name in cls.get_aliases():
cls._models[name] = cls
@classmethod
def get_aliases(cls) -> Tuple[str]:
"""Get all the aliases by which this model can be identified."""
return (cls.__name__.lower(),) + cls._alias
def _extract_kwarg_values(self, **kwargs):
"""Return the (optionally updated) model's optional parameters.
Parameters
----------------
**kwargs
Optional parameter values appropriate for the model. These are received
directly from the subclass's ``__call__`` method.
Returns
-------
use_kwargs : dict values
Potentially updated parameter values for the parameters
passed in. This allows for a very simple
interface with the :mod:`~hera_sim.defaults`: module, which
will automatically update parameter default values if
active.
"""
# retrieve the default set of kwargs
use_kwargs = self.kwargs.copy()
# apply new defaults if the defaults class is active
if defaults._override_defaults:
kwargs = defaults.apply(use_kwargs, **kwargs)
# make sure that any kwargs passed make it through
use_kwargs.update(kwargs)
return use_kwargs.values()
def __init__(self, **kwargs):
self.kwargs = kwargs
@abstractmethod
def __call__(self, **kwargs):
"""Compute the component model."""
pass
def _check_kwargs(self, **kwargs):
if any(key not in self.kwargs for key in kwargs):
error_msg = "The following keywords are not supported: "
error_msg += ", ".join(key for key in kwargs if key not in self.kwargs)
raise ValueError(error_msg)
@classmethod
def _update_call_docstring(cls):
init_docstring = str(cls.__init__.__doc__)
call_docstring = str(cls.__call__.__doc__)
if any("Parameters" not in doc for doc in (init_docstring, call_docstring)):
return
init_params = cls._extract_param_section(init_docstring)
call_params = cls._extract_param_section(call_docstring)
full_params = call_params + init_params
cls.__call__.__doc__ = call_docstring.replace(call_params, full_params)
@staticmethod
def _extract_param_section(docstring):
# make a regular expression to capture section headings
pattern = re.compile("[A-Za-z]+\n.*-+\n")
# get the section headings
section_headings = pattern.findall(docstring)
if not section_headings[0].lower().startswith("param"):
# TODO: make this error message a bit better
# or just make it a warning instead
raise SyntaxError(
"Please ensure that the 'Parameters' section of "
"the docstring comes first."
)
# get everything after the first heading
param_section = docstring.partition(section_headings[0])[-1]
# just return this if there are no more sections
if len(section_headings) == 1:
return param_section
# return everything before the next section
return param_section.partition(section_headings[1])[0]
@classmethod
def get_models(cls, with_aliases=False) -> Dict[str, SimulationComponent]:
"""Get a dictionary of models associated with this component."""
if with_aliases:
return deepcopy(cls._models)
else:
return {
model.__name__.lower(): model for model in set(cls._models.values())
}
@classmethod
def get_model(cls, mdl: str) -> SimulationComponent:
"""Get a model with a particular name (including aliases)."""
return cls._models[mdl.lower()]
# class decorator for tracking subclasses
def component(cls):
"""Decorator to create a new :class:`SimulationComponent` that tracks its models."""
cls._models = {}
# This function creates a new class dynamically.
# The idea is to create a new class that is essentially the input cls, but has a
# new superclass -- the SimulationComponent. We pass the "is_abstract" keyword into
# the __init_subclass__ so that any class directly decorated with "@component" is
# seen to be an abstract class, not an actual model. Finally, the exec_body just
# adds all the stuff from cls into the new class.
cls = new_class(
name=cls.__name__,
bases=(SimulationComponent,),
kwds={"is_abstract": True},
exec_body=lambda namespace: namespace.update(dict(cls.__dict__)),
)
_available_components[cls.__name__] = cls
# Don't require users to write a class docstring (even if they should)
if cls.__doc__ is None:
cls.__doc__ = """"""
# Add some common text to the docstring.
cls.__doc__ += """
This is an *abstract* class, and should not be directly instantiated. It represents
a "component" -- a modular part of a simulation for which several models may be
defined. Models for this component may be defined by subclassing this abstract base
class and implementing (at least) the :meth:`__call__` method. Some of these are
implemented within hera_sim already, but custom models may be implemented outside
of hera_sim, and used on equal footing with the the internal models (as long as
they subclass this abstract component).
As with all components, all parameters that define the behaviour of the model are
accepted at class instantiation. The :meth:`__call__` method actually computes the
simulated effect of the component (typically, but not always, a set of visibilities
or gains), by *default* using these parameters. However, these parameters can be
over-ridden at call-time. Inputs such as the frequencies, times or baselines at
which to compute the effect are specific to the call, and do not get passed at
instantiation.
"""
return cls
def get_all_components(with_aliases=False) -> Dict[str, Dict[str, SimulationComponent]]:
"""Get a dictionary of component names mapping to a dictionary of models."""
return {
cmp_name.lower(): cmp.get_models(with_aliases)
for cmp_name, cmp in _available_components.items()
}
def get_models(cmp: str, with_aliases: bool = False) -> Dict[str, SimulationComponent]:
"""Get a dict of model names mapping to model classes for a particular component."""
return get_all_components(with_aliases)[cmp.lower()]
def get_all_models(with_aliases: bool = False) -> Dict[str, SimulationComponent]:
"""Get a dictionary of model names mapping to their classes for all possible models.
See Also
--------
:func:`get_models`
Return a similar dictionary but filtered to a single kind of component.
"""
all_cmps = get_all_components(with_aliases)
out = {}
for models in all_cmps.values():
# models here is a dictionary of all models of a particular component.
out.update(models)
return out
def get_model(mdl: str, cmp: Optional[str] = None) -> Type[SimulationComponent]:
"""Get a particular model, based on its name.
Parameters
----------
mdl
The name (or alias) of the model to get.
cmp
If desired, limit the search to a specific component name. This helps if there
are name clashes between models.
Returns
-------
cmp
The :class:`SimulationComponent` corresponding to the desired model.
"""
if cmp:
return get_models(cmp, with_aliases=True)[mdl.lower()]
else:
return get_all_models(with_aliases=True)[mdl.lower()]
def list_all_components(with_aliases: bool = True) -> str:
"""Lists all discoverable components.
Parameters
----------
with_aliases
If True, also include model aliases in the output.
Returns
-------
str
A string summary of the available models.
"""
cmps = get_all_components(with_aliases)
out = ""
for cmp, models in cmps.items():
out += f"{cmp}:\n"
model_to_name = defaultdict(lambda: [])
for name, model in models.items():
model_to_name[model].append(name)
for names in model_to_name.values():
out += " " + " | ".join(names) + "\n"
return out
| UTF-8 | Python | false | false | 11,289 | py | 72 | components.py | 45 | 0.64399 | 0.643458 | 0 | 297 | 37.010101 | 88 |
QColeman97/BrahmsRestoreML | 5,823,975,692,164 | 6883f7c180a36ee96de54902055790303d050167 | 9a0048ab1342a0a013202551ce93ec6d9cf69b37 | /spgm_demo.py | eb86c42f155dddd2c4308d1581870c83411e593a | []
| no_license | https://github.com/QColeman97/BrahmsRestoreML | 3280c0c54af1a36fa2b0a938d563401303cb0349 | 1504835dd981481a8f9a1c1f24ae4293e0ba225b | refs/heads/master | 2023-07-04T14:35:59.705274 | 2021-08-12T01:17:11 | 2021-08-12T01:17:11 | 302,243,939 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from audio_data_processing import EPSILON, PIANO_WDW_SIZE, make_spectrogram
from matplotlib.ticker import FuncFormatter
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
from librosa.display import specshow
import librosa
from scipy.io import wavfile
# # Fixing random state for reproducibility
# np.random.seed(19680801)
# dt = 0.0005
# t = np.arange(0.0, 20.0, dt)
# s1 = np.sin(2 * np.pi * 100 * t)
# s2 = 2 * np.sin(2 * np.pi * 400 * t)
# # create a transient "chirp"
# s2[t <= 10] = s2[12 <= t] = 0
# # add some noise into the mix
# nse = 0.01 * np.random.random(size=len(t))
# x = s1 + s2 + nse # the signal
# NFFT = 1024 # the length of the windowing segments
# Fs = int(1.0 / dt) # the sampling frequency
sr, sig = wavfile.read('brahms.wav')
sig = sig.astype('float64')
sig = np.mean(sig, axis=-1)
# fig, (ax1, ax2) = plt.subplots(nrows=2)
# # fig, ax1 = plt.subplots()
# ax1.plot(t, x)
# Pxx, freqs, bins, im = ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
# # Pxx, freqs, bins, im = ax1.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
# # print(Pxx)
# # print(freqs)
# # print(bins)
# # print(im)
# # The `specgram` method returns 4 objects. They are:
# # - Pxx: the periodogram
# # - freqs: the frequency vector
# # - bins: the centers of the time bins
# # - im: the .image.AxesImage instance representing the data in the plot
# # plt.show()
spgm, phses = make_spectrogram(sig, PIANO_WDW_SIZE, EPSILON, ova=True)
spgm = spgm.T
# # toy
# spgm = np.arange(0,12).reshape((3,4))
rows, cols = spgm.shape
def frequency_in_hz(x, pos):
# return '%.1f Hz' % x
return '%.2f Hz' % ((x * sr)/PIANO_WDW_SIZE)
# https://matplotlib.org/3.1.1/gallery/ticks_and_spines
formatter = FuncFormatter(frequency_in_hz)
# Graph the spectrogram from 2D array (maplotlib specgram doesn't do this)
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
ax.title.set_text('Spectrogram')
ax.set_ylabel('Frequency')
ax.set_xlabel('Time Segments')
# y_ticks = [((y * sr) / PIANO_WDW_SIZE) for y in range((PIANO_WDW_SIZE//2)+1)]
# ax.set_yticks(y_ticks)
img = ax.imshow(np.log(spgm),
aspect=3,
origin='lower',
extent=[-0.5, cols-0.5, -0.5, (rows//5)-0.5])
# img.set_extent([-0.5, cols-0.5, -0.5, (rows//2)-0.5])
# print(img.aspect)
# # plt.matshow(Pxx)
# # fig = plt.figure()
# # t_ax = fig.add_subplot(121)
# # t_ax.imshow(Pxx, interpolation='nearest', cmap=cm.Greys_r)
# # plt.pcolormesh(t, freqs, np.abs(Pxx))#, cmap=cm.Greys_r)
# plt.pcolormesh(np.abs(Pxx))#, cmap=cm.Greys_r)
# spgm, phses = make_spectrogram(sig, NFFT, EPSILON, ova=True)
# spgm = spgm.T
# spgm = librosa.amplitude_to_db(abs(spgm))
# print('Shape of My Spgm:', spgm.shape)
# print('My Spgm:', spgm[0])
# lib_stft = librosa.stft(sig, n_fft=NFFT, hop_length=NFFT//2)
# lib_spgm = librosa.amplitude_to_db(abs(lib_stft))
# print('Shape of Librosa Spgm:', lib_spgm.shape)
# print('Librosa Spgm:', lib_spgm[0])
# plt.figure(figsize=(15, 5))
# specshow(spgm, sr=sr, hop_length=NFFT//2, x_axis='time', y_axis='linear')
# plt.colorbar(format='%+2.0f dB')
# plt.show()
# plt.figure(figsize=(15, 5))
# specshow(lib_spgm, sr=sr, hop_length=NFFT//2, x_axis='time', y_axis='linear')
# plt.colorbar(format='%+2.0f dB')
plt.show() | UTF-8 | Python | false | false | 3,278 | py | 1,923 | spgm_demo.py | 48 | 0.651007 | 0.616229 | 0 | 103 | 30.834951 | 79 |
akashverma13/speedPI | 5,806,795,808,337 | 4ec89e78a76950667d2e4fa54b1e318aff90027b | d8a5c690d873a785bd8eb77007d5a1373179ad4e | /code/speedtest.py | d87471b44a0a0538bb8a49b001b74713bce81a47 | []
| no_license | https://github.com/akashverma13/speedPI | 4b072d691a85f072a9425ab636ee366e0fc28aaa | 156cf3cc70e339da34f6a5a04166739a1862ca52 | refs/heads/master | 2022-03-30T14:07:22.665556 | 2020-01-31T15:56:17 | 2020-01-31T15:56:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #pip install speedtest-cli
import speedtest
#Codice necessario per il display LCD
import time
from RPLCD import CharLCD
import socket
import fcntl
import struct
#Funzione che mi ritorna l'indirizzo Ip
def ipAddress(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915,
struct.pack('256s', ifname[:15])
)[20:24])
#Funzione che esegue il speedtest
def test():
s = speedtest.Speedtest()
s.get_servers()
s.get_best_server()
s.download()
s.upload()
res = s.results.dict()
return res["download"], res["upload"], res["ping"]
def main():
lcd = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])
#Scrivo ad un file CSV
with open('file.csv', 'w') as f:
f.write('download,upload,ping\n')
for i in range(3):
print('Making test #{}'.format(i+1))
d, u, p = test()
f.write('{},{},{}\n'.format(d, u, p))
#Formattazione del file CSV
with open('file.txt', 'w') as f:
for i in range(3):
print('Making test #{}'.format(i+1))
d, u, p = test()
f.write('Test #{}\n'.format(i+1))
f.write('Download: {:.2f} Kb/s\n'.format(d / 1024))
f.write('Upload: {:.2f} Kb/s\n'.format(u / 1024))
f.write('Ping: {}\n'.format(p))
lcd.write_string(u"Test della velocità in corso...")
time.sleep(1)
lcd.clear()
time.sleep(1)
#Stampo indirizzo ip sullo schermo
lcd = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])
lcd.write_string("IP address e velocità:")
#Sposto il cursore
lcd.cursor_pos = (1, 0)
lcd.write_string(ipAddress('eth0'))
#Stampo sulla console i risultati
for i in range(3):
d, u, p = test()
print('Test #{}\n'.format(i+1))
print('Download: {:.2f} Kb/s\n'.format(d / 1024))
print('Upload: {:.2f} Kb/s\n'.format(u / 1024))
print('Ping: {}\n'.format(p))
media_download = media_download + d / 1024
media_upload = media_upload + u / 1024
media_ping = media_ping + p
#Stampo download sullo schermo LCD
lcd.cursor_pos = (2, 0)
lcd.write_string('Download: {:.2f} Kb/s\n'.format(media_download / 3))
#Stampo upload sullo schermo LCD
lcd.cursor_pos = (3, 0)
lcd.write_string('Upload: {:.2f} Kb/s\n'.format(media_upload / 3))
#Stampo ping sullo schermo LCD
lcd.cursor_pos = (4, 0)
lcd.write_string('Ping: {}\n'.format(media_ping / 3))
if __name__ == '__main__':
main()
| UTF-8 | Python | false | false | 2,657 | py | 5 | speedtest.py | 2 | 0.568362 | 0.53258 | 0 | 84 | 30.607143 | 83 |
aatelitsina/Data_mining_course | 7,730,941,175,768 | bc77126ac9ed620c621a1364d3b014dc299b7e7f | 0c9a73060c5798d8339abb5f8cdd106f8d92e7cb | /homework_2.py | addc7d6a1cfee926ac6564f40cc32ccf06823211 | []
| no_license | https://github.com/aatelitsina/Data_mining_course | fd158585ef05ef41130235a2672a0ef699a8d75e | a202499136ceb57fe392a8bc691185c395610e6f | refs/heads/master | 2020-03-29T20:41:13.891286 | 2018-10-08T21:06:50 | 2018-10-08T21:06:50 | 150,325,070 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # 1. (3 балла)
# Напишите программу, в которой пользователь вводит числа по одному, пока не введет слово "done". Для полученного списка
# чисел найдите среднее арифметическое. Для ввода используйте встроенную функцию input().
# numbers = []
# user_str = ''
# avg_arch = 0
# min_val = None
# max_val = None
# while user_str != 'done':
# user_str = input('Введите число или для завершения - done:')
# numbers.append(user_str)
# for val in numbers[:-1]:
# avg_arch += int(val)
# # 2. (1 балл)
# # Напишите аналогичную программу, но для полученного списка найдите минимум и максимум.
# if not min_val or int(val) <= min_val:
# min_val=int(val)
# elif not max_val or int(val) >= max_val:
# max_val=int(val)
# #
# avg_arch = avg_arch/len(numbers[:-1])
# print(avg_arch)
# print('max:%d , min:%d'%(max_val,min_val))
#
# 3. (2 балла, 1+1)
# На вход подается два словаря d1 и d2 с карточками продуктов (см. пример ниже). Необходимо объединить оба словаря в один
# и удалить дубликаты значений (values в терминах метода dict()), если они есть, и вывести итоговый словарь.
# За объединение словаря 1 балл и еще 1 балл за корректное удаление дубликатов.
# При простом объединении словарей, если совпадают и ключи и значения, словарь сам убирает дубликаты.
# В этом плане он похож на set(). Но наш случай не настолько тривиальный, у нас основные ключи разные, а значения,
# то есть вложенные словари, могут быть одинаковыми. Вот как раз от одинаковых значений (вложенных словарей) надо избавиться.
# Какой в итоге ему ключ будет присвоен из дубликатов - не имеет значения.
#
# d1 = {'Item1': {'Name': 'Cake', 'Price': 20},
# 'Item2': {'Name': 'Pie', 'Price': 10},
# 'Item3': {'Name': 'Chocobar', 'Price': 5}}
#
# d2={'Item4': {'Name': 'Brownie', 'Price': 15},
# 'Item5': {'Name': 'Cake', 'Price': 20}}
# union_dict = {}
# summ = 0
# union_keys = list(d1.keys()) + list(d2.keys())
# union_values = list(d1.values()) + list(d2.values())
# for key in union_keys:
# for value in union_values:
# if value not in union_dict.values():
# union_dict[key]= value
# print(union_dict)
# 4. (1 балл)
# Для объединенного словаря из прошлого примера посчитайте итоговую сумму продуктов.
# for union_val in union_dict.values():
# summ+=union_val['Price']
# print ('Sum of d products is:',summ)
# 5. (2 балла)
# Дан один словарь с запасами продуктов на складе. Дан второй словарь со стоимостью этих товаров. Создайте словарь с балансом этих продуктов.
d1={'Item1': 120, 'Item2': 100, 'Item3': 500}
d2={'Item1': 5, 'Item2': 12, 'Item3': 7}
balance = {}
for cost_key, cost_val in d1.items():
for count_key, count_val in d2.items():
if cost_key == count_key:
balance[cost_key]=cost_val*count_val
print(balance)
| UTF-8 | Python | false | false | 3,833 | py | 3 | homework_2.py | 2 | 0.659415 | 0.636947 | 0 | 68 | 40.220588 | 141 |
Hank-learner/load_balancer_server | 9,457,517,998,686 | 903f8d0a7ce29960ae82bd4be2df76f14f4d75d4 | 4f56329552ea9a3d908007a7e192b99ac605fe5b | /autoreq.py | 85e285fda4580683f788ff838ce37a7dab4b1bd4 | []
| no_license | https://github.com/Hank-learner/load_balancer_server | 1dc63477d401b9e3e6c561f1dd19594f01f0c11b | a5a5159588b97c06bef392b892b53ce157c9a14c | refs/heads/master | 2020-08-14T05:42:52.950847 | 2019-10-14T17:48:15 | 2019-10-14T17:48:15 | 215,108,221 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import requests
import random
idval = random.randint(1,1000)
cpu = random.randint(1,30)
memory = random.randint(1,220)
reqtime = random.randint(0,1000)
tabledetails = {'ID':idval,'CPU_required':cpu,'Memory_required':memory ,'time_required_for_completion':reqtime}
request = requests.post("http://localhost:81/loadbalancer.php",tabledetails) | UTF-8 | Python | false | false | 345 | py | 6 | autoreq.py | 4 | 0.75942 | 0.704348 | 0 | 12 | 27.833333 | 111 |
FlorianPommerening/msc-python-implementation | 1,829,656,078,807 | 6a06635c47ea6b17d38ca0489af58c7e23b0b42f | 3bb61d4b9d2cadc5d67cc8125bf9861ad9ee411b | /implementation/src/search/lmcut.py | e0d73ade8195668d1a56ac98c95cfea463253a60 | []
| no_license | https://github.com/FlorianPommerening/msc-python-implementation | 5df2a4f390ba83db9bf1273147f936140462479c | 58d3fdfca44568443e561855a251f6229127605f | refs/heads/master | 2022-11-05T18:41:18.051051 | 2012-06-22T12:41:29 | 2012-06-22T12:41:29 | 274,693,234 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from collections import defaultdict
from .hmax import hmax
from .Debug import debug_message
def calculate_lmcut(task, debug_value_list=None):
'''
Convenience method to calculate heuristic value of initial state
'''
return LMcut().initial_state(task, debug_value_list).heuristic_value
class LMcut:
def __init__(self):
'''
The fields of this class are used to keep track of previous calls to incremental_lmcut
'''
self.task = None
self.landmarks = []
# TODO: mapping an operator to exactly one landmark is only possible with unit cost operators.
# think about another way to do this with arbitrary costs
self.operator_to_landmark = {}
self.operator_costs = {}
self.heuristic_value = 0
def initial_state(self, task, debug_value_list=None):
'''
calculates the heuristic value for the initial state and returns self for convenience
cannot use constructor as empty constructor is needed for clone
'''
self.task = task
self.operator_costs = {op:op.cost for op in task.operators}
self.heuristic_value = self._lmcut(self.task.initial_state, debug_value_list)
return self
def operator_applied(self, applied_operator, state):
'''
applied_operator contains operator that was just added to the plan (executed to reach state)
returns a heuristic value for state
op+ is not in any LM:
All LMs stay LMs.
op cost of all operators stays the same
op+ is in LM l+ which also contains op1, ..., opn:
l+ is no longer a LM.
By removing l+ the heuristic value decreases by l+.cost.
All other LMs stay LMs.
Operator costs of operators op1, ..., opn can be increases by l+.cost.
'''
self.operator_costs[applied_operator] = -1
if self.operator_to_landmark.has_key(applied_operator):
landmark = self.operator_to_landmark[applied_operator]
self.landmarks.remove(landmark)
# TODO maybe store instead of recalculate
landmark_cost = 0
for op in landmark:
if op.cost > landmark_cost:
landmark_cost = op.cost
self.heuristic_value -= landmark_cost
for op in landmark:
if op != applied_operator:
self.operator_costs[op] += landmark_cost
return self._lmcut(state)
def operator_forbidden(self, forbidden_operator, state):
'''
forbidden_operator contains the operator, which was just excluded from the plan (i.e. no plan will use this operator)
returns a heuristic value for state
op- is not in any LM:
All LMs stay LMs.
op cost of all operators stays the same
op- is the only operator in LM l-:
problem unsolvable: return infinity
op- is in LM l- which also contains op1, ..., opn:
remove op- from l-
All LMs (including l-\{op-}) stay LMs.
heuristic value can change if op- was maximum cost in l-
op cost of all operators stays the same
'''
self.operator_costs[forbidden_operator] = -1
if self.operator_to_landmark.has_key(forbidden_operator):
landmark = self.operator_to_landmark[forbidden_operator]
landmark.remove(forbidden_operator)
if len(landmark) == 0:
self.heuristic_value = float("infinity")
return self.heuristic_value
# TODO maybe store instead of recalculate
landmark_cost = 0
for op in landmark:
if op.cost > landmark_cost:
landmark_cost = op.cost
old_landmark_cost = max(landmark_cost, forbidden_operator.cost)
self.heuristic_value -= (old_landmark_cost - landmark_cost)
return self._lmcut(state)
def _lmcut(self, state, debug_value_list=None):
'''
Returns heuristic value of state by calculating LMcut with the current operator cost function.
The returned value includes the cost of all previously discovered landmarks stored in self.heuristic_value,
wich are assumed to stay valid. All landmarks that became invalid should be removed before calling this function
and self.heuristic_value has to be up to date
Newly discovered landmarks are appended to self.landmarks and registered in self.operator_to_landmark
'''
#TODO: for now this only works with operator costs in (0,1)
hmax_value, hmax_function, precondition_choice_function = hmax(self.task, state, self.operator_costs)
debug_message("hmax(state) = %s" % str(hmax_value), 0)
if hmax_value == float("infinity"):
return hmax_value
debug_values = None
additional_cost = 0
while hmax_value != 0:
if debug_value_list is not None:
debug_values = debug_value_list.newEntry()
cut = self._find_cut(state, precondition_choice_function, debug_values)
if debug_values is not None:
debug_values.hmax_function = hmax_function
debug_values.pcf = precondition_choice_function
debug_values.hmax_value = hmax_value
debug_values.cut = list(cut)
self.landmarks.append(cut)
for op in cut:
self.operator_to_landmark[op] = cut
landmark_cost = max([self.operator_costs[op] for op in cut])
additional_cost += landmark_cost
for op in cut:
self.operator_costs[op] -= landmark_cost
hmax_value, hmax_function, precondition_choice_function = hmax(self.task, state, self.operator_costs)
debug_message("hlmcut(state) = %d" % additional_cost, 0)
self.heuristic_value += additional_cost
return self.heuristic_value
def _find_cut(self, state, precondition_choice_function, debug_values=None):
effect_to_zero_cost_operators = defaultdict(list)
for op, cost in self.operator_costs.items():
if cost == 0:
for e in op.effect:
effect_to_zero_cost_operators[e].append(op)
goal_zone = set()
stack = list(self.task.goal)
while stack:
v = stack.pop()
assert v != "@@init"
if v in goal_zone:
continue
goal_zone.add(v)
for op in effect_to_zero_cost_operators[v]:
if self.operator_costs[op] == -1:
continue
# if pcf has no key for op, this means that the preconditions of op
# are not satisfiable with the available operators
if not precondition_choice_function.has_key(op):
continue
stack.append(precondition_choice_function[op])
if debug_values is not None:
debug_values.near_goal_area = list(goal_zone)
for op in self.task.operators:
op.unsatisfied_preconditions = len(op.precondition)
stack = list(state)
closed = []
cut = set()
while stack:
v = stack.pop()
if v in closed:
continue
closed.append(v)
for op in self.task.precondition_to_operators[v]:
if self.operator_costs[op] == -1:
continue
op.unsatisfied_preconditions -= 1
if op.unsatisfied_preconditions == 0:
for e in op.effect:
if e in goal_zone:
cut.add(op)
break
else:
stack.extend(op.effect)
return cut
def copy(self):
copy = LMcut()
copy.task = self.task
copy.landmarks = [list(landmark) for landmark in self.landmarks]
# TODO is there an faster way to get the new references?
copy.operator_to_landmark = {}
for landmark in copy.landmarks:
for op in landmark:
copy.operator_to_landmark[op] = landmark
copy.operator_costs = self.operator_costs.copy()
copy.heuristic_value = self.heuristic_value
return copy
| UTF-8 | Python | false | false | 8,673 | py | 53 | lmcut.py | 41 | 0.568661 | 0.566355 | 0 | 197 | 41.984772 | 125 |
miamor/pwcrack_web | 17,557,826,325,437 | 384324599f2b0619922ed9554aaf38605346b7e9 | d757f2ef493f0b33a6a4567da51c9220d30c5ee9 | /app/lib/api/definitions/node.py | eb8979e5333fb271a852d649d6ce78394b29ed54 | []
| no_license | https://github.com/miamor/pwcrack_web | 1c72bba9a93faa1e75e36a61f0da71b081d8d84f | a270bf23643945408f91476682c383d6df9801d8 | refs/heads/master | 2023-04-23T06:59:10.316997 | 2021-05-10T06:34:56 | 2021-05-10T06:34:56 | 333,353,095 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Node:
def __init__(self):
self.id = 0
self.name = ''
self.hostname = ''
self.port = 0
self.username = ''
self.password = ''
self.active = True
| UTF-8 | Python | false | false | 209 | py | 54 | node.py | 26 | 0.449761 | 0.440191 | 0 | 9 | 22.222222 | 26 |
BinaryScary/WPA-Looter | 14,851,996,944,946 | e3fb0e961d33b22f4f2e93c79faa6b0bfc31f716 | 8f2c2317858a8b93049809092a916cbf6efa5535 | /wpa-looter.py | e769163ce559a700d57b28e7aaf0ffde02ab7357 | []
| no_license | https://github.com/BinaryScary/WPA-Looter | bee5ca64134496204766223ebf559d66c37a6217 | 34a04feca7ec36c9eda740d244db5d424fcc8da1 | refs/heads/master | 2023-06-01T08:11:27.930197 | 2021-06-19T20:25:57 | 2021-06-19T20:25:57 | 377,934,537 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
import pyshark
import sys
from tqdm import tqdm
if __name__ == "__main__":
if len(sys.argv) <= 1:
print("Provide packet capture file")
quit()
# parse EAPOL handshakes
eapol = pyshark.FileCapture(sys.argv[1],display_filter="eapol")
messages = {2:set(),3:set(),4:set()}
pmks = set()
# only need packets 2,3 or 3,4 from the same handshake to crack PMK
for pkt in tqdm(eapol):
source = pkt['wlan'].sa
dest = pkt['wlan'].da
try:
messnum = pkt['eapol'].wlan_rsna_keydes_msgnr
except AttributeError:
continue
# probably a better way to id handshakes, then AP mac
if messnum == '2':
messages[2].add(dest)
if dest in messages[3]:
pmks.add(dest)
if messnum == '3':
messages[3].add(source)
if source in messages[2]:
pmks.add(source)
if source in messages[4]:
pmks.add(source)
if messnum == '4':
messages[4].add(dest)
if dest in messages[3]:
pmks.add(dest)
eapol.close()
# parse EAPOL handshake message 1 for pmkids
eapol_pmkid = pyshark.FileCapture(sys.argv[1],display_filter="eapol && wlan.rsn.ie.pmkid")
pmkids = set()
for pkt in tqdm(eapol_pmkid):
pmkids.add(pkt['wlan'].sa)
eapol_pmkid.close()
# check for no loot
if len(pmkids) == 0 and len(pmks) == 0:
print('[-] Packets do not contain loot')
quit()
# get ESSIDS from beacon packets
bssids = set()
bssids.update(pmkids)
bssids.update(pmks)
# is there a limit to display filter size?
dfilter = "wlan.fc.type_subtype==0x08 && ( wlan.sa==" + " || wlan.sa==".join(bssids) + ")"
beacons = pyshark.FileCapture(sys.argv[1],display_filter=dfilter)
essids = {}
for pkt in tqdm(beacons):
bssid = pkt['wlan'].sa
try:
ssid = pkt['wlan.mgt'].wlan_ssid
except AttributeError:
continue
if pkt['wlan.mgt'].wlan_ssid == 'SSID: ':
continue
essids[bssid] = ssid
if len(essids) == len(bssids):
break
beacons.close()
# print loot
if len(pmks) > 0:
print('[-] Access points with PMKs retrieved from EAPOL 4-Way Handshake')
for ap in set(pmks):
print(essids.get(ap,"(no beacons found for AP)"), end='')
print(f' {ap}')
print()
if len(pmkids) > 0:
print('[-] Access points with PMKID retreived from association packets (Handshake Message One)')
for ap in set(pmkids):
print(essids.get(ap,"(no beacons found for AP)"), end='')
print(f' {ap}')
| UTF-8 | Python | false | false | 2,777 | py | 2 | wpa-looter.py | 1 | 0.549874 | 0.538711 | 0 | 88 | 30.545455 | 104 |
santhosh-kumar/AlgorithmsAndDataStructures | 4,647,154,640,853 | 2566cdaf1070076a2d62a1588c613735a29d1c7d | d77e61d5a9eb08736d5c3621896a66ab970ccea6 | /python/problems/binary_tree/convert_sorted_array_to_bst.py | ae6535053dd7d6ea56df1b8efcf93f8d5331e5cb | []
| no_license | https://github.com/santhosh-kumar/AlgorithmsAndDataStructures | edc1a296746e2d2b0e1d4c748d050fe12af7b65f | 11f4d25cb211740514c119a60962d075a0817abd | refs/heads/master | 2022-11-15T00:22:53.930170 | 2020-07-10T03:31:30 | 2020-07-10T03:31:30 | 269,263,401 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | """
Convert Sorted Array to a Balanced Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height
balanced BST.
"""
from common.binary_tree import BinaryTreeNode
from common.problem import Problem
class ConvertSortedArrayToBST(Problem):
"""
Convert Sorted Array to a Balanced Binary Search Tree
"""
PROBLEM_NAME = "ConvertSortedArrayToBST"
def __init__(self, input_list):
"""Convert Sorted Array to a Balanced Binary Search Tree
Args:
input_list: Contains a sorted list of integers
Returns:
None
Raises:
None
"""
assert (len(input_list) > 0)
super().__init__(self.PROBLEM_NAME)
self.input_list = input_list
def solve(self):
"""Solve the problem
Note: O(n) (runtime) and O(log n) space works with the divide and conquer methodology.
Args:
Returns:
None
Raises:
None
"""
print("Solving {} problem ...".format(self.PROBLEM_NAME))
return self.sorted_array_to_bst(self.input_list, 0, len(self.input_list) - 1)
def sorted_array_to_bst(self, number_list, start, end):
"""Convert sorted array to Binary Search Tree
Args:
number_list: input list
start: start index
end: end index
Returns:
BinaryTreeNode
Raises:
None
"""
if start > end:
return None
middle = int((start + end) / 2)
node = BinaryTreeNode(number_list[middle])
node.left = self.sorted_array_to_bst(number_list, start, middle - 1)
node.right = self.sorted_array_to_bst(number_list, middle + 1, end)
return node
| UTF-8 | Python | false | false | 1,804 | py | 252 | convert_sorted_array_to_bst.py | 250 | 0.583703 | 0.580377 | 0 | 73 | 23.712329 | 94 |
L30M4GN4/OOP | 4,466,766,021,391 | ea8ad693091997b231a99caf031ef0843f799bec | 7aac602cb4f6f8dbd83805fae084ab4699f43829 | /classes/statistic.py | b11a203095ef64bae61a1112eb87e51359cde8ab | []
| no_license | https://github.com/L30M4GN4/OOP | fcce1dd29f2146ba029fb71505db4ce8933449ce | b6c51cc23ff027b3502187227f20f3f43f6fd765 | refs/heads/master | 2020-06-01T05:33:22.225495 | 2019-06-06T22:29:53 | 2019-06-06T22:29:53 | 190,657,127 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
from math import sqrt
class statistic():
stat_obj = 0
def __init__(self, obj):
self.stat_obj = obj
def expected_value(self, diapason):
self.tmp = self.stat_obj.exp_calculating(diapason)
return sum(self.tmp)/len(self.tmp)
def dispersion(self, diapason):
self.tmp = self.stat_obj.exp_calculating(diapason)
# return expected_value((tmp[i]-expected_value(diapason))**2)
return np.var(self.tmp)
def standard_deviation(self, diapason):
return sqrt(self.dispersion(diapason))
| UTF-8 | Python | false | false | 514 | py | 9 | statistic.py | 8 | 0.717899 | 0.714008 | 0 | 18 | 27.555556 | 62 |
wilyostrich/abitur_psuti | 1,778,116,478,340 | 9fe11baa5fa974cb064420577592f272577ae0f0 | 0e09441ff0440c498d00d66689d094173ca0cd75 | /views/course.py | e173f5ecf4d4182214a013cbeff5019daead0693 | []
| no_license | https://github.com/wilyostrich/abitur_psuti | 6e1ad75200541268028dacfd94b667a6f6df40ca | ac85f2b979d70d3e6f50bd45f02697abc115bbfb | refs/heads/master | 2020-05-26T12:52:11.218689 | 2017-06-12T19:32:20 | 2017-06-12T19:32:20 | 82,478,026 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | from telebot import types
from views import general
from di_configuration import DIConfige, DIBot
def course(message):
bot = DIBot.di_bot()
keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
keyboard.row('Инженерный лицей', 'Школа программистов')
keyboard.row('Подготовка к ЕГЭ и внутренним экзаменам')
keyboard.row('Меню')
msg = bot.send_message(message.chat.id, 'Выберите интересующий вас курс!', reply_markup=keyboard)
bot.register_next_step_handler(msg,course_info)
def course_info(message):
config = DIConfige.config_ini()
bot = DIBot.di_bot()
if message.text == 'Подготовка к ЕГЭ и внутренним экзаменам':
bot.send_message(message.chat.id, text=config["COURSE"]["ege"], parse_mode='HTML')
msg_exam = bot.send_message(message.chat.id, 'Получить более подробную информаци, а также записаться на курсы,'
' можно перейдя по ссылке: http://abitur.psuti.ru/'
'center/podgotovitelnye-kursy-k-ege-i-vnutrennim-ekzamenam/',
disable_web_page_preview=True)
bot.register_next_step_handler(msg_exam, course_info)
elif message.text == 'Школа программистов':
bot.send_message(message.chat.id, '<b>Школа программистов</b>\n'
'Обучение платное для учащихся 8-х, 9-х, 10-х и 11-х классов, проводится '
'в 3 этапа:\n'
'1. Информатика;\n'
'2. Программирование;\n'
'3. Информационные системы и технологии.\n'
'Срок обучения в школе – 5 месяцев.\n'
'Окончившим Школу программистов выдается «Свидетельство об окончании», '
'которое дает право преимущественного зачисления в ПГУТИ.\n'
'Справки по телефону: (846) 228-00-51, (846) 228-00-58.', parse_mode='HTML')
msg_school = bot.send_message(message.chat.id, 'Получить более подробную информаци, а также записаться в школу '
'программистов, можно перейдя по ссылке: '
'http://abitur.psuti.ru/center/shkola-programmistov/',
disable_web_page_preview=True, parse_mode='HTML')
bot.register_next_step_handler(msg_school, course_info)
elif message.text == 'Инженерный лицей':
bot.send_message(message.chat.id, text=config["COURSE"]["engineer"], parse_mode='HTML')
msg_engineer = bot.send_message(message.chat.id, 'Получить более подробную информаци, а также '
'записаться на занятия, можно перейдя по ссылке: '
'http://abitur.psuti.ru/center/inzhenernyy-litsey/',
disable_web_page_preview=True, parse_mode='HTML')
bot.register_next_step_handler(msg_engineer, course_info)
elif message.text == 'Меню':
general.help_message(message)
else:
try:
if message.text == 'Меню':
general.help_message(message)
except:
print('ERROR')
handlers = {'course': course} | UTF-8 | Python | false | false | 4,222 | py | 19 | course.py | 17 | 0.541537 | 0.532747 | 0 | 57 | 60.894737 | 120 |
bossjones/openheating | 17,051,020,175,887 | 60fa6147a01f3760aeffc9f75ee8ffc05e785a82 | ed3f903a7bd944d38bb0110f266b2b89e1ff1fdc | /openheating/dbus/tests/easy_suite.py | 31441d46c6deae3ed67dc7872d3937ea4aa7e9fc | []
| no_license | https://github.com/bossjones/openheating | 68e9c38f29c8b0762f5e14afd20798638dd9a9c8 | 99d3705b949a7fd2cb3908014be94a73e8eca7aa | refs/heads/master | 2020-12-01T01:14:54.120483 | 2015-01-26T19:35:04 | 2015-01-26T19:35:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from openheating.dbus.tests.basic_tests import suite as basic_suite
from openheating.dbus.tests.client_tests import suite as client_suite
from openheating.dbus.tests.object_tests import suite as object_suite
from openheating.dbus.tests.service_tests import suite as service_suite
import unittest
suite = unittest.TestSuite()
suite.addTest(basic_suite)
suite.addTest(client_suite)
suite.addTest(object_suite)
suite.addTest(service_suite)
| UTF-8 | Python | false | false | 439 | py | 63 | easy_suite.py | 62 | 0.829157 | 0.829157 | 0 | 12 | 35.583333 | 71 |
wangdi2014/tb-amr-benchmarking | 1,245,540,544,123 | c7d6d00e25ace2e11f71af5d58d8aaa2f9a34743 | c5a004f26bf249f888be3849114dd35dbd24cb24 | /python/evalrescallers/ten_k_reads_download.py | 46818b149d4435dbc1cac01543f5c94aeda976dc | [
"MIT"
]
| permissive | https://github.com/wangdi2014/tb-amr-benchmarking | f7cf331608cfe7b9cc8995906d991573323dc87a | 276f4f7f30639dacc62b3e8e395b2d2ce8675089 | refs/heads/master | 2022-03-10T00:41:07.364006 | 2019-11-08T09:37:23 | 2019-11-08T09:37:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import csv
import multiprocessing
import os
import subprocess
import evalrescallers
def make_dir(d):
if not os.path.exists(d):
os.mkdir(d)
def download_one_run(run_id, outdir):
success_file = f'{outdir}.success'
fail_file = f'{outdir}.fail'
if os.path.exists(success_file):
return True
elif os.path.exists(fail_file):
return False
command = f'enaDataGet -f fastq -d {outdir} {run_id}'
print(command)
completed_process = subprocess.run(command, shell=True, stdout=subprocess.PIPE)
if completed_process.returncode == 0:
with open(success_file, 'w') as f:
return True
else:
with open(fail_file, 'w') as f:
return False
def cat_reads_and_clean(to_cat, outfile):
if len(to_cat) == 1:
os.rename(to_cat[0], outfile)
return True
else:
cat = 'cat ' + ' '.join(to_cat) + ' > ' + outfile
print(cat)
completed_process = subprocess.run(cat, shell=True, stdout=subprocess.PIPE)
if completed_process.returncode == 0:
for f in to_cat:
os.unlink(f)
return True
else:
return False
def download_sample(outdir, sample_id, run_ids):
success_file = os.path.join(outdir, 'success')
fail_file = os.path.join(outdir, 'fail')
if os.path.exists(success_file):
return True
elif os.path.exists(fail_file):
return False
elif os.path.exists(outdir):
completed_process = subprocess.run(f'rm -rf {outdir}', shell=True)
make_dir(outdir)
success_statuses = {}
fwd_reads = []
rev_reads = []
for run_id in sorted(run_ids):
run_out = os.path.join(outdir, run_id)
success_statuses[run_id] = download_one_run(run_id, run_out)
if not success_statuses[run_id]:
with open(fail_file, 'w') as f:
return False
fwd = os.path.join(outdir, run_id, run_id, f'{run_id}_1.fastq.gz')
fwd_reads.append(fwd)
rev = os.path.join(outdir, run_id, run_id, f'{run_id}_2.fastq.gz')
rev_reads.append(rev)
if not (os.path.exists(fwd) and os.path.exists(rev)):
with open(fail_file, 'w') as f:
return False
fwd_reads.sort()
rev_reads.sort()
fwd = os.path.join(outdir, 'reads_1.fastq.gz')
rev = os.path.join(outdir, 'reads_2.fastq.gz')
fwd_cat_ok = cat_reads_and_clean(fwd_reads, fwd)
if fwd_cat_ok:
rev_cat_ok = cat_reads_and_clean(rev_reads, rev)
if rev_cat_ok:
for f in os.listdir(outdir):
f_path = os.path.join(outdir, f)
if os.path.isdir(f_path) or f.endswith('.success'):
command = f'rm -rf {f_path}'
completed_process = subprocess.run(command, shell=True, stdout=subprocess.PIPE)
if completed_process.returncode != 0:
with open(fail_file, 'w') as f:
return False
with open(success_file, 'w') as f:
return True
with open(fail_file, 'w') as f:
return False
def load_accessions():
eval_dir = os.path.abspath(os.path.dirname(evalrescallers.__file__))
data_dir = os.path.join(eval_dir, 'data')
pheno_file = os.path.join(data_dir, '10k_validation.phenotype.tsv')
accessions = []
with open(pheno_file) as f:
dict_reader = csv.DictReader(f, delimiter='\t')
accessions = [x['ena_id'] for x in dict_reader]
accessions.sort()
return accessions
def get_sample(sample):
runs = sorted(sample.split('.'))
print('Getting', sample, ','.join(runs))
samples_dir = sample[:6]
make_dir(samples_dir)
sample_dir = os.path.join(samples_dir, sample)
if download_sample(sample_dir, sample, runs):
print('Success', sample, ','.join(runs))
else:
print('Fail', sample, ','.join(runs))
def get_samples(output_dir, threads=1):
samples = load_accessions()
print(f'Going to download {len(samples)} samples using {threads} thread(s)...')
make_dir(output_dir)
os.chdir(output_dir)
with multiprocessing.Pool(threads) as pool:
pool.map(get_sample, samples)
| UTF-8 | Python | false | false | 4,244 | py | 70 | ten_k_reads_download.py | 27 | 0.585533 | 0.582469 | 0 | 137 | 29.963504 | 99 |
huafengw/facenet | 15,324,443,329,061 | b61046b99d10a12b90498205cd08150b5225741f | f29832f7373a38bfcb41b81f961253343b90d497 | /src/vip_train_tripletloss_spark.py | 69632d36bd295aedb1f9712d9b687370483e92b1 | [
"MIT"
]
| permissive | https://github.com/huafengw/facenet | e01e0e43e32af5ed8c7a13fb82527f0ee169b831 | fee32eb9c15918dc0ffcbdf7205b501ba94479e6 | refs/heads/master | 2021-05-08T21:08:28.367600 | 2018-03-19T05:30:25 | 2018-03-19T05:30:25 | 119,630,087 | 0 | 0 | null | true | 2018-01-31T03:33:55 | 2018-01-31T03:33:55 | 2018-01-31T02:12:33 | 2017-12-28T22:26:34 | 2,931 | 0 | 0 | 0 | null | false | null | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from pyspark.context import SparkContext
from pyspark.conf import SparkConf
from tensorflowonspark import TFCluster, TFNode
from datetime import datetime
import os
def main_fun(argv, ctx):
from src import facenet_distributed_train
from src import vipus_distributed_train
import sys
job_name = ctx.job_name
assert job_name in ['ps', 'worker'], 'job_name must be ps or worker'
print("argv:", argv)
sys.argv = argv
cluster, server = TFNode.start_cluster_server(ctx, num_gpus=1)
if job_name == 'ps':
server.join()
else:
if argv.model == 'FACENET':
facenet_distributed_train.train(server, ctx.cluster_spec, argv, ctx)
elif argv.model == 'VIPUS':
vipus_distributed_train.train(server, ctx.cluster_spec, argv, ctx)
if __name__ == '__main__':
# parse arguments needed by the Spark driver
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--model", type=str, choices=['FACENET', 'VIPUS'],
help='The model to use', default='FACENET')
parser.add_argument("--epochs", help="number of epochs", type=int, default=200)
parser.add_argument("--transfer_learning", help="Start training from pretrained inception model", action="store_true")
parser.add_argument("--sync_replicas", help="Use SyncReplicasOptimizer", action="store_true")
parser.add_argument("--local_data_path", type=str, help="The local fs path of input dataset")
parser.add_argument('--num_executor', default=3, type=int, help='The spark executor num')
parser.add_argument("--tensorboard", help="launch tensorboard process", action="store_true")
parser.add_argument("--pretrained_ckpt", help="The pretrained inception model", default='hdfs://bipcluster/user/vincent.wang/facenet/inception_resnet_v2_2016_08_30.ckpt')
parser.add_argument("--spark_executor_cores", default=4, type=int, help='The spark executor cores')
parser.add_argument('--workspace', type=str,
help='Directory where to write event logs and checkpoints on hdfs.', default='hdfs://bipcluster/user/vincent.wang/facenet')
parser.add_argument('--checkpoint_dir', type=str, help='Directory where to write checkpoints on hdfs.')
parser.add_argument('--weight_decay', type=float,
help='L2 weight regularization.', default=0.000002)
parser.add_argument('--batch_size', type=int,
help='Number of images to process in a batch.', default=90)
parser.add_argument('--image_size', type=int,
help='Image size (height, width) in pixels.', default=299)
parser.add_argument('--classes_per_batch', type=int,
help='Number of classes per batch.', default=150)
parser.add_argument('--images_per_class', type=int,
help='Number of images per class.', default=3)
parser.add_argument('--epoch_size', type=int,
help='Number of batches per epoch.', default=100)
parser.add_argument('--alpha', type=float,
help='Positive to negative triplet distance margin.', default=0.2)
parser.add_argument('--embedding_size', type=int,
help='Dimensionality of the embedding.', default=128)
parser.add_argument('--optimizer', type=str, choices=['ADAGRAD', 'ADADELTA', 'ADAM', 'RMSPROP', 'MOM'],
help='The optimization algorithm to use', default='ADAM')
parser.add_argument('--learning_rate', type=float,
help='Initial learning rate. If set to a negative value a learning rate ' +
'schedule can be specified in the file "learning_rate_schedule.txt"', default=0.0002)
parser.add_argument('--learning_rate_decay_epochs', type=int,
help='Number of epochs between learning rate decay.', default=100)
parser.add_argument('--learning_rate_decay_factor', type=float,
help='Learning rate decay factor.', default=1.0)
parser.add_argument('--moving_average_decay', type=float,
help='Exponential decay for tracking of training parameters.', default=0.9999)
parser.add_argument('--random_flip',
help='Performs random horizontal flipping of training images.', action='store_true')
parser.add_argument('--lfw_nrof_folds', type=int,
help='Number of folds to use for cross validation. Mainly used for testing.', default=10)
classpath=os.popen(os.environ["HADOOP_HOME"] + "/bin/hadoop classpath --glob").read()
args = parser.parse_args()
spark_executor_instances = args.num_executor
spark_cores_max = spark_executor_instances * args.spark_executor_cores
conf = SparkConf() \
.setAppName("triplet_distributed_train") \
.set("spark.eventLog.enabled", "false") \
.set("spark.dynamicAllocation.enabled", "false") \
.set("spark.shuffle.service.enabled", "false") \
.set("spark.executor.cores", str(args.spark_executor_cores)) \
.set("spark.cores.max", str(spark_cores_max)) \
.set("spark.task.cpus", str(args.spark_executor_cores)) \
.set("spark.executor.instances", str(args.num_executor)) \
.setExecutorEnv("JAVA_HOME", os.environ["JAVA_HOME"]) \
.setExecutorEnv("HADOOP_HDFS_HOME", os.environ["HADOOP_HOME"]) \
.setExecutorEnv("LD_LIBRARY_PATH", os.environ["JAVA_HOME"] + "/jre/lib/amd64/server:" + os.environ["HADOOP_HOME"] + "/lib/native:" + "/usr/local/cuda-8.0/lib64" ) \
.setExecutorEnv("CLASSPATH", classpath) \
.set("hostbalance_shuffle","true")
print("{0} ===== Start".format(datetime.now().isoformat()))
sc = SparkContext(conf = conf)
# sc.setLogLevel("DEBUG")
num_executors = int(args.num_executor)
num_ps = 1
cluster = TFCluster.run(sc, main_fun, args, num_executors, num_ps, args.tensorboard, TFCluster.InputMode.TENSORFLOW)
cluster.shutdown()
print("{0} ===== Stop".format(datetime.now().isoformat()))
import traceback
try:
sc.stop()
except BaseException as e:
traceback.print_exc()
| UTF-8 | Python | false | false | 5,836 | py | 6 | vip_train_tripletloss_spark.py | 6 | 0.696196 | 0.684887 | 0 | 117 | 48.871795 | 172 |
aithlab/ppo | 4,844,723,155,327 | dacc2991b464566db1e74ca1bd99b111f31f13ce | f35c7fda0bac151889ff8f412f2932e5ceb33eef | /buffer.py | d4a539b0152b9ddb11105cd85d6cc82c51bb755d | []
| no_license | https://github.com/aithlab/ppo | 0ef1931c535afa7e0d95d5a68c1b1b0fc32b9d79 | 434ec88b37c85c0e9a1ac6170e02d3eded87bc34 | refs/heads/master | 2020-07-23T14:26:26.616219 | 2019-09-15T16:52:47 | 2019-09-15T16:52:47 | 207,591,562 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 14 18:25:52 2019
@author: taehwan
"""
import torch
class Buffer():
def __init__(self, K):
self.K = K
self.reset()
def update(self, s, a, next_s, r, log_prob, entropy):
for key, value in zip(self.data.keys(), (s,a,next_s,r,log_prob,entropy)):
self.data[key].append(value)
self.current_length += 1
if self.current_length > self.K:
for key in self.data.keys():
self.data[key].pop(0)
def get_data(self, batch_size):
n_data = len(self.data['s'])
idxs = torch.randperm(n_data)
self.buffer2torch(self.data)
for start_pt in range(0,n_data,batch_size):
state = self.data['s'][idxs][start_pt:start_pt+batch_size]
action = self.data['a'][idxs][start_pt:start_pt+batch_size]
next_s = self.data['next_s'][idxs][start_pt:start_pt+batch_size]
reward = self.data['r'][idxs][start_pt:start_pt+batch_size]
log_prob = self.data['log_prob'][idxs][start_pt:start_pt+batch_size]
entropy = self.data['entropy'][idxs][start_pt:start_pt+batch_size]
advantage = self.data['advantage'][idxs][start_pt:start_pt+batch_size]
yield state, action, next_s, reward, log_prob, entropy, advantage
def buffer2torch(self, buffer):
for key in buffer.keys():
if type(buffer[key]) is not torch.Tensor:
buffer[key] = torch.stack(buffer[key], dim=0)
def reset(self,):
self.data = {'s':[], 'a':[], 'next_s':[], 'r': [],
'log_prob':[], 'entropy':[]}
self.current_length = 0
| UTF-8 | Python | false | false | 1,599 | py | 6 | buffer.py | 5 | 0.596623 | 0.58349 | 0 | 48 | 32.229167 | 77 |
alexandraback/datacollection | 19,284,403,195,823 | 59622f3abb50419a6c38c11cf7451ea83c11522c | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5639104758808576_0/Python/chengineer/A.py | 7484d4bfeeb753f61b0a3cf9d89e76c9086f56e0 | []
| no_license | https://github.com/alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | import sys
input = str(sys.argv[1]).strip()
output = open(sys.argv[2], 'w')
def calc(S_max, audience):
friends = 0
clapping = 0
for i in range(S_max + 1):
S_i = int(audience[i])
if clapping >= i:
clapping += S_i
else:
add = i - clapping
friends += add
clapping += add + S_i
return friends
with open(input) as f:
content = f.readlines()
T = int(content[0].strip())
for case in range(1, T+1):
line = content[case].strip().split()
S_max = int(line[0])
audience = line[1]
result = calc(S_max, audience)
output.write('Case #' + str(case) + ': ' + str(result) + '\n')
| UTF-8 | Python | false | false | 595 | py | 122,470 | A.py | 117,790 | 0.603361 | 0.586555 | 0 | 29 | 19.517241 | 63 |
HailMyHeart/httpProxy | 13,718,125,570,556 | bd67f708dc40d5a238f3188629e5359b8868061a | 695c43f02dfaf36050dc1ae87dc234da296be74d | /HTTP_Proxy/src/main/__init__.py | 91c5aed93cabd6cbc87e85aba0e3b40bcc7ddc87 | []
| no_license | https://github.com/HailMyHeart/httpProxy | 1b4797c9117f58d78a8455c4eee2531a152e833f | 57e1c4211302ef44a82726ffb7d4f28aa0d5715c | refs/heads/master | 2021-01-09T20:01:14.575523 | 2016-06-08T11:36:22 | 2016-06-08T11:36:22 | 60,693,135 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os,sys,thread,socket
import url
import pickle
import hashlib
CLIENT_NUM = 50 #max client can be connected
MAX_DATA_RECV = 4096 #message max size
redirectFile = open('redirectFile.pkl', 'rb') #phishing words mapping file
forbiddenFile = open('forbiddenFile.pkl', 'rb') #forbidden words mapping file
redirectDict = pickle.load(redirectFile)
forbiddenDict = pickle.load(forbiddenFile)
def ProxyClient(connectionSocket, addr):
#message header parse to find the host and port
request = connectionSocket.recv(MAX_DATA_RECV)
head_line = request.split(r'\n')[0]
url = head_line.split(' ')[1]
print head_line
print
print "URL", url
print
########################
# newMD5 = hashlib.md5()
# newMD5.update(url)
# cacheFilename = newMD5.hexdigest()+'.cached'
#########################
httpPos = url.find("://")
if (httpPos == -1):
t = url
else:
t = url[(httpPos+3):]
portPos = t.find(":")
webServerPos = t.find("/")
if webServerPos == -1:
webServerPos = len(t)
webServer = ""
port = -1
if (portPos == -1 or webServerPos<portPos):
port = 80
webServer = t[:webServerPos]
else:
port = int(t[(portPos+1):][:webServerPos-portPos-1])
webServer = t[:portPos]
###########################
# notModified = False
# dataToUpdate = ""
# if os.path.exists(cacheFilename):
# print 'Cache hit'
# cacheFile = open(cacheFilename, 'rb')
# cacheData = cacheFile.readlines()
# for eLine in cacheData:
# if "Date:" in eLine:
# try:
# modifiedRequest = head_line+'''\nHost: '''+webServer+'''\r\nIf-Modified-Since:'''+eLine.partition("Date:")[2]+'''\r\n\r\n'''
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((webServer, port))
# s.send(modifiedRequest)
# while 1:
# data = s.recv(MAX_DATA_RECV)
#
# if len(data)>0:
# ######lock here
# if "304 Not Modified" in data:
# notModified = True
#
# break;
# else:
# dataToUpdate = dataToUpdate+data
# connectionSocket.send(data)
#
# else:
# break
# s.close()
# except socket.error, (message):
# if s:
# s.close()
# print "Runtime Error:", message
# sys.exit(1)
# break
# cacheFile.close()
# if notModified:
# for eLine in cacheData:
# connectionSocket.send(eLine)
# else:
# cacheFile = open(cacheFilename, 'wb')
# cacheFile.writelines(dataToUpdate)
# else:
###################################
#matching the host to the phishing list and forbidden dictionary
findFlag = False
findFlag2 = False
#matching to the phishing dictionary
for redirectItem in redirectDict.keys():
if redirectItem in webServer: #got it!
port = 80 #redirect to phishing port and host
request = request.replace(webServer, redirectDict[redirectItem])
webServer = redirectDict[redirectItem]
findFlag = True
break;
print "Connect to:", webServer, port
#matching to the forbidden dictionary
if not findFlag:
for forbiddenItem in forbiddenDict:
if forbiddenItem in webServer: #got it and sent 403 message to client
connectionSocket.send('''HTTP/1.1 403 Forbidden\r\nContent-Type: text/html; charset=UTF-8\r\nDate: Wed, 08 Jan 2014 03:39:14 GMT\r\nServer: GFE/2.0\r\nAlternate-Protocol: 80:quic\r\n\r\n<html><head><title>Sorry...</title></head><body>you are forbidden by this request.</body></html>''')
findFlag2 = True
break;
#Proxy Client
if findFlag or (not findFlag and not findFlag2):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((webServer, port)) #connect to the server
s.send(request)
while 1: #receive message
data = s.recv(MAX_DATA_RECV)
print type(data)
if len(data)>0:
connectionSocket.send(data)
else:
break
s.close()
connectionSocket.close()
except socket.error, (message):
if s:
s.close()
if connectionSocket:
connectionSocket.close()
print "Runtime Error:", message
sys.exit(1)
def Server():
port = int(raw_input("Enter port:"))
host = '127.0.0.1'
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port)) #bind the port to the socket
s.listen(CLIENT_NUM) #listen the "knocking"
except socket.error, (message):
if s:
s.close()
print "Socket create failed:", message
sys.exit(1)
while 1: #listening...
connectionSocket, addr = s.accept() #dispatch a thread to the connection
print "s.accept()"
thread.start_new_thread(ProxyClient, (connectionSocket, addr))
s.close()
Server()
| UTF-8 | Python | false | false | 5,780 | py | 3 | __init__.py | 3 | 0.503979 | 0.492042 | 0 | 152 | 37.019737 | 302 |
Huib0513/AoC2018 | 8,976,481,675,140 | e28e2c8dfeef34d874f634b1de64c5d5006bde6e | f3be7da4d0f520e60e173c26d0d2069d997e2f85 | /dag8a.py | 8b1dff0de4e9a0cfe58b24a088c91dd7b95a917b | []
| no_license | https://github.com/Huib0513/AoC2018 | 0c29d0a883fe3ae7e83e36bc4a32cd53c5a42f1f | 679dfd69a3458243d09e981e27fbb1e6739ac46d | refs/heads/master | 2020-04-30T08:03:34.241939 | 2019-03-20T09:58:27 | 2019-03-20T09:58:27 | 176,703,992 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!python3
#tree = open('testinput.dag8').read().split(' ')
tree = open('input.dag8').read().split(' ')
print(tree, len(tree))
# Yuck, globale variabele...
index = 0
def verwerkNode():
global index
resultaat = 0
# Lees header
aantalkids = int(tree[index])
aantalmetas = int(tree[index + 1])
index += 2
kindwaarde = []
print("Header gelezen: " + str(aantalkids) + " kinderen en " + str(aantalmetas) + " meta-informatie.")
# Verwerk kinderen
for kind in range(aantalkids):
print("Child number " + str(kind + 1))
kindwaarde.append(verwerkNode())
if aantalkids == 0:
# Verwerk metadata
for meta in range(aantalmetas):
resultaat += int(tree[index])
index += 1
else:
for meta in range(aantalmetas):
ref = int(tree[index])
if ref <= aantalkids:
resultaat += kindwaarde[(ref-1)]
index += 1
print("Waarde node: " + str(resultaat) + ", kindwaarde: " + str(kindwaarde))
return resultaat
# Main loop
totaalmeta = 0 + verwerkNode()
print("Het winnende nummer is: " + str(totaalmeta))
| UTF-8 | Python | false | false | 1,151 | py | 23 | dag8a.py | 23 | 0.582971 | 0.571677 | 0 | 44 | 25.159091 | 106 |
chivay/contests | 16,003,048,157,117 | 0e730af8de5a882b42943f75b145d0865cd60205 | 65722d9858f1f20a1b3e9c9a9f8f8ace428811ce | /Project Euler/problem12.py | 6668afaca5321c0346c2f821d5d9991e3e242f0f | []
| no_license | https://github.com/chivay/contests | 91699f4e827e4b3a5aa8838de893ae4c16c1069d | 9171ccc2dae6c0a2666ed8b35ba92111f65f116d | refs/heads/master | 2016-09-22T21:38:31.455816 | 2014-04-22T11:54:57 | 2014-04-22T11:54:57 | 60,353,674 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | def CountDivisors(n):
counter = 2
i = 2
while (i**2 <= n):
if (n%i == 0):
counter +=2
i +=1
return counter
add = 0
num = 0
add += 1
num += add
while CountDivisors(num) <= 500:
add += 1
num += add
print num | UTF-8 | Python | false | false | 222 | py | 55 | problem12.py | 55 | 0.554054 | 0.495495 | 0 | 20 | 10.15 | 32 |
nadhirhasan/nfl_impact_detection | 8,057,358,654,810 | 9667ec164c539b54aa40a56efaf74881a5e0ad8d | 86b2d54cc7ac9428166e15a1473539e12ce87e6c | /src/inference/classifier_aux.py | dea64a4859f4612e3e6f6a46e04d07145d8ca97f | []
| no_license | https://github.com/nadhirhasan/nfl_impact_detection | da655231887023ea334595c1380dec6a8b30f3b2 | db375c28138d3db5306d5cbc7e50d9e24d51b102 | refs/heads/main | 2023-03-22T10:39:29.556737 | 2021-01-06T19:33:56 | 2021-01-06T19:33:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import torch
import torchvision
import numpy as np
import torch.nn as nn
import resnest.torch as resnest_torch
from params import NUM_WORKERS
from model_zoo.models_cls import RESNETS, forward_with_aux_efficientnet, forward_with_aux_resnet
from utils.torch import load_model_weights
from data.transforms import get_transfos_cls
from efficientnet_pytorch import EfficientNet
from torch.utils.data import DataLoader
from inference.classifier import NFLDatasetClsInference
def get_model_cls_aux(
name,
num_classes=1,
num_classes_aux=0,
):
"""
Loads a pretrained model.
Supports Resnet based models.
Args:
name (str): Model name
num_classes (int, optional): Number of classes. Defaults to 1.
Raises:
NotImplementedError: Specified model name is not supported.
Returns:
torch model -- Pretrained model.
"""
# Load pretrained model
if "resnest" in name:
model = getattr(resnest_torch, name)(pretrained=False)
elif name in RESNETS:
model = getattr(torchvision.models, name)(pretrained=False)
elif "efficientnet" in name:
model = EfficientNet.from_name(name)
else:
raise NotImplementedError
model.name = name
model.num_classes = num_classes
model.num_classes_aux = num_classes_aux
if "efficientnet" not in name:
model.conv1.stride = (1, 1)
model.nb_ft = model.fc.in_features
model.fc = nn.Linear(model.nb_ft, num_classes)
model.forward = lambda x: forward_with_aux_resnet(model, x)
if num_classes_aux:
model.fc_aux = nn.Linear(model.nb_ft, num_classes_aux)
else:
model._conv_stem.stride = (1, 1)
model.nb_ft = model._fc.in_features
model._fc = nn.Linear(model.nb_ft, num_classes)
model.forward = lambda x: forward_with_aux_efficientnet(model, x)
if num_classes_aux:
model._fc_aux = nn.Linear(model.nb_ft, num_classes_aux)
return model
def retrieve_model_aux(config, fold=0, log_folder=""):
model = get_model_cls_aux(
config["name"],
num_classes=config["num_classes"],
num_classes_aux=config["num_classes_aux"],
).eval()
model.zero_grad()
model = load_model_weights(model, log_folder + f"{config['name']}_{fold}.pt")
return model
def inference_aux(df, models, batch_size=256, device="cuda", root=""):
models = [model.to(device).eval() for model in models]
dataset = dataset = NFLDatasetClsInference(
df.copy(),
transforms=get_transfos_cls(train=False),
root=root,
)
loader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=False,
num_workers=NUM_WORKERS,
pin_memory=True,
)
preds = []
preds_aux = []
with torch.no_grad():
for img in loader:
img = img.to(device)
preds_img = []
preds_aux_img = []
for model in models:
y_pred, y_pred_aux = model(img)
preds_img.append(y_pred.sigmoid().detach().cpu().numpy())
preds_aux_img.append(y_pred_aux.softmax(-1).detach().cpu().numpy())
preds.append(np.mean(preds_img, 0))
preds_aux.append(np.mean(preds_aux_img, 0))
return np.concatenate(preds), np.concatenate(preds_aux)
| UTF-8 | Python | false | false | 3,359 | py | 142 | classifier_aux.py | 17 | 0.626675 | 0.622209 | 0 | 122 | 26.532787 | 96 |
MatteoAllemandi/School | 8,108,898,255,107 | 6bb7fb94fa4d4fbd6a9beb3c55e79f285578624f | 8a127272527a19515e0587eefbcc77157061627c | /Sistemi/Crittografia/RSA.py | b68e84d2b940cbdc2c4389f79031382da8ddb340 | []
| no_license | https://github.com/MatteoAllemandi/School | 7191b5934e2423ce0e8d27e8b409c83d3734ad7d | 66005767bd381d55aea1292bfb72d61e5845871c | refs/heads/master | 2021-08-04T18:25:30.373733 | 2020-05-16T20:26:29 | 2020-05-16T20:26:29 | 173,294,869 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | '''Matteo Allemandi RSA in python'''
import math
import random
import numpy as np
def isPrime(n): #controlla se il numero è primo
for p in range(2, int(np.sqrt(n)) + 1):
if (n % p == 0):
return False
return True
def mcm(n1,n2): #trova minimo comune multiplo
return int((n1*n2)/math.gcd(n1,n2))
def trovaC(m): #trova un numero compreso fra 2 ed m che abbia il massimo comune divisore uguale ad 1
for c in range(m,2,-1):
if(math.gcd(c,m) == 1):
break
return c
def trovaD(c,m): #trova un numero compreso fra 0 ed m il cui modulo del prodotto con il C precedentemente trovato sia uguale ad 1
for d in range(0,m):
if ((c*d)%m == 1):
break
return d
def codifica(l,c,n): #codifica del numero da inviare
return ((l**c)%n)
def decodifica(lc,d,n): #Decodifica del numero codificato
return ((lc**d)%n)
def main():
prime=False
while prime==False:
p = int(input("inserisci numero P: "))
prime = isPrime(p)
prime = False
while prime==False:
q = int(input("inserisci numero Q: "))
prime = isPrime(q)
n=p*q #trovo N
m = mcm(p-1,q-1) #trovo M
c = trovaC(m) #chiamata alla funzione per trovare C
if c == -1: #se C non viene trovato, termina il programma
print("errore")
exit(0)
else:
d = trovaD(c,m)
print(f"n-->{n}\nc --> {c}\nd--> {d}\nm--> {m}\n")
l = 12
print(f"lettera da codificare ---> {l}")
lc = codifica(l,c,n)
print(f"lettera codificata ---> {c}") #codifica la lettera usando le chiavi trovate
#print(str(decodifica(lc,d,n))) stampa eventuale decodifica della lettera
main()
| UTF-8 | Python | false | false | 1,868 | py | 30 | RSA.py | 27 | 0.540439 | 0.527584 | 0 | 65 | 27.723077 | 145 |
walinchus/Chapter_27 | 11,381,663,363,724 | d8ea26a6731b0a0ebcbf6d4436a9d83553a90502 | 9ced5dc83bd7e9364ee1bc5ec691584dc637f61c | /scraper.py | fb0bbb452bf497d143710684db11e81135a21a44 | []
| no_license | https://github.com/walinchus/Chapter_27 | 369e6c1125e8c08956d55cdf7d5a55587f2d484d | 3b472dffacd738102b005181769f64de31d27054 | refs/heads/master | 2021-01-25T04:15:45.580630 | 2017-06-05T15:56:18 | 2017-06-05T15:56:18 | 93,418,630 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import scraperwiki
import csv
#guidance on csv library at https://scraperwiki.com/docs/python/python_csv_guide/
#scrape the csv file into new variable 'data'
data = scraperwiki.scrape('https://data.birmingham.gov.uk/dataset/e9c314fc-fb6d-4189-a19c-7eec962733a8/resource/6b00d8f0-3855-4be0-ae2b-6775df64010a/download/traffic-signals-dec2016.csv')
#first attempt generated an error: "SqliteError: Binary strings must be utf-8 encoded"
#So we need to trace which part of our data is responsible. We're going to
#use .reader function and .splitlines() method to put 'data' into csv object 'reader'
reader = csv.reader(data.splitlines())
print reader
record = {}
idno = 0
#Some code that decodes UTF-8
#http://yosaito.co.uk/scraperlibs/python/scraperwiki/sqlite.py
for row in reader:
print type(row[0])
print type(row[1])
print type(row[2])
print type(row[3])
print type(row[4])
print type(row[5])
print type(row[6])
record['usrn'] = row[0]
record['row'] = row[1]
record['district'] = row[2]
record['ward'] = row[3]
record['captured by'] = row[4]
record['longitude'] = row[5]
record['latitude'] = row[6]
idno += 1
record['ID'] = idno
print record
scraperwiki.sqlite.save(['ID'], record)
#This will generate an error with this data:
#SqliteError: Binary strings must be utf-8 encoded
# This is a template for a Python scraper on morph.io (https://morph.io)
# including some code snippets below that you should find helpful
# import scraperwiki
# import lxml.html
#
# # Read in a page
# html = scraperwiki.scrape("http://foo.com")
#
# # Find something on the page using css selectors
# root = lxml.html.fromstring(html)
# root.cssselect("div[align='left']")
#
# # Write out to the sqlite database using scraperwiki library
# scraperwiki.sqlite.save(unique_keys=['name'], data={"name": "susan", "occupation": "software developer"})
#
# # An arbitrary query against the database
# scraperwiki.sql.select("* from data where 'name'='peter'")
# You don't have to do things with the ScraperWiki and lxml libraries.
# You can use whatever libraries you want: https://morph.io/documentation/python
# All that matters is that your final data is written to an SQLite database
# called "data.sqlite" in the current working directory which has at least a table
# called "data".
| UTF-8 | Python | false | false | 2,343 | py | 1 | scraper.py | 1 | 0.715322 | 0.688434 | 0 | 68 | 33.455882 | 187 |
CheHaoKang/Docker-Flask-MongoDB | 8,065,948,617,287 | e8b983d3093202b9a3b65871d1bbe4e3a17e1fa5 | b71461226b2ebbc46f8effabf6397822b48dd07c | /test_class.py | b39375bab89803ef6f7a28e7ad1f629cdfbaa473 | []
| no_license | https://github.com/CheHaoKang/Docker-Flask-MongoDB | 1735f09b1c60ee43d05010cde0944ec6dd14d75c | 8af46e27825d315551af785c0a02f9c7453df7ac | refs/heads/master | 2020-03-23T09:03:41.852503 | 2018-07-18T01:35:41 | 2018-07-18T01:35:41 | 141,364,679 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from pymongo import MongoClient
import pandas as pd
import numpy as np
class TestClass:
def is_int_float(self, input):
'''Check the numeric type of the input.
If the input is an integer, return 'int'.
If the input is a float, return 'float'.
Neither case, return 'none' '''
try:
int(input)
return 'int'
except ValueError:
pass
try:
float(input)
return 'float'
except ValueError:
return 'none'
def connect_to_db(self, uri, db, collection):
client = MongoClient(uri)
client_db = client[db]
client_collect = client_db[collection]
return client, client_collect
def test_load(self):
uri = "mongodb://deckenkang66:97155434@db:27017/Pluvio"
# uri = "mongodb://db:27017/Pluvio"
db = 'Pluvio'
collection = 'fruits'
client, collect = self.connect_to_db(uri, db, collection)
df = pd.read_csv('fruits.csv', header=None)
np_df = np.array(df)
for one_row in np_df:
for index in range(len(one_row)):
type_check = self.is_int_float(one_row[index])
if type_check=='float':
one_row[index] = float(one_row[index])
elif type_check=='int':
one_row[index] = int(one_row[index])
find_result = collect.find_one({'sid':one_row[0],
'fruit':one_row[1],
'amount':one_row[2],
'price':one_row[3]})
assert find_result is not None
client.close()
def test_alter(self):
uri = "mongodb://deckenkang66:97155434@db:27017/Pluvio"
# uri = "mongodb://db:27017/Pluvio"
db = 'Pluvio'
collection = 'fruits'
client, collect = self.connect_to_db(uri, db, collection)
df = pd.read_csv('fruits.csv', header=None)
np_df = np.array(df)
for one_row in np_df:
for index in range(len(one_row)):
type_check = self.is_int_float(one_row[index])
if type_check=='float':
one_row[index] = float(one_row[index])
elif type_check=='int':
one_row[index] = int(one_row[index])
find_result = collect.find_one({'sid':one_row[0],
'fruit':one_row[1],
'amount':one_row[2],
'price':one_row[3]})
assert find_result is not None
client.close()
| UTF-8 | Python | false | false | 2,741 | py | 7 | test_class.py | 3 | 0.485224 | 0.467713 | 0 | 89 | 29.797753 | 65 |
CrisRonda/Pandas | 5,050,881,555,273 | ecd05a7abaee79d735574bfcab7fc049cb2bd080 | 73c77e13cff9ec66a8e83481efef5dc4b8ac099a | /playground.py | 2bf5aa57e3285ec706c0fa88b3995315a6f900d2 | []
| no_license | https://github.com/CrisRonda/Pandas | b8ea60f087d84d5c732437cb8a6290c1c6c53581 | 2f0934593880a6678150c983de9f685e53e62858 | refs/heads/master | 2021-03-06T11:33:17.109627 | 2020-03-19T21:44:56 | 2020-03-19T21:44:56 | 246,197,859 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import pandas as pd
import numpy as np
df_data = pd.read_csv('Data.csv', encoding="ISO-8859-1")
# Columna para seleccion
df_data.set_index("Date", inplace=True)
df_data = df_data.replace(np.nan, 0)
df_data = df_data.replace("N/A", "0")
df_data = df_data.replace("NR", "0")
df_data['WRank'] = df_data.WRank.astype(int)
df_data['LRank'] = df_data.WRank.astype(int)
df_data['W1'] = df_data.WRank.astype(int)
selection = df_data.loc[(df_data['WRank'] > 20) & (df_data['WRank'] <= 45), [
"Winner", "WRank", 'LRank', "W1"]]
print(selection.index)
# Ordenamiento sin numpy
# order_by_WRank = selection.sort_values(by=["WRank"], ascending=False)
# Ordenamiento con numpy en todas las columnas
order_np = pd.DataFrame(np.sort(selection.values, axis=0),
index=selection.index, columns=selection.columns)
print(order_np)
| UTF-8 | Python | false | false | 839 | py | 19 | playground.py | 6 | 0.674613 | 0.656734 | 0 | 21 | 38.952381 | 77 |
pandichef/django-materialize | 6,657,199,315,177 | cf978cc16c2373c660fbc581c6f61d3c89460564 | b29977caf98ba7b2064b85e1c4c7da9a5f520371 | /django_materialize/admin/apps.py | 46a5318ea313cde8970c98c3216ea643b6286f80 | [
"BSD-3-Clause",
"BSD-2-Clause"
]
| permissive | https://github.com/pandichef/django-materialize | b12d5cc668f8904d9dd19c720eafe39a5afada59 | 4017f258c91193a1919819133f3ce10aa0cba394 | refs/heads/master | 2021-04-07T08:35:28.559194 | 2018-02-13T22:40:06 | 2018-02-13T22:40:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import warnings
from importlib import import_module
from django.apps import AppConfig
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import RegexURLResolver, Resolver404
from django.template import Template, TemplateDoesNotExist
from django.template.loader import get_template
from django.utils.module_loading import module_has_submodule
class ModuleMatchName(str):
pass
class ModuleURLResolver(RegexURLResolver):
def __init__(self, *args, **kwargs):
self._module = kwargs.pop('module')
super(ModuleURLResolver, self).__init__(*args, **kwargs)
def resolve(self, *args, **kwargs):
result = super(ModuleURLResolver, self).resolve(*args, **kwargs)
if result and not getattr(self._module, 'installed', True):
raise Resolver404({'message': 'Module not installed'})
result.url_name = ModuleMatchName(result.url_name)
result.url_name.module = self._module
return result
class ModuleMixin(object):
"""
Extension for the django AppConfig. Makes django app pluggable at runtime.
- Application level user permission access
- Runtime app installation/deinstallation
- Autodiscovery for <app_module>/urls.py
- Collect common website menu from `<app_label>/menu.html`
Example::
class Sales(ModuleMixin, AppConfig):
name = 'sales'
icon = '<i class="material-icons">call</i>'
The application have to have <app_module>/urls.py file, with
a single no-parametrized url with name='index', ex::
urlpatterns = [
url('^$', generic.TemplateView.as_view(template_name="sales/index.html"), name="index"),
]
All AppConfigs urls will be included into material.frontend.urls automatically under /<app_label>/ prefix
The AppConfig.label, used for the urls namespace.
The menu.html sample::
<ul>
<li><a href="{% url 'sales:index' %}">Dashboard</a></li>
<li><a href="{% url 'sales:customers' %}">Customers</a></li>
{% if perms.sales.can_add_lead %}<li><a href="{% url 'sales:leads' %}">Leads</a></li>{% endif %}
</ul>
In all application templates, the current application config
instance would be available as `current_module` template variable
"""
order = 10
icon = '<i class="material-icons">receipt</i>'
@property
def verbose_name(self):
return self.label.title()
@property
def installed(self):
from .models import Module as DbModule
return DbModule.objects.installed(self.label)
def description(self):
return (self.__doc__ or "").strip()
def has_perm(self, user):
return True
def get_urls(self):
if module_has_submodule(self.module, 'urls'):
urls_module_name = '%s.%s' % (self.name, 'urls')
urls_module = import_module(urls_module_name)
if hasattr(urls_module, 'urlpatterns'):
return urls_module.urlpatterns
warnings.warn('Module {} have not urls.py submodule or `urlpatterns` in it'.format(self.label))
return []
@property
def urls(self):
base_url = r'^{}/'.format(self.label)
return ModuleURLResolver(base_url, self.get_urls(), module=self, app_name=self.label, namespace=self.label)
def index_url(self):
return reverse('{}:index'.format(self.label))
def menu(self):
try:
return get_template('{}/menu.html'.format(self.label))
except TemplateDoesNotExist:
return Template('')
class MaterialAdminConfig(ModuleMixin, AppConfig):
name = 'django_materialize.admin'
label = "django_materialize_admin"
icon = '<i class="material-icons">settings_application</i>'
verbose_name = _("Administration")
order = 1000
@property
def urls(self):
return ModuleURLResolver(r'^admin/', admin.site.urls[0], namespace='admin', module=self)
def index_url(self):
return reverse('admin:index'.format(self.label))
def has_perm(self, user):
return user.is_staff
| UTF-8 | Python | false | false | 4,196 | py | 12 | apps.py | 3 | 0.651573 | 0.648475 | 0 | 120 | 33.966667 | 115 |
kryvokhyzha/examples-and-courses | 13,477,607,395,752 | 74af51d7d32776245a32674141a763089481f11f | 24443f1c2bcea7595bf1ba807bdf0b07fbca4b39 | /aischool-mlprod/other/torch_jit.py | c8a59bb5463384c00d4a7a911a769dc069ff449f | [
"MIT"
]
| permissive | https://github.com/kryvokhyzha/examples-and-courses | 488e8ba2d12728897822283d0d1bb6e7a7c0a7f4 | f6e42dfdf69e63c02331ee0f8d6f0d302506189e | refs/heads/master | 2023-05-23T08:16:46.698814 | 2023-02-25T20:51:06 | 2023-02-25T20:51:06 | 226,865,952 | 7 | 6 | MIT | false | 2023-02-23T16:04:52 | 2019-12-09T12:27:59 | 2023-02-10T18:01:25 | 2023-02-23T16:04:50 | 1,222,922 | 6 | 7 | 26 | Jupyter Notebook | false | false | import time
import numpy as np
import torch
from torchvision import models
from utils.apex_utils import get_dataloaders
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
dataloaders, dataset_sizes, class_names = get_dataloaders(data_dir='hymenoptera_data')
dataloader = dataloaders['train']
batch_size = 4
resnet = torch.jit.trace(models.resnet18(pretrained=True).to(device), torch.rand(batch_size, 3, 224, 224).to(device))
# resnet_fp16 = torch.jit.trace(models.resnet18(pretrained=True).half().to(device), torch.rand(batch_size, 3, 224, 224).half().to(device))
resnet_torch_32 = models.resnet18(pretrained=True).to(device)
def resnet_infer(inputs):
cuda_tensor = inputs.to(device)
return resnet(cuda_tensor).argmax(1)
def resnet_fp16_infer(inputs):
cuda_tensor = inputs.half().to(device)
return resnet_fp16(cuda_tensor).argmax(1)
def resnet_torch_infer(inputs):
cuda_tensor = inputs.to(device)
return resnet_torch_32(cuda_tensor).argmax(1)
def process_set(model_infer, model_name):
times = []
for inputs, values in dataloader:
time1 = time.time()
model_infer(inputs)
time2 = time.time()
times.append(time2 - time1)
print(f"Avegage FPS - {model_name}:", 4 / np.mean(times[1:]))
process_set(model_infer=resnet_infer, model_name='resnet_jit_fp32')
# process_set(model_infer=resnet_fp16_infer, model_name='resnet_jit_fp16')
process_set(model_infer=resnet_torch_infer, model_name='resnet_torch_fp32')
| UTF-8 | Python | false | false | 1,503 | py | 1,594 | torch_jit.py | 270 | 0.71324 | 0.680639 | 0 | 47 | 30.978723 | 138 |
franksalas/CS3420-Class-Project | 9,139,690,423,138 | 33b99fe9a0ecfd3710a708f322305dd4595a7f4c | eb230532d3cbcd5be25a1b9189a8d86d47df84d4 | /draf_1/npyscreenTest.py | 303bfb12836bf2cdfc279f54816200840c1b9e3e | []
| no_license | https://github.com/franksalas/CS3420-Class-Project | cf3df3c68de179f43c8538990c7ccd64e8b60b82 | ca6f5ab1ce162624bfcb17b82421f418117650c8 | refs/heads/master | 2016-05-06T17:25:24.352047 | 2016-03-31T20:13:46 | 2016-03-31T20:13:46 | 51,043,577 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import npyscreen
def simple_function(*arguments):
pass
if (__name__ == "__main__"):
npyscreen.wrapper_basic(simple_function)
| UTF-8 | Python | false | false | 137 | py | 11 | npyscreenTest.py | 10 | 0.656934 | 0.656934 | 0 | 9 | 14.222222 | 44 |
Paulius-Maruska/python-isign | 9,698,036,197,068 | 02dc3ecd7e78447fb445a5ae02b186a6efc8c577 | 5de368aebb55fbf46f3a2b5e963133685c50e897 | /src/isign/model/mobile_login_response.py | e48aa1cc88b432353a644e90b70849d6534a40f2 | [
"MIT"
]
| permissive | https://github.com/Paulius-Maruska/python-isign | a5a088c707f124a868a475c3efcb1e243bfeb9b6 | 0474b90654c36125f58f0cdb3c7803b1678d3f18 | refs/heads/master | 2020-01-19T21:38:03.742753 | 2017-07-25T08:48:00 | 2017-07-25T08:48:00 | 94,220,780 | 2 | 0 | null | false | 2017-07-25T08:48:01 | 2017-06-13T14:17:02 | 2017-06-14T11:49:02 | 2017-07-25T08:48:01 | 37 | 2 | 0 | 0 | Python | null | null | from .certificate import Certificate
from .response import Response
class MobileLoginResponse(Response):
@property
def certificate(self) -> Certificate:
return Certificate(self.raw["certificate"])
@property
def country(self) -> str:
return str(self.raw["country"])
@property
def code(self) -> str:
return str(self.raw["code"])
@property
def name(self) -> str:
return str(self.raw["name"])
@property
def surname(self) -> str:
return str(self.raw["surname"])
@property
def token(self) -> str:
return str(self.raw["token"])
@property
def control_code(self) -> str:
return str(self.raw["control_code"])
class MobileLoginStatusResponse(Response):
pass
| UTF-8 | Python | false | false | 773 | py | 42 | mobile_login_response.py | 38 | 0.626132 | 0.626132 | 0 | 36 | 20.472222 | 51 |
perrozzi/cmg-cmssw | 13,683,765,846,834 | 606c79d780a7da9693f478fbae1cfa3ee09d8588 | 5330918e825f8d373d3907962ba28215182389c3 | /CMGTools/WMass/python/analyzers/ZTreeProducer.py | 15d60cd114800035db117cfa6320f425b2217737 | []
| no_license | https://github.com/perrozzi/cmg-cmssw | 31103a7179222c7aa94f65e83d090a5cf2748e27 | 1f4cfd936da3a6ca78f25959a41620925c4907ca | refs/heads/CMG_PAT_V5_18_from-CMSSW_5_3_22 | 2021-01-16T23:15:58.556441 | 2017-05-11T22:43:15 | 2017-05-11T22:43:15 | 13,272,641 | 1 | 0 | null | true | 2017-05-11T22:43:16 | 2013-10-02T14:05:21 | 2016-11-03T08:01:49 | 2017-05-11T22:43:16 | 959,175 | 0 | 0 | 1 | C++ | null | null |
from CMGTools.WMass.analyzers.CoreTreeProducer import *
#from ZAnalyzer import testLegID
# def bookJetCollections( tree, pName ):
# var(tree, '{pName}_number'.format(pName=pName),int)
# tree.vars['{pName}_pt'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_pt'.format(pName=pName),tree.vars['{pName}_pt'.format(pName=pName)] ,'{pName}_pt'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_eta'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_eta'.format(pName=pName),tree.vars['{pName}_eta'.format(pName=pName)] ,'{pName}_eta'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_phi'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_phi'.format(pName=pName),tree.vars['{pName}_phi'.format(pName=pName)] ,'{pName}_phi'.format(pName=pName)+'[10]/D' )
# def bookLeptonCollections( tree, pName ):
# var(tree, '{pName}_number'.format(pName=pName),int)
# tree.vars['{pName}_charge'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_charge'.format(pName=pName),tree.vars['{pName}_charge'.format(pName=pName)] ,'{pName}_charge'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_ID'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_ID'.format(pName=pName),tree.vars['{pName}_ID'.format(pName=pName)] ,'{pName}_ID'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_ID_8TeV'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_ID_8TeV'.format(pName=pName),tree.vars['{pName}_ID_8TeV'.format(pName=pName)] ,'{pName}_ID_8TeV'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_Iso'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_Iso'.format(pName=pName),tree.vars['{pName}_Iso'.format(pName=pName)] ,'{pName}_Iso'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_IsPromt'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_IsPromt'.format(pName=pName),tree.vars['{pName}_IsPromt'.format(pName=pName)] ,'{pName}_IsPromt'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_IsTrig'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_IsTrig'.format(pName=pName),tree.vars['{pName}_IsTrig'.format(pName=pName)] ,'{pName}_IsTrig'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_pt'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_pt'.format(pName=pName),tree.vars['{pName}_pt'.format(pName=pName)] ,'{pName}_pt'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_eta'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_eta'.format(pName=pName),tree.vars['{pName}_eta'.format(pName=pName)] ,'{pName}_eta'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_phi'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_phi'.format(pName=pName),tree.vars['{pName}_phi'.format(pName=pName)] ,'{pName}_phi'.format(pName=pName)+'[10]/D' )
# # tree.vars['{pName}_Zmatch'.format(pName=pName)]= my_n.zeros(10, dtype=int)
# # tree.tree.Branch('{pName}_Zmatch'.format(pName=pName),tree.vars['{pName}_Zmatch'.format(pName=pName)] ,'{pName}_Zmatch'.format(pName=pName)+'[10]/I' )
# def bookElectrons( tree, pName ):
# var(tree, '{pName}_number'.format(pName=pName),int)
# tree.vars['{pName}_pt'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_pt'.format(pName=pName),tree.vars['{pName}_pt'.format(pName=pName)] ,'{pName}_pt'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_eta'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_eta'.format(pName=pName),tree.vars['{pName}_eta'.format(pName=pName)] ,'{pName}_eta'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_phi'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_phi'.format(pName=pName),tree.vars['{pName}_phi'.format(pName=pName)] ,'{pName}_phi'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_TightID'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_TightID'.format(pName=pName),tree.vars['{pName}_TightID'.format(pName=pName)] ,'{pName}_TightID'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_TightIso'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_TightIso'.format(pName=pName),tree.vars['{pName}_TightIso'.format(pName=pName)] ,'{pName}_TightIso'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_charge'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_charge'.format(pName=pName),tree.vars['{pName}_charge'.format(pName=pName)] ,'{pName}_charge'.format(pName=pName)+'[10]/D' )
# tree.vars['{pName}_IsPromt'.format(pName=pName)]= my_n.zeros(10, dtype=float)
# tree.tree.Branch('{pName}_IsPromt'.format(pName=pName),tree.vars['{pName}_IsPromt'.format(pName=pName)] ,'{pName}_IsPromt'.format(pName=pName)+'[10]/D' )
# def bookcmgPFcands( tree, pName ):
# var(tree, '{pName}_number'.format(pName=pName),int)
# tree.vars['{pName}_pt'.format(pName=pName)]= my_n.zeros(5000, dtype=float)
# tree.tree.Branch('{pName}_pt'.format(pName=pName),tree.vars['{pName}_pt'.format(pName=pName)] ,'{pName}_pt'.format(pName=pName)+'[5000]/D' )
# tree.vars['{pName}_eta'.format(pName=pName)]= my_n.zeros(5000, dtype=float)
# tree.tree.Branch('{pName}_eta'.format(pName=pName),tree.vars['{pName}_eta'.format(pName=pName)] ,'{pName}_eta'.format(pName=pName)+'[5000]/D' )
# tree.vars['{pName}_phi'.format(pName=pName)]= my_n.zeros(5000, dtype=float)
# tree.tree.Branch('{pName}_phi'.format(pName=pName),tree.vars['{pName}_phi'.format(pName=pName)] ,'{pName}_phi'.format(pName=pName)+'[5000]/D' )
# tree.vars['{pName}_pdgId'.format(pName=pName)]= my_n.zeros(5000, dtype=float)
# tree.tree.Branch('{pName}_pdgId'.format(pName=pName),tree.vars['{pName}_pdgId'.format(pName=pName)] ,'{pName}_pdgId'.format(pName=pName)+'[5000]/D' )
# tree.vars['{pName}_fromPV'.format(pName=pName)]= my_n.zeros(5000, dtype=float)
# tree.tree.Branch('{pName}_fromPV'.format(pName=pName),tree.vars['{pName}_fromPV'.format(pName=pName)] ,'{pName}_fromPV'.format(pName=pName)+'[5000]/D' )
# tree.vars['{pName}_dZfromPV'.format(pName=pName)]= my_n.zeros(5000, dtype=float)
# tree.tree.Branch('{pName}_dZfromPV'.format(pName=pName),tree.vars['{pName}_dZfromPV'.format(pName=pName)] ,'{pName}_dZfromPV'.format(pName=pName)+'[5000]/D' )
# def bookPFJets( tree, pName ):
# var(tree, '{pName}_number'.format(pName=pName),int)
# tree.vars['{pName}_pt'.format(pName=pName)]= my_n.zeros(100, dtype=float)
# tree.tree.Branch('{pName}_pt'.format(pName=pName),tree.vars['{pName}_pt'.format(pName=pName)] ,'{pName}_pt'.format(pName=pName)+'[100]/D' )
# tree.vars['{pName}_eta'.format(pName=pName)]= my_n.zeros(100, dtype=float)
# tree.tree.Branch('{pName}_eta'.format(pName=pName),tree.vars['{pName}_eta'.format(pName=pName)] ,'{pName}_eta'.format(pName=pName)+'[100]/D' )
# tree.vars['{pName}_phi'.format(pName=pName)]= my_n.zeros(100, dtype=float)
# tree.tree.Branch('{pName}_phi'.format(pName=pName),tree.vars['{pName}_phi'.format(pName=pName)] ,'{pName}_phi'.format(pName=pName)+'[100]/D' )
# tree.vars['{pName}_pdgId'.format(pName=pName)]= my_n.zeros(100, dtype=float)
# # tree.tree.Branch('{pName}_pdgId'.format(pName=pName),tree.vars['{pName}_pdgId'.format(pName=pName)] ,'{pName}_pdgId'.format(pName=pName)+'[100]/D' )
# # tree.vars['{pName}_fromPV'.format(pName=pName)]= my_n.zeros(100, dtype=float)
# # tree.tree.Branch('{pName}_fromPV'.format(pName=pName),tree.vars['{pName}_fromPV'.format(pName=pName)] ,'{pName}_fromPV'.format(pName=pName)+'[100]/D' )
# # tree.vars['{pName}_dZfromPV'.format(pName=pName)]= my_n.zeros(100, dtype=float)
# # tree.tree.Branch('{pName}_dZfromPV'.format(pName=pName),tree.vars['{pName}_dZfromPV'.format(pName=pName)] ,'{pName}_dZfromPV'.format(pName=pName)+'[100]/D' )
# def fillJets( tree, pName, particles ):
# fill(tree, '{pName}_number'.format(pName=pName),len(particles))
# for i in range(0, min(len(particles),10)):
# tree.vars['{pName}_pt'.format(pName=pName)][i] = particles[i].pt()
# tree.vars['{pName}_eta'.format(pName=pName)][i] = particles[i].eta()
# tree.vars['{pName}_phi'.format(pName=pName)][i] = particles[i].phi()
# def fillMuons( tree, pName, particles , event):
# fill(tree, '{pName}_number'.format(pName=pName),len(particles))
# for i in range(0, min(len(particles),10)):
# tree.vars['{pName}_pt'.format(pName=pName)][i] = particles[i].pt()
# tree.vars['{pName}_eta'.format(pName=pName)][i] = particles[i].eta()
# tree.vars['{pName}_phi'.format(pName=pName)][i] = particles[i].phi()
# tree.vars['{pName}_charge'.format(pName=pName)][i] = float(particles[i].charge())
# tree.vars['{pName}_ID'.format(pName=pName)][i] = event.ZallMuonsID[i]
# tree.vars['{pName}_ID_8TeV'.format(pName=pName)][i] = event.ZallMuonsID_8TeV[i]
# tree.vars['{pName}_Iso'.format(pName=pName)][i] = particles[i].relIso(0.5)
# tree.vars['{pName}_IsTrig'.format(pName=pName)][i] = int(event.ZallMuonsTrig[i])
# def fillMuonsGen( tree, pName, particles , event):
# for i in range(0, min(len(particles),10)):
# #print i, ' len ', len(particles)
# tree.vars['{pName}_IsPromt'.format(pName=pName)][i] = event.ZallMuonsMatched[i]
# def fillElectrons( tree, pName, particles,event ):
# fill(tree, '{pName}_number'.format(pName=pName),len(particles))
# for i in range(0, min(len(particles),10)):
# tree.vars['{pName}_pt'.format(pName=pName)][i] = particles[i].pt()
# tree.vars['{pName}_eta'.format(pName=pName)][i] = particles[i].eta()
# tree.vars['{pName}_phi'.format(pName=pName)][i] = particles[i].phi()
# tree.vars['{pName}_TightID'.format(pName=pName)][i] = event.ZElTightID[i]
# tree.vars['{pName}_TightIso'.format(pName=pName)][i] = event.ZElTightIso[i]
# tree.vars['{pName}_charge'.format(pName=pName)][i] = particles[i].charge()
# def fillcmgPFcands( tree, pName, particles,vertex,event ):
# fill(tree, '{pName}_number'.format(pName=pName),len(particles))
# for i in range(0, min(len(particles),2000)):
# # print particles[i].pdgId(), math.fabs(particles[i].vertex().z()-vertex.z())
# tree.vars['{pName}_pt'.format(pName=pName)][i] = particles[i].pt()
# tree.vars['{pName}_eta'.format(pName=pName)][i] = particles[i].eta()
# tree.vars['{pName}_phi'.format(pName=pName)][i] = particles[i].phi()
# tree.vars['{pName}_pdgId'.format(pName=pName)][i] = particles[i].pdgId()
# tree.vars['{pName}_fromPV'.format(pName=pName)][i] = particles[i].fromPV()
# tree.vars['{pName}_dZfromPV'.format(pName=pName)][i] = math.fabs(particles[i].vertex().z()-vertex.z())
# def fillPFJets( tree, pName, particles,event ):
# fill(tree, '{pName}_number'.format(pName=pName),len(particles))
# for i in range(0, min(len(particles),100)):
# # print particles[i].pdgId(), math.fabs(particles[i].vertex().z()-vertex.z())
# tree.vars['{pName}_pt'.format(pName=pName)][i] = particles[i].pt()
# tree.vars['{pName}_eta'.format(pName=pName)][i] = particles[i].eta()
# tree.vars['{pName}_phi'.format(pName=pName)][i] = particles[i].phi()
# # print 'particles[',i,'].mva() ', particles[i].mva()
# # tree.vars['{pName}_pdgId'.format(pName=pName)][i] = particles[i].pdgId()
# # tree.vars['{pName}_fromPV'.format(pName=pName)][i] = particles[i].fromPV()
# # tree.vars['{pName}_dZfromPV'.format(pName=pName)][i] = math.fabs(particles[i].vertex().z()-vertex.z())
# def fillNeutralcmgPFcands( tree, pName, particles,vertex,event ):
# jneu=0
# for i in range(0, min(len(particles),2500)):
# # case 211: return h;
# # case 11: return e;
# # case 13: return mu;
# # case 22: return gamma;
# # case 130: return h0;
# # case 1: return h_HF;
# # case 2: return egamma_HF;
# # case 0: return X;
# if(math.fabs(particles[i].pdgId())==130 or math.fabs(particles[i].pdgId())==1 \
# or math.fabs(particles[i].pdgId())==2 or math.fabs(particles[i].pdgId())==22):
# tree.vars['{pName}_pt'.format(pName=pName)][jneu] = particles[i].pt()
# tree.vars['{pName}_eta'.format(pName=pName)][jneu] = particles[i].eta()
# tree.vars['{pName}_phi'.format(pName=pName)][jneu] = particles[i].phi()
# tree.vars['{pName}_pdgId'.format(pName=pName)][jneu] = particles[i].pdgId()
# tree.vars['{pName}_fromPV'.format(pName=pName)][jneu] = particles[i].fromPV()
# tree.vars['{pName}_dZfromPV'.format(pName=pName)][i] = math.fabs(particles[i].vertex().z()-vertex.z())
# jneu = jneu+1
# fill(tree, '{pName}_number'.format(pName=pName),jneu)
# def fillElectronsGen(tree, pName, particles,event ):
# for i in range(0, min(len(particles),10)):
# tree.vars['{pName}_IsPromt'.format(pName=pName)][i] = event.ZElIsPromt[i]
class ZTreeProducer( CoreTreeProducer ):
MuonClass = Muon
def declareHandles(self):
super(ZTreeProducer, self).declareHandles()
self.declareCoreHandles()
customMetFlavor_str = [ 'tkmethemu' , 'h0','gamma','hegammaHF' ]
customMetEtaBinEdge_str = ['m5p0','m3p0','m2p4','m2p1','m1p4','1p4','2p1','2p4','3p0','5p0']
customMetPtBinEdge_str = ['0p0','0p5','1p0','1p5','2p0','3p0','5p0','10p0']
if hasattr(self.cfg_ana,'storeMyCustomMets'):
for particleId in xrange(len(customMetFlavor_str)):
for EtaBinEdge in xrange(len(customMetEtaBinEdge_str)-1):
for PtBinEdge in xrange(len(customMetPtBinEdge_str)):
if( ( ('gamma' is not customMetFlavor_str[particleId]) and ('h0' not in customMetFlavor_str[particleId]) ) and (PtBinEdge > 4) ): continue
if( ('h0' not in customMetFlavor_str[particleId]) and (PtBinEdge > 5) ): continue
# print 'my%sPFmetPt0p0EtaMin%sEtaMax%s'%(customMetFlavor_str[particleId],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1])
self.handles['my%sPFmetPt%sEtaMin%sEtaMax%s'%(customMetFlavor_str[particleId],customMetPtBinEdge_str[PtBinEdge],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1])] = AutoHandle(
'my%sPFmetPt%sEtaMin%sEtaMax%s'%(customMetFlavor_str[particleId],customMetPtBinEdge_str[PtBinEdge],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1]),
'std::vector<reco::PFMET>' )
# if hasattr(self.cfg_ana,'storeNeutralCMGcandidates') or hasattr(self.cfg_ana,'storeCMGcandidates'):
# self.handles['cmgCandidates'] = AutoHandle('cmgCandidates','std::vector<cmg::Candidate>')
# # self.handles['kt6PFJets'] = AutoHandle('kt6PFJets','std::vector<reco::PFJet>')
def declareVariables(self):
tr = self.tree
self.declareCoreVariables(self.cfg_comp.isMC)
var( tr, 'njets', int)
var( tr, 'evtHasTrg', int)
var( tr, 'evtZSel', int)
var( tr, 'nMuons', int)
var( tr, 'nTrgMuons', int)
# var( tr, 'nNoTrgMuons', int)
var( tr, 'noTrgExtraMuonsLeadingPt', int)
###--------------------------- BOOK OTHER MET infos ------------------------------
# # customMetFlavor_str = [ 'h' , 'h0','gamma','hf' ,'ele','mu']
# # customMetPtMin_str = ['0p0','0p5','1p0','1p5','2p0']
# # customMetEtaMin_str = ['0p0','1p4','2p1','2p5','3p0']
# # customMetEtaMax_str = ['1p4','2p1','2p5','3p0','5p0']
# customMetFlavor_str = ['h0','gamma','hf']
# customMetPtMin_str = ['0p0','1p0','2p0']
# customMetEtaMin_str = ['0p0','1p4','2p5','3p0']
# customMetEtaMax_str = ['1p4','2p5','3p0','5p0']
# for iFlavor in xrange(len(customMetFlavor_str)):
# for iPtMin in xrange(len(customMetPtMin_str)):
# for jEtaMax in xrange(len(customMetEtaMax_str)):
# bookCustomMET(tr, \
# 'met'+customMetFlavor_str[iFlavor]+'Pt'+customMetPtMin_str[iPtMin]+\
# 'EtaMin'+customMetEtaMin_str[jEtaMax]+'EtaMax'+customMetEtaMax_str[jEtaMax] )
customMetFlavor_str = [ 'tkmethemu' , 'h0','gamma','hegammaHF' ]
customMetEtaBinEdge_str = ['m5p0','m3p0','m2p4','m2p1','m1p4','1p4','2p1','2p4','3p0','5p0']
customMetPtBinEdge_str = ['0p0','0p5','1p0','1p5','2p0','3p0','5p0','10p0']
if hasattr(self.cfg_ana,'storeMyCustomMets'):
for particleId in xrange(len(customMetFlavor_str)):
for EtaBinEdge in xrange(len(customMetEtaBinEdge_str)-1):
for PtBinEdge in xrange(len(customMetPtBinEdge_str)):
if( ( ('gamma' is not customMetFlavor_str[particleId]) and ('h0' not in customMetFlavor_str[particleId]) ) and (PtBinEdge > 4) ): continue
if( ('h0' not in customMetFlavor_str[particleId]) and (PtBinEdge > 5) ): continue
# print 'my%sPFmetPt0p0EtaMin%sEtaMax%s'%(customMetFlavor_str[particleId],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1])
bookMET(tr, 'my%sPFmetPt%sEtaMin%sEtaMax%s'%(customMetFlavor_str[particleId],customMetPtBinEdge_str[PtBinEdge],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1]) )
var(tr, 'my%sPFmetPt%sEtaMin%sEtaMax%s_sumEt'%(customMetFlavor_str[particleId],customMetPtBinEdge_str[PtBinEdge],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1]) )
###--------------------------- BOOK Z and muon infos ------------------------------
bookZ(tr, 'Z')
var(tr, 'Z_mt')
var(tr, 'pt_vis')
var(tr, 'phi_vis')
if (self.cfg_comp.isMC):
if not hasattr(self.cfg_ana,'storeSlimGenInfo'):
bookZ(tr, 'ZGen')
bookZ(tr, 'ZGen_PostFSR')
var(tr, 'ZGen_mt')
# if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# var( tr, 'u1')
# var( tr, 'u2')
bookMuon(tr, 'MuPos')
var(tr, 'MuPos_dxy')
var(tr, 'MuPos_dz')
var(tr, 'MuPosTrg', int)
# if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# var(tr, 'MuPosIsTightAndIso', int)
var(tr, 'MuPosIsTight', int)
# if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# var(tr, 'MuPosMatchCMGmuon', int)
if (self.cfg_comp.isMC):
bookParticle(tr, 'MuPosGen')
bookParticle(tr, 'MuPosGenStatus1')
var(tr, 'FSRWeight')
# var(tr, 'MuPosGen_pdgId', int)
bookMuon(tr, 'MuNeg')
var(tr, 'MuNeg_dxy')
var(tr, 'MuNeg_dz')
var(tr, 'MuNegTrg', int)
# if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# var(tr, 'MuNegIsTightAndIso', int)
var(tr, 'MuNegIsTight', int)
# if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# var(tr, 'MuNegMatchCMGmuon', int)
if (self.cfg_comp.isMC):
bookParticle(tr, 'MuNegGen')
bookParticle(tr, 'MuNegGenStatus1')
# var(tr, 'MuNegGen_pdgId', int)
if not hasattr(self.cfg_ana,'storeSlimGenInfo'):
var(tr, 'MuPosDRGenP')
var(tr, 'MuNegDRGenP')
bookMuonCovMatrix(tr,'MuPos' )
bookMuonCovMatrix(tr,'MuNeg' )
bookJet(tr, 'Jet_leading')
# #print 'booking stuff'
# # if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# # bookJetCollections(tr,'cmgjets' )
# # bookLeptonCollections(tr,'cmgmuons' )
# # bookElectrons(tr,'cmgelectrons' )
# if hasattr(self.cfg_ana,'storeNeutralCMGcandidates') or hasattr(self.cfg_ana,'storeCMGcandidates'):
# bookcmgPFcands(tr,'cmgCandidates' )
# # bookPFJets(tr,'kt6PFJets' )
# # print 'booked stuff'
def process(self, iEvent, event):
self.readCollections( iEvent )
tr = self.tree
tr.reset()
# print 'ola'
# print 'event.savegenpZ= ',event.savegenpZ,' self.cfg_comp.isMC= ',self.cfg_comp.isMC,' event.ZGoodEvent= ',event.ZGoodEvent
# if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# fillMuons(tr, 'cmgmuons', event.ZallMuons, event)
# fillElectrons( tr,'cmgelectrons' ,event.ZselElectrons ,event)
# fillJets(tr, 'cmgjets', event.ZselJets)
self.fillCoreVariables(tr, iEvent, event, self.cfg_comp.isMC)
# this contain at least 1VTX, 2 muons, trigger
fill( tr, 'evtZSel', event.ZGoodEvent)
fill( tr, 'evtHasTrg', True)
fill( tr, 'njets', len(event.ZselJets))
if len(event.ZselJets)>0:
fillJet(tr, 'Jet_leading', event.ZselJets[0])
###--------------------------- FILL Z and muon infos ------------------------------
# if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# fillElectronsGen( tr,'cmgelectrons' ,event.ZElIsPromt ,event)
# fillMuonsGen (tr, 'cmgmuons', event.ZallMuonsMatched, event)
if (event.savegenpZ and self.cfg_comp.isMC):
fill(tr, 'FSRWeight',event.fsrWeight)
fillZ(tr, 'ZGen_PostFSR', event.genZ_PostFSR)
fill(tr, 'ZGen_mt', event.genZ_mt)
fillParticle(tr, 'MuPosGenStatus1', event.genMuPosStatus1[0])
fillParticle(tr, 'MuNegGenStatus1', event.genMuNegStatus1[0])
if not hasattr(self.cfg_ana,'storeSlimGenInfo'):
fillZ(tr, 'ZGen', event.genZ[0].p4())
fillParticle(tr, 'MuPosGen', event.genMuPos[0])
fillParticle(tr, 'MuNegGen', event.genMuNeg[0])
fill(tr, 'MuPosDRGenP', event.muPosGenDeltaRgenP)
fill(tr, 'MuNegDRGenP', event.muNegGenDeltaRgenP)
if event.ZGoodEvent == True :
# if hasattr(self.cfg_ana,'storeNeutralCMGcandidates') or hasattr(self.cfg_ana,'storeCMGcandidates'):
# cmgPFcands = self.handles['cmgCandidates'].product()
# # # kt6PFJets = self.handles['kt6PFJets'].product()
# # # fillPFJets(tr, 'kt6PFJets', kt6PFJets, event)
# # if hasattr(self.cfg_ana,'storeCMGcandidates'):
# # fillcmgPFcands( tr,'cmgCandidates' ,cmgPFcands, event.goodVertices[0], event)
# # if hasattr(self.cfg_ana,'storeNeutralCMGcandidates'):
# # fillNeutralcmgPFcands( tr,'cmgCandidates' ,cmgPFcands ,event.goodVertices[0], event)
fillZ(tr, 'Z', event.Z4V)
fill(tr, 'pt_vis', event.Z4V.Pt())
fill(tr, 'phi_vis', event.Z4V.Phi())
fill(tr, 'Z_mt', event.Z4V_mt)
# if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# fill(tr, 'u1', event.Zu1)
# fill(tr, 'u2', event.Zu2)
# fillW(tr, 'WlikePos', event.Wpos4VfromZ)
# fill(tr, 'WlikePos_mt', event.Wpos4VfromZ_mt)
# fillMET(tr, 'pfmetWlikePos', event.ZpfmetWpos)
# fillW(tr, 'WlikeNeg', event.Wneg4VfromZ)
# fill(tr, 'WlikeNeg_mt', event.Wneg4VfromZ_mt)
# fillMET(tr, 'pfmetWlikeNeg', event.ZpfmetWneg)
fillMuon(tr, 'MuPos', event.BestZPosMuon)
if ( event.BestZPosMuon.isGlobalMuon() or event.BestZPosMuon.isTrackerMuon() ) and event.passedVertexAnalyzer:
fill(tr, 'MuPos_dxy', math.fabs(event.BestZPosMuon.dxy()))
fill(tr, 'MuPos_dz',math.fabs(event.BestZPosMuon.dz()))
fill(tr, 'MuPosTrg', event.BestZPosMuonHasTriggered)
# if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# fill(tr, 'MuPosIsTightAndIso',event.BestZPosMuonIsTightAndIso)
fill(tr, 'MuPosIsTight',event.BestZPosMuonIsTight)
# if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# fill(tr, 'MuPosMatchCMGmuon',event.BestZPosMatchIndex)
fillMuon(tr, 'MuNeg', event.BestZNegMuon)
if ( event.BestZNegMuon.isGlobalMuon() or event.BestZNegMuon.isTrackerMuon() ) and event.passedVertexAnalyzer:
fill(tr, 'MuNeg_dxy', math.fabs(event.BestZNegMuon.dxy()))
fill(tr, 'MuNeg_dz',math.fabs(event.BestZNegMuon.dz()))
fill(tr, 'MuNegTrg', event.BestZNegMuonHasTriggered)
# if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# fill(tr, 'MuNegIsTightAndIso',event.BestZNegMuonIsTightAndIso)
fill(tr, 'MuNegIsTight',event.BestZNegMuonIsTight)
# if not hasattr(self.cfg_ana,'storeSlimRecoInfo'):
# fill(tr, 'MuNegMatchCMGmuon',event.BestZNegMatchIndex)
fillMuonCovMatrix( tr,'MuPos' ,event.covMatrixPosMuon ,event)
fillMuonCovMatrix( tr,'MuNeg' ,event.covMatrixNegMuon ,event)
###--------------------------- FILL extra infos ------------------------------
if (event.savegenpZ and self.cfg_comp.isMC) or event.ZGoodEvent:
fill( tr, 'nMuons', len(event.ZallMuons))
fill( tr, 'nTrgMuons', len(event.ZselTriggeredMuons))
# fill( tr, 'nNoTrgMuons', len(event.ZselNoTriggeredMuons))
if(len(event.ZselNoTriggeredExtraMuonsLeadingPt)>0):
fill( tr, 'noTrgExtraMuonsLeadingPt', event.ZselNoTriggeredExtraMuonsLeadingPt[0].pt())
###--------------------------- FILL OTHER MET ------------------------------
customMetFlavor_str = [ 'tkmethemu' , 'h0','gamma','hegammaHF' ]
customMetEtaBinEdge_str = ['m5p0','m3p0','m2p4','m2p1','m1p4','1p4','2p1','2p4','3p0','5p0']
customMetPtBinEdge_str = ['0p0','0p5','1p0','1p5','2p0','3p0','5p0','10p0']
if hasattr(self.cfg_ana,'storeMyCustomMets'):
for particleId in xrange(len(customMetFlavor_str)):
for EtaBinEdge in xrange(len(customMetEtaBinEdge_str)-1):
for PtBinEdge in xrange(len(customMetPtBinEdge_str)):
if( ( ('gamma' is not customMetFlavor_str[particleId]) and ('h0' not in customMetFlavor_str[particleId]) ) and (PtBinEdge > 4) ): continue
if( ('h0' not in customMetFlavor_str[particleId]) and (PtBinEdge > 5) ): continue
# print 'my%sPFmetPt0p0EtaMin%sEtaMax%s'%(customMetFlavor_str[particleId],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1])
fillMET(tr, 'my%sPFmetPt%sEtaMin%sEtaMax%s'%(customMetFlavor_str[particleId],customMetPtBinEdge_str[PtBinEdge],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1]),
self.handles['my%sPFmetPt%sEtaMin%sEtaMax%s'%(customMetFlavor_str[particleId],customMetPtBinEdge_str[PtBinEdge],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1])].product()[0].p4()
)
fill(tr, 'my%sPFmetPt%sEtaMin%sEtaMax%s_sumEt'%(customMetFlavor_str[particleId],customMetPtBinEdge_str[PtBinEdge],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1]),
self.handles['my%sPFmetPt%sEtaMin%sEtaMax%s'%(customMetFlavor_str[particleId],customMetPtBinEdge_str[PtBinEdge],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1])].product()[0].sumEt())
# if('gamma' in customMetFlavor_str[particleId]):
# if('0p5' in customMetPtBinEdge_str[PtBinEdge]):
# print 'my%sPFmetPt%sEtaMin%sEtaMax%s'%(customMetFlavor_str[particleId],customMetPtBinEdge_str[PtBinEdge],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1]),\
# self.handles['my%sPFmetPt%sEtaMin%sEtaMax%s'%(customMetFlavor_str[particleId],customMetPtBinEdge_str[PtBinEdge],customMetEtaBinEdge_str[EtaBinEdge],customMetEtaBinEdge_str[EtaBinEdge+1])].product()[0].sumEt()
# print 'raw',event.pfmetraw.pt(), event.pfmetraw.phi(), event.pfmetraw.sumEt(), \
# 'pfMetForRegression',event.pfMetForRegression.pt(),event.pfMetForRegression.phi(),event.pfMetForRegression.sumEt()
# event.customMetFlavor = [[211], [130], [22] ,[1,2],[11] ,[13]]
# event.customMetPtMin = [0.0, 0.5, 1.0, 1.5, 2.0]
# event.customMetEtaMax = [2.1, 2.5, 3.0, 5.0, 10.0]
# for iFlavor in xrange(len(event.customMetFlavor)):
# for iPtMin in xrange(len(event.customMetPtMin)):
# for jEtaMax in xrange(len(event.customMetEtaMax)):
# fillCustomMET(tr, \
# 'met'+event.customMetFlavor_str[iFlavor]+'Pt'+event.customMetPtMin_str[iPtMin]+\
# 'EtaMin'+event.customMetEtaMin_str[jEtaMax]+'EtaMax'+event.customMetEtaMax_str[jEtaMax], \
# event.customMet[iFlavor][iPtMin][jEtaMax] )
# customMetFlavor_str = [ 'tkmethemu' , 'h0','gamma','egammaHF' ]
# customMetPtMin_str = ['m5p0','m3p0','m2p4','m1p4','1p4','2p4','3p0','5p0']
# customMetEtaMin_str = ['0p0','1p4','2p1','2p5','3p0']
# customMetEtaMax_str = ['1p4','2p1','2p5','3p0','5p0']
# mygammaPFmetPt0p0EtaMin1p4EtaMax2p1
#print 'filling'
self.tree.tree.Fill()
| UTF-8 | Python | false | false | 29,711 | py | 2,731 | ZTreeProducer.py | 2,216 | 0.615159 | 0.596547 | 0 | 459 | 63.71024 | 239 |
GeorgeProjects/MC3-Multispectral | 10,634,339,067,991 | 2aa1a6ad283bfc93445107d954d63f64bea8ca00 | 28db530e6529d776f516db6cf0fa9a47c6e463c5 | /server/app4.py | 71a84fe78c04e8250d07ea10fc5dbb58b2639455 | []
| no_license | https://github.com/GeorgeProjects/MC3-Multispectral | 48831304b86ae132c89e63cd492e46bdf19a37f6 | 84a04d0a5a48f4550529e05f1a2c68832a687c3e | refs/heads/master | 2021-06-21T05:05:21.839234 | 2017-07-30T10:21:47 | 2017-07-30T10:21:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # from flask import Flask, render_template
# app = Flask(__name__)
# @app.route('/')
# def page():
# return render_template('dist/index.html')
# if __name__ == '__main__':
# app.run()
import tornado.ioloop
import tornado.web
import tornado.httpserver
import tornado.options
import os
import sys
import json, ast
from tornado.options import define, options
import tornado.websocket
# from pymongo import MongoClient
# client = MongoClient('192.168.10.9', 27066)
client_file_root_path = os.path.join(os.path.split(__file__)[0],'dist/')
client_file_root_path = os.path.abspath(client_file_root_path)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.content_type = 'application/json'
self.add_header("Access-Control-Allow-Origin", "*")
self.write("Hello, world")
# class AllDataHandler(tornado.web.RequestHandler):
# def post(self):
# self.content_type = 'application/json'
# self.add_header("Access-Control-Allow-Origin", "*")
# databaseName = self.get_argument('databaseName')
# print('...............wsHandler')
# print(databaseName)
# result = queryDatabase(databaseName)
# print(result)
# # self.write('vuex update handler')
# class UpdateMatrixDataHandler(tornado.web.RequestHandler):
# def post(self):
# self.content_type = 'application/json'
# self.add_header("Access-Control-Allow-Origin", "*")
# databaseName = self.get_argument('databaseName')
# imageName = self.get_argument('imageName')
# dataType = self.get_argument('dataType')
# updateData = self.get_argument('updateData')
# collection = databaseName['MatrixData']
# if dataType == 'FeatureData':
# collection.update({'imageName': imageName},{$set:{'featuresArray':updateData}})
# else if dataType == 'EventData':
# collection.update({'imageName': imageName},{$set:{'eventsArrays':updateData}})
# class UpdateVueDataHandler(tornado.web.RequestHandler):
# def post(self):
# self.content_type = 'application/json'
# self.add_header("Access-Control-Allow-Origin", "*")
# databaseName = self.get_argument('databaseName')
# databaseName = self.get_argument('ObjId')
# class QueryHandler(tornado.web.RequestHandler):
# def get(self):
# self.content_type = 'application/json'
# self.add_header("Access-Control-Allow-Origin", "*")
# databaseName = self.get_argument('databaseName')
# result = queryDatabase(databaseName)
# self.write('vuex query handler')
# class InitHandler(tornado.web.RequestHandler):
# def post(self):
# print('init handler')
# self.content_type = 'application/json'
# self.add_header("Access-Control-Allow-Origin", "*")
# databaseName = self.get_argument('databaseName')
# originalData = self.get_argument('originalData')
# db = client['vastchallenge2017mc3']
# print(databaseName)
# collection = db[databaseName]
# print(collection)
# print(originalData)
# print(databaseName)
# print(type(originalData))
# originalData = ast.literal_eval(originalData)
# print('originalData', originalData)
# print('type', type(originalData))
# originalObj = json.loads(originalData)
# print(type(originalObj))
# print('originalObj', originalObj)
# print('array', [originalObj])
# collection.insert_one(originalObj)
# # self.write('vuex query handler')
# class VuexInitHandler(tornado.web.RequestHandler):
# def get(self):
# print('self')
# class ImageMatrixInitHandler(tornado.web.RequestHandler):
# def get(self):
# print('self')
# class ImageMatrixUpdateHandler(tornado.web.RequestHandler):
# def get(self):
# self.write('image matrix update handler')
# class ImageMatrixQueryHandler(tornado.web.RequestHandler):
# def get(self):
# self.write('image matrix query handler')
# def queryDatabase(databaseName):
# db = client['vastchallenge2017mc3']
# collection = db[databaseName]
# cur = collection.find({})
# result = []
# for index in cur:
# del index['_id']
# result.append(index)
# return result
# def writeDatabase(data):
# db = client['vastchallenge2017mc3']
# # collection = db[itemName]
# # cur = collection.insert(data)
# def updateDatabase(databaseName, className, data):
# db = client['vastchallenge2017mc3']
# collection = db[databaseName]
# collection.update({'class': className}, {'$set':{'source': data}})
if __name__ == "__main__":
tornado.options.parse_command_line()
print('server running at 127.0.0.1:%d ...'%(5011))
application = tornado.web.Application([
# (r'/hello', tornado.web.StaticFileHandler, {'path': client_file_root_path, 'default_filename': 'index.html'}), # fetch client files
(r'/api/hello', MainHandler)
# (r'/api/all', AllDataHandler)#,
# (r"/api/update", ImageMatrixInitHandler),
# (r"/api/imageMatrixView/update", ImageMatrixUpdateHandler),
# (r"/api/imageMatrixView/all", ImageMatrixQueryHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(5011, address="127.0.0.1")
tornado.ioloop.IOLoop.current().start()
| UTF-8 | Python | false | false | 5,052 | py | 66 | app4.py | 51 | 0.68943 | 0.678543 | 0 | 145 | 33.841379 | 138 |
royess/intro-computation-materials | 292,057,780,835 | d29162d90303a2043321a31f02cf0d817ace534f | 79b4573ba5b420c961aec157953ce3ca87251042 | /11-19/meili.py | dbddf9a7ddec86750258f999ac151cef511737f8 | []
| no_license | https://github.com/royess/intro-computation-materials | 09e27bab1fc0dec2dc5afb4c8e50147871731bc6 | a3938053d8f61b646cbc29a0de7ef7111575c2e2 | refs/heads/master | 2023-02-04T01:14:03.816562 | 2020-12-17T07:00:10 | 2020-12-17T07:00:10 | 304,322,009 | 3 | 1 | null | false | 2020-11-03T11:05:38 | 2020-10-15T12:39:50 | 2020-10-22T07:59:55 | 2020-11-03T11:05:37 | 170 | 1 | 1 | 0 | Python | false | false | def digits_sum(n):
s = 0
while n!=0:
s += n%10
n //= 10
return s
def k_min_beau(k):
i = 1
n = 1
while i<=k:
if digits_sum(n)==10:
i += 1
n += 9
n -= 9
return n
k = int(input())
print(k_min_beau(k)) | UTF-8 | Python | false | false | 218 | py | 29 | meili.py | 16 | 0.5 | 0.440367 | 0 | 19 | 10.526316 | 23 |
sdpython/_automation | 15,891,379,022,009 | 6f3f1719d8e222962afbd32ae51272eca65da852 | 70293055602fe40451176d8c7f2a06af73fa88ee | /jenkins/start_pypi.py | 1bfa118b8271b9f44c848988af5cf086bad80c01 | []
| no_license | https://github.com/sdpython/_automation | 7cdb99bad563e485ad699e80ceec9bb26d7eb8aa | 7d0fc27b1f584dd324332089deea603d8164f927 | refs/heads/master | 2023-08-25T02:54:43.834619 | 2023-08-22T08:59:05 | 2023-08-22T08:59:05 | 97,163,054 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Start a local pypi server
=========================
This Script launches a :epkg:`pipy` server and leaves
without waiting for the end. It runs the scripts:
::
pypi-server --port=8067 --root=/var/lib/jenkins/workspace/local_pypi/local_pypi_server/
nohup pypi-server --port=8067 --root=/var/lib/jenkins/workspace/local_pypi/local_pypi_server/ > /var/lib/jenkins/workspace/local_pypi/pypi.txt &
"""
#########################################
# import
import os
import sys
from pyquickhelper.loghelper import run_cmd
#########################################
# pypi
pypis = [sys.executable.replace("pythonw", "python")]
pypi = list(filter(lambda p: os.path.exists(p), pypis))
if len(pypi) == 0:
raise FileNotFoundError(
"Unable to find any of\n'{0}'".format("\n".join(pypis)))
pypi = pypi[0]
#########################################
# command line
if sys.platform.startswith("win"):
cmd = '{0} -c "from pypiserver.__main__ import main;main(r\'--port={1} --root={2}\'.split())"'
else:
cmd = "pypi-server --port {1} --root {2}"
#########################################
# parameters
port = "8067"
letter = "d" if os.path.exists("d:") else "c"
paths = ["/var/lib/jenkins/workspace/local_pypi/local_pypi_server/",
letter + r":\jenkins\local_pypi\local_pypi_server",
letter + r":\jenkins\local_pypi_server",
letter + r":\jenkins\local_pypi",
letter + r":\local_pypi\local_pypi_server",
letter + r":\local_pypi",
letter + r":\local_pypi_server",
letter + r":\temp"]
path = list(filter(lambda p: os.path.exists(p), paths))
#########################################
# start pypi
if any(path):
path = path[0]
dest = os.path.normpath(os.path.join(path, "..", "pypi.log.txt"))
cmd = cmd.format(pypi, port, path, dest)
print("cmd '{0}'".format(cmd))
run_cmd(cmd, wait=False, fLOG=print)
else:
print("Unable to find any of\n{0}.".format("\n".join(paths)))
| UTF-8 | Python | false | false | 1,990 | py | 24 | start_pypi.py | 18 | 0.561307 | 0.549246 | 0 | 60 | 32.166667 | 148 |
loveinlastnight/micolog | 10,548,439,695,659 | fe0135bd4a7986ff6cf8e6aa4ad6002d3f875362 | 7dac228a13beba14447e4beaeeea75c9ce617645 | /plugins/xheditor/xheditor.py | 2412f7423c2e1ee6c92ac49a08fe49196c704950 | [
"MIT"
]
| permissive | https://github.com/loveinlastnight/micolog | e4db0a0b88f33dd6d712a0a17fb7cebe52fec5dc | b49bf39bc8870797a49b4dcd3a0a5231cfe984ea | refs/heads/master | 2020-08-06T05:34:15.343160 | 2019-10-05T14:47:46 | 2019-10-05T14:47:46 | 212,854,929 | 0 | 0 | MIT | true | 2019-10-04T16:10:03 | 2019-10-04T16:10:02 | 2019-09-05T03:06:13 | 2012-06-07T15:43:13 | 5,940 | 0 | 0 | 0 | null | false | false | from micolog_plugin import *
import logging,os
from model import *
from google.appengine.api import users
class xheditor(Plugin):
def __init__(self):
Plugin.__init__(self,__file__)
self.author="xuming"
self.authoruri="http://xuming.net"
self.uri="http://xuming.net"
self.description="xheditor."
self.name="xheditor plugin"
self.version="0.1"
self.register_urlzip('/xheditor/(.*)','xheditor.zip')
self.register_filter('editor_header',self.head)
def head(self,content,blog=None,*arg1,**arg2):
if blog.language=='zh_CN':
js='xheditor-zh-cn.js'
else:
js='xheditor-en.js'
sret='''<script type="text/javascript" src="/xheditor/%s"></script>
<script type="text/javascript">
$(function(){
$("#content").xheditor(true,{
upImgUrl:'!/admin/uploadex?ext=jpg|png|jpeg|gif',
upFlashUrl:'!/admin/uploadex?ext=swf',
upMediaUrl:'!/admin/uploadex?ext=wmv|avi|wma|mp3|mid'});
});
</script>'''%js
return sret
def get(self,page):
return '''<h3>xheditor Plugin </h3>
<p>This is a demo for write editor plugin.</p>
<h4>feature</h4>
<p><ol>
<li>Change editor as xheditor.</li>
</ol></p>
'''
| UTF-8 | Python | false | false | 1,196 | py | 32 | xheditor.py | 14 | 0.627926 | 0.620401 | 0 | 44 | 25.181818 | 69 |
wrlssqi/pymap3d | 19,619,410,638,429 | 47d629f45c02d3c3cae04dcfc7e64e4975a80067 | dff3da60503e46e1d4e1c8a1b690ac984f2eec59 | /src/pymap3d/__init__.py | a0bacc74696e55efba1453bed1d94d3dba715e78 | [
"BSD-2-Clause"
]
| permissive | https://github.com/wrlssqi/pymap3d | ad6e1fed83cdbe5ff65f050ac68f2d89bc43d316 | bd91a5ff4e9066eb33fead3006ba9de191e2c5e5 | refs/heads/master | 2023-08-03T17:37:26.148060 | 2021-06-09T19:39:08 | 2021-06-09T19:39:08 | 287,708,941 | 0 | 0 | BSD-2-Clause | true | 2020-08-15T08:35:13 | 2020-08-15T08:35:12 | 2020-08-15T08:33:54 | 2020-07-23T19:35:32 | 1,373 | 0 | 0 | 0 | null | false | false | """
PyMap3D provides coordinate transforms and geodesy functions with a similar API
to the Matlab Mapping Toolbox, but was of course independently derived.
For all functions, the default units are:
distance : float
METERS
angles : float
DEGREES
time : datetime.datetime
UTC time of observation
These functions may be used with any planetary body, provided the appropriate
reference ellipsoid is defined. The default ellipsoid is WGS-84
deg : bool = True means degrees. False = radians.
Most functions accept NumPy arrays of any shape, as well as compatible data types
including AstroPy, Pandas and Xarray that have Numpy-like data properties.
For clarity, we omit all these types in the docs, and just specify the scalar type.
Other languages
---------------
Companion packages exist for:
* Matlab / GNU Octave: [Matmap3D](https://github.com/geospace-code/matmap3d)
* Fortran: [Maptran3D](https://github.com/geospace-code/maptran3d)
"""
from .aer import ecef2aer, aer2ecef, geodetic2aer, aer2geodetic
from .enu import enu2geodetic, geodetic2enu, aer2enu, enu2aer
from .ned import ned2ecef, ned2geodetic, geodetic2ned, ecef2nedv, ned2aer, aer2ned, ecef2ned
from .ecef import (
geodetic2ecef,
ecef2geodetic,
eci2geodetic,
geodetic2eci,
ecef2enuv,
enu2ecef,
ecef2enu,
enu2uvw,
uvw2enu,
)
from .sidereal import datetime2sidereal, greenwichsrt
from .ellipsoid import Ellipsoid
from .timeconv import str2dt
try:
from .azelradec import radec2azel, azel2radec
from .eci import eci2ecef, ecef2eci
from .aer import eci2aer, aer2eci
except ImportError:
from .vallado import radec2azel, azel2radec
| UTF-8 | Python | false | false | 1,661 | py | 3 | __init__.py | 3 | 0.762191 | 0.737508 | 0 | 56 | 28.660714 | 92 |
FXTD-ODYSSEY/vscode-mayapy | 2,473,901,183,307 | 54a43329e94a11b2d456141624df72111aad58da | 395e64776ee7c435e9c8ccea6c2bf0d987770153 | /mayaSDK/pymel/core/general.py | 6e09d114d5c183e7a7d744d23e5acf4c939a97b7 | [
"MIT"
]
| permissive | https://github.com/FXTD-ODYSSEY/vscode-mayapy | e1ba63021a2559287073ca2ddf90b634f95ba7cb | 5766a0bf0a007ca61b8249f7dfb329f1dfcdbfbb | refs/heads/master | 2023-03-07T08:01:27.965144 | 2022-04-02T02:46:31 | 2022-04-02T02:46:31 | 208,568,717 | 29 | 11 | MIT | false | 2023-03-03T06:45:31 | 2019-09-15T09:10:58 | 2023-02-09T07:21:00 | 2023-03-03T06:45:30 | 21,750 | 29 | 6 | 4 | Python | false | false | import exceptions
"""
For the rest of the class hierarchy, including `DependNode <pymel.core.nodetypes.DependNode>`, `Transform <pymel.core.nodetypes.Transform>`,
and `Attribute <pymel.core.nodetypes.Attribute>`, see :mod:`pymel.core.nodetypes`.
"""
from pymel.internal.plogging import getLogger as _getLogger
class ComponentIndex(tuple):
"""
Class used to specify a multi-dimensional component index.
If the length of a ComponentIndex object < the number of dimensions,
then the remaining dimensions are taken to be 'complete' (ie, have not yet
had indices specified).
"""
def __add__(self, other):
pass
def __repr__(self):
pass
def __new__(cls, *args, **kwargs):
"""
:Parameters:
label : `string`
Component label for this index.
Useful for components whose 'mel name' may vary - ie, an isoparm
may be specified as u, v, or uv.
"""
pass
__dict__ = None
class MayaObjectError(exceptions.TypeError):
"""
#--------------------------
# PyNode Exceptions
#--------------------------
"""
def __init__(self, node='None'):
pass
def __str__(self):
pass
__weakref__ = None
class NodeTracker(object):
"""
A class for tracking Maya Objects as they are created and deleted.
Can (and probably should) be used as a context manager
"""
def __enter__(self):
pass
def __exit__(self, exctype, excval, exctb):
pass
def __init__(self):
pass
def endTrack(self):
"""
Stop tracking and remove the callback
"""
pass
def getNodes(self, returnType="'PyNode'"):
"""
Return a list of maya objects as strings.
Parameters
----------
returnType : {'PyNode', 'str', 'MObject'}
"""
pass
def isTracking(self):
"""
Return True/False
"""
pass
def reset(self):
pass
def startTrack(self):
pass
__dict__ = None
__weakref__ = None
import pymel.util as _util
class PyNode(_util.ProxyUnicode):
"""
Abstract class that is base for all pymel nodes classes.
The names of nodes and attributes can be passed to this class, and the appropriate subclass will be determined.
>>> PyNode('persp')
nt.Transform(u'persp')
>>> PyNode('persp.tx')
Attribute(u'persp.translateX')
If the passed node or attribute does not exist an error will be raised.
"""
def __apimfn__(self):
"""
Get a ``maya.OpenMaya*.MFn*`` instance
"""
pass
def __eq__(self, other):
"""
:rtype: `bool`
"""
pass
def __ge__(self, other):
pass
def __getitem__(*args, **kwargs):
"""
The function 'pymel.core.general.PyNode.__getitem__' is deprecated and will become unavailable in future pymel versions. Convert to string first using str() or PyNode.name()
deprecated
"""
pass
def __gt__(self, other):
pass
def __init__(self, *args, **kwargs):
pass
def __le__(self, other):
pass
def __lt__(self, other):
pass
def __melobject__(self):
"""
Special method for returning a mel-friendly representation.
"""
pass
def __ne__(self, other):
"""
:rtype: `bool`
"""
pass
def __nonzero__(self):
"""
:rtype: `bool`
"""
pass
def __radd__(self, other):
pass
def __reduce__(self):
"""
allows PyNodes to be pickled
"""
pass
def __repr__(self):
"""
:rtype: `unicode`
"""
pass
def addPrefix(self, prefix):
"""
Returns the object's name with a prefix added to the beginning of the name
:rtype: `other.NameParser`
"""
pass
def connections(*args, **kwargs):
"""
This command returns a list of all attributes/objects of a specified type that are connected to the given object(s). If
no objects are specified then the command lists the connections on selected nodes.
Modifications:
- returns an empty list when the result is None
- returns an empty list (with a warning) when the arg is an empty list, tuple,
set, or frozenset, making it's behavior consistent with when None is
passed, or no args and nothing is selected (would formerly raise a
TypeError)
- When 'connections' flag is True, the attribute pairs are returned in a 2D-array::
[['checker1.outColor', 'lambert1.color'], ['checker1.color1', 'fractal1.outColor']]
- added sourceFirst keyword arg. when sourceFirst is true and connections is also true,
the paired list of plugs is returned in (source,destination) order instead of (thisnode,othernode) order.
this puts the pairs in the order that disconnectAttr and connectAttr expect.
- added ability to pass a list of types
:rtype: `PyNode` list
Flags:
- connections : c (bool) [create]
If true, return both attributes involved in the connection. The one on the specified object is given first. Default
false.
- destination : d (bool) [create]
Give the attributes/objects that are on the destinationside of connection to the given object. Default true.
- exactType : et (bool) [create]
When set to true, -t/type only considers node of this exact type. Otherwise, derived types are also taken into account.
- plugs : p (bool) [create]
If true, return the connected attribute names; if false, return the connected object names only. Default false;
- shapes : sh (bool) [create]
Actually return the shape name instead of the transform when the shape is selected. Default false.
- skipConversionNodes : scn (bool) [create]
If true, skip over unit conversion nodes and return the node connected to the conversion node on the other side.
Default false.
- source : s (bool) [create]
Give the attributes/objects that are on the sourceside of connection to the given object. Default true.
- type : t (unicode) [create]
If specified, only take objects of a specified type. Flag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.listConnections`
"""
pass
def deselect(self):
pass
def exists(self, **kwargs):
"""
objExists
"""
pass
def future(*args, **kwargs):
"""
Modifications:
- returns an empty list when the result is None
- added a much needed 'type' filter
- added an 'exactType' filter (if both 'exactType' and 'type' are present, 'type' is ignored)
:rtype: `DependNode` list
"""
pass
def history(*args, **kwargs):
"""
This command traverses backwards or forwards in the graph from the specified node and returns all of the nodes whose
construction history it passes through. The construction history consists of connections to specific attributes of a
node defined as the creators and results of the node's main data, eg. the curve for a Nurbs Curve node. For information
on history connections through specific plugs use the listConnectionscommand first to find where the history begins then
use this command on the resulting node.
Modifications:
- returns an empty list when the result is None
- raises a RuntimeError when the arg is an empty list, tuple, set, or
frozenset, making it's behavior consistent with when None is passed, or
no args and nothing is selected (would formerly raise a TypeError)
- added a much needed 'type' filter
- added an 'exactType' filter (if both 'exactType' and 'type' are present, 'type' is ignored)
:rtype: `DependNode` list
Flags:
- allConnections : ac (bool) [create]
If specified, the traversal that searches for the history or future will not restrict its traversal across nodes to only
dependent plugs. Thus it will reach all upstream nodes (or all downstream nodes for f/future).
- allFuture : af (bool) [create]
If listing the future, list all of it. Otherwise if a shape has an attribute that represents its output geometry data,
and that plug is connected, only list the future history downstream from that connection.
- allGraphs : ag (bool) [create]
This flag is obsolete and has no effect.
- breadthFirst : bf (bool) [create]
The breadth first traversal will return the closest nodes in the traversal first. The depth first traversal will follow
a complete path away from the node, then return to any other paths from the node. Default is depth first.
- future : f (bool) [create]
List the future instead of the history.
- futureLocalAttr : fl (bool) [query]
This flag allows querying of the local-space future-related attribute(s) on shape nodes.
- futureWorldAttr : fw (bool) [query]
This flag allows querying of the world-space future-related attribute(s) on shape nodes.
- groupLevels : gl (bool) [create]
The node names are grouped depending on the level. 1 is the lead, the rest are grouped with it.
- historyAttr : ha (bool) [query]
This flag allows querying of the attribute where history connects on shape nodes.
- interestLevel : il (int) [create]
If this flag is set, only nodes whose historicallyInteresting attribute value is not less than the value will be listed.
The historicallyInteresting attribute is 0 on nodes which are not of interest to non-programmers. 1 for the TDs, 2 for
the users.
- leaf : lf (bool) [create]
If transform is selected, show history for its leaf shape. Default is true.
- levels : lv (int) [create]
Levels deep to traverse. Setting the number of levels to 0 means do all levels. All levels is the default.
- pruneDagObjects : pdo (bool) [create]
If this flag is set, prune at dag objects. Flag can have multiple arguments, passed either as a tuple
or a list.
Derived from mel command `maya.cmds.listHistory`
"""
pass
def listConnections(*args, **kwargs):
"""
This command returns a list of all attributes/objects of a specified type that are connected to the given object(s). If
no objects are specified then the command lists the connections on selected nodes.
Modifications:
- returns an empty list when the result is None
- returns an empty list (with a warning) when the arg is an empty list, tuple,
set, or frozenset, making it's behavior consistent with when None is
passed, or no args and nothing is selected (would formerly raise a
TypeError)
- When 'connections' flag is True, the attribute pairs are returned in a 2D-array::
[['checker1.outColor', 'lambert1.color'], ['checker1.color1', 'fractal1.outColor']]
- added sourceFirst keyword arg. when sourceFirst is true and connections is also true,
the paired list of plugs is returned in (source,destination) order instead of (thisnode,othernode) order.
this puts the pairs in the order that disconnectAttr and connectAttr expect.
- added ability to pass a list of types
:rtype: `PyNode` list
Flags:
- connections : c (bool) [create]
If true, return both attributes involved in the connection. The one on the specified object is given first. Default
false.
- destination : d (bool) [create]
Give the attributes/objects that are on the destinationside of connection to the given object. Default true.
- exactType : et (bool) [create]
When set to true, -t/type only considers node of this exact type. Otherwise, derived types are also taken into account.
- plugs : p (bool) [create]
If true, return the connected attribute names; if false, return the connected object names only. Default false;
- shapes : sh (bool) [create]
Actually return the shape name instead of the transform when the shape is selected. Default false.
- skipConversionNodes : scn (bool) [create]
If true, skip over unit conversion nodes and return the node connected to the conversion node on the other side.
Default false.
- source : s (bool) [create]
Give the attributes/objects that are on the sourceside of connection to the given object. Default true.
- type : t (unicode) [create]
If specified, only take objects of a specified type. Flag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.listConnections`
"""
pass
def listFuture(*args, **kwargs):
"""
Modifications:
- returns an empty list when the result is None
- added a much needed 'type' filter
- added an 'exactType' filter (if both 'exactType' and 'type' are present, 'type' is ignored)
:rtype: `DependNode` list
"""
pass
def listHistory(*args, **kwargs):
"""
This command traverses backwards or forwards in the graph from the specified node and returns all of the nodes whose
construction history it passes through. The construction history consists of connections to specific attributes of a
node defined as the creators and results of the node's main data, eg. the curve for a Nurbs Curve node. For information
on history connections through specific plugs use the listConnectionscommand first to find where the history begins then
use this command on the resulting node.
Modifications:
- returns an empty list when the result is None
- raises a RuntimeError when the arg is an empty list, tuple, set, or
frozenset, making it's behavior consistent with when None is passed, or
no args and nothing is selected (would formerly raise a TypeError)
- added a much needed 'type' filter
- added an 'exactType' filter (if both 'exactType' and 'type' are present, 'type' is ignored)
:rtype: `DependNode` list
Flags:
- allConnections : ac (bool) [create]
If specified, the traversal that searches for the history or future will not restrict its traversal across nodes to only
dependent plugs. Thus it will reach all upstream nodes (or all downstream nodes for f/future).
- allFuture : af (bool) [create]
If listing the future, list all of it. Otherwise if a shape has an attribute that represents its output geometry data,
and that plug is connected, only list the future history downstream from that connection.
- allGraphs : ag (bool) [create]
This flag is obsolete and has no effect.
- breadthFirst : bf (bool) [create]
The breadth first traversal will return the closest nodes in the traversal first. The depth first traversal will follow
a complete path away from the node, then return to any other paths from the node. Default is depth first.
- future : f (bool) [create]
List the future instead of the history.
- futureLocalAttr : fl (bool) [query]
This flag allows querying of the local-space future-related attribute(s) on shape nodes.
- futureWorldAttr : fw (bool) [query]
This flag allows querying of the world-space future-related attribute(s) on shape nodes.
- groupLevels : gl (bool) [create]
The node names are grouped depending on the level. 1 is the lead, the rest are grouped with it.
- historyAttr : ha (bool) [query]
This flag allows querying of the attribute where history connects on shape nodes.
- interestLevel : il (int) [create]
If this flag is set, only nodes whose historicallyInteresting attribute value is not less than the value will be listed.
The historicallyInteresting attribute is 0 on nodes which are not of interest to non-programmers. 1 for the TDs, 2 for
the users.
- leaf : lf (bool) [create]
If transform is selected, show history for its leaf shape. Default is true.
- levels : lv (int) [create]
Levels deep to traverse. Setting the number of levels to 0 means do all levels. All levels is the default.
- pruneDagObjects : pdo (bool) [create]
If this flag is set, prune at dag objects. Flag can have multiple arguments, passed either as a tuple
or a list.
Derived from mel command `maya.cmds.listHistory`
"""
pass
def listSets(self, *args, **kwargs):
"""
Returns list of sets this object belongs
listSets -o $this
:rtype: 'PyNode' list
"""
pass
def namespaceList(self):
"""
Useful for cascading references. Returns all of the namespaces of the calling object as a list
:rtype: `unicode` list
"""
pass
def nodeType(*args, **kwargs):
pass
def objExists(self, **kwargs):
"""
objExists
"""
pass
def select(self, **kwargs):
pass
def stripNamespace(self, *args, **kwargs):
"""
Returns the object's name with its namespace removed. The calling instance is unaffected.
The optional levels keyword specifies how many levels of cascading namespaces to strip, starting with the topmost (leftmost).
The default is 0 which will remove all namespaces.
:rtype: `other.NameParser`
"""
pass
def swapNamespace(self, prefix):
"""
Returns the object's name with its current namespace replaced with the provided one.
The calling instance is unaffected.
:rtype: `other.NameParser`
"""
pass
def __new__(cls, *args, **kwargs):
"""
Catch all creation for PyNode classes, creates correct class depending on type passed.
For nodes:
MObject
MObjectHandle
MDagPath
string/unicode
For attributes:
MPlug
MDagPath, MPlug
string/unicode
"""
pass
__apiobjects__ = {}
class AmbiguityWarning(exceptions.Warning):
__weakref__ = None
class Scene(object):
"""
The Scene class provides an attribute-based method for retrieving `PyNode` instances of
nodes in the current scene.
>>> SCENE = Scene()
>>> SCENE.persp
nt.Transform(u'persp')
>>> SCENE.persp.t
Attribute(u'persp.translate')
An instance of this class is provided for you with the name `SCENE`.
"""
def __getattr__(self, obj):
pass
def __init__(self, *p, **k):
pass
def __new__(cls, *p, **k):
"""
# redefine __new__
"""
pass
__dict__ = None
__weakref__ = None
class ProxySlice(object):
"""
slice(stop)
slice(start, stop[, step])
Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).
"""
def __cmp__(self, *args, **kwargs):
"""
x.__cmp__(y) <==> cmp(x,y)
"""
pass
def __delattr__(self, *args, **kwargs):
"""
x.__delattr__('name') <==> del x.name
"""
pass
def __format__(self, *args, **kwargs):
"""
default object formatter
"""
pass
def __hash__(self, *args, **kwargs):
"""
x.__hash__() <==> hash(x)
"""
pass
def __init__(self, *args, **kwargs):
pass
def __repr__(self, *args, **kwargs):
"""
x.__repr__() <==> repr(x)
"""
pass
def __str__(self, *args, **kwargs):
"""
x.__str__() <==> str(x)
"""
pass
def indices(self, *args, **kwargs):
"""
S.indices(len) -> (start, stop, stride)
Assuming a sequence of length len, calculate the start and stop
indices, and the stride length of the extended slice described by
S. Out of bounds indices are clipped in a manner consistent with the
handling of normal slices.
"""
pass
start = None
step = None
stop = None
__dict__ = None
__weakref__ = None
class Component(PyNode):
"""
Abstract base class for pymel components.
"""
def __apicomponent__(self):
pass
def __apihandle__(self):
pass
def __apimdagpath__(self):
"""
Return the MDagPath for the node of this component, if it is valid
"""
pass
def __apimfn__(self):
pass
def __apimobject__(self):
"""
get the MObject for this component if it is valid
"""
pass
def __apiobject__(self):
pass
def __eq__(self, other):
pass
def __init__(self, *args, **kwargs):
pass
def __melobject__(self):
pass
def __nonzero__(self):
"""
:rtype: `bool`
"""
pass
def __str__(self):
pass
def __unicode__(self):
pass
def isComplete(self, *args, **kwargs):
pass
def name(self):
pass
def namespace(self, *args, **kwargs):
pass
def node(self):
pass
def plugAttr(self):
pass
def plugNode(self):
pass
def numComponentsFromStrings(*componentStrings):
"""
Does basic string processing to count the number of components
given a number of strings, which are assumed to be the valid mel names
of components.
"""
pass
__readonly__ = {}
class MayaAttributeError(MayaObjectError, exceptions.AttributeError):
pass
class AttributeDefaults(PyNode):
def __apimdagpath__(self):
"""
Return the MDagPath for the node of this attribute, if it is valid
"""
pass
def __apimobject__(self):
"""
Return the MObject for this attribute, if it is valid
"""
pass
def __apimplug__(self):
"""
Return the MPlug for this attribute, if it is valid
"""
pass
def __apiobject__(self):
"""
Return the default API object for this attribute, if it is valid
"""
pass
def accepts(self, type):
"""
Returns true if this attribute can accept a connection of the given type.
:Parameters:
type : `Data.Type`
data type
values: 'numeric', 'plugin', 'pluginGeometry', 'string', 'matrix', 'stringArray', 'doubleArray', 'floatArray', 'intArray', 'pointArray', 'vectorArray', 'matrixArray', 'componentList', 'mesh', 'lattice', 'nurbsCurve', 'nurbsSurface', 'sphere', 'dynArrayAttrs', 'dynSweptGeometry', 'subdSurface', 'NObject', 'NId', 'any'
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnData.accepts`
"""
pass
def addToCategory(self, category):
"""
Add the attribute to the named category.
:Parameters:
category : `unicode`
New category to which the attribute is to be added
Derived from api method `maya.OpenMaya.MFnAttribute.addToCategory`
**Undo is not currently supported for this method**
"""
pass
def getAddAttrCmd(self, useLongName='False'):
"""
Returns a string containing the addAttr command which would be required to recreate the attribute on a node. The command includes the terminating semicolon and is formatted as if for use with a selected node, meaning that it contains no node name.
:Parameters:
useLongName : `bool`
if true, use the attribute's long name rather than its short name
:rtype: `unicode`
Derived from api method `maya.OpenMaya.MFnAttribute.getAddAttrCmd`
"""
pass
def getAffectsAppearance(self):
"""
Returns true if this attribute affects the appearance of the object when rendering in the viewport.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.affectsAppearance`
"""
pass
def getCategories(self):
"""
Get all of the categories to which this attribute belongs.
:rtype: `list` list
Derived from api method `maya.OpenMaya.MFnAttribute.getCategories`
"""
pass
def getDisconnectBehavior(self):
"""
Returns the behavior of this attribute when it is disconnected. The possible settings are as follows:
:rtype: `AttributeDefaults.DisconnectBehavior`
Derived from api method `maya.OpenMaya.MFnAttribute.disconnectBehavior`
"""
pass
def getIndexMatters(self):
"""
Determines whether the user must specify an index when connecting to this attribute, or whether the next available index can be used. This method only applies to array attributes which are non readable, i.e. destination attributes.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.indexMatters`
"""
pass
def getInternal(self):
"""
Returns true if a node has internal member data representing this attribute.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.internal`
"""
pass
def getUsesArrayDataBuilder(self):
"""
Returns true if this attribute uses an array data builder. If so, then the MArrayDataBuilder class may be used with this attribute.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.usesArrayDataBuilder`
"""
pass
def hasCategory(self, category):
"""
Check to see if the attribute belongs to the named category.
:Parameters:
category : `unicode`
Category to check for attribute membership
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.hasCategory`
"""
pass
def isAffectsWorldSpace(self):
"""
Returns true if this attribute affects worldspace.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isAffectsWorldSpace`
"""
pass
def isArray(self):
"""
Returns true if this attribute supports an array of data.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isArray`
"""
pass
def isCached(self):
"""
Returns true if this attribute is cached locally in the node's data block. The default for this is true. Caching a node locally causes a copy of the attribute value for the node to be cached with the node. This removes the need to traverse through the graph to get the value each time it is requested.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isCached`
"""
pass
def isChannelBoxFlagSet(self):
"""
Returns true if this attribute has its channel box flag set. Attributes will appear in the channel box if their channel box flag is set or if they are keyable.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isChannelBoxFlagSet`
"""
pass
def isConnectable(self):
"""
Returns true if this attribute accepts dependency graph connections. If it does, then the readable and writable methods will indicate what types of connections are accepted.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isConnectable`
"""
pass
def isDynamic(self):
"""
Returns true if this attribute is a dynamic attribute.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isDynamic`
"""
pass
def isExtension(self):
"""
Returns true if this attribute is an extension attribute.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isExtension`
"""
pass
def isHidden(self):
"""
Returns true if this attribute is to hidden from the UI. The attribute will not show up in attribute editors.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isHidden`
"""
pass
def isIndeterminant(self):
"""
Returns true if this attribute is indeterminant. If an attribute may or may not be used during an evaluation then it is indeterminant. This attribute classification is mainly used on rendering nodes to indicate that some attributes are not always used.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isIndeterminant`
"""
pass
def isKeyable(self):
"""
Returns true if this attribute is keyable. Keyable attributes will be keyed by AutoKey and the Set Keyframe UI. Non-keyable attributes prevent the user from setting keys via the obvious UI provided for keying. Being non-keyable is not a hard block against adding keys to an attribute.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isKeyable`
"""
pass
def isReadable(self):
"""
Returns true if this attribute is readable. If an attribute is readable, then it can be used as the source in a dependency graph connection.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isReadable`
"""
pass
def isRenderSource(self):
"""
Returns true if this attribute is a render source. This attribute is used on rendering nodes to override the rendering sampler info.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isRenderSource`
"""
pass
def isStorable(self):
"""
Returns true if this attribute is to be stored when the node is saved to a file.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isStorable`
"""
pass
def isUsedAsColor(self):
"""
Returns true if this attribute is to be presented as a color in the UI.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isUsedAsColor`
"""
pass
def isUsedAsFilename(self):
"""
Returns true if this attribute is to be used as a filename. In the UI this attr will be presented as a file name.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isUsedAsFilename`
"""
pass
def isWorldSpace(self):
"""
Returns true if this attribute is worldspace.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isWorldSpace`
"""
pass
def isWritable(self):
"""
Returns true if this attribute is writable. If an attribute is writable, then it can be used as the destination in a dependency graph connection.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MFnAttribute.isWritable`
"""
pass
def name(self):
pass
def parent(self):
"""
Get the parent of this attribute, if it has one.
:rtype: `PyNode`
Derived from api method `maya.OpenMaya.MFnAttribute.parent`
"""
pass
def removeFromCategory(self, category):
"""
Remove the attribute from the named category.
:Parameters:
category : `unicode`
Category from which the attribute is to be removed
Derived from api method `maya.OpenMaya.MFnAttribute.removeFromCategory`
**Undo is not currently supported for this method**
"""
pass
def setAffectsAppearance(self, state):
"""
Sets whether this attribute affects the appearance of the object when rendering in the viewport.
:Parameters:
state : `bool`
whether the attribute affects the appearance of the object when rendering in the viewport.
Derived from api method `maya.OpenMaya.MFnAttribute.setAffectsAppearance`
"""
pass
def setAffectsWorldSpace(self, state):
"""
Sets whether this attribute should affect worldspace. NOTES: This property is ignored on non-dag nodes.
:Parameters:
state : `bool`
whether the attribute should affect worldspace
Derived from api method `maya.OpenMaya.MFnAttribute.setAffectsWorldSpace`
"""
pass
def setArray(self, state):
"""
Sets whether this attribute should have an array of data. This should be set to true if the attribute needs to accept multiple incoming connections.
:Parameters:
state : `bool`
whether the attribute is to have an array of data
Derived from api method `maya.OpenMaya.MFnAttribute.setArray`
"""
pass
def setCached(self, state):
"""
Sets whether the data for this attribute is cached locally in the node's data block. The default for this is true. Caching a node locally causes a copy of the attribute value for the node to be cached with the node. This removes the need to traverse through the graph to get the value each time it is requested. This should only get called in the initialize call of your node creator.
:Parameters:
state : `bool`
whether the attribute is to be cached locally
Derived from api method `maya.OpenMaya.MFnAttribute.setCached`
"""
pass
def setChannelBox(self, state):
"""
Sets whether this attribute should appear in the channel box when the node is selected. This should only get called in the initialize call of your node creator. Keyable attributes are always shown in the channel box so this flag is ignored on keyable attributes. It is for intended for use on non-keyable attributes which you want to appear in the channel box.
:Parameters:
state : `bool`
whether the attribute is to appear in the channel box
Derived from api method `maya.OpenMaya.MFnAttribute.setChannelBox`
**Undo is not currently supported for this method**
"""
pass
def setConnectable(self, state):
"""
Sets whether this attribute should allow dependency graph connections. This should only get called in the initialize call of your node creator.
:Parameters:
state : `bool`
whether the attribute is to be connectable
Derived from api method `maya.OpenMaya.MFnAttribute.setConnectable`
"""
pass
def setDisconnectBehavior(self, behavior):
"""
Sets the disconnection behavior for this attribute. This determines what happens when a connection to this attribute is deleted. This should only get called in the initialize call of your node creator.
:Parameters:
behavior : `AttributeDefaults.DisconnectBehavior`
the new disconnect behavior
values: 'delete', 'reset', 'nothing'
Derived from api method `maya.OpenMaya.MFnAttribute.setDisconnectBehavior`
"""
pass
def setHidden(self, state):
"""
Sets whether this attribute should be hidden from the UI. This is useful if the attribute is being used for blind data, or if it is being used as scratch space for a geometry calculation (should also be marked non-connectable in that case).
:Parameters:
state : `bool`
whether the attribute is to be hidden
Derived from api method `maya.OpenMaya.MFnAttribute.setHidden`
"""
pass
def setIndeterminant(self, state):
"""
Sets whether this attribute is indeterminant. If an attribute may or may not be used during an evaluation then it is indeterminant. This attribute classification is mainly used on rendering nodes to indicate that some attributes are not always used.
:Parameters:
state : `bool`
whether the attribute indeterminant
Derived from api method `maya.OpenMaya.MFnAttribute.setIndeterminant`
"""
pass
def setIndexMatters(self, state):
"""
If the attribute is an array, then this method specifies whether to force the user to specify an index when connecting to this attribute, or to use the next available index.
:Parameters:
state : `bool`
whether the attribute's index must be specified when connecting to this attribute using the connectAttr command
Derived from api method `maya.OpenMaya.MFnAttribute.setIndexMatters`
"""
pass
def setInternal(self, state):
"""
The function controls an attribute's data storage. When set to true, the virtual methods MPxNode::setInternalValueInContext() and MPxNode::getInternalValueInContext() are invoked whenever the attribute value is set or queried, respectively. By default, attributes are not internal.
:Parameters:
state : `bool`
whether the attribute uses internal data
Derived from api method `maya.OpenMaya.MFnAttribute.setInternal`
"""
pass
def setKeyable(self, state):
"""
Sets whether this attribute should accept keyframe data. This should only get called in the initialize call of your node creator. Keyable attributes will be keyed by AutoKey and the Set Keyframe UI. Non-keyable attributes prevent the user from setting keys via the obvious UI provided for keying. Being non-keyable is not a hard block against adding keys to an attribute.
:Parameters:
state : `bool`
whether the attribute is to be keyable
Derived from api method `maya.OpenMaya.MFnAttribute.setKeyable`
"""
pass
def setNiceNameOverride(self, localizedName):
"""
Sets the localized string which should be used for this attribute in the UI.
:Parameters:
localizedName : `unicode`
The name to use for the current locale.
Derived from api method `maya.OpenMaya.MFnAttribute.setNiceNameOverride`
**Undo is not currently supported for this method**
"""
pass
def setReadable(self, state):
"""
Sets whether this attribute should be readable. If an attribute is readable, then it can be used as the source in a dependency graph connection.
:Parameters:
state : `bool`
whether the attribute is to be readable
Derived from api method `maya.OpenMaya.MFnAttribute.setReadable`
"""
pass
def setRenderSource(self, state):
"""
Sets whether this attribute should be used as a render source attribute. When writing shader plug-ins, it is sometimes useful to be able to modify the sampler info, so upstream shading network can be re- evaluated with different sampler info values.
:Parameters:
state : `bool`
whether the attribute is to be a render source
Derived from api method `maya.OpenMaya.MFnAttribute.setRenderSource`
"""
pass
def setStorable(self, state):
"""
Sets whether this attribute should be storable. If an attribute is storable, then it will be writen out when the node is stored to a file. This should only get called in the initialize call of your node creator.
:Parameters:
state : `bool`
whether the attribute is to be storable
Derived from api method `maya.OpenMaya.MFnAttribute.setStorable`
"""
pass
def setUsedAsColor(self, state):
"""
Sets whether this attribute should be presented as a color in the UI.
:Parameters:
state : `bool`
whether the attribute is to be presented as a color
Derived from api method `maya.OpenMaya.MFnAttribute.setUsedAsColor`
"""
pass
def setUsedAsFilename(self, state):
"""
Sets whether this attribute should be presented as a filename in the UI.
:Parameters:
state : `bool`
whether the attribute is to be presented as a filename
Derived from api method `maya.OpenMaya.MFnAttribute.setUsedAsFilename`
"""
pass
def setUsesArrayDataBuilder(self, state):
"""
Sets whether this attribute uses an array data builder. If true, then the MArrayDataBuilder class may be used with this attribute to generate its data. If false, MArrayDataHandle::builder will fail.
:Parameters:
state : `bool`
whether the attribute uses an array data builder
Derived from api method `maya.OpenMaya.MFnAttribute.setUsesArrayDataBuilder`
"""
pass
def setWorldSpace(self, state):
"""
Sets whether this attribute should be treated as worldspace. Being worldspace indicates the attribute is dependent on the worldSpace transformation of this node, and will be marked dirty by any attribute changes in the hierarchy that affects the worldSpace transformation. The attribute needs to be an array since during instancing there are multiple worldSpace paths to the node & Maya requires one array element per path for worldSpace attributes.
:Parameters:
state : `bool`
whether the attribute is to be presented as worldspace
Derived from api method `maya.OpenMaya.MFnAttribute.setWorldSpace`
"""
pass
def setWritable(self, state):
"""
Sets whether this attribute should be writable. If an attribute is writable, then it can be used as the destination in a dependency graph connection. If an attribute is not writable then setAttr commands will fail to change the attribute.
:Parameters:
state : `bool`
whether the attribute is to be writable
Derived from api method `maya.OpenMaya.MFnAttribute.setWritable`
"""
pass
def shortName(self):
"""
Returns the short name of the attribute. If the attribute has no short name then its long name is returned.
:rtype: `unicode`
Derived from api method `maya.OpenMaya.MFnAttribute.shortName`
"""
pass
DisconnectBehavior = {}
__apicls__ = None
__readonly__ = {}
class HashableSlice(ProxySlice):
"""
# Really, don't need to have another class inheriting from
# the proxy class, but do this so I can define a method using
# normal class syntax...
"""
def __cmp__(self, other):
pass
def __hash__(self):
pass
def __init__(self, *args, **kwargs):
pass
start = None
step = None
stop = None
class MayaNodeError(MayaObjectError):
pass
class Attribute(PyNode):
"""
Attribute class
see pymel docs for details on usage
"""
def __apimattr__(self):
"""
Return the MFnAttribute for this attribute, if it is valid
"""
pass
def __apimdagpath__(self):
"""
Return the MDagPath for the node of this attribute, if it is valid
"""
pass
def __apimobject__(self):
"""
Return the MObject for this attribute, if it is valid
"""
pass
def __apimplug__(self):
"""
Return the MPlug for this attribute, if it is valid
"""
pass
def __apiobject__(self):
"""
Return the default API object (MPlug) for this attribute, if it is valid
"""
pass
def __call__(self, *args, **kwargs):
pass
def __delitem__(self, index='None', break_='False'):
pass
def __eq__(self, other):
"""
:rtype: `bool`
"""
pass
def __floordiv__(self, other):
"""
operator for 'disconnectAttr'
>>> from pymel.core import *
>>> SCENE.persp.tx >> SCENE.top.tx # connect
>>> SCENE.persp.tx // SCENE.top.tx # disconnect
"""
pass
def __getattr__(self, attr):
pass
def __getitem__(self, index):
"""
This method will find and return a plug with the given logical index. The logical index is the sparse array index used in MEL scripts. If a plug does not exist at the given Index, Maya will create a plug at that index. This is not the case with elementByPhysicalIndex() . If needed, elementByLogicalIndex can be used to expand an array plug on a node. It is important to note that Maya assumes that all such plugs serve a purpose and it will not free non-networked plugs that result from such an array expansion.
:Parameters:
index : `int`
The index of the plug to be found
:rtype: `PyNode`
Derived from api method `maya.OpenMaya.MPlug.elementByLogicalIndex`
"""
pass
def __hash__(self):
"""
:rtype: `int`
"""
pass
def __iter__(self):
"""
iterator for multi-attributes
>>> from pymel.core import *
>>> f=newFile(f=1) #start clean
>>>
>>> at = PyNode( 'defaultLightSet.dagSetMembers' )
>>> nt.SpotLight()
nt.SpotLight(u'spotLightShape1')
>>> nt.SpotLight()
nt.SpotLight(u'spotLightShape2')
>>> nt.SpotLight()
nt.SpotLight(u'spotLightShape3')
>>> for x in at: print x
...
defaultLightSet.dagSetMembers[0]
defaultLightSet.dagSetMembers[1]
defaultLightSet.dagSetMembers[2]
"""
pass
def __ne__(self, other):
"""
:rtype: `bool`
"""
pass
def __rshift__(self, other):
"""
operator for 'connectAttr'
>>> from pymel.core import *
>>> SCENE.persp.tx >> SCENE.top.tx # connect
>>> SCENE.persp.tx // SCENE.top.tx # disconnect
"""
pass
def __str__(self):
"""
:rtype: `str`
"""
pass
def __unicode__(self):
"""
:rtype: `unicode`
"""
pass
def affected(self, **kwargs):
pass
def affects(self, **kwargs):
pass
def array(self):
"""
Returns the array (multi) attribute of the current element:
>>> n = Attribute(u'initialShadingGroup.groupNodes[0]')
>>> n.isElement()
True
>>> n.array()
Attribute(u'initialShadingGroup.groupNodes')
This method will raise an error for attributes which are not elements of
an array:
>>> m = Attribute(u'initialShadingGroup.groupNodes')
>>> m.isElement()
False
>>> m.array()
Traceback (most recent call last):
...
TypeError: initialShadingGroup.groupNodes is not an array (multi) attribute
:rtype: `Attribute`
"""
pass
def attr(self, attr):
"""
:rtype: `Attribute`
"""
pass
def attrName(self, longName='False', includeNode='False'):
"""
Just the name of the attribute for this plug
This will have no indices, no parent attributes, etc...
This is suitable for use with cmds.attributeQuery
>>> at = SCENE.persp.instObjGroups.objectGroups
>>> at.name()
u'persp.instObjGroups[-1].objectGroups'
>>> at.attrName()
u'og'
>>> at.attrName(longName=True)
u'objectGroups'
"""
pass
def children(self):
"""
attributeQuery -listChildren
:rtype: `Attribute` list
"""
pass
def connect(source, destination, **kwargs):
"""
Connect the attributes of two dependency nodes and return the names of the two connected attributes. The connected
attributes must be be of compatible types. First argument is the source attribute, second one is the destination. Refer
to dependency node documentation.
Maya Bug Fix:
- even with the 'force' flag enabled, the command would raise an error if the connection already existed.
Flags:
- force : f (bool) [create]
Forces the connection. If the destination is already connected, the old connection is broken and the new one made.
- lock : l (bool) [create]
If the argument is true, the destination attribute is locked after making the connection. If the argument is false, the
connection is unlocked before making the connection.
- nextAvailable : na (bool) [create]
If the destination multi-attribute has set the indexMatters to be false with this flag specified, a connection is made
to the next available index. No index need be specified.
- referenceDest : rd (unicode) [create]
This flag is used for file io only. The flag indicates that the connection replaces a connection made in a referenced
file, and the flag argument indicates the original destination from the referenced file. This flag is used so that if
the reference file is modified, maya can still attempt to make the appropriate connections in the main scene to the
referenced object. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.connectAttr`
"""
pass
def delete(self):
"""
deleteAttr
"""
pass
def disconnect(source, destination='None', inputs='None', outputs='None', **kwargs):
"""
Disconnects two connected attributes. First argument is the source attribute, second is the destination.
Modifications:
- If no destination is passed, then all inputs will be disconnected if inputs
is True, and all outputs will be disconnected if outputs is True; if
neither are given (or both are None), both all inputs and all outputs
will be disconnected
Flags:
- nextAvailable : na (bool) [create]
If the destination multi-attribute has set the indexMatters to be false, the command will disconnect the first matching
connection. No index needs to be specified. Flag can have multiple arguments, passed either as a tuple
or a list.
Derived from mel command `maya.cmds.disconnectAttr`
"""
pass
def elementByLogicalIndex(self, index):
"""
This method will find and return a plug with the given logical index. The logical index is the sparse array index used in MEL scripts. If a plug does not exist at the given Index, Maya will create a plug at that index. This is not the case with elementByPhysicalIndex() . If needed, elementByLogicalIndex can be used to expand an array plug on a node. It is important to note that Maya assumes that all such plugs serve a purpose and it will not free non-networked plugs that result from such an array expansion.
:Parameters:
index : `int`
The index of the plug to be found
:rtype: `PyNode`
Derived from api method `maya.OpenMaya.MPlug.elementByLogicalIndex`
"""
pass
def elementByPhysicalIndex(self, index):
"""
This method will find and return a plug with the given physical index. The index can range from 0 to numElements() - 1. This function is particularly useful for iteration through the element plugs of an array plug. It is equivalent to operator [] (int) This method is only valid for array plugs.
:Parameters:
index : `int`
The physical array index of the plug to be found
:rtype: `PyNode`
Derived from api method `maya.OpenMaya.MPlug.elementByPhysicalIndex`
"""
pass
def elements(self):
"""
``listAttr -multi``
Return a list of strings representing all the attributes in the array.
If you don't need actual strings, it is recommended that you simply iterate through the elements in the array.
See `Attribute.__iter__`.
Modifications:
- returns an empty list when the result is None
"""
pass
def evaluate(self, **kwargs):
pass
def evaluateNumElements(self):
"""
Return the total number of elements in the datablock of this array plug. The return count will include both connected and non-connected elements, and will perform an evaluate in order to make sure that the datablock is as up-to-date as possible since some nodes do not place array elements into the datablock until the attribute is evaluated.
:rtype: `int`
Derived from api method `maya.OpenMaya.MPlug.evaluateNumElements`
"""
pass
def exists(self):
"""
Whether the attribute actually exists.
In spirit, similar to 'attributeQuery -exists'...
...however, also handles multi (array) attribute elements, such as plusMinusAverage.input1D[2]
:rtype: `bool`
"""
pass
def firstParent(*args, **kwargs):
"""
The function 'pymel.core.general.Attribute.firstParent' is deprecated and will become unavailable in future pymel versions. use Attribute.getParent instead
deprecated: use getParent instead
"""
pass
def get(attr, default='None', **kwargs):
"""
This command returns the value of the named object's attribute. UI units are used where applicable. Currently, the types
of attributes that can be displayed are: numeric attributesstring attributesmatrix attributesnumeric compound attributes
(whose children are all numeric)vector array attributesdouble array attributesint32 array attributespoint array
attributesdata component list attributesOther data types cannot be retrieved. No result is returned if the attribute
contains no data.
Maya Bug Fix:
- maya pointlessly returned vector results as a tuple wrapped in a list ( ex. '[(1,2,3)]' ). This command unpacks the vector for you.
Modifications:
- casts double3 datatypes to `Vector`
- casts matrix datatypes to `Matrix`
- casts vectorArrays from a flat array of floats to an array of Vectors
- when getting a multi-attr, maya would raise an error, but pymel will return a list of values for the multi-attr
- added a default argument. if the attribute does not exist and this argument is not None, this default value will be returned
- added support for getting message attributes
Flags:
- asString : asString (bool) [create]
This flag is only valid for enum attributes. It allows you to get the attribute values as strings instead of integer
values. Note that the returned string value is dependent on the UI language Maya is running in (about -uiLanguage).
- caching : ca (bool) [create]
Returns whether the attribute is set to be cached internally
- channelBox : cb (bool) [create]
Returns whether the attribute is set to show in the channelBox. Keyable attributes also show in the channel box.
- expandEnvironmentVariables : x (bool) [create]
Expand any environment variable and (tilde characters on UNIX) found in string attributes which are returned.
- keyable : k (bool) [create]
Returns the keyable state of the attribute.
- lock : l (bool) [create]
Returns the lock state of the attribute.
- multiIndices : mi (bool) [create]
If the attribute is a multi, this will return a list containing all of the valid indices for the attribute.
- settable : se (bool) [create]
Returns 1 if this attribute is currently settable by setAttr, 0 otherwise. An attribute is settable if it's not locked
and either not connected, or has only keyframed animation.
- silent : sl (bool) [create]
When evaluating an attribute that is not a numeric or string value, suppress the error message saying that the data
cannot be displayed. The attribute will be evaluated even though its data cannot be displayed. This flag does not
suppress all error messages, only those that are benign.
- size : s (bool) [create]
Returns the size of a multi-attribute array. Returns 1 if non-multi.
- time : t (time) [create]
Evaluate the attribute at the given time instead of the current time.
- type : typ (bool) [create]
Returns the type of data currently in the attribute. Attributes of simple types such as strings and numerics always
contain data, but attributes of complex types (arrays, meshes, etc) may contain no data if none has ever been assigned
to them. When this happens the command will return with no result: not an empty string, but no result at all. Attempting
to directly compare this non-result to another value or use it in an expression will result in an error, but you can
assign it to a variable in which case the variable will be set to the default value for its type (e.g. an empty string
for a string variable, zero for an integer variable, an empty array for an array variable). So to be safe when using
this flag, always assign its result to a string variable, never try to use it directly. Flag can have
multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.getAttr`
"""
pass
def getAlias(self, **kwargs):
"""
Returns the alias for this attribute, or None.
The alias of the attribute is set through
Attribute.setAlias, or the aliasAttr command.
"""
pass
def getAllParents(self, arrays='False'):
"""
Return a list of all parents above this.
Starts from the parent immediately above, going up.
:rtype: `Attribute` list
"""
pass
def getArrayIndices(self):
"""
Get all set or connected array indices. Raises an error if this is not an array Attribute
:rtype: `int` list
"""
pass
def getChildren(self):
"""
attributeQuery -listChildren
:rtype: `Attribute` list
"""
pass
def getEnums(attr):
"""
Get the enumerators for an enum attribute.
:rtype: `util.enum.EnumDict`
>>> addAttr( "persp", ln='numbers', at='enum', enumName="zero:one:two:thousand=1000:three")
>>> numbers = Attribute('persp.numbers').getEnums()
>>> sorted(numbers.items())
[(u'one', 1), (u'thousand', 1000), (u'three', 1001), (u'two', 2), (u'zero', 0)]
>>> numbers[1]
u'one'
>>> numbers['thousand']
1000
"""
pass
def getMax(self):
"""
attributeQuery -max
Returns None if max does not exist.
:rtype: `float`
"""
pass
def getMin(self):
"""
attributeQuery -min
Returns None if min does not exist.
:rtype: `float`
"""
pass
def getNumElements(self):
"""
Return the total number of elements in the datablock of this array plug. The return count will include all existing non-connected elements plus connected elements if they have been evaluated. It will not include connected elements that have not yet been placed into the datablock. The method MPlug::evaluateNumElements can be used in the sitution where you want an accurate count that includes all connected elements.
:rtype: `int`
Derived from api method `maya.OpenMaya.MPlug.numElements`
"""
pass
def getParent(self, generations='1', arrays='False'):
"""
Modifications:
- added optional generations keyword arg, which gives the number of
levels up that you wish to go for the parent
Negative values will traverse from the top.
A value of 0 will return the same node.
The default value is 1.
If generations is None, it will be interpreted as 'return all
parents', and a list will be returned.
Since the original command returned None if there is no parent,
to sync with this behavior, None will be returned if generations
is out of bounds (no IndexError will be thrown).
- added optional arrays keyword arg, which if True, will also
traverse from an array element to an array plug
:rtype: `Attribute`
"""
pass
def getRange(self):
"""
attributeQuery -range
returns a two-element list containing min and max. if the attribute does not have
a softMin or softMax the corresponding element will be set to None.
:rtype: `float`
"""
pass
def getSetAttrCmds(self, valueSelector="'all'", useLongNames='False'):
"""
Returns an array of strings containing setAttr commands for this plug and all of its descendent plugs.
:Parameters:
valueSelector : `Attribute.MValueSelector`
" cellpadding="3">
kAll- return setAttr commands for the plug and its children, regardless of their values. kNonDefault- only return setAttr commands for the plug or its children if they are not at their default values. kChanged- for nodes from referenced files, setAttr commands are only returned if the plug or one of its children has changed since its file was loaded. For all other nodes, the behaviour is the same a kNonDefault. Note that if the plug is compound and one of its children has changed, then setAttrs will be generated for *all* of its children, even those which have not changed.
(default: kAll)
values: 'all', 'nonDefault', 'changed', 'lastAttrSelector'
useLongNames : `bool`
Normally, the returned commands will use the short names for flags and attributes. If this parameter is true then their long names will be used instead. (default: false)
:rtype: `list` list
Derived from api method `maya.OpenMaya.MPlug.getSetAttrCmds`
"""
pass
def getSiblings(self):
"""
attributeQuery -listSiblings
:rtype: `Attribute` list
"""
pass
def getSoftMax(self):
"""
attributeQuery -softMax
Returns None if softMax does not exist.
:rtype: `float`
"""
pass
def getSoftMin(self):
"""
attributeQuery -softMin
Returns None if softMin does not exist.
:rtype: `float`
"""
pass
def getSoftRange(self):
"""
attributeQuery -softRange
returns a two-element list containing softMin and softMax. if the attribute does not have
a softMin or softMax the corresponding element in the list will be set to None.
:rtype: [`float`, `float`]
"""
pass
def index(self):
"""
Returns the logical index of the element this plug refers to. The logical index is a sparse index, equivalent to the array index used in MEL.
:rtype: `int`
Derived from api method `maya.OpenMaya.MPlug.logicalIndex`
"""
pass
def indexMatters(self):
pass
def info(self):
"""
This method returns a string containing the name of the node this plug belongs to and the attributes that the plug refers to. The string is of the form dependNode:atr1.atr2[].attr3 ...
:rtype: `unicode`
Derived from api method `maya.OpenMaya.MPlug.info`
"""
pass
def inputs(self, **kwargs):
"""
``listConnections -source 1 -destination 0``
see `Attribute.connections` for the full ist of flags.
:rtype: `PyNode` list
"""
pass
def insertInput(self, node, nodeOutAttr, nodeInAttr):
"""
connect the passed node.outAttr to this attribute and reconnect
any pre-existing connection into node.inAttr. if there is no
pre-existing connection, this method works just like connectAttr.
for example, for two nodes with the connection::
a.out-->b.in
running this command::
b.in.insertInput( 'c', 'out', 'in' )
causes the new connection order (assuming 'c' is a node with 'in' and 'out' attributes)::
a.out-->c.in
c.out-->b.in
"""
pass
def isArray(self):
"""
This method determines if the plug is an array plug. Array plugs refer to array attributes and contain element plugs.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isArray`
"""
pass
def isCaching(self):
"""
Returns true if this plug or its attribute has its caching flag set.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isCachingFlagSet`
"""
pass
def isChild(self):
"""
This method determines if the plug is a child plug. A child plug's parent is always a compound plug.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isChild`
"""
pass
def isCompound(self):
"""
This method determines if the plug is a compound plug. Compound plugs refer to compound attributes and have child plugs.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isCompound`
"""
pass
def isConnectable(self):
"""
attributeQuery -connectable
:rtype: `bool`
"""
pass
def isConnected(self):
"""
Determines if this plug is connected to one or more plugs.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isConnected`
"""
pass
def isConnectedTo(self, other, ignoreUnitConversion='False', checkLocalArray='False', checkOtherArray='False'):
"""
Determine if the attribute is connected to the passed attribute.
If checkLocalArray is True and the current attribute is a multi/array, the current attribute's elements will also be tested.
If checkOtherArray is True and the passed attribute is a multi/array, the passed attribute's elements will also be tested.
If checkLocalArray and checkOtherArray are used together then all element combinations will be tested.
"""
pass
def isDestination(self):
"""
Determines if this plug is connected as a destination.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isDestination`
"""
pass
def isDirty(self, **kwargs):
"""
:rtype: `bool`
"""
pass
def isDynamic(self):
"""
Determines whether the attribute is of dynamic type or not.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isDynamic`
"""
pass
def isElement(self):
"""
This method determines if the plug is an element plug. Element plugs refer to array attributes and are members of array plugs.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isElement`
"""
pass
def isFreeToChange(self, checkParents='True', checkChildren='True'):
"""
Returns true if the plug's value is allowed to be set directly. A plug isFreeToChange if it is not locked, and it is not a destination or if it is a destination, then it must be a special case (such as connected to an anim curve).
:Parameters:
checkParents : `bool`
Check parent plugs.
checkChildren : `bool`
Check child plugs.
:rtype: `Attribute.FreeToChangeState`
Derived from api method `maya.OpenMaya.MPlug.isFreeToChange`
"""
pass
def isFromReferencedFile(self):
"""
This method determines whether this plug came from a referenced file. A plug is considered to have come from a referenced file if it is connected and that connection was made within a referenced file.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isFromReferencedFile`
"""
pass
def isHidden(self):
"""
attributeQuery -hidden
:rtype: `bool`
"""
pass
def isIgnoredWhenRendering(self):
"""
Determines whether a connection to the attribute should be ignored during rendering.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isIgnoredWhenRendering`
"""
pass
def isInChannelBox(self):
"""
Returns true if this plug or its attribute has its channel box flag set. Attributes will appear in the channel box if their channel box flag is set or if they are keyable.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isChannelBoxFlagSet`
"""
pass
def isKeyable(self):
"""
Determines if this plug is keyable. The default keyability of a plug is determined by its attribute, and can be retrieved using MFnAttribute::isKeyable . Keyable plugs will be keyed by AutoKey and the Set Keyframe UI. Non-keyable plugs prevent the user from setting keys via the obvious UI provided for keying. Being non-keyable is not a hard block against adding keys to an attribute.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isKeyable`
"""
pass
def isLocked(self):
"""
Determines the locked state of this plug's value. A plug's locked state determines whether or not the plug's value can be changed.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isLocked`
"""
pass
def isMulti(self):
"""
This method determines if the plug is an array plug. Array plugs refer to array attributes and contain element plugs.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isArray`
"""
pass
def isMuted(self):
"""
mute -q
:rtype: `bool`
"""
pass
def isNetworked(self):
"""
This method determines if the plug is networked or non-networked.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isNetworked`
"""
pass
def isNull(self):
"""
This method determines whether this plug is valid. A plug is valid if it refers to an attribute.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isNull`
"""
pass
def isProcedural(self):
"""
This method determines if the plug is a procedural plug. A procedural plug is one which is created by Maya's internal procedures or by the nodes themselves and which should not be saved to or restored from files.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isProcedural`
"""
pass
def isSettable(self):
"""
getAttr -settable
:rtype: `bool`
"""
pass
def isSource(self):
"""
Determines if this plug is connected as a source.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MPlug.isSource`
"""
pass
def isUsedAsColor(self):
"""
attributeQuery -usedAsColor
"""
pass
def item(self):
"""
Returns the logical index of the element this plug refers to. The logical index is a sparse index, equivalent to the array index used in MEL.
:rtype: `int`
Derived from api method `maya.OpenMaya.MPlug.logicalIndex`
"""
pass
def iterDescendants(self, levels='None', leavesOnly='False'):
"""
Yields all attributes "below" this attribute, recursively,
traversing down both through multi/array elements, and through
compound attribute children.
Parameters
----------
levels : int or None
the number of levels deep to descend; each descent from an array
to an array element, and from a compound to it's child, counts as
one level (so, if you have a compound-multi attr parentAttr, to get
to parentAttr[0].child would require levels to be at least 2); None
means no limit
leavesOnly : bool
if True, then results will only be returned if they do not have any
children to recurse into (either because it's not an arry or
compound, or because we've hit the levels limit)
"""
pass
def lastPlugAttr(self, longName='False'):
"""
>>> from pymel.core import *
>>> at = SCENE.persp.t.tx
>>> at.lastPlugAttr(longName=False)
u'tx'
>>> at.lastPlugAttr(longName=True)
u'translateX'
:rtype: `unicode`
"""
pass
def lock(self, checkReference='False'):
"""
setAttr -locked 1
"""
pass
def logicalIndex(self):
"""
Returns the logical index of the element this plug refers to. The logical index is a sparse index, equivalent to the array index used in MEL.
:rtype: `int`
Derived from api method `maya.OpenMaya.MPlug.logicalIndex`
"""
pass
def longName(self, fullPath='False'):
"""
>>> from pymel.core import *
>>> at = SCENE.persp.t.tx
>>> at.longName(fullPath=False)
u'translateX'
>>> at.longName(fullPath=True)
u'translate.translateX'
:rtype: `unicode`
"""
pass
def mute(self, **kwargs):
"""
mute
Mutes the attribute.
"""
pass
def name(self, includeNode='True', longName='True', fullAttrPath='False', fullDagPath='False', placeHolderIndices='True'):
"""
Returns the name of the attribute (plug)
>>> tx = SCENE.persp.t.tx
>>> tx.name()
u'persp.translateX'
>>> tx.name(includeNode=False)
u'translateX'
>>> tx.name(longName=False)
u'persp.tx'
>>> tx.name(fullAttrPath=True, includeNode=False)
u'translate.translateX'
>>> vis = SCENE.perspShape.visibility
>>> vis.name()
u'perspShape.visibility'
>>> vis.name(fullDagPath=True)
u'|persp|perspShape.visibility'
>>> og = SCENE.persp.instObjGroups.objectGroups
>>> og.name()
u'persp.instObjGroups[-1].objectGroups'
>>> og.name(placeHolderIndices=False)
u'persp.instObjGroups.objectGroups'
:rtype: `unicode`
"""
pass
def namespace(self, *args, **kwargs):
pass
def node(self):
"""
plugNode
:rtype: `DependNode`
"""
pass
def nodeName(self):
"""
The node part of this plug as a string
:rtype: `unicode`
"""
pass
def numChildren(self):
"""
Return the total number of children of this compound plug.
:rtype: `int`
Derived from api method `maya.OpenMaya.MPlug.numChildren`
"""
pass
def numConnectedChildren(self):
"""
Return the number of children of this plug that are connected in the dependency graph.
:rtype: `int`
Derived from api method `maya.OpenMaya.MPlug.numConnectedChildren`
"""
pass
def numConnectedElements(self):
"""
Return the total number of connected element plugs belonging to this array plug.
:rtype: `int`
Derived from api method `maya.OpenMaya.MPlug.numConnectedElements`
"""
pass
def numElements(self):
"""
The number of elements in an array attribute. Raises an error if this is not an array Attribute
Be aware that ``getAttr(..., size=1)`` does not always produce the expected value. It is recommend
that you use `Attribute.numElements` instead. This is a maya bug, *not* a pymel bug.
>>> from pymel.core import *
>>> f=newFile(f=1) #start clean
>>>
>>> dls = SCENE.defaultLightSet
>>> dls.dagSetMembers.numElements()
0
>>> nt.SpotLight() # create a light, which adds to the lightSet
nt.SpotLight(u'spotLightShape1')
>>> dls.dagSetMembers.numElements()
1
>>> nt.SpotLight() # create another light, which adds to the lightSet
nt.SpotLight(u'spotLightShape2')
>>> dls.dagSetMembers.numElements()
2
:rtype: `int`
"""
pass
def outputs(self, **kwargs):
"""
``listConnections -source 0 -destination 1``
see `Attribute.connections` for the full ist of flags.
:rtype: `PyNode` list
"""
pass
def parent(self, generations='1', arrays='False'):
"""
Modifications:
- added optional generations keyword arg, which gives the number of
levels up that you wish to go for the parent
Negative values will traverse from the top.
A value of 0 will return the same node.
The default value is 1.
If generations is None, it will be interpreted as 'return all
parents', and a list will be returned.
Since the original command returned None if there is no parent,
to sync with this behavior, None will be returned if generations
is out of bounds (no IndexError will be thrown).
- added optional arrays keyword arg, which if True, will also
traverse from an array element to an array plug
:rtype: `Attribute`
"""
pass
def plugAttr(self, longName='False', fullPath='False'):
"""
>>> from pymel.core import *
>>> at = SCENE.persp.t.tx
>>> at.plugAttr(longName=False, fullPath=False)
u'tx'
>>> at.plugAttr(longName=False, fullPath=True)
u't.tx'
>>> at.plugAttr(longName=True, fullPath=True)
u'translate.translateX'
:rtype: `unicode`
"""
pass
def plugNode(self):
"""
plugNode
:rtype: `DependNode`
"""
pass
def remove(self, **kwargs):
"""
removeMultiInstance
"""
pass
def removeMultiInstance(self, index='None', break_='False'):
pass
def set(attr, *args, **kwargs):
"""
Sets the value of a dependency node attribute. No value for the the attribute is needed when the -l/-k/-s flags are
used. The -type flag is only required when setting a non-numeric attribute. The following chart outlines the syntax of
setAttr for non-numeric data types: TYPEbelow means any number of values of type TYPE, separated by a space[TYPE]means
that the value of type TYPEis optionalA|Bmeans that either of Aor Bmay appearIn order to run its examples, first execute
these commands to create the sample attribute types:sphere -n node; addAttr -ln short2Attr -at short2; addAttr -ln
short2a -p short2Attr -at short; addAttr -ln short2b -p short2Attr -at short; addAttr -ln short3Attr -at short3; addAttr
-ln short3a -p short3Attr -at short; addAttr -ln short3b -p short3Attr -at short; addAttr -ln short3c -p short3Attr -at
short; addAttr -ln long2Attr -at long2; addAttr -ln long2a -p long2Attr -at long; addAttr -ln long2b -p long2Attr -at
long; addAttr -ln long3Attr -at long3; addAttr -ln long3a -p long3Attr -at long; addAttr -ln long3b -p long3Attr -at
long; addAttr -ln long3c -p long3Attr -at long; addAttr -ln float2Attr -at float2; addAttr -ln float2a -p float2Attr -at
float; addAttr -ln float2b -p float2Attr -at float; addAttr -ln float3Attr -at float3; addAttr -ln float3a -p float3Attr
-at float; addAttr -ln float3b -p float3Attr -at float; addAttr -ln float3c -p float3Attr -at float; addAttr -ln
double2Attr -at double2; addAttr -ln double2a -p double2Attr -at double; addAttr -ln double2b -p double2Attr -at double;
addAttr -ln double3Attr -at double3; addAttr -ln double3a -p double3Attr -at double; addAttr -ln double3b -p double3Attr
-at double; addAttr -ln double3c -p double3Attr -at double; addAttr -ln int32ArrayAttr -dt Int32Array; addAttr -ln
doubleArrayAttr -dt doubleArray; addAttr -ln pointArrayAttr -dt pointArray; addAttr -ln vectorArrayAttr -dt vectorArray;
addAttr -ln stringArrayAttr -dt stringArray; addAttr -ln stringAttr -dt string; addAttr -ln matrixAttr -dt matrix;
addAttr -ln sphereAttr -dt sphere; addAttr -ln coneAttr -dt cone; addAttr -ln meshAttr -dt mesh; addAttr -ln latticeAttr
-dt lattice; addAttr -ln spectrumRGBAttr -dt spectrumRGB; addAttr -ln reflectanceRGBAttr -dt reflectanceRGB; addAttr -ln
componentListAttr -dt componentList; addAttr -ln attrAliasAttr -dt attributeAlias; addAttr -ln curveAttr -dt nurbsCurve;
addAttr -ln surfaceAttr -dt nurbsSurface; addAttr -ln trimFaceAttr -dt nurbsTrimface; addAttr -ln polyFaceAttr -dt
polyFaces; -type short2Array of two short integersValue Syntaxshort shortValue Meaningvalue1 value2Mel ExamplesetAttr
node.short2Attr -type short2 1 2;Python Examplecmds.setAttr('node.short2Attr',1,2,type='short2')-type short3Array of
three short integersValue Syntaxshort short shortValue Meaningvalue1 value2 value3Mel ExamplesetAttr node.short3Attr
-type short3 1 2 3;Python Examplecmds.setAttr('node.short3Attr',1,2,3,type='short3')-type long2Array of two long
integersValue Syntaxlong longValue Meaningvalue1 value2Mel ExamplesetAttr node.long2Attr -type long2 1000000
2000000;Python Examplecmds.setAttr('node.long2Attr',1000000,2000000,type='long2')-type long3Array of three long
integersValue Syntaxlong long longValue Meaningvalue1 value2 value3Mel ExamplesetAttr node.long3Attr -type long3 1000000
2000000 3000000;Python Examplecmds.setAttr('node.long3Attr',1000000,2000000,3000000,type='long3')-type
Int32ArrayVariable length array of long integersValue SyntaxValue MeaningMel ExamplesetAttr node.int32ArrayAttr -type
Int32Array 2 12 75;Python Examplecmds.setAttr('node.int32ArrayAttr',[2,12,75],type='Int32Array')-type float2Array of two
floatsValue Syntaxfloat floatValue Meaningvalue1 value2Mel ExamplesetAttr node.float2Attr -type float2 1.1 2.2;Python
Examplecmds.setAttr('node.float2Attr',1.1,2.2,type='float2')-type float3Array of three floatsValue Syntaxfloat float
floatValue Meaningvalue1 value2 value3Mel ExamplesetAttr node.float3Attr -type float3 1.1 2.2 3.3;Python
Examplecmds.setAttr('node.float3Attr',1.1,2.2,3.3,type='float3')-type double2Array of two doublesValue Syntaxdouble
doubleValue Meaningvalue1 value2Mel ExamplesetAttr node.double2Attr -type double2 1.1 2.2;Python
Examplecmds.setAttr('node.double2Attr',1.1,2.2,type='double2')-type double3Array of three doublesValue Syntaxdouble
double doubleValue Meaningvalue1 value2 value3Mel ExamplesetAttr node.double3Attr -type double3 1.1 2.2 3.3;Python
Examplecmds.setAttr('node.double3Attr',1.1,2.2,3.3,type='double3')-type doubleArrayVariable length array of doublesValue
SyntaxValue MeaningMel ExamplesetAttr node.doubleArrayAttr -type doubleArray 2 3.14159 2.782;Python Examplecmds.setAttr(
node.doubleArrayAttr, (2, 3.14159, 2.782,), type=doubleArray)-type matrix4x4 matrix of doublesValue Syntaxdouble double
double doubledouble double double doubledouble double double doubledouble double double doubleValue Meaningrow1col1
row1col2 row1col3 row1col4row2col1 row2col2 row2col3 row2col4row3col1 row3col2 row3col3 row3col4row4col1 row4col2
row4col3 row4col4Alternate Syntaxstring double double doubledouble double doubleintegerdouble double doubledouble double
doubledouble double doubledouble double doubledouble double doubledouble double doubledouble double double doubledouble
double double doubledouble double doublebooleanAlternate MeaningxformscaleX scaleY scaleZrotateX rotateY
rotateZrotationOrder (0=XYZ, 1=YZX, 2=ZXY, 3=XZY, 4=YXZ, 5=ZYX)translateX translateY translateZshearXY shearXZ
shearYZscalePivotX scalePivotY scalePivotZscaleTranslationX scaleTranslationY scaleTranslationZrotatePivotX rotatePivotY
rotatePivotZrotateTranslationX rotateTranslationY rotateTranslationZrotateOrientW rotateOrientX rotateOrientY
rotateOrientZjointOrientW jointOrientX jointOrientY jointOrientZinverseParentScaleX inverseParentScaleY
inverseParentScaleZcompensateForParentScale Mel ExamplesetAttr node.matrixAttr -type matrix1 0 0 0 0 1 0 0 0 0 1 0 2 3 4
1;setAttr node.matrixAttr -type matrixxform1 1 1 0 0 0 0 2 3 4 0 0 00 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 0
false;Python Examplecmds.setAttr('node.matrixAttr',(1,0,0,0,0,1,0,0,0,0,1,0,2,3,4,1),type='matrix')cmds.setAttr('node.ma
trixAttr','xform',(1,1,1),(0,0,0),0,(2,3,4),(0,0,0),(0,0,0),(0,0,0),(0,0,0),(0,1,1),(0,0,1,0),(1,0,1,0),(1,2,3),False,ty
pe=matrix)-type pointArrayVariable length array of pointsValue SyntaxValue MeaningMel ExamplesetAttr node.pointArrayAttr
-type pointArray 2 1 1 1 1 2 2 2 1;Python
Examplecmds.setAttr('node.pointArrayAttr',2,(1,1,1,1),(2,2,2,1),type='pointArray')-type vectorArrayVariable length array
of vectorsValue SyntaxValue MeaningMel ExamplesetAttr node.vectorArrayAttr -type vectorArray 2 1 1 1 2 2 2;Python
Examplecmds.setAttr('node.vectorArrayAttr',2,(1,1,1),(2,2,2),type='vectorArray')-type stringCharacter stringValue
SyntaxstringValue MeaningcharacterStringValueMel ExamplesetAttr node.stringAttr -type stringblarg;Python
Examplecmds.setAttr('node.stringAttr',blarg,type=string)-type stringArrayVariable length array of stringsValue
SyntaxValue MeaningMel ExamplesetAttr node.stringArrayAttr -type stringArray 3 abc;Python
Examplecmds.setAttr('node.stringArrayAttr',3,a,b,c,type='stringArray')-type sphereSphere dataValue SyntaxdoubleValue
MeaningsphereRadiusExamplesetAttr node.sphereAttr -type sphere 5.0;-type coneCone dataValue Syntaxdouble doubleValue
MeaningconeAngle coneCapMel ExamplesetAttr node.coneAttr -type cone 45.0 5.0;Python
Examplecmds.setAttr('node.coneAttr',45.0,5.0,type='cone')-type reflectanceRGBReflectance dataValue Syntaxdouble double
doubleValue MeaningredReflect greenReflect blueReflectMel ExamplesetAttr node.reflectanceRGBAttr -type reflectanceRGB
0.5 0.5 0.1;Python Examplecmds.setAttr('node.reflectanceRGBAttr',0.5,0.5,0.1,type='reflectanceRGB')-type
spectrumRGBSpectrum dataValue Syntaxdouble double doubleValue MeaningredSpectrum greenSpectrum blueSpectrumMel
ExamplesetAttr node.spectrumRGBAttr -type spectrumRGB 0.5 0.5 0.1;Python
Examplecmds.setAttr('node.spectrumRGBAttr',0.5,0.5,0.1,type='spectrumRGB')-type componentListVariable length array of
componentsValue SyntaxValue MeaningMel ExamplesetAttr node.componentListAttr -type componentList 3 cv[1] cv[12]
cv[3];Python Examplecmds.setAttr('node.componentListAttr',3,'cv[1]','cv[12]','cv[3]',type='componentList')-type
attributeAliasString alias dataValue Syntaxstring stringValue MeaningnewAlias currentNameMel ExamplesetAttr
node.attrAliasAttr -type attributeAliasGoUp, translateY, GoLeft, translateX;Python
Examplecmds.setAttr('node.attrAliasAttr',(GoUp, translateY,GoLeft, translateX),type='attributeAlias')-type
nurbsCurveNURBS curve dataValue SyntaxValue MeaningMel Example// degree is the degree of the curve(range 1-7)// spans is
the number of spans // form is open (0), closed (1), periodic (2)// dimension is 2 or 3, depending on the dimension of
the curve// isRational is true if the curve CVs contain a rational component // knotCount is the size of the knot list//
knotValue is a single entry in the knot list// cvCount is the number of CVs in the curve// xCVValue,yCVValue,[zCVValue]
[wCVValue] is a single CV.// zCVValue is only present when dimension is 3.// wCVValue is only present when isRational
is true.//setAttr node.curveAttr -type nurbsCurve 3 1 0 no 36 0 0 0 1 1 14 -2 3 0 -2 1 0 -2 -1 0 -2 -3 0;-type
nurbsSurfaceNURBS surface dataValue Syntaxint int int int bool Value MeaninguDegree vDegree uForm vForm
isRationalTRIM|NOTRIMExample// uDegree is degree of the surface in U direction (range 1-7)// vDegree is degree of the
surface in V direction (range 1-7)// uForm is open (0), closed (1), periodic (2) in U direction// vForm is open (0),
closed (1), periodic (2) in V direction// isRational is true if the surface CVs contain a rational component//
uKnotCount is the size of the U knot list// uKnotValue is a single entry in the U knot list// vKnotCount is the size of
the V knot list// vKnotValue is a single entry in the V knot list// If TRIMis specified then additional trim
information is expected// If NOTRIMis specified then the surface is not trimmed// cvCount is the number of CVs in the
surface// xCVValue,yCVValue,zCVValue [wCVValue]is a single CV.// zCVValue is only present when dimension is 3.//
wCVValue is only present when isRational is true//setAttr node.surfaceAttr -type nurbsSurface 3 3 0 0 no 6 0 0 0 1 1 16
0 0 0 1 1 116 -2 3 0 -2 1 0 -2 -1 0 -2 -3 0-1 3 0 -1 1 0 -1 -1 0 -1 -3 01 3 0 1 1 0 1 -1 0 1 -3 03 3 0 3 1 0 3 -1 0 3 -3
0;-type nurbsTrimfaceNURBS trim face dataValue SyntaxValue MeaningExample// flipNormal if true turns the surface inside
out// boundaryCount: number of boundaries// boundaryType: // tedgeCountOnBoundary : number of edges in a boundary//
splineCountOnEdge : number of splines in an edge in// edgeTolerance : tolerance used to build the 3d edge//
isEdgeReversed : if true, the edge is backwards// geometricContinuity : if true, the edge is tangent
continuous// splineCountOnPedge : number of splines in a 2d edge// isMonotone : if true, curvature is
monotone// pedgeTolerance : tolerance for the 2d edge//-type polyFacePolygon face dataValue SyntaxfhmfmhmufcValue
MeaningfhmfmhmufcExample// This data type (polyFace) is meant to be used in file I/O// after setAttrs have been written
out for vertex position// arrays, edge connectivity arrays (with corresponding start// and end vertex descriptions),
texture coordinate arrays and// color arrays. The reason is that this data type references// all of its data through
ids created by the former types.//// fspecifies the ids of the edges making up a face -// negative value if the edge
is reversed in the face// hspecifies the ids of the edges making up a hole -// negative value if the edge is
reversed in the face// mfspecifies the ids of texture coordinates (uvs) for a face.// This data type is obsolete as
of version 3.0. It is replaced by mu.// mhspecifies the ids of texture coordinates (uvs) for a hole// This data type
is obsolete as of version 3.0. It is replaced by mu.// muThe first argument refers to the uv set. This is a zero-
based// integer number. The second argument refers to the number of vertices (n)// on the face which have valid
uv values. The last n values are the uv// ids of the texture coordinates (uvs) for the face. These indices// are
what used to be represented by the mfand mhspecification.// There may be more than one muspecification, one for each
unique uv set.// fcspecifies the color index values for a face//setAttr node.polyFaceAttr -type polyFaces f3 1 2 3 fc3 4
4 6;-type meshPolygonal meshValue SyntaxValue Meaningvvn[vtesmooth|hard]Example// vspecifies the vertices of the
polygonal mesh// vnspecifies the normal of each vertex// vtis optional and specifies a U,V texture coordinate for each
vertex// especifies the edge connectivity information between vertices//setAttr node.meshAttr -type mesh v3 0 0 0 0 1 0
0 0 1vn3 1 0 0 1 0 0 1 0 0vt3 0 0 0 1 1 0e3 0 1 hard1 2 hard2 0 hard;-type latticeLattice dataValue SyntaxValue
MeaningsDivisionCount tDivisionCount uDivisionCountExample// sDivisionCount is the horizontal lattice division count//
tDivisionCount is the vertical lattice division count// uDivisionCount is the depth lattice division count// pointCount
is the total number of lattice points// pointX,pointY,pointZ is one lattice point. The list is// specified varying
first in S, then in T, last in U so the// first two entries are (S=0,T=0,U=0) (s=1,T=0,U=0)//setAttr node.latticeAttr
-type lattice 2 5 2 20-2 -2 -2 2 -2 -2 -2 -1 -2 2 -1 -2 -2 0 -22 0 -2 -2 1 -2 2 1 -2 -2 2 -2 2 2 -2-2 -2 2 2 -2 2 -2 -1
2 2 -1 2 -2 0 22 0 2 -2 1 2 2 1 2 -2 2 2 2 2 2;In query mode, return type is based on queried flag.
Maya Bug Fix:
- setAttr did not work with type matrix.
Modifications:
- No need to set type, this will automatically be determined
- Adds support for passing a list or tuple as the second argument for datatypes such as double3.
- When setting stringArray datatype, you no longer need to prefix the list with the number of elements - just pass a list or tuple as with other arrays
- Added 'force' kwarg, which causes the attribute to be added if it does not exist.
- if no type flag is passed, the attribute type is based on type of value being set (if you want a float, be sure to format it as a float, e.g. 3.0 not 3)
- currently does not support compound attributes
- currently supported python-to-maya mappings:
============ ===========
python type maya type
============ ===========
float double
------------ -----------
int long
------------ -----------
str string
------------ -----------
bool bool
------------ -----------
Vector double3
------------ -----------
Matrix matrix
------------ -----------
[str] stringArray
============ ===========
>>> addAttr( 'persp', longName= 'testDoubleArray', dataType='doubleArray')
>>> setAttr( 'persp.testDoubleArray', [0,1,2])
>>> setAttr( 'defaultRenderGlobals.preMel', 'sfff')
- Added ability to set enum attributes using the string values; this may be
done either by setting the 'asString' kwarg to True, or simply supplying
a string value for an enum attribute.
Flags:
- alteredValue : av (bool) [create]
The value is only the current value, which may change in the next evalution (if the attribute has an incoming
connection). This flag is only used during file I/O, so that attributes with incoming connections do not have their data
overwritten during the first evaluation after a file is opened.
- caching : ca (bool) [create]
Sets the attribute's internal caching on or off. Not all attributes can be defined as caching. Only those attributes
that are not defined by default to be cached can be made caching. As well, multi attribute elements cannot be made
caching. Caching also affects child attributes for compound attributes.
- capacityHint : ch (int) [create]
Used to provide a memory allocation hint to attributes where the -size flag cannot provide enough information. This flag
is optional and is primarily intended to be used during file I/O. Only certain attributes make use of this flag, and the
interpretation of the flag value varies per attribute. This flag is currently used by (node.attribute): mesh.face -
hints the total number of elements in the face edge lists
- channelBox : cb (bool) [create]
Sets the attribute's display in the channelBox on or off. Keyable attributes are always display in the channelBox
regardless of the channelBox settting.
- clamp : c (bool) [create]
For numeric attributes, if the value is outside the range of the attribute, clamp it to the min or max instead of
failing
- keyable : k (bool) [create]
Sets the attribute's keyable state on or off.
- lock : l (bool) [create]
Sets the attribute's lock state on or off.
- size : s (int) [create]
Defines the size of a multi-attribute array. This is only a hint, used to help allocate memory as efficiently as
possible.
- type : typ (unicode) [create]
Identifies the type of data. If the -type flag is not present, a numeric type is assumed. Flag can
have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.setAttr`
"""
pass
def setAlias(self, alias):
"""
Sets the alias for this attribute (similar to aliasAttr).
"""
pass
def setCaching(self, isCaching):
"""
Sets whether this plug is cached internally. Note: turning caching on for a plug will force the plug to become networked. Network plugs take longer to look up in the DG; therefore you should only make a plug cached only if you are certain that the network plug look-up will take less than the saved evaluation cost.
:Parameters:
isCaching : `bool`
True if this plug should be cached
Derived from api method `maya.OpenMaya.MPlug.setCaching`
"""
pass
def setDirty(self, **kwargs):
pass
def setEnums(attr, enums):
"""
Set the enumerators for an enum attribute.
"""
pass
def setKey(self, **kwargs):
"""
This command creates keyframes for the specified objects, or the active objects if none are specified on the command
line. The default time for the new keyframes is the current time. Override this behavior with the -tflag on the command
line. The default value for the keyframe is the current value of the attribute for which a keyframe is set. Override
this behavior with the -vflag on the command line. When setting keyframes on animation curves that do not have timeas an
input attribute (ie, they are unitless animation curves), use -f/-floatto specify the unitless value at which to set a
keyframe. The -time and -float flags may be combined in one command. This command sets up Dependency Graph relationships
for proper evaluation of a given attribute at a given time.
Flags:
- animLayer : al (unicode) [create]
Specifies that the new key should be placed in the specified animation layer. Note that if the objects being keyframed
are not already part of the layer, this flag will be ignored.
- animated : an (bool) [create]
Add the keyframe only to the attribute(s) that have already a keyframe on. Default: false
- attribute : at (unicode) [create]
Attribute name to set keyframes on.
- breakdown : bd (bool) [create,query,edit]
Sets the breakdown state for the key. Default is false
- clip : c (unicode) [create]
Specifies that the new key should be placed in the specified clip. Note that if the objects being keyframed are not
already part of the clip, this flag will be ignored.
- controlPoints : cp (bool) [create]
Explicitly specify whether or not to include the control points of a shape (see -sflag) in the list of attributes.
Default: false.
- dirtyDG : dd (bool) [create]
Allow dirty messages to be sent out when a keyframe is set.
- float : f (float) [create]
Float time at which to set a keyframe on float-based animation curves.
- hierarchy : hi (unicode) [create]
Controls the objects this command acts on, relative to the specified (or active) target objects. Valid values are
above,below,both,and none.Default is hierarchy -query
- identity : id (bool) [create]
Sets an identity key on an animation layer. An identity key is one that nullifies the effect of the anim layer. This
flag has effect only when the attribute being keyed is being driven by animation layers.
- inTangentType : itt (unicode) [create]
The in tangent type for keyframes set by this command. Valid values are: auto, clamped, fast, flat, linear, plateau,
slow, spline, and stepnextDefault is keyTangent -q -g -inTangentType
- insert : i (bool) [create]
Insert keys at the given time(s) and preserve the shape of the animation curve(s). Note: the tangent type on inserted
keys will be fixed so that the curve shape can be preserved.
- insertBlend : ib (bool) [create]
If true, a pairBlend node will be inserted for channels that have nodes other than animCurves driving them, so that such
channels can have blended animation. If false, these channels will not have keys inserted. If the flag is not specified,
the blend will be inserted based on the global preference for blending animation.
- minimizeRotation : mr (bool) [create]
For rotations, ensures that the key that is set is a minimum distance away from the previous key. Default is false
- noResolve : nr (bool) [create]
When used with the -value flag, causes the specified value to be set directly onto the animation curve, without
attempting to resolve the value across animation layers.
- outTangentType : ott (unicode) [create]
The out tangent type for keyframes set by this command. Valid values are: auto, clamped, fast, flat, linear, plateau,
slow, spline, step, and stepnext. Default is keyTangent -q -g -outTangentType
- respectKeyable : rk (bool) [create]
When used with the -attribute flag, prevents the keying of the non keyable attributes.
- shape : s (bool) [create]
Consider attributes of shapes below transforms as well, except controlPoints. Default: true
- time : t (time) [create]
Time at which to set a keyframe on time-based animation curves.
- useCurrentLockedWeights : lw (bool) [create]
If we are setting a key over an existing key, use that key tangent's locked weight value for the new locked weight
value. Default is false
- value : v (float) [create]
Value at which to set the keyframe. Using the value flag will not cause the keyed attribute to change to the specified
value until the scene re-evaluates. Therefore, if you want the attribute to update to the new value immediately, use the
setAttr command in addition to setting the key. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.setKeyframe`
"""
pass
def setKeyable(self, keyable):
"""
This overrides the default keyability of a plug set with MFnAttribute::setKeyable . Keyable plugs will be keyed by AutoKey and the Set Keyframe UI. Non-keyable plugs prevent the user from setting keys via the obvious UI provided for keying. Being non-keyable is not a hard block against adding keys to an attribute.
:Parameters:
keyable : `bool`
True if this plug should be keyable
Derived from api method `maya.OpenMaya.MPlug.setKeyable`
"""
pass
def setLocked(self, locked, checkReference='False'):
"""
Sets the locked state for this plug's value. A plug's locked state determines whether or not the plug's value can be changed.
:Parameters:
locked : `bool`
True if this plug's value is to be locked
checkReference : `bool`
Set True to raise errors on referenced attributes.
By default pymel and the maya api do not check if the node is referenced before
setting the locked state. This is unsafe because changes to the locked state on
referenced nodes are not saved with the scene.
"""
pass
def setMax(self, newMax):
pass
def setMin(self, newMin):
pass
def setNumElements(self, elements):
"""
The method is used to pre-allocate the number of elements that an array plug will contain. The plug passed to this method must be an array plug and there must be no elements already allocated.
:Parameters:
elements : `int`
new array size
Derived from api method `maya.OpenMaya.MPlug.setNumElements`
"""
pass
def setRange(self, *args):
"""
provide a min and max value as a two-element tuple or list, or as two arguments to the
method. To remove a limit, provide a None value. for example:
>>> from pymel.core import *
>>> s = polyCube()[0]
>>> s.addAttr( 'new' )
>>> s.new.setRange( -2, None ) #sets just the min to -2 and removes the max limit
>>> s.new.setMax( 3 ) # sets just the max value and leaves the min at its previous default
>>> s.new.getRange()
[-2.0, 3.0]
"""
pass
def setSoftMax(self, newMax):
pass
def setSoftMin(self, newMin):
pass
def setSoftRange(self, *args):
pass
def shortName(self, fullPath='False'):
"""
>>> from pymel.core import *
>>> at = SCENE.persp.t.tx
>>> at.shortName(fullPath=False)
u'tx'
>>> at.shortName(fullPath=True)
u't.tx'
:rtype: `unicode`
"""
pass
def showInChannelBox(self, inChannelBox):
"""
Sets whether this plug is displayed in the channel box. This overrides the default display of a plug set with MFnAttribute::setChannelBox . Keyable attributes are always shown in the channel box so this flag is ignored on keyable plugs.
:Parameters:
inChannelBox : `bool`
True if this plug should be displayed in the channel box
Derived from api method `maya.OpenMaya.MPlug.setChannelBox`
"""
pass
def siblings(self):
"""
attributeQuery -listSiblings
:rtype: `Attribute` list
"""
pass
def type(self):
"""
getAttr -type
:rtype: `unicode`
"""
pass
def unlock(self, checkReference='False'):
"""
setAttr -locked 0
"""
pass
def unmute(self, **kwargs):
"""
mute -disable -force
Unmutes the attribute
"""
pass
FreeToChangeState = {}
MValueSelector = {}
__apicls__ = None
__readonly__ = {}
attrItemReg = None
class DimensionedComponent(Component):
"""
Components for which having a __getitem__ of some sort makes sense
ie, myComponent[X] would be reasonable.
"""
def __getitem__(self, item):
pass
def __init__(self, *args, **kwargs):
pass
def currentDimension(self):
"""
Returns the dimension index that an index operation - ie, self[...] /
self.__getitem__(...) - will operate on.
If the component is completely specified (ie, all dimensions are
already indexed), then None is returned.
"""
pass
VALID_SINGLE_INDEX_TYPES = []
__readonly__ = {}
dimensions = 0
class MayaComponentError(MayaAttributeError):
pass
class Pivot(Component):
__readonly__ = {}
class MItComponent(Component):
"""
Abstract base class for pymel components that can be accessed via iterators.
(ie, `MeshEdge`, `MeshVertex`, and `MeshFace` can be wrapped around
MItMeshEdge, etc)
If deriving from this class, you should set __apicls__ to an appropriate
MIt* type - ie, for MeshEdge, you would set __apicls__ = _api.MItMeshEdge
"""
def __apimfn__(self):
pass
def __apimit__(self, alwaysUnindexed='False'):
pass
def __init__(self, *args, **kwargs):
pass
__readonly__ = {}
class MayaAttributeEnumError(MayaAttributeError):
def __init__(self, node='None', enum='None'):
pass
def __str__(self):
pass
class MayaParticleAttributeError(MayaComponentError):
pass
class ContinuousComponent(DimensionedComponent):
"""
Components whose dimensions are continuous.
Ie, there are an infinite number of possible components, referenced by
floating point parameters.
Example: nurbsCurve.u[7.48], nurbsSurface.uv[3.85][2.1]
Derived classes should implement:
_dimRange
"""
def __iter__(self):
pass
VALID_SINGLE_INDEX_TYPES = ()
__readonly__ = {}
class DiscreteComponent(DimensionedComponent):
"""
Components whose dimensions are discretely indexed.
Ie, there are a finite number of possible components, referenced by integer
indices.
Example: polyCube.vtx[38], f.cv[3][2]
Derived classes should implement:
_dimLength
"""
def __init__(self, *args, **kwargs):
pass
def __iter__(self):
pass
def __len__(self):
pass
def count(self):
pass
def currentItem(self):
pass
def currentItemIndex(self):
"""
Returns the component indices for the current item in this component
group
If the component type has more then one dimension, the return result
will be a ComponentIndex object which is a sub-class of tuple; otherwise,
it will be a single int.
These values correspond to the indices that you would use when selecting
components in mel - ie, vtx[5], cv[3][2]
"""
pass
def getIndex(self):
"""
Returns the current 'flat list' index for this group of components -
ie, if this component holds the vertices:
[5, 7, 12, 13, 14, 25]
then if the 'flat list' index is 2, then we are pointing to vertex 12.
"""
pass
def indices(self):
"""
A list of all the indices contained by this component.
"""
pass
def indicesIter(self):
"""
An iterator over all the indices contained by this component,
as ComponentIndex objects (which are a subclass of tuple).
"""
pass
def next(self):
pass
def reset(self):
pass
def setIndex(self, index):
pass
def totalSize(self):
"""
The maximum possible number of components
ie, for a polygon cube, the totalSize for verts would be 8, for edges
would be 12, and for faces would be 6
"""
pass
VALID_SINGLE_INDEX_TYPES = ()
__readonly__ = {}
class Component2D(DiscreteComponent):
__readonly__ = {}
dimensions = 2
class Component2DFloat(ContinuousComponent):
__readonly__ = {}
dimensions = 2
class Component1D(DiscreteComponent):
def currentItem(self):
pass
def currentItemIndex(self):
"""
Returns the component indices for the current item in this component
group
If the component type has more then one dimension, the return result
will be a ComponentIndex object which is a sub-class of tuple; otherwise,
it will be a single int.
These values correspond to the indices that you would use when selecting
components in mel - ie, vtx[5], cv[3][2]
"""
pass
def index(self):
pass
def indicesIter(self):
"""
An iterator over all the indices contained by this component,
as integers.
"""
pass
def name(self):
pass
__readonly__ = {}
dimensions = 1
class Component1D64(DiscreteComponent):
def __len__(self):
pass
def totalSize(self):
pass
__readonly__ = {}
dimensions = 2
class Component1DFloat(ContinuousComponent):
def index(self):
pass
__readonly__ = {}
dimensions = 1
class Component3D(DiscreteComponent):
__readonly__ = {}
dimensions = 3
class NurbsCurveKnot(Component1D):
__readonly__ = {}
class MItComponent1D(MItComponent, Component1D):
__readonly__ = {}
class NurbsSurfaceEP(Component2D):
__readonly__ = {}
class SubdUV(Component1D):
def totalSize(self):
pass
__readonly__ = {}
class SubdFace(Component1D64):
__readonly__ = {}
class NurbsCurveParameter(Component1DFloat):
__readonly__ = {}
class NurbsSurfaceFace(Component2D):
__readonly__ = {}
class NurbsSurfaceCV(Component2D):
__readonly__ = {}
class SubdEdge(Component1D64):
__readonly__ = {}
class NurbsSurfaceKnot(Component2D):
__readonly__ = {}
class MeshVertexFace(Component2D):
def __melobject__(self):
"""
# getting all the mel strings for MeshVertexFace is SLLOOOWW - so check if
# it's complete, and if so, just return the .vtxFace[*] form
"""
pass
def totalSize(self):
pass
__readonly__ = {}
class NurbsSurfaceIsoparm(Component2DFloat):
def __init__(self, *args, **kwargs):
pass
__readonly__ = {}
class LatticePoint(Component3D):
__readonly__ = {}
class ParticleComponent(Component1D):
def __getattr__(self, attr):
pass
def attr(self, attr):
pass
__readonly__ = {}
class MeshUV(Component1D):
__readonly__ = {}
class NurbsCurveEP(Component1D):
__readonly__ = {}
class SubdVertex(Component1D64):
__readonly__ = {}
class NurbsSurfaceRange(NurbsSurfaceIsoparm):
def __getitem__(self, item):
pass
__readonly__ = {}
class MeshFace(MItComponent1D):
def connectedEdges(self):
"""
:rtype: `MeshEdge` list
"""
pass
def connectedFaces(self):
"""
:rtype: `MeshFace` list
"""
pass
def connectedVertices(self):
"""
:rtype: `MeshVertex` list
"""
pass
def geomChanged(self):
"""
Reset the geom pointer in the MItMeshPolygon . This is now being handled automatically inside the iterator, and users should no longer need to call this method directly to sync up the iterator to changes made by MFnMesh
Derived from api method `maya.OpenMaya.MItMeshPolygon.geomChanged`
**Undo is not currently supported for this method**
"""
pass
def getArea(self, space="'preTransform'"):
"""
This method gets the area of the face
:Parameters:
space : `Space.Space`
World Space or Object Space
values: 'transform', 'preTransform', 'object', 'world'
:rtype: `float`
Derived from api method `maya.OpenMaya.MSpace.getArea`
"""
pass
def getAxisAtUV(self, uvPoint, space="'preTransform'", uvSet='None', tolerance='0.0'):
"""
Return the axis of the point at the given UV value in the current polygon.
:Parameters:
uvPoint : (`float`, `float`)
The UV value to try to locate
space : `Space.Space`
The coordinate system for this operation
values: 'transform', 'preTransform', 'object', 'world'
uvSet : `unicode`
UV set to work with
tolerance : `float`
tolerance value to compare float data type
:rtype: (`Vector`, `Vector`, `Vector`)
Derived from api method `maya.OpenMaya.MSpace.getAxisAtUV`
"""
pass
def getColor(self, colorSetName='None'):
"""
This method gets the average color of the all the vertices in this face
:Parameters:
colorSetName : `unicode`
Name of the color set.
:rtype: `Color`
Derived from api method `maya.OpenMaya.MItMeshPolygon.getColor`
"""
pass
def getColorIndex(self, vertexIndex, colorSetName='None'):
"""
This method returns the colorIndex for a vertex of the current face.
:Parameters:
vertexIndex : `int`
Face-relative index of vertex.
colorSetName : `unicode`
Name of the color set.
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshPolygon.getColorIndex`
"""
pass
def getColorIndices(self, colorSetName='None'):
"""
This method returns the colorIndices for each vertex on the face.
:Parameters:
colorSetName : `unicode`
Name of the color set.
:rtype: `int` list
Derived from api method `maya.OpenMaya.MItMeshPolygon.getColorIndices`
"""
pass
def getColors(self, colorSetName='None'):
"""
This method gets the color of the each vertex in the current face.
:Parameters:
colorSetName : `unicode`
Name of the color set.
:rtype: `Color` list
Derived from api method `maya.OpenMaya.MItMeshPolygon.getColors`
"""
pass
def getEdges(self):
"""
This method gets the indices of the edges contained in the current face.
:rtype: `int` list
Derived from api method `maya.OpenMaya.MItMeshPolygon.getEdges`
"""
pass
def getNormal(self, space="'preTransform'"):
"""
Return the face normal of the current polygon.
:Parameters:
space : `Space.Space`
The transformation space
values: 'transform', 'preTransform', 'object', 'world'
:rtype: `Vector`
Derived from api method `maya.OpenMaya.MSpace.getNormal`
"""
pass
def getNormals(self, space="'preTransform'"):
"""
Returns the normals for all vertices in the current face
:Parameters:
space : `Space.Space`
The transformation space
values: 'transform', 'preTransform', 'object', 'world'
:rtype: `Vector` list
Derived from api method `maya.OpenMaya.MSpace.getNormals`
"""
pass
def getPoint(self, index, space="'preTransform'"):
"""
Return the position of the vertex at index in the current polygon.
:Parameters:
index : `int`
The face-relative index of the vertex in the current polygon
space : `Space.Space`
The coordinate system for this operation
values: 'transform', 'preTransform', 'object', 'world'
:rtype: `Point`
Derived from api method `maya.OpenMaya.MSpace.point`
"""
pass
def getPointAtUV(self, uvPoint, space="'preTransform'", uvSet='None', tolerance='0.0'):
"""
Return the position of the point at the given UV value in the current polygon.
:Parameters:
uvPoint : (`float`, `float`)
The UV value to try to locate
space : `Space.Space`
The coordinate system for this operation
values: 'transform', 'preTransform', 'object', 'world'
uvSet : `unicode`
UV set to work with
tolerance : `float`
tolerance value to compare float data type
:rtype: `Point`
Derived from api method `maya.OpenMaya.MSpace.getPointAtUV`
"""
pass
def getPoints(self, space="'preTransform'"):
"""
Retrieves the positions of the vertices on the current face/polygon that the iterator is pointing to. Vertex positions will be inserted into the given array and will be indexed using face-relative vertex IDs (ie. ordered from 0 to (vertexCount of the face) - 1), which should not be confused with the vertexIDs of each vertex in relation to the entire mesh object.
:Parameters:
space : `Space.Space`
The coordinate system for this operation
values: 'transform', 'preTransform', 'object', 'world'
:rtype: `Point` list
Derived from api method `maya.OpenMaya.MSpace.getPoints`
"""
pass
def getUV(self, vertex, uvSet='None'):
"""
Return the texture coordinate for the given vertex.
:Parameters:
vertex : `int`
The face-relative vertex index to get UV for
uvSet : `unicode`
UV set to work with
:rtype: (`float`, `float`)
Derived from api method `maya.OpenMaya.MItMeshPolygon.getUV`
"""
pass
def getUVArea(self, uvSet='None'):
"""
This method gets the UV area of the face
:Parameters:
uvSet : `unicode`
UV set to work with
:rtype: `float`
Derived from api method `maya.OpenMaya.MItMeshPolygon.getUVArea`
"""
pass
def getUVAtPoint(self, pt, space="'preTransform'", uvSet='None'):
"""
Find the point closest to the given point in the current polygon, and return the UV value at that point.
:Parameters:
pt : `Point`
The point to try to get UV for
space : `Space.Space`
The coordinate system for this operation
values: 'transform', 'preTransform', 'object', 'world'
uvSet : `unicode`
UV set to work with
:rtype: (`float`, `float`)
Derived from api method `maya.OpenMaya.MSpace.getUVAtPoint`
"""
pass
def getUVIndex(self, vertex, uvSet='None'):
"""
Returns the index of the texture coordinate for the given vertex. This index refers to an element of the texture coordinate array for the polygonal object returned by MFnMesh::getUVs .
:Parameters:
vertex : `int`
The face-relative vertex index of the current polygon
uvSet : `unicode`
UV set to work with
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshPolygon.getUVIndex`
"""
pass
def getUVSetNames(self):
"""
This method is used to find the UV set names mapped to the current face.
:rtype: `list` list
Derived from api method `maya.OpenMaya.MItMeshPolygon.getUVSetNames`
"""
pass
def getUVs(self, uvSet='None'):
"""
Return the all the texture coordinates for the vertices of this face (in local vertex order).
:Parameters:
uvSet : `unicode`
UV set to work with
:rtype: (`float` list, `float` list)
Derived from api method `maya.OpenMaya.MItMeshPolygon.getUVs`
"""
pass
def getVertices(self):
"""
This method gets the indices of the vertices of the current face
:rtype: `int` list
Derived from api method `maya.OpenMaya.MItMeshPolygon.getVertices`
"""
pass
def hasColor(self):
"""
This method determines whether the current face has color-per-vertex set for any vertex.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.hasColor`
"""
pass
def hasUVs(self):
"""
Tests whether this face has UV's mapped or not (either all the vertices for a face should have UV's, or none of them do, so the UV count for a face is either 0, or equal to the number of vertices).
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.hasUVs`
"""
pass
def hasValidTriangulation(self):
"""
This method checks if the face has a valid triangulation. If it doesn't, then the face was bad geometry: it may gave degenerate points or cross over itself.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.hasValidTriangulation`
"""
pass
def isConnectedTo(self, component):
"""
:rtype: bool
"""
pass
def isConnectedToEdge(self, index):
"""
This method determines whether the given edge is connected to a vertex in the current face
:Parameters:
index : `int`
Index of the edge to be tested for
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.isConnectedToEdge`
"""
pass
def isConnectedToFace(self, index):
"""
This method determines whether the given face is adjacent to the current face
:Parameters:
index : `int`
Index of the face to be tested for
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.isConnectedToFace`
"""
pass
def isConnectedToVertex(self, index):
"""
This method determines whether the given vertex shares an edge with a vertex in the current face.
:Parameters:
index : `int`
Index of the vertex to be tested for
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.isConnectedToVertex`
"""
pass
def isConvex(self):
"""
This method checks if the face is convex.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.isConvex`
"""
pass
def isHoled(self):
"""
This method checks if the face has any holes.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.isHoled`
"""
pass
def isLamina(self):
"""
This method checks if the face is a lamina (the face is folded over onto itself).
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.isLamina`
"""
pass
def isOnBoundary(self):
"""
This method determines whether the current face is on a boundary
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.onBoundary`
"""
pass
def isPlanar(self):
"""
This method checks if the face is planar
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.isPlanar`
"""
pass
def isStarlike(self):
"""
This method checks if the face is starlike. That is, a line from the centre to any vertex lies entirely within the face.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.isStarlike`
"""
pass
def isZeroArea(self):
"""
This method checks if its a zero area face
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.zeroArea`
"""
pass
def isZeroUVArea(self):
"""
This method checks if the UV area of the face is zero
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshPolygon.zeroUVArea`
"""
pass
def normalIndex(self, localVertexIndex):
"""
Returns the normal index for the specified vertex. This index refers to an element in the normal array returned by MFnMesh::getNormals . These normals are per-polygon per-vertex normals. See the MFnMesh description for more information on normals.
:Parameters:
localVertexIndex : `int`
The face-relative index of the vertex to examine for the current polygon
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshPolygon.normalIndex`
"""
pass
def numColors(self, colorSetName='None'):
"""
This method checks for the number of colors on vertices in this face.
:Parameters:
colorSetName : `unicode`
Name of the color set.
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshPolygon.numColors`
"""
pass
def numConnectedEdges(self):
"""
This method checks for the number of connected edges on the vertices of this face
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshPolygon.numConnectedEdges`
"""
pass
def numConnectedFaces(self):
"""
This method checks for the number of connected faces
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshPolygon.numConnectedFaces`
"""
pass
def numTriangles(self):
"""
This Method checks for the number of triangles in this face in the current triangulation
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshPolygon.numTriangles`
"""
pass
def numVertices(self):
"""
Return the number of vertices for the current polygon.
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshPolygon.polygonVertexCount`
"""
pass
def polygonVertexCount(self):
"""
Return the number of vertices for the current polygon.
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshPolygon.polygonVertexCount`
"""
pass
def setPoint(self, point, index, space="'preTransform'"):
"""
Set the vertex at the given index in the current polygon.
:Parameters:
point : `Point`
The new position for the vertex
index : `int`
The face-relative index of the vertex in the current polygon
space : `Space.Space`
The coordinate system for this operation
values: 'transform', 'preTransform', 'object', 'world'
Derived from api method `maya.OpenMaya.MSpace.setPoint`
"""
pass
def setPoints(self, pointArray, space="'preTransform'"):
"""
Sets new locations for vertices of the current polygon that the iterator is pointing to.
:Parameters:
pointArray : `Point` list
The new positions for the vertices.
space : `Space.Space`
The coordinate system for this operation.
values: 'transform', 'preTransform', 'object', 'world'
Derived from api method `maya.OpenMaya.MSpace.setPoints`
"""
pass
def setUV(self, vertexId, uvPoint, uvSet='None'):
"""
Modify the UV value for the given vertex in the current face. If the face is not already mapped, this method will fail.
:Parameters:
vertexId : `int`
face-relative index of the vertex to set UV for.
uvPoint : (`float`, `float`)
The UV values to set it to
uvSet : `unicode`
UV set to work with
Derived from api method `maya.OpenMaya.MItMeshPolygon.setUV`
"""
pass
def setUVs(self, uArray, vArray, uvSet='None'):
"""
Modify the UV value for all vertices in the current face. If the face has not already been mapped, this method will fail.
:Parameters:
uArray : `float` list
All the U values - in local face order
vArray : `float` list
The corresponding V values
uvSet : `unicode`
UV set to work with
Derived from api method `maya.OpenMaya.MItMeshPolygon.setUVs`
"""
pass
def updateSurface(self):
"""
Signal that this polygonal surface has changed and needs to redraw itself.
Derived from api method `maya.OpenMaya.MItMeshPolygon.updateSurface`
**Undo is not currently supported for this method**
"""
pass
__apicls__ = None
__readonly__ = {}
class NurbsCurveCV(MItComponent1D):
def getPosition(self, space="'preTransform'"):
"""
Return the position of the current CV.
:Parameters:
space : `Space.Space`
the co-oordinate system for the returned point
values: 'transform', 'preTransform', 'object', 'world'
:rtype: `Point`
Derived from api method `maya.OpenMaya.MSpace.position`
"""
pass
def hasHistoryOnCreate(self):
"""
This method determines if the shape was created with history.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItCurveCV.hasHistoryOnCreate`
"""
pass
def isDone(self):
"""
Returns true if the iteration is finished, i.e. there are no more CVs to iterate on.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItCurveCV.isDone`
"""
pass
def setPosition(self, pt, space="'preTransform'"):
"""
Set the position of the current CV to the specified point.
:Parameters:
pt : `Point`
new position of CV
space : `Space.Space`
the co-ordinate system for this transformation.
values: 'transform', 'preTransform', 'object', 'world'
Derived from api method `maya.OpenMaya.MSpace.setPosition`
"""
pass
def translateBy(self, vec, space="'preTransform'"):
"""
Translates the current CV by the amount specified in vec .
:Parameters:
vec : `Vector`
translation to be applied to the CV
space : `Space.Space`
the co-oordinate system for this transformation.
values: 'transform', 'preTransform', 'object', 'world'
Derived from api method `maya.OpenMaya.MSpace.translateBy`
**Undo is not currently supported for this method**
"""
pass
def updateCurve(self):
"""
This method is used to signal the curve that it has been changed and needs to redraw itself.
Derived from api method `maya.OpenMaya.MItCurveCV.updateCurve`
**Undo is not currently supported for this method**
"""
pass
__apicls__ = None
__readonly__ = {}
class MeshVertex(MItComponent1D):
def connectedEdges(self):
"""
:rtype: `MeshEdge` list
"""
pass
def connectedFaces(self):
"""
:rtype: `MeshFace` list
"""
pass
def connectedVertices(self):
"""
:rtype: `MeshVertex` list
"""
pass
def geomChanged(self):
"""
Reset the geom pointer in the MItMeshVertex . If you're using MFnMesh to update Normals or Color per vertex while iterating, you must call geomChanged on the iteratior immediately after the MFnMesh call to make sure that your geometry is up to date. A crash may result if this method is not called. A similar approach must be taken for updating upstream vertex tweaks with an MPlug . After the update, call this method.
Derived from api method `maya.OpenMaya.MItMeshVertex.geomChanged`
**Undo is not currently supported for this method**
"""
pass
def getColor(self, *args, **kwargs):
pass
def getColorIndices(self, colorSetName='None'):
"""
This method returns the colorIndices into the color array see MFnMesh::getColors() of the current vertex.
:Parameters:
colorSetName : `unicode`
Name of the color set.
:rtype: `int` list
Derived from api method `maya.OpenMaya.MItMeshVertex.getColorIndices`
"""
pass
def getColors(self, colorSetName='None'):
"""
This method gets the colors of the current vertex for each face it belongs to. If no colors are assigned to the vertex at all, the return values will be (-1 -1 -1 1). If some but not all of the vertex/face colors have been explicitly set, the ones that have not been set will be (0, 0, 0, 1).
:Parameters:
colorSetName : `unicode`
Name of the color set.
:rtype: `Color` list
Derived from api method `maya.OpenMaya.MItMeshVertex.getColors`
"""
pass
def getNormal(self, space="'preTransform'"):
"""
Return the normal or averaged normal if unshared of the current vertex.
:Parameters:
space : `Space.Space`
The transformation space.
values: 'transform', 'preTransform', 'object', 'world'
:rtype: `Vector`
Derived from api method `maya.OpenMaya.MSpace.getNormal`
"""
pass
def getNormalIndices(self):
"""
This method returns the normal indices of the face/vertex associated with the current vertex.
:rtype: `int` list
Derived from api method `maya.OpenMaya.MItMeshVertex.getNormalIndices`
"""
pass
def getNormals(self, space="'preTransform'"):
"""
Return the normals of the current vertex for all faces
:Parameters:
space : `Space.Space`
The transformation space.
values: 'transform', 'preTransform', 'object', 'world'
:rtype: `Vector` list
Derived from api method `maya.OpenMaya.MSpace.getNormals`
"""
pass
def getPosition(self, space="'preTransform'"):
"""
Return the position of the current vertex in the specified space. Object space ignores all transformations for the polygon, world space includes all such transformations.
:Parameters:
space : `Space.Space`
The transformation space
values: 'transform', 'preTransform', 'object', 'world'
:rtype: `Point`
Derived from api method `maya.OpenMaya.MSpace.position`
"""
pass
def getUV(self, uvSet='None'):
"""
Get the shared UV value at this vertex
:Parameters:
uvSet : `unicode`
Name of the uv set to work with.
:rtype: (`float`, `float`)
Derived from api method `maya.OpenMaya.MItMeshVertex.getUV`
"""
pass
def getUVIndices(self, uvSet='None'):
"""
This method returns the uv indices into the normal array see MFnMesh::getUVs() of the current vertex.
:Parameters:
uvSet : `unicode`
Name of the uv set.
:rtype: `int` list
Derived from api method `maya.OpenMaya.MItMeshVertex.getUVIndices`
"""
pass
def getUVs(self, uvSet='None'):
"""
Get the UV values for all mapped faces at the current vertex. If at least one face was mapped the method will succeed.
:Parameters:
uvSet : `unicode`
Name of the uv set to work with
:rtype: (`float` list, `float` list, `int` list)
Derived from api method `maya.OpenMaya.MItMeshVertex.getUVs`
"""
pass
def hasColor(self):
"""
This method determines whether the current Vertex has a color set for one or more faces.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshVertex.hasColor`
"""
pass
def isConnectedTo(self, component):
"""
pass a component of type `MeshVertex`, `MeshEdge`, `MeshFace`, with a single element
:rtype: bool
"""
pass
def isConnectedToEdge(self, index):
"""
This method determines whether the given edge contains the current vertex
:Parameters:
index : `int`
Index of edge to check.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshVertex.connectedToEdge`
"""
pass
def isConnectedToFace(self, index):
"""
This method determines whether the given face contains the current vertex
:Parameters:
index : `int`
Index of face to check.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshVertex.connectedToFace`
"""
pass
def isOnBoundary(self):
"""
This method determines whether the current vertex is on a Boundary
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshVertex.onBoundary`
"""
pass
def numConnectedEdges(self):
"""
This Method checks for the number of connected Edges on this vertex
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshVertex.numConnectedEdges`
"""
pass
def numConnectedFaces(self):
"""
This Method checks for the number of Connected Faces
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshVertex.numConnectedFaces`
"""
pass
def numUVs(self, uvSet='None'):
"""
This method returns the number of unique UVs mapped on this vertex
:Parameters:
uvSet : `unicode`
Name of the uv set to work with
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshVertex.numUVs`
"""
pass
def setColor(self, color):
pass
def setPosition(self, point, space="'preTransform'"):
"""
Set the position of the current vertex in the given space.
:Parameters:
point : `Point`
The new position for the current vertex
space : `Space.Space`
Transformation space
values: 'transform', 'preTransform', 'object', 'world'
Derived from api method `maya.OpenMaya.MSpace.setPosition`
"""
pass
def setUV(self, uvPoint, uvSet='None'):
"""
Set the shared UV value at this vertex
:Parameters:
uvPoint : (`float`, `float`)
The UV value to set.
uvSet : `unicode`
Name of the UV set to work with
Derived from api method `maya.OpenMaya.MItMeshVertex.setUV`
"""
pass
def setUVs(self, uArray, vArray, faceIds, uvSet='None'):
"""
Set the UV value for the specified faces at the current vertex. If the face is not already mapped, the value will not be set. If at least ne face was previously mapped, the method should succeed. If no faces were mapped, the method will fail.
:Parameters:
uArray : `float` list
All the U values - in local face order
vArray : `float` list
The corresponding V values
faceIds : `int` list
The corresponding face Ids
uvSet : `unicode`
Name of the uv set to work with
Derived from api method `maya.OpenMaya.MItMeshVertex.setUVs`
"""
pass
def translateBy(self, vector, space="'preTransform'"):
"""
Translate the current vertex by the amount specified by the given vector.
:Parameters:
vector : `Vector`
The amount of translation
space : `Space.Space`
The transformation space
values: 'transform', 'preTransform', 'object', 'world'
Derived from api method `maya.OpenMaya.MSpace.translateBy`
**Undo is not currently supported for this method**
"""
pass
def updateSurface(self):
"""
Signal that this polygonal surface has changed and needs to redraw itself.
Derived from api method `maya.OpenMaya.MItMeshVertex.updateSurface`
**Undo is not currently supported for this method**
"""
pass
__apicls__ = None
__readonly__ = {}
class MeshEdge(MItComponent1D):
def connectedEdges(self):
"""
:rtype: `MeshEdge` list
"""
pass
def connectedFaces(self):
"""
:rtype: `MeshFace` list
"""
pass
def connectedVertices(self):
"""
:rtype: `MeshVertex` list
"""
pass
def getLength(self, space="'preTransform'"):
"""
This method returns the length of the current edge.
:Parameters:
space : `Space.Space`
Coordinate space in which to perform the operation.
values: 'transform', 'preTransform', 'object', 'world'
:rtype: `float`
Derived from api method `maya.OpenMaya.MSpace.getLength`
"""
pass
def getPoint(self, index, space="'preTransform'"):
"""
Return the position of the specified vertex of the current edge.
:Parameters:
index : `int`
The vertex of the edge we wish to examine (0 or 1)
space : `Space.Space`
The coordinate system for this operation
values: 'transform', 'preTransform', 'object', 'world'
:rtype: `Point`
Derived from api method `maya.OpenMaya.MSpace.point`
"""
pass
def isConnectedTo(self, component):
"""
:rtype: bool
"""
pass
def isConnectedToEdge(self, index):
"""
This method determines whether the given edge is connected to the current edge
:Parameters:
index : `int`
Index of edge to check.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshEdge.connectedToEdge`
"""
pass
def isConnectedToFace(self, index):
"""
This method determines whether the given face contains the current edge
:Parameters:
index : `int`
Index of face to check.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshEdge.connectedToFace`
"""
pass
def isOnBoundary(self):
"""
This method checks to see if the current edge is a border edge.
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshEdge.onBoundary`
"""
pass
def isSmooth(self):
"""
This method determines if the current edge in the iteration is smooth (soft).
:rtype: `bool`
Derived from api method `maya.OpenMaya.MItMeshEdge.isSmooth`
"""
pass
def numConnectedEdges(self):
"""
This method returns the number of edges connected to the current edge.
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshEdge.numConnectedEdges`
"""
pass
def numConnectedFaces(self):
"""
This method returns the number of faces (1 or 2 ) connected to the current edge.
:rtype: `int`
Derived from api method `maya.OpenMaya.MItMeshEdge.numConnectedFaces`
"""
pass
def setPoint(self, point, index, space="'preTransform'"):
"""
Set the specified vertex of the current edge to the given value.
:Parameters:
point : `Point`
The new value for the edge
index : `int`
The vertex index of the current edge we wish to set (0 or 1)
space : `Space.Space`
The coordinate system for this operation
values: 'transform', 'preTransform', 'object', 'world'
Derived from api method `maya.OpenMaya.MSpace.setPoint`
"""
pass
def setSmoothing(self, smooth='True'):
"""
This method sets the current edge to be hard or smooth (soft). The cleanupSmoothing method is no longer required to be called after setSmoothing in Maya3.0 and later versions.
:Parameters:
smooth : `bool`
if true the edge will be smooth (soft), otherwise the edge will be hard.
Derived from api method `maya.OpenMaya.MItMeshEdge.setSmoothing`
**Undo is not currently supported for this method**
"""
pass
def updateSurface(self):
"""
Signal that this polygonal surface has changed and needs to redraw itself.
Derived from api method `maya.OpenMaya.MItMeshEdge.updateSurface`
**Undo is not currently supported for this method**
"""
pass
__apicls__ = None
__readonly__ = {}
def isolateSelect(*args, **kwargs):
"""
This command turns on/off isolate select mode in a specified modeling view, specified as the argument. Isolate select
mode is a display mode where the currently selected objects are added to a list and only those objects are displayed in
the view. It allows for selective viewing of specific objects and object components.
Flags:
- addDagObject : ado (PyNode) []
Add the specified object to the set of objects to be displayed in the view.
- addSelected : addSelected (bool) []
Add the currently active objects to the set of objects to be displayed in the view.
- addSelectedObjects : aso (bool) []
Add selected objects to the set of objects to be displayed in the view. This flag differs from addSelected in that it
will ignore selected components and add the entire object.
- loadSelected : ls (bool) []
Replace the objects being displayed with the currently active objects.
- removeDagObject : rdo (PyNode) []
Remove the specified object from the set of objects to be displayed in the view.
- removeSelected : rs (bool) []
Remove the currently active objects to the set of objects to be displayed in the view.
- state : s (bool) [query]
Turns isolate select mode on/off.
- update : u (bool) []
Update the view's list of objects due to a change to the set of objects to be displayed.
- viewObjects : vo (bool) [query]
Returns the name (if any) of the objectSet which contains the list of objects visible in the view if isolate select mode
is on. If isolate select mode is off, an empty string is returned. Flag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.isolateSelect`
"""
pass
def displayColor(*args, **kwargs):
"""
This command changes or queries the display color for anything in the application that allows the user to set its color.
The color is defined by a color index into either the dormant or active color palette. These colors are part of the UI
and not part of the saved data for a model. This command is not undoable. In query mode, return type is based on
queried flag.
Flags:
- active : a (bool) [create]
Specifies the color index applies to active color palette. name Specifies the name of color to change. index The color
index for the color.
- create : c (bool) [create]
Creates a new display color which can be queried or set. If is used only when saving color preferences.
- dormant : d (bool) [create]
Specifies the color index applies to dormant color palette. If neither of the dormant or active flags is specified,
dormant is the default.
- list : l (bool) [create]
Writes out a list of all color names and their value.
- queryIndex : qi (int) [create]
Allows you to obtain a list of color names with the given color indices.
- resetToFactory : rf (bool) [create]
Resets all display colors to their factory defaults.
- resetToSaved : rs (bool) [create]
Resets all display colors to their saved values. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.displayColor`
"""
pass
def isDirty(*args, **kwargs):
"""
The isDirtycommand is used to check if a plug is dirty. The return value is 0 if it is not and 1 if it is. If more
than one plug is specified then the result is the logical orof all objects (ie. returns 1 if \*any\* of the plugs are
dirty).
Flags:
- connection : c (bool) [create]
Check the connection of the plug (default).
- datablock : d (bool) [create]
Check the datablock entry for the plug. Flag can have multiple arguments, passed either as a tuple or a
list.
Derived from mel command `maya.cmds.isDirty`
"""
pass
def listConnections(*args, **kwargs):
"""
This command returns a list of all attributes/objects of a specified type that are connected to the given object(s). If
no objects are specified then the command lists the connections on selected nodes.
Modifications:
- returns an empty list when the result is None
- returns an empty list (with a warning) when the arg is an empty list, tuple,
set, or frozenset, making it's behavior consistent with when None is
passed, or no args and nothing is selected (would formerly raise a
TypeError)
- When 'connections' flag is True, the attribute pairs are returned in a 2D-array::
[['checker1.outColor', 'lambert1.color'], ['checker1.color1', 'fractal1.outColor']]
- added sourceFirst keyword arg. when sourceFirst is true and connections is also true,
the paired list of plugs is returned in (source,destination) order instead of (thisnode,othernode) order.
this puts the pairs in the order that disconnectAttr and connectAttr expect.
- added ability to pass a list of types
:rtype: `PyNode` list
Flags:
- connections : c (bool) [create]
If true, return both attributes involved in the connection. The one on the specified object is given first. Default
false.
- destination : d (bool) [create]
Give the attributes/objects that are on the destinationside of connection to the given object. Default true.
- exactType : et (bool) [create]
When set to true, -t/type only considers node of this exact type. Otherwise, derived types are also taken into account.
- plugs : p (bool) [create]
If true, return the connected attribute names; if false, return the connected object names only. Default false;
- shapes : sh (bool) [create]
Actually return the shape name instead of the transform when the shape is selected. Default false.
- skipConversionNodes : scn (bool) [create]
If true, skip over unit conversion nodes and return the node connected to the conversion node on the other side.
Default false.
- source : s (bool) [create]
Give the attributes/objects that are on the sourceside of connection to the given object. Default true.
- type : t (unicode) [create]
If specified, only take objects of a specified type. Flag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.listConnections`
"""
pass
def exactWorldBoundingBox(*args, **kwargs):
"""
This command figures out an exact-fit bounding box for the specified objects (or selected objects if none are specified)
This bounding box is always in world space.
Flags:
- calculateExactly : ce (bool) []
- ignoreInvisible : ii (bool) [create]
Should the bounding box calculation include or exclude invisible objects? Flag can have multiple
arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.exactWorldBoundingBox`
"""
pass
def commandPort(*args, **kwargs):
"""
Opens or closes the Maya command port. The command port comprises a socket to which a client program may connect. An
example command port client mcpis included in the Motion Capture developers kit. It supports multi-byte commands and
uses utf-8 as its transform format. It will receive utf8 command string and decode it to Maya native coding. The result
will also be encoded to utf-8 before sending back. Care should be taken regarding INET domain sockets as no user
identification, or authorization is required to connect to a given socket, and all commands (including system(...)) are
allowed and executed with the user id and permissions of the Maya user. The prefix flag can be used to reduce this
security risk, as only the prefix command is executed. The query flag can be used to determine if a given command port
exists. See examples below.
Flags:
- bufferSize : bs (int) [create]
Commands and results are each subject to size limits. This option allows the user to specify the size of the buffer used
to communicate with Maya. If unspecified the default buffer size is 4096 characters. Commands longer than bufferSize
characters will cause the client connection to close. Results longer that bufferSize characters are replaced with an
error message.
- close : cl (bool) [create]
Closes the commandPort, deletes the pipes
- echoOutput : eo (bool) [create]
Sends a copy of all command output to the command port. Typically only the result is transmitted. This option provides a
copy of all output.
- listPorts : lp (bool) []
- name : n (unicode) [create]
Specifies the name of the command port which this command creates. CommandPort names of the form namecreate a UNIX
domain socket on the localhost corresponding to name. If namedoes not begin with /, then /tmp/nameis used. If namebegins
with /, namedenotes the full path to the socket. Names of the form :port numbercreate an INET domain on the local host
at the given port.
- noreturn : nr (bool) [create]
Do not write the results from executed commands back to the command port socket. Instead, the results from executed
commands are written to the script editor window. As no information passes back to the command port client regarding the
execution of the submitted commands, care must be taken not to overflow the command buffer, which would cause the
connection to close.
- pickleOutput : po (bool) [create]
Python output will be pickled.
- prefix : pre (unicode) [create]
The string argument is the name of a Maya command taking one string argument. This command is called each time data is
sent to the command port. The data written to the command port is passed as the argument to the prefix command. The data
from the command port is encoded as with enocodeString and enclosed in quotes. If newline characters are embedded in
the command port data, the input is split into individual lines. These lines are treated as if they were separate writes
to the command port. Only the result to the last prefix command is returned.
- returnNumCommands : rnc (bool) [create]
Ignore the result of the command, but return the number of commands that have been read and executed in this call. This
is a simple way to track buffer overflow. This flag is ignored when the noreturnflag is specified.
- securityWarning : sw (bool) [create]
Enables security warning on command port input.
- sourceType : stp (unicode) [create]
The string argument is used to indicate which source type would be passed to the commandPort, like mel, python. The
default source type is mel. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.commandPort`
"""
pass
def selectPriority(*args, **kwargs):
"""
The selectPrioritycommand is used to change the selection priority of particular types of objects that can be selected
when using the select tool. It accepts no other arguments besides the flags. These flags are the same as used by the
'selectType' command.
Flags:
- allComponents : alc (int) [create,query]
Set all component selection priority
- allObjects : alo (int) [create,query]
Set all object selection priority
- animBreakdown : abd (int) [create,query]
Set animation breakdown selection priority
- animCurve : ac (int) [create,query]
Set animation curve selection priority
- animInTangent : ait (int) [create,query]
Set animation in-tangent selection priority
- animKeyframe : ak (int) [create,query]
Set animation keyframe selection priority
- animOutTangent : aot (int) [create,query]
Set animation out-tangent selection priority
- byName : bn (unicode, bool) [create]
Set selection priority for the specified user-defined selection type
- camera : ca (int) [create,query]
Set camera selection priority
- cluster : cl (int) [create,query]
Set cluster selection priority
- collisionModel : clm (int) [create,query]
Set collision model selection priority
- controlVertex : cv (int) [create,query]
Set control vertex selection priority
- curve : c (int) [create,query]
Set curve selection priority
- curveKnot : ck (int) [create,query]
Set curve knot selection priority
- curveOnSurface : cos (int) [create,query]
Set curve-on-surface selection priority
- curveParameterPoint : cpp (int) [create,query]
Set curve parameter point selection priority
- dimension : dim (int) [create,query]
Set dimension shape selection priority
- dynamicConstraint : dc (int) [create,query]
Set dynamicConstraint selection priority
- edge : eg (int) [create,query]
Set mesh edge selection priority
- editPoint : ep (int) [create,query]
Set edit-point selection priority
- emitter : em (int) [create,query]
Set emitter selection priority
- facet : fc (int) [create,query]
Set mesh face selection priority
- field : fi (int) [create,query]
Set field selection priority
- fluid : fl (int) [create,query]
Set fluid selection priority
- follicle : fo (int) [create,query]
Set follicle selection priority
- hairSystem : hs (int) [create,query]
Set hairSystem selection priority
- handle : ha (int) [create,query]
Set object handle selection priority
- hull : hl (int) [create,query]
Set hull selection priority
- ikEndEffector : iee (int) [create,query]
Set ik end effector selection priority
- ikHandle : ikh (int) [create,query]
Set ik handle selection priority
- imagePlane : ip (int) [create,query]
Set image plane selection mask priority
- implicitGeometry : ig (int) [create,query]
Set implicit geometry selection priority
- isoparm : iso (int) [create,query]
Set surface iso-parm selection priority
- joint : j (int) [create,query]
Set ik handle selection priority
- jointPivot : jp (int) [create,query]
Set joint pivot selection priority
- lattice : la (int) [create,query]
Set lattice selection priority
- latticePoint : lp (int) [create,query]
Set lattice point selection priority
- light : lt (int) [create,query]
Set light selection priority
- localRotationAxis : ra (int) [create,query]
Set local rotation axis selection priority
- locator : lc (int) [create,query]
Set locator (all types) selection priority
- locatorUV : luv (int) [create,query]
Set uv locator selection priority
- locatorXYZ : xyz (int) [create,query]
Set xyz locator selection priority
- meshUVShell : msh (int) [create,query]
Set uv shell component mask on/off.
- motionTrailPoint : mtp (int) [create,query]
Set motion point selection priority
- motionTrailTangent : mtt (int) [create,query]
Set motion point tangent priority
- nCloth : ncl (int) [create,query]
Set nCloth selection priority
- nParticle : npr (int) [create,query]
Set nParticle point selection priority
- nParticleShape : nps (int) [create,query]
Set nParticle shape selection priority
- nRigid : nr (int) [create,query]
Set nRigid selection priority
- nonlinear : nl (int) [create,query]
Set nonlinear selection priority
- nurbsCurve : nc (int) [create,query]
Set nurbs-curve selection priority
- nurbsSurface : ns (int) [create,query]
Set nurbs-surface selection priority
- orientationLocator : ol (int) [create,query]
Set orientation locator selection priority
- particle : pr (int) [create,query]
Set particle point selection priority
- particleShape : ps (int) [create,query]
Set particle shape selection priority
- plane : pl (int) [create,query]
Set sketch plane selection priority
- polymesh : p (int) [create,query]
Set poly-mesh selection priority
- polymeshEdge : pe (int) [create,query]
Set poly-mesh edge selection priority
- polymeshFace : pf (int) [create,query]
Set poly-mesh face selection priority
- polymeshFreeEdge : pfe (int) [create,query]
Set poly-mesh free-edge selection priority
- polymeshUV : puv (int) [create,query]
Set poly-mesh UV point selection priority
- polymeshVertex : pv (int) [create,query]
Set poly-mesh vertex selection priority
- polymeshVtxFace : pvf (int) [create,query]
Set poly-mesh vtxFace selection priority
- queryByName : qbn (unicode) [query]
Query selection priority for the specified user-defined selection type
- rigidBody : rb (int) [create,query]
Set rigid body selection priority
- rigidConstraint : rc (int) [create,query]
Set rigid constraint selection priority
- rotatePivot : rp (int) [create,query]
Set rotate pivot selection priority
- scalePivot : sp (int) [create,query]
Set scale pivot selection priority
- sculpt : sc (int) [create,query]
Set sculpt selection priority
- selectHandle : sh (int) [create,query]
Set select handle selection priority
- spring : spr (int) [create,query]
Set spring shape selection priority
- springComponent : spc (int) [create,query]
Set individual spring selection priority
- stroke : str (int) [create,query]
Set stroke selection priority
- subdiv : sd (int) [create,query]
Set subdivision surface selection priority
- subdivMeshEdge : sme (int) [create,query]
Set subdivision surface mesh edge selection priority
- subdivMeshFace : smf (int) [create,query]
Set subdivision surface mesh face selection priority
- subdivMeshPoint : smp (int) [create,query]
Set subdivision surface mesh point selection priority
- subdivMeshUV : smu (int) [create,query]
Set subdivision surface mesh UV map selection priority
- surfaceEdge : se (int) [create,query]
Set surface edge selection priority
- surfaceFace : sf (int) [create,query]
Set surface face selection priority
- surfaceKnot : sk (int) [create,query]
Set surface knot selection priority
- surfaceParameterPoint : spp (int) [create,query]
Set surface parameter point selection priority
- surfaceRange : sr (int) [create,query]
Set surface range selection priority
- texture : tx (int) [create,query]
Set texture selection priority
- vertex : v (int) [create,query]
Set mesh vertex selection priority Flag can have multiple arguments, passed either as a tuple or a
list.
Derived from mel command `maya.cmds.selectPriority`
"""
pass
def selectedNodes(*args, **kwargs):
"""
Flags:
- dagObjects : do (bool) []
Derived from mel command `maya.cmds.selectedNodes`
"""
pass
def align(*args, **kwargs):
"""
Align or spread objects along X Y and Z axis.
Flags:
- alignToLead : atl (bool) [create]
When set, the min, center or max values are computed from the lead object. Otherwise, the values are averaged for all
objects. Default is false
- coordinateSystem : cs (PyNode) [create]
Defines the X, Y, and Z coordinates. Default is the world coordinates
- xAxis : x (unicode) [create]
Any of none, min, mid, max, dist, stack. This defines the kind of alignment to perfom, default is none.
- yAxis : y (unicode) [create]
Any of none, min, mid, max, dist, stack. This defines the kind of alignment to perfom, default is none.
- zAxis : z (unicode) [create]
Any of none, min, mid, max, dist, stack. This defines the kind of alignment to perfom, default is none.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.align`
"""
pass
def colorManagementFileRules(*args, **kwargs):
"""
This non-undoable action manages the list of rules that Maya uses to assign an initial input color space to dependency
graph nodes that read in color information from a file. Rules are structured in a chain of responsibility, from highest
priority rule to lowest priority rule, each rule matching a file path pattern and extension. If a rule matches a given
file path, its color space is returned as the result of rules evaluation, and no further rule is considered. The lowest
priority rule will always return a match. Rules can be added, removed, and changed in priority in the list. Each rule
can have its file path pattern, extension, and color space changed. The rule list can be saved to user preferences, and
loaded from user preferences. In query mode, return type is based on queried flag.
Flags:
- addRule : add (unicode) [create,edit]
Add a rule with the argument name to the list of rules, as the highest-priority rule. If this flag is used, the
pattern, extension, and colorSpace flags must be used as well, to specify the file rule pattern, extension, and color
space, respectively.
- colorSpace : cs (unicode) [create,query,edit]
The input color space for the rule. If the rule matches a file path, this is the color space that is returned. This
color space must match an existing color space in the input color space list.
- down : dwn (unicode) [create,edit]
Move the rule with the argument name down one position towards lower priority.
- evaluate : ev (unicode) [create,edit]
Evaluates the list of rules and returns the input color space name that corresponds to the argument file path.
- extension : ext (unicode) [create,query,edit]
The file extension for the rule, expressed as a glob pattern: for example, '\*' matches all extensions. For more
information about glob pattern syntax, see http://en.wikipedia.org/wiki/Glob_%28programming%29.
- listRules : lsr (bool) [create,edit]
Returns an array of rule name strings, in order, from lowest-priority (rule 0) to highest-priority (last rule in array).
- load : ld (bool) [create,edit]
Read the rules from Maya preferences. Any existing rules are cleared.
- moveUp : up (unicode) [create,edit]
Move the rule with the argument name up one position towards higher priority.
- pattern : pat (unicode) [create,query,edit]
The file path pattern for the rule. This is the substring to match in the file path, expressed as a glob pattern: for
example, '\*' matches all files. For more information about glob pattern syntax, see
http://en.wikipedia.org/wiki/Glob_%28programming%29.
- remove : rm (unicode) [create,edit]
Remove the rule with the argument name from the list of rules.
- save : sav (bool) [create,edit]
Save the rules to Maya preferences. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.colorManagementFileRules`
"""
pass
def vnnCompound(*args, **kwargs):
"""
The vnnCompoundcommand is used to operate compound and its VNN graph. The first parameter is the full name of the DG
node that contains the VNN graph. The second parameter is the name of the compound.
Flags:
- addNode : an (unicode) [create]
Add a node into the compound.
- addStatePortUI : spu (bool) [create]
Pop up a window to add iteration state port.
- canResetToFactory : crf (unicode) [create]
Query if the specified compound can be reset to its initial status.
- connected : cn (bool) [create]
Used with listNodesor listPortsto query the nodes or internal ports that have connections when the argument is true. If
the arguments is false, return all nodes which have no connection. The other side of the connection could be another
node or port.
- connectedTo : ct (unicode) [create]
Used with listNodesto query all nodes that connect to the specified ports.
- connectedToInput : cti (bool) [create]
Used with listNodesto query all nodes which connect to any input ports.
- connectedToOutput : cto (bool) [create]
Used with listNodesto query all nodes that connect to any output ports.
- create : c (unicode) [create]
Create a sub compound in the specified compound. The name of the created sub compound cannot be used before in the
specified compound.
- createInputPort : cip (unicode, unicode) [create]
Create an input port in the compound. The first argument is the name of the port. The second argument is the data type
of the port.
- createOutputPort : cop (unicode, unicode) [create]
Create an output port in the compound. The first argument is the name of the port. The second argument is the data type
of the port.
- deletePort : dp (unicode) [create]
Delete a input or output port from the compound.
- explode : ec (unicode) [create]
Explode a specified compound and move the nodes from it to its parent.
- inputPort : ip (bool) [create]
Used with listPortsto query all internal ports which connect to any input ports in the compound.
- listNodes : ln (bool) [create]
List all nodes in the compound. Can be used with other flags, such as dataType, connectedToInputto query some specified
nodes. The returned result is a list of node names.
- listPortChildren : lpc (unicode) [create]
List the children of specified port.
- listPorts : lp (bool) [create]
List all internal ports in the compound, including input and output ports. Can be used with other flags, such as output,
connectedto query some specified ports.
- moveNodeIn : mi (unicode) [create]
Move the specified node into the compound.
- movePort : mp (unicode, int) [create]
Move a port to the specified index in the compound
- nodeType : nt (unicode) [create]
Used with listNodesto query all nodes which are specified node type in the compound.
- outputPort : op (bool) [create]
Used with listPortsto query all nodes which connect to any output ports in the compound.
- portDefaultValue : pdv (unicode, unicode) [create]
Set the default value to a specified port The port cannot be connected.
- publish : pub (unicode, unicode, unicode, bool) [create]
Used to publish the compound. The arguments are, in order, the file path where to save, the namespace where to store the
compound, the name to use for the nodedef and whether or not the compound should be referenced upon publishing.
- queryIsImported : qii (bool) [create]
Query if the compound is imported.
- queryIsReferenced : qir (bool) [create]
Query if the compound is referenced.
- queryMetaData : qmd (unicode) [create]
Query the value(s) of a metadata.
- queryPortDataType : qpt (unicode) [create]
Query the data type of a specified port.
- queryPortDefaultValue : qpv (unicode) [create]
Query the default value of a specified port
- queryPortMetaDataValue : qpm (unicode, unicode) [create]
Query the metadata value of a specified port. The first argument is the port to query, the second is the type of
metadata to query.
- removeNode : rmn (unicode) [create]
Remove the specified node from the compound.
- renameNode : rn (unicode, unicode) [create]
Rename a node in the compound. The first argument is the old name of the node. The second argument is the new name.
- renamePort : rp (unicode, unicode) [create]
Rename a port of the compound. The first argument is the old name of the port. The second argument is the new name.
- resetToFactory : rtf (unicode) [create]
Reset the specified compound to its initial status. The specified compound must be able to be reset.
- saveAs : sa (unicode) [create]
Used to export Compound in the Compound menu of the Node Editor. The argument is the file path to save.
- setIsReferenced : sir (bool) [create]
Change the referenced status of the compound. If -sir/setIsReferencedis true, the compound will be made public, else the
compound will be made private to its parent compound.
- setMetaData : smd (unicode, unicode) [create]
Set the value of a metatada. The arguments are, in order, metadata name, metadata value to be set.
- setPortDataType : spt (unicode, unicode) [create]
Set the data type of a specified compound port.
- setPortMetaDataValue : spm (unicode, unicode, unicode) [create]
Set the metadata value of a specified compound port. The arguments are, in order, port name, metadata name, metadata
value to be set.
- specializedTypeName : stn (bool) [create]
Used to query the specialized implementation class names such as Bifrost_DoWhile, or Compoundfor a normal compound
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.vnnCompound`
"""
pass
def makeLive(*args, **kwargs):
"""
This commmand makes an object live. A live object defines the surface on which to create objects and to move object
relative to. Only construction planes, nurbs surfaces and polygon meshes can be made live. The makeLive command expects
one of these types of objects as an explicit argument. If no argument is explicitly specified, then there are a number
of default behaviours based on what is currently active. The command will fail if there is more than one object active
or the active object is not one of the valid types of objects. If there is nothing active, the current live object will
become dormant. Otherwise, the active object will become the live object.
Flags:
- none : n (bool) [create]
If the -n/none flag, the live object will become dormant. Use of this flag causes any arguments to be ignored.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.makeLive`
"""
pass
def pickWalk(*args, **kwargs):
"""
The pickWalk command allows you to quickly change the selection list relative to the nodes that are currently selected.
It is called pickWalk, because it walks from one selection list to another by unselecting what's currently selected, and
selecting nodes that are in the specified direction from the currently selected list. If you specify objects on the
command line, the pickWalk command will walk from those objects instead of the selected list. If the -type flag is
instances, then the left and right direction will walk to the previous or next instance of the same selected dag node.
Flags:
- direction : d (unicode) [create]
The direction to walk from the node. The choices are up | down | left | right | in | out. up walks to the parent node,
down to the child node, and left and right to the sibling nodes. If a CV on a surface is selected, the left and right
directions walk in the U parameter direction of the surface, and the up and down directions walk in the V parameter
direction. In and out are only used if the type flag is 'latticepoints'. Default is right.
- recurse : r (bool) []
- type : typ (unicode) [create]
The choices are nodes | instances | edgeloop | edgering | faceloop | keys | latticepoints | motiontrailpoints. If type
is nodes, then the left and right direction walk to the next dag siblings. If type is instances, the left and right
direction walk to the previous or next instance of the same dag node. If type is edgeloop, then the edge loop starting
at the first selected edge will be selected. If type is edgering, then the edge ring starting at the first selected edge
will be selected. If type is faceloop, and there are two connected quad faces selected which define a face loop, then
that face loop will be selected. edgeloop, edgering and faceloop all remember which was the first edge or faces
selected for as long as consecutive selections are made by this command. They use this information to determine what
the nextloop or ring selection should be. Users can make selections forwards and backwards by using the direction flag
with leftor right. If type is motiontrailpoints, then the left and right direction walk to the previous or next motion
trail points respectively. Default is nodes. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.pickWalk`
"""
pass
def nodeType(node, **kwargs):
"""
This command returns a string which identifies the given node's type. When no flags are used, the unique type name is
returned. This can be useful for seeing if two nodes are of the same type. When the apiflag is used, the MFn::Type of
the node is returned. This can be useful for seeing if a plug-in node belongs to a given class. The apiflag cannot be
used in conjunction with any other flags. When the derivedflag is used, the command returns a string array containing
the names of all the currently known node types which derive from the node type of the given object. When the
inheritedflag is used, the command returns a string array containing the names of all the base node types inherited by
the the given node. If the isTypeNameflag is present then the argument provided to the command is taken to be the name
of a node type rather than the name of a specific node. This makes it possible to query the hierarchy of node types
without needing to have instances of each node type.
Note: this will return the dg node type for an object, like maya.cmds.nodeType,
NOT the pymel PyNode class. For objects like components or attributes,
nodeType will return the dg type of the node to which the PyNode is attached.
:rtype: `unicode`
Flags:
- apiType : api (bool) [create]
Return the MFn::Type value (as a string) corresponding to the given node. This is particularly useful when the given
node is defined by a plug-in, since in this case, the MFn::Type value corresponds to the underlying proxy class. This
flag cannot be used in combination with any of the other flags.
- derived : d (bool) [create]
Return a string array containing the names of all the currently known node types which derive from the type of the
specified node.
- inherited : i (bool) [create]
Return a string array containing the names of all the base node types inherited by the specified node.
- isTypeName : itn (bool) [create]
If this flag is present, then the argument provided to the command is the name of a node type rather than the name of a
specific node. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.nodeType`
"""
pass
def baseTemplate(*args, **kwargs):
"""
This is the class for the commands that edit and/or query templates. In query mode, return type is based on
queried flag.
Flags:
- exists : ex (bool) [query]
Returns true or false depending upon whether the specified template exists. When used with the matchFile argument, the
query will return true if the template exists and the filename it was loaded from matches the filename given.
- fileName : fn (unicode) [create,query]
Specifies the filename associated with the template. This argument can be used in conjunction with load, save or query
modes. If no filename is associated with a template, a default file name based on the template name will be used. It is
recommended but not required that the filename and template name correspond.
- force : f (bool) [create]
This flag is used with some actions to allow them to proceed with an overwrite or destructive operation. When used with
load, it will allow an existing template to be reloaded from a file. When used in create mode, it will allow an
existing template to be recreated (for example when using fromContainer argument to regenerate a template).
- load : l (bool) []
Load an existing template from a file. If a filename is specified for the template, the entire file (and all templates
in it) will be loaded. If no file is specified, a default filename will be assumed, based on the template name.
- matchFile : mf (unicode) [query]
Used in query mode in conjunction with other flags this flag specifies an optional file name that is to be matched as
part of the query operation.
- silent : si (bool) [create,query,edit]
Silent mode will suppress any error or warning messages that would normally be reported from the command execution. The
return values are unaffected.
- unload : u (bool) [create]
Unload the specified template. This action will not delete the associated template file if one exists, it merely
removes the template definition from the current session.
- viewList : vl (unicode) [create,query]
Used in query mode, returns a list of all views defined on the template. Flag can have
multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.baseTemplate`
"""
pass
def duplicate(*args, **kwargs):
"""
This command duplicates the given objects. If no objects are given, then the selected list is duplicated. The smart
transform feature allows duplicate to transform newly duplicated objects based on previous transformations between
duplications. Example: Duplicate an object and move it to a new location. Duplicate it again with the smart duplicate
flag. It should have moved once again the distance you had previously moved it. Note: changing the selected list between
smart duplications will cause the transform information to be deleted The upstream Nodes option forces duplication of
all upstream nodes leading upto the selected objects.. Upstream nodes are defined as all nodes feeding into selected
nodes. During traversal of Dependency graph, if another dagObject is encountered, then that node and all it's parent
transforms are also duplicated. The inputConnections option forces the duplication of input connections to the nodes
that are to be duplicated. This is very useful especially in cases where two nodes that are connected to each other are
specified as nodes to be duplicated. In that situation, the connection between the nodes is also duplicated. See
also:instance
Modifications:
- new option: addShape
If addShape evaluates to True, then all arguments fed in must be shapes, and each will be duplicated and added under
the existing parent transform, instead of duplicating the parent transform.
The following arguments are incompatible with addShape, and will raise a ValueError if enabled along with addShape:
renameChildren (rc), instanceLeaf (ilf), parentOnly (po), smartTransform (st)
- returns wrapped classes
- returnRootsOnly is forced on for dag objects. This is because the duplicate command does not use full paths when returning
the names of duplicated objects and will fail if the name is not unique.
Flags:
- inputConnections : ic (bool) [create]
Input connections to the node to be duplicated, are also duplicated. This would result in a fan-out scenario as the
nodes at the input side are not duplicated (unlike the -un option).
- instanceLeaf : ilf (bool) [create]
instead of duplicating leaf DAG nodes, instance them.
- name : n (unicode) [create]
name to give duplicated object(s)
- parentOnly : po (bool) [create]
Duplicate only the specified DAG node and not any of its children.
- renameChildren : rc (bool) [create]
rename the child nodes of the hierarchy, to make them unique.
- returnRootsOnly : rr (bool) [create]
return only the root nodes of the new hierarchy. When used with upstreamNodes flag, the upstream nodes will be omitted
in the result. This flag controls only what is returned in the output string[], and it does NOT change the behaviour of
the duplicate command.
- smartTransform : st (bool) [create]
remembers last transformation and applies it to duplicated object(s)
- upstreamNodes : un (bool) [create]
the upstream nodes leading upto the selected nodes (along with their connections) are also duplicated.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.duplicate`
"""
pass
def _getPymelType(arg, name):
"""
Get the correct Pymel Type for an object that can be a MObject, PyNode or name of an existing Maya object,
if no correct type is found returns DependNode by default.
If the name of an existing object is passed, the name and MObject will be returned
If a valid MObject is passed, the name will be returned as None
If a PyNode instance is passed, its name and MObject will be returned
"""
pass
def scaleComponents(*args, **kwargs):
"""
This is a limited version of the scale command. First, it only works on selected components. You provide a pivot in
world space, and you can provide a rotation. This rotation affects the scaling, so that rather than scaling in X, Y, Z,
this is scaling in X, Y, and Z after they have been rotated by the given rotation. This allows selected components to be
scaled in any arbitrary space, not just object or world space as the regular scale allows. Scale values are always
relative, not absolute.
Flags:
- pivot : p (float, float, float) [create]
The pivot position in world space (default is origin)
- rotation : ro (float, float, float) [create]
The rotational offset for the scaling (default is none) Flag can have multiple arguments, passed either
as a tuple or a list.
Derived from mel command `maya.cmds.scaleComponents`
"""
pass
def container(*args, **kwargs):
"""
This command can be used to create and query container nodes. It is also used to perform operations on containers such
as: add and remove nodes from the containerpublish attributes from nodes inside the containerreplace the connections and
values from one container onto another oneremove a container without removing its member nodes
Modifications:
- returns a list of PyNode objects for flags: (query and (nodeList or connectionList))
- returns a PyNode object for flags: (query and (findContainer or asset))
- <lambda>(result) for flags: (query and bindAttr and not (publishName or publishAsParent or publishAsChild))
- f(result) for flags: (query and unbindAttr and not (publishName or publishAsParent or publishAsChild))
Flags:
- addNode : an (<type 'unicode'>, ...) [create,edit]
Specifies the list of nodes to add to container.
- asset : a (<type 'unicode'>, ...) [query]
When queried, if all the nodes in nodeList belong to the same container, returns container's name. Otherwise returns
empty string. This flag is functionally equivalent to the findContainer flag.
- assetMember : am (unicode) [query]
Can be used during query in conjunction with the bindAttr flag to query for the only published attributes related to the
specified node within the container.
- bindAttr : ba (unicode, unicode) [query,edit]
Bind a contained attribute to an unbound published name on the interface of the container; returns a list of bound
published names. The first string specifies the node and attribute name to be bound in node.attrformat. The second
string specifies the name of the unbound published name. In query mode, returns a string array of the published names
and their corresponding attributes. The flag can also be used in query mode in conjunction with the -publishName,
-publishAsParent, and -publishAsChild flags.
- connectionList : cl (bool) [query]
Returns a list of the exterior connections to the container node.
- current : c (bool) [create,query,edit]
In create mode, specify that the newly created asset should be current. In edit mode, set the selected asset as current.
In query, return the current asset.
- fileName : fn (<type 'unicode'>, ...) [query]
Used to query for the assets associated with a given file name.
- findContainer : fc (<type 'unicode'>, ...) [query]
When queried, if all the nodes in nodeList belong to the same container, returns container's name. Otherwise returns
empty string.
- force : f (bool) [create,edit]
This flag can be used in conjunction with -addNode and -removeNode flags only. If specified with -addNode, nodes will be
disconnected from their current containers before they are added to new one. If specified with -removeNode, nodes will
be removed from all containers, instead of remaining in the parent container if being removed from a nested container.
- includeHierarchyAbove : iha (bool) [create,edit]
Used to specify that the parent hierarchy of the supplied node list should also be included in the container (or deleted
from the container). Hierarchy inclusion will stop at nodes which are members of other containers.
- includeHierarchyBelow : ihb (bool) [create,edit]
Used to specify that the hierarchy below the supplied node list should also be included in the container (or delete from
the container). Hierarchy inclusion will stop at nodes which are members of other containers.
- includeNetwork : inc (bool) [create,edit]
Used to specify that the node network connected to supplied node list should also be included in the container. Network
traversal will stop at default nodes and nodes which are members of other containers.
- includeNetworkDetails : ind (unicode) [create,edit]
Used to specify specific parts of the network that should be included. Valid arguments to this flag are: channels, sdk,
constraints, historyand expressions, inputs, outputs. The difference between this flag and the includeNetwork flag, is
that it will include all connected nodes regardless of their type. Note that dag containers include their children, so
they will always include constraint nodes that are parented beneath the selected objects, even when constraints are not
specified as an input.
- includeShaders : isd (bool) [create,edit]
Used to specify that for any shapes included, their shaders will also be included in the container.
- includeShapes : ish (bool) [create,edit]
Used to specify that for any transforms selected, their direct child shapes will be included in the container (or
deleted from the container). This flag is not necessary when includeHierarchyBelow is used since the child shapes and
all other descendents will automatically be included.
- includeTransform : it (bool) [create,edit]
Used to specify that for any shapes selected, their parent transform will be included in the container (or deleted from
the container). This flag is not necessary when includeHierarchyAbove is used since the parent transform and all of its
parents will automatically be included.
- isContainer : isc (bool) [query]
Return true if the selected or specified node is a container node. If multiple containers are queried, only the state of
the first will be returned.
- name : n (unicode) [create]
Sets the name of the newly-created container.
- nodeList : nl (bool) [query]
When queried, returns a list of nodes in container. The list will be sorted in the order they were added to the
container. This will also display any reordering done with the reorderContainer command.
- nodeNamePrefix : nnp (bool) [create,edit]
Specifies that the name of published attributes should be of the form node_attr. Must be used with the
-publishConnections/-pc flag.
- parentContainer : par (bool) [query]
Flag to query the parent container of a specified container.
- preview : p (bool) [create]
This flag is valid in create mode only. It indicates that you do not want the container to be created, instead you want
to preview its contents. When this flag is used, Maya will select the nodes that would be put in the container if you
did create the container. For example you can see what would go into the container with -includeNetwork, then modify
your selection as desired, and do a create container with the selected objects only.
- publishAndBind : pb (unicode, unicode) [edit]
Publish the given name and bind the attribute to the given name. First string specifies the node and attribute name in
node.attrformat. Second string specifies the name it should be published with.
- publishAsChild : pac (unicode, unicode) [query,edit]
Publish contained node to the interface of the container to indicate it can be a child of external nodes. The second
string is the name of the published node. In query mode, returns a string of the published names and the corresponding
nodes. If -publishName flag is used in query mode, only returns the published names; if -bindAttr flag is used in query
mode, only returns the name of the published nodes.
- publishAsParent : pap (unicode, unicode) [query,edit]
Publish contained node to the interface of the container to indicate it can be a parent to external nodes. The second
string is the name of the published node. In query mode, returns a string of array of the published names and the
corresponding nodes. If -publishName flag is used in query mode, only returns the published names; if -bindAttr flag is
used in query mode, only returns the name of the published nodes.
- publishAsRoot : pro (unicode, bool) [query,edit]
Publish or unpublish a node as a root. The significance of root transform node is twofold. When container-centric
selection is enabled, the root transform will be selected if a container node in the hierarchy below it is selected in
the main scene view. Also, when exporting a container proxy, any published root transformation attributes such as
translate, rotate or scale will be hooked up to attributes on a stand-in node. In query mode, returns the node that has
been published as root.
- publishAttr : pa (unicode) [query]
In query mode, can only be used with the -publishName(-pn) flag, and takes an attribute as an argument; returns the
published name of the attribute, if any.
- publishConnections : pc (bool) [create,edit]
Publish all connections from nodes inside the container to nodes outside the container.
- publishName : pn (unicode) [query,edit]
Publish a name to the interface of the container, and returns the actual name published to the interface. In query
mode, returns the published names for the container. If the -bindAttr flag is specified, returns only the names that are
bound; if the -unbindAttr flag is specified, returns only the names that are not bound; if the
-publishAsParent/-publishAsChild flags are specified, returns only names of published parents/children. if the
-publishAttr is specified with an attribute argument in the node.attrformat, returns the published name for that
attribute, if any.
- removeContainer : rc (bool) [edit]
Disconnects all the nodes from container and deletes container node.
- removeNode : rn (<type 'unicode'>, ...) [edit]
Specifies the list of nodes to remove from container. If node is a member of a nested container, it will be added to the
parent container. To remove from all containers completely, use the -force flag.
- type : typ (unicode) [create,query]
By default, a container node will be created. Alternatively, the type flag can be used to indicate that a different type
of container should be created. At the present time, the only other valid type of container node is dagContainer.
- unbindAndUnpublish : ubp (unicode) [edit]
Unbind the given attribute (in node.attrformat) and unpublish its associated name. Unbinding a compound may trigger
unbinds of its compound parents/children. So the advantage of using this one flag is that it will automatically
unpublish the names associated with these automatic unbinds.
- unbindAttr : ua (unicode, unicode) [query,edit]
Unbind a published attribute from its published name on the interface of the container, leaving an unbound published
name on the interface of the container; returns a list of unbound published names. The first string specifies the node
and attribute name to be unbound in node.attrformat, and the second string specifies the name of the bound published
name. In query mode, can only be used with the -publishName, -publishAsParent and -publishAsChild flags.
- unbindChild : unc (unicode) [edit]
Unbind the node published as child, but do not remove its published name from the interface of the container.
- unbindParent : unp (unicode) [edit]
Unbind the node published as parent, but do not remove its published name from the interface of the container.
- unpublishChild : upc (unicode) [edit]
Unpublish node published as child from the interface of the container
- unpublishName : un (unicode) [edit]
Unpublish an unbound name from the interface of the container.
- unpublishParent : upp (unicode) [edit]
Unpublish node published as parent from the interface of the container
- unsortedOrder : uso (bool) [query]
This flag has no effect on the operation of the container command (OBSOLETE). Flag can have multiple
arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.container`
"""
pass
def scale(obj, *args, **kwargs):
"""
The scale command is used to change the sizes of geometric objects. The default behaviour, when no objects or flags are
passed, is to do a relative scale on each currently selected object object using each object's existing scale pivot
point.
Modifications:
- allows any iterable object to be passed as first argument::
scale("pSphere1", [0,1,2])
NOTE: this command also reorders the argument order to be more intuitive, with the object first
Flags:
- absolute : a (bool) [create]
Perform an absolute operation.
- centerPivot : cp (bool) [create]
Let the pivot be the center of the bounding box of all objects
- constrainAlongNormal : xn (bool) [create]
When true, transform constraints are applied along the vertex normal first and only use the closest point when no
intersection is found along the normal.
- deletePriorHistory : dph (bool) [create]
If true then delete the history prior to the current operation.
- distanceOnly : dso (bool) [create]
Scale only the distance between the objects.
- localSpace : ls (bool) [create]
Use local space for scaling
- objectCenterPivot : ocp (bool) [create]
Let the pivot be the center of the bounding box of each object
- objectSpace : os (bool) [create]
Use object space for scaling
- orientAxes : oa (float, float, float) [create]
Use the angles for the orient axes.
- pivot : p (float, float, float) [create]
Define the pivot point for the transformation
- preserveChildPosition : pcp (bool) [create]
When true, transforming an object will apply an opposite transform to its child transform to keep them at the same
world-space position. Default is false.
- preserveGeometryPosition : pgp (bool) [create]
When true, transforming an object will apply an opposite transform to its geometry points to keep them at the same
world-space position. Default is false.
- preserveUV : puv (bool) [create]
When true, UV values on scaled components are projected along the axis of scaling in 3d space. For small edits, this
will freeze the world space texture mapping on the object. When false, the UV values will not change for a selected
vertices. Default is false.
- reflection : rfl (bool) [create]
To move the corresponding symmetric components also.
- reflectionAboutBBox : rab (bool) [create]
Sets the position of the reflection axis at the geometry bounding box
- reflectionAboutOrigin : rao (bool) [create]
Sets the position of the reflection axis at the origin
- reflectionAboutX : rax (bool) [create]
Specifies the X=0 as reflection plane
- reflectionAboutY : ray (bool) [create]
Specifies the Y=0 as reflection plane
- reflectionAboutZ : raz (bool) [create]
Specifies the Z=0 as reflection plane
- reflectionTolerance : rft (float) [create]
Specifies the tolerance to findout the corresponding reflected components
- relative : r (bool) [create]
Perform a operation relative to the object's current position
- scaleX : x (bool) [create]
Scale in X direction
- scaleXY : xy (bool) [create]
Scale in X and Y direction
- scaleXYZ : xyz (bool) [create]
Scale in all directions (default)
- scaleXZ : xz (bool) [create]
Scale in X and Z direction
- scaleY : y (bool) [create]
Scale in Y direction
- scaleYZ : yz (bool) [create]
Scale in Y and Z direction
- scaleZ : z (bool) [create]
Scale in Z direction
- symNegative : smn (bool) [create]
When set the component transformation is flipped so it is relative to the negative side of the symmetry plane. The
default (no flag) is to transform components relative to the positive side of the symmetry plane.
- worldSpace : ws (bool) [create]
Use world space for scaling
- xformConstraint : xc (unicode) [create]
Apply a transform constraint to moving components. none - no constraintsurface - constrain components to the surfaceedge
- constrain components to surface edgeslive - constraint components to the live surfaceFlag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.scale`
"""
pass
def lockNode(*args, **kwargs):
"""
Locks or unlocks one or more dependency nodes. A locked node is restricted in the following ways: It may not be
deleted.It may not be renamed.Its parenting may not be changed.Attributes may not be added to or removed from it.Locked
attributes may not be unlocked.Unlocked attributes may not be locked.Note that an unlocked attribute of a locked node
may still have its value set, or connections to it made or broken. For more information on attribute locking, see the
setAttrcommand. If no node names are specified then the current selection list is used. There are a few special
behaviors when locking containers. Containers are automatically expanded to their constituent objects. When a container
is locked, members of the container may not be unlocked and the container membership may not be modified. Containers may
also be set to lock unpublished attributes. When in this state, unpublished member attributes may not have existing
connections broken, new connections cannot be made, and values on unconnected attributes may not be modified. Parenting
is allowed to change on members of locked containers that have been published as parent or child anchors.
Flags:
- ignoreComponents : ic (bool) [create,query]
Normally, the presence of a component in the list of objects to be locked will cause the command to fail with an error.
But if this flag is supplied then components will be silently ignored.
- lock : l (bool) [create,query]
Specifies the new lock state for the node. The default is true.
- lockName : ln (bool) [create,query]
Specifies the new lock state for the node's name.
- lockUnpublished : lu (bool) [create,query]
Used in conjunction with the lock flag. On a container, lock or unlock all unpublished attributes on the members of the
container. For non-containers, lock or unlock unpublished attributes on the specified node.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.lockNode`
"""
pass
def cycleCheck(*args, **kwargs):
"""
This command searches for plug cycles in the dependency graph. If a plug or node is selected then it searches for cycles
that that plug or node is involved with. Plugs or nodes can also be passed as arguments. If the -all flag is used then
the entire graph is searched. Normally the return value is a boolean indicating whether or not the given items were
involved in a cycle. If the -list flag is used then the return value is the list of all plugs in cycles (involving the
selected plug or node if any). Note that it is possible for evaluation cycles to occur even where no DG connections
exist. Here are some examples: 1) Nodes with evaluation-time dependent connections: An example is expression nodes,
because we cannot tell what an expression node is actually referring to until it is evaluated, and such evaluation-time
dependent nodes may behave differently based on the context (e.g. time) they are evaluated at. If you suspect a cycle
due to such a connection, the best way to detect the cycle is through manual inspection. 2) Cycles due to DAG hierarchy:
noting that DAG nodes are implicitely connected through parenting, if a child DAG node connects an output into the input
of a parent node, a cycle will exist if the plugs involved also affect each other. In order to enable detection of
cycles involving the DAG, add the -dag flag to the command line. Note also that this command may incorrectly report a
cycle on an instanced skeleton where some of the instances use IK. You will have to examine the reported cycle yourself
to determine if it is truly a cycle or not. The evaluation time cycle checking will not report false cycles.
Flags:
- all : all (bool) [create]
search the entire graph for cycles instead of the selection list. (Note: if nothing is selected, -all is assumed).
- children : c (bool) [create]
Do not consider cycles on the children, only the specified plugs
- dag : dag (bool) [create]
Also look for cycles due to relationships in the DAG. For each DAG node, the parenting connection on its children is
also considered when searching for cycles.
- evaluation : e (bool) [create,query]
Turn on and off cycle detection during graph evaluation
- firstCycleOnly : fco (bool) [create]
When -list is used to return a plug list, the list may contain multiple cycles or partial cycles. When -firstCycleOnly
is specified only the first such cycle (which will be a full cycle) is returned.
- firstPlugPerNode : fpn (bool) [create]
When -list is used to return a plug list, the list will typically contain multiple plugs per node (e.g. ... A.output
B.input B.output C.input ...), reflecting internal affectsrelationships rather than external DG connections. When
-firstPlugPerNode is specified, only the first plug in the list for each node is returned (B.input in the example).
- lastPlugPerNode : lpn (bool) [create]
When -list is used to return a plug list, the list will typically contain multiple plugs per node (e.g. ... A.output
B.input B.output C.input ...), reflecting internal affectsrelationships rather than external DG connections. When
-lastPlugPerNode is specified, only the last plug in the list for each node is returned (B.output in the example).
- list : l (bool) [create]
Return all plugs involved in one or more cycles. If not specified, returns a boolean indicating whether a cycle exists.
- listSeparator : ls (unicode) [create]
When -list is used to return a plug list, the list may contain multiple cycles or partial cycles. Use -listSeparator to
specify a string that will be inserted into the returned string array to separate the cycles.
- parents : p (bool) [create]
Do not consider cycles on the parents, only the specified plugs
- secondary : s (bool) [create]
Look for cycles on related plugs as well as the specified plugs Default is onfor the -allcase and offfor others
- timeLimit : tl (time) [create]
Limit the search to the given amount of time Flag can have multiple arguments, passed either as a tuple
or a list.
Derived from mel command `maya.cmds.cycleCheck`
"""
pass
def attributeInfo(*args, **kwargs):
"""
This command lists all of the attributes that are marked with certain flags. Combinations of flags may be specified and
all will be considered. (The method of combination depends on the state of the logicalAnd/andflag.) When the
allAttributes/allflag is specified, attributes of all types will be listed.
Flags:
- allAttributes : all (bool) [create]
Show all attributes associated with the node regardless of type. Use of this flag overrides any other attribute type
flags and logical operation that may be specified on the command.
- bool : b (bool) [create]
Show the attributes that are of type boolean. Use the 'on' state to get only boolean attributes; the 'off' state to
ignore boolean attributes.
- enumerated : e (bool) [create]
Show the attributes that are of type enumerated. Use the 'on' state to get only enumerated attributes; the 'off' state
to ignore enumerated attributes.
- hidden : h (bool) [create]
Show the attributes that are marked as hidden. Use the 'on' state to get hidden attributes; the 'off' state to get non-
hidden attributes.
- inherited : inherited (bool) [create]
Filter the attributes based on whether they belong to the node type directly or have been inherited from a root type
(e.g. meshShape/direct or dagObject/inherited). Use the 'on' state to get only inherited attributes, the 'off' state to
get only directly owned attributes, and leave the flag unspecified to get both.
- internal : i (bool) [create]
Show the attributes that are marked as internal to the node. Use the 'on' state to get internal attributes; the 'off'
state to get non-internal attributes.
- leaf : l (bool) [create]
Show the attributes that are complex leaves (ie. that have parent attributes and have no children themselves). Use the
'on' state to get leaf attributes; the 'off' state to get non-leaf attributes.
- logicalAnd : logicalAnd (bool) [create]
The default is to take the logical 'or' of the above conditions. Specifying this flag switches to the logical 'and'
instead.
- multi : m (bool) [create]
Show the attributes that are multis. Use the 'on' state to get multi attributes; the 'off' state to get non-multi
attributes.
- short : s (bool) [create]
Show the short attribute names instead of the long names.
- type : t (unicode) [create]
static node type from which to get 'affects' information Flag can have multiple
arguments, passed either as a tuple or a list.
- userInterface : ui (bool) [create]
Show the UI-friendly attribute names instead of the Maya ASCII names. Takes precedence over the -s/-short flag if both
are specified.
- writable : w (bool) [create]
Show the attributes that are writable (ie. can have input connections). Use the 'on' state to get writable attributes;
the 'off' state to get non-writable attributes.
Derived from mel command `maya.cmds.attributeInfo`
"""
pass
def containerBind(*args, **kwargs):
"""
This is an accessory command to the container command which is used for some automated binding operations on the
container. A container's published interface can be bound using a bindingSet on the associated container template.
In query mode, return type is based on queried flag.
Flags:
- allNames : all (bool) [create]
Specifies that all published names on the container should be considered during the binding operation. By default only
unbound published names will be operated on. Additionally specifying the 'force' option with 'all' will cause all
previously bound published names to be reset (or unbound) before the binding operation is performed; in the event that
there is no appropriate binding found for the published name, it will be left in the unbound state.
- bindingSet : bs (unicode) [query]
Specifies the name of the template binding set to use for the bind or query operation. This flag is not available in
query mode.
- bindingSetConditions : bsc (bool) [query]
Used in query mode, returns a list of binding set condition entries from the specified template binding set. The list
returned is composed of of all published name / condition string pairs for each entry in the binding set. This flag
returns all entries in the associated binding set and does not take into account the validity of each entry with respect
to the container's list of published names, bound or unbound state, etc.
- bindingSetList : bsl (bool) [query,edit]
Used in query mode, returns a list of available binding sets that are defined on the associated container template.
- force : f (bool) [create]
This flag is used to force certain operations to proceed that would normally not be performed.
- preview : p (bool) [create]
This flag will provide a preview of the results of a binding operation but will not actually perform it. A list of
publishedName/boundName pairs are returned for each published name that would be affected by the binding action. If the
binding of a published name will not change as a result of the action it will not be listed. Published names that were
bound but will become unbound are also listed, in this case the associated boundName will be indicated by an empty
string. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.containerBind`
"""
pass
def displayLevelOfDetail(*args, **kwargs):
"""
This command is responsible for setting the display level-of-detail for edit refreshes. If enabled, objects will draw
with lower detail based on their distance from the camera. When disabled objects will display at full resolution at all
times. This is not an undoable command In query mode, return type is based on queried flag.
Flags:
- levelOfDetail : lod (bool) []
Enable/disable level of detail. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.displayLevelOfDetail`
"""
pass
def displayRGBColor(*args, **kwargs):
"""
This command changes or queries the display color for anything in the application that allows the user to set its color.
These colors are part of the UI and not part of the saved data for a model. This command is not undoable.
Flags:
- create : c (bool) [create]
Creates a new RGB display color which can be queried or set. If is used only when saving color preferences. name
Specifies the name of color to change.
- hueSaturationValue : hsv (bool) [create,query]
Indicates that rgb values are really hsv values. Upon query, returns the HSV valuses as an array of 3 floats. r g b The
RGB values for the color. (Between 0-1)
- list : l (bool) [create]
Writes out a list of all RGB color names and their value.
- resetToFactory : rf (bool) [create]
Resets all the RGB display colors to their factory defaults.
- resetToSaved : rs (bool) [create]
Resets all the RGB display colors to their saved values. Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.displayRGBColor`
"""
pass
def paramDimension(*args, **kwargs):
"""
This command is used to create a param dimension to display the parameter value of a curve/surface at a specified point
on the curve/surface.
Derived from mel command `maya.cmds.paramDimension`
"""
pass
def affectedNet(*args, **kwargs):
"""
This command gets the list of attributes on a node or node type and creates nodes of type TdnAffect, one for each
attribute, that are connected iff the source node's attribute affects the destination node's attribute. In query mode,
return type is based on queried flag.
Flags:
- name : n (unicode) []
- type : t (unicode) [create]
Get information from the given node type instead of one node Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.affectedNet`
"""
pass
def listHistory(*args, **kwargs):
"""
This command traverses backwards or forwards in the graph from the specified node and returns all of the nodes whose
construction history it passes through. The construction history consists of connections to specific attributes of a
node defined as the creators and results of the node's main data, eg. the curve for a Nurbs Curve node. For information
on history connections through specific plugs use the listConnectionscommand first to find where the history begins then
use this command on the resulting node.
Modifications:
- returns an empty list when the result is None
- raises a RuntimeError when the arg is an empty list, tuple, set, or
frozenset, making it's behavior consistent with when None is passed, or
no args and nothing is selected (would formerly raise a TypeError)
- added a much needed 'type' filter
- added an 'exactType' filter (if both 'exactType' and 'type' are present, 'type' is ignored)
:rtype: `DependNode` list
Flags:
- allConnections : ac (bool) [create]
If specified, the traversal that searches for the history or future will not restrict its traversal across nodes to only
dependent plugs. Thus it will reach all upstream nodes (or all downstream nodes for f/future).
- allFuture : af (bool) [create]
If listing the future, list all of it. Otherwise if a shape has an attribute that represents its output geometry data,
and that plug is connected, only list the future history downstream from that connection.
- allGraphs : ag (bool) [create]
This flag is obsolete and has no effect.
- breadthFirst : bf (bool) [create]
The breadth first traversal will return the closest nodes in the traversal first. The depth first traversal will follow
a complete path away from the node, then return to any other paths from the node. Default is depth first.
- future : f (bool) [create]
List the future instead of the history.
- futureLocalAttr : fl (bool) [query]
This flag allows querying of the local-space future-related attribute(s) on shape nodes.
- futureWorldAttr : fw (bool) [query]
This flag allows querying of the world-space future-related attribute(s) on shape nodes.
- groupLevels : gl (bool) [create]
The node names are grouped depending on the level. 1 is the lead, the rest are grouped with it.
- historyAttr : ha (bool) [query]
This flag allows querying of the attribute where history connects on shape nodes.
- interestLevel : il (int) [create]
If this flag is set, only nodes whose historicallyInteresting attribute value is not less than the value will be listed.
The historicallyInteresting attribute is 0 on nodes which are not of interest to non-programmers. 1 for the TDs, 2 for
the users.
- leaf : lf (bool) [create]
If transform is selected, show history for its leaf shape. Default is true.
- levels : lv (int) [create]
Levels deep to traverse. Setting the number of levels to 0 means do all levels. All levels is the default.
- pruneDagObjects : pdo (bool) [create]
If this flag is set, prune at dag objects. Flag can have multiple arguments, passed either as a tuple
or a list.
Derived from mel command `maya.cmds.listHistory`
"""
pass
def uniqueObjExists(name):
"""
Returns True if name uniquely describes an object in the scene.
"""
pass
def encodeString(*args, **kwargs):
"""
This action will take a string and encode any character that would need to be escaped before being sent to some other
command. Such characters include:double quotesnewlinestabs
Derived from mel command `maya.cmds.encodeString`
"""
pass
def selectPref(*args, **kwargs):
"""
This command controls state variables used to selection UI behavior.
Flags:
- affectsActive : aa (bool) [create,query]
Set affects-active toggle which when on causes the active list to be affected when changing between object and component
selection mode.
- allowHiliteSelection : ahs (bool) [create,query]
When in component selection mode, allow selection of objects for editing. If an object is selected for editing, it
appears in the hilite color and its selectable components are automatically displayed.
- autoSelectContainer : asc (bool) [query]
When enabled, with container centric selection also on, whenever the root transform is selected in the viewport, the
container node will automatically be selected as well.
- autoUseDepth : aud (bool) [query]
When enabled, useDepth and paintSelectWithDepth will be automatically enabled in shaded display mode and disabled in
wireframe display mode.
- clickBoxSize : cbs (int) [create,query]
When click selecting, this value defines the size of square picking region surrounding the cursor. The size of the
square is twice the specified value. That is, the value defines the amount of space on all four sides of the cursor
position. The size must be positive.
- clickDrag : cld (bool) [create,query]
Set click/drag selection interaction on/off
- containerCentricSelection : ccs (bool) [query]
When enabled, selecting any DAG node in a container in the viewport will select the container's root transform if there
is one. If there is no root transform then the highest DAG node in the container will be selected. There is no effect
when selecting nodes which are not in a container.
- disableComponentPopups : dcp (bool) [create,query]
A separate preference to allow users to disable popup menus when selecting components. This pref is only meaningful if
the popupMenuSelection pref is enabled.
- expandPopupList : epl (bool) [create,query]
When in popup selection mode, if this is set then all selection items that contain multiple objects or components will
be be expanded such that each object or component will be a single new selection item.
- ignoreSelectionPriority : isp (bool) [create,query]
If this is set, selection priority will be ignored when performing selection.
- manipClickBoxSize : mcb (int) [create,query]
When selecting a manipulator, this value defines the size of square picking region surrounding the cursor. The size of
the square is twice the specified value. That is, the value defines the amount of space on all four sides of the cursor
position. The size must be positive.
- paintSelect : ps (bool) [query]
When enabled, the select tool will use drag selection instead of marquee selection.
- paintSelectRefine : psf (bool) []
- paintSelectWithDepth : psd (bool) [query]
When enabled, paint selection will not select components that are behind the surface in the current camera view.
- popupMenuSelection : pms (bool) [create,query]
If this is set, a popup menu will be displayed and used to determine the object to select. The menu lists the current
user box (marquee) of selected candidate objects.
- preSelectBackfacing : psb (bool) [query]
When enabled preselection will highlight backfacing components whose normals face away from the camera.
- preSelectClosest : psc (bool) [query]
When enabled and the cursor is over a surface, preselection highlighting will try to preselect the closest component to
the cursor regardless of distance.
- preSelectDeadSpace : pds (int) [query]
This value defines the size of the region around the cursor used for preselection highlighting when the cursor is
outside the surface.
- preSelectHilite : psh (bool) [query]
When enabled, the closest component under the cursor will be highlighted to indicate that clicking will select that
component.
- preSelectHiliteSize : phs (float) [query]
This value defines the size of the region around the cursor used for preselection highlighting. Within this region the
closest component to the cursor will be highlighted.
- preSelectSize : pss (int) []
- preSelectTweakDeadSpace : pdt (int) [query]
This value defines the size of the region around the cursor used for preselection highlighting when the cursor is
outside the surface in tweak mode.
- selectTypeChangeAffectsActive : stc (bool) [query]
If true then the active list will be updated according to the new selection preferences.
- selectionChildHighlightMode : sch (int) [create,query]
Controls the highlighting of the children of a selected object. Valid modes are: 0: Always highlight children 1: Never
highlight children 2: Use per-object Selection Child Highlightsetting. Default mode is (0): Always highlight children.
For (2), each DAG object has an individual Selection Child Highlightboolean flag. By default, this flag will be TRUE.
When mode (2) is enabled, the control is deferred to the selected object's Selection Child Highlightflag.
- singleBoxSelection : sbs (bool) [create,query]
Set single box selection on/off. This flag indicates whether just single object will be selected when the user box
(marquee) selects several objects if flag set to true. Otherwise, all those objects inside the box will be selected.
- straightLineDistance : sld (bool) [query]
If true then use straight line distances for selection proximity.
- trackSelectionOrder : tso (bool) [query]
When enabled, the order of selected objects and components will be tracked. The 'ls' command will be able to return the
active list in the order of selection which will allow scripts to be written that depend on the order.
- useDepth : ud (bool) [query]
When enabled, marquee selection will not select components that are behind the surface in the current camera view.
- xformNoSelect : xns (bool) [create,query]
Disable selection in xform tools Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.selectPref`
"""
pass
def format(*args, **kwargs):
"""
This command takes a format string, where the format string contains format specifiers. The format specifiers have a
number associated with them relating to which parameter they represent to allow for alternate ordering of the passed-in
values for other languages by merely changing the format string
Flags:
- stringArg : s (unicode) [create]
Specify the arguments for the format string. Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.format`
"""
pass
def connectAttr(source, destination, **kwargs):
"""
Connect the attributes of two dependency nodes and return the names of the two connected attributes. The connected
attributes must be be of compatible types. First argument is the source attribute, second one is the destination. Refer
to dependency node documentation.
Maya Bug Fix:
- even with the 'force' flag enabled, the command would raise an error if the connection already existed.
Flags:
- force : f (bool) [create]
Forces the connection. If the destination is already connected, the old connection is broken and the new one made.
- lock : l (bool) [create]
If the argument is true, the destination attribute is locked after making the connection. If the argument is false, the
connection is unlocked before making the connection.
- nextAvailable : na (bool) [create]
If the destination multi-attribute has set the indexMatters to be false with this flag specified, a connection is made
to the next available index. No index need be specified.
- referenceDest : rd (unicode) [create]
This flag is used for file io only. The flag indicates that the connection replaces a connection made in a referenced
file, and the flag argument indicates the original destination from the referenced file. This flag is used so that if
the reference file is modified, maya can still attempt to make the appropriate connections in the main scene to the
referenced object. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.connectAttr`
"""
pass
def strDeprecateDecorator(func):
"""
#@decorator
"""
pass
def resetTool(*args, **kwargs):
"""
This command resets a tool back to its factory settings
Derived from mel command `maya.cmds.resetTool`
"""
pass
def aliasAttr(*args, **kwargs):
"""
Allows aliases (alternate names) to be defined for any attribute of a specified node. When an attribute is aliased, the
alias will be used by the system to display information about the attribute. The user may, however, freely use either
the alias or the original name of the attribute. Only a single alias can be specified for an attribute so setting an
alias on an already-aliased attribute destroys the old alias.
Flags:
- remove : rm (bool) [create]
Specifies that aliases listed should be removed (otherwise new aliases are added). Flag
can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.aliasAttr`
"""
pass
def listNodeTypes(*args, **kwargs):
"""
Lists dependency node types satisfying a specified classification string. See the 'getClassification' command for a list
of the standard classification strings.
Flags:
- exclude : ex (unicode) [create]
Nodes that satisfies this exclude classification will be filtered out. Flag can have multiple
arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.listNodeTypes`
"""
pass
def itemFilterRender(*args, **kwargs):
"""
Flags:
- anyTextures : at (bool) []
- category : cat (unicode) []
- classification : cls (unicode) []
- exclusiveLights : exl (bool) []
- exists : ex (bool) []
- lightSets : ls (bool) []
- lights : l (bool) []
- linkedLights : ll (bool) []
- listBuiltInFilters : lbf (bool) []
- listOtherFilters : lof (bool) []
- listUserFilters : luf (bool) []
- negate : neg (bool) []
- nodeClassification : nc (unicode) []
- nonExclusiveLights : nxl (bool) []
- nonIlluminatingLights : nil (bool) []
- parent : p (unicode) []
- postProcess : pp (bool) []
- renderUtilityNode : run (bool) []
- renderableObjectSets : ros (bool) []
- renderingNode : rn (bool) []
- shaders : s (bool) []
- text : t (unicode) []
- textures2d : t2d (bool) []
- textures3d : t3d (bool) []
- texturesProcedural : tp (bool) []
Derived from mel command `maya.cmds.itemFilterRender`
"""
pass
def refresh(*args, **kwargs):
"""
This command is used to force a redraw during script execution. Normally, redraw is suspended while scripts are
executing but sometimes it is useful to show intermediate results for purposes such as capturing images from the screen.
If the -cv flag is specified, then only the current active view is redrawn.
Flags:
- currentView : cv (bool) [create]
Redraw only the current view (default redraws all views).
- fileExtension : fe (unicode) []
- filename : fn (unicode) []
- force : f (bool) [create]
Force the refresh regardless of the state of the model.
- suspend : su (bool) [create]
Suspends or resumes Maya's handling of refresh events. Specify onto suspend refreshing, and offto resume refreshing.
Note that resuming refresh does not itself cause a refresh -- the next natural refresh event in Maya after refresh
-suspend offis issued will cause the refresh to occur. Use this flag with caution: although it provides opportunities to
enhance performance, much of Maya's dependency graph evaluation in interactive mode is refresh driven, thus use of this
flag may lead to slight solve differences when you have a complex dependency graph with interrelations.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.refresh`
"""
pass
def pause(*args, **kwargs):
"""
Pause for a specified number of seconds for canned demos or for test scripts to allow user to view results.
Flags:
- seconds : sec (int) [create]
Pause for the specified number of seconds. Flag can have multiple arguments, passed either as a tuple
or a list.
Derived from mel command `maya.cmds.pause`
"""
pass
def toolPropertyWindow(*args, **kwargs):
"""
End users should only call this command as 1. a query (in the custom tool property sheet code) or 2. with no arguments
to create the default tool property sheet. The more complex uses of it are internal. In query mode, return type is
based on queried flag.
Flags:
- field : fld (unicode) [query,edit]
Sets/returns the name of the text field used to store the tool name in the property sheet.
- helpButton : hb (unicode) [query,edit]
Sets/returns the name of the button used to show help on the tool in the property sheet.
- icon : icn (unicode) [query,edit]
Sets/returns the name of the static picture object (used to display the tool icon in the property sheet).
- inMainWindow : imw (bool) [create]
Specify true if you want the tool settings to appear in the main window rather than a separate window.
- location : loc (unicode) [query,edit]
Sets/returns the location of the current tool property sheet, or an empty string if there is none.
- noviceMode : nm (bool) [query,edit]
Sets/returns the 'novice mode' flag.(unused at the moment)
- resetButton : rb (unicode) [query,edit]
Sets/returns the name of the button used to restore the tool settings in the property sheet.
- selectCommand : sel (unicode) [query,edit]
Sets/returns the property sheet's select command.
- showCommand : shw (unicode) [query,edit]
Sets/returns the property sheet's display command. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.toolPropertyWindow`
"""
pass
def performanceOptions(*args, **kwargs):
"""
Sets the global performance options for the application. The options allow the disabling of features such as stitch
surfaces or deformers to cut down on computation time in the scene. Performance options that are in effect may be on all
the time, or they can be turned on only for interaction. In the latter case, the options will only take effect during
UI interaction or playback. Note that none of these performance options will affect rendering.
Flags:
- clusterResolution : cr (float) [query]
Sets the global cluster resolution. This value may range between 0.0 (exact calculation) and 10.0 (rough approximation)
- disableStitch : ds (unicode) [query]
Sets the state of stitch surface disablement. Setting this to onsuppresses the generation of stitch surfaces. Valid
values are on, off, interactive.
- disableTrimBoundaryDisplay : dtb (unicode) []
- disableTrimDisplay : dt (unicode) [query]
Sets the state of trim drawing disablement. Setting this to onsuppresses the drawing of surface trims. Valid values are
on, off, interactive.
- latticeResolution : lr (float) [query]
Sets the global lattice resolution. This value may range between 0.0 (exact calculation) and 1.0 (rough approximation)
- passThroughBindSkinAndFlexors : pbf (unicode) [query]
Sets the state of bind skin and all flexors pass through. Valid values are on, off, interactive.
- passThroughBlendShape : pbs (unicode) [query]
Sets the state of blend shape deformer pass through. Valid values are on, off, interactive.
- passThroughCluster : pc (unicode) [query]
Sets the state of cluster deformer pass through. Valid values are on, off, interactive.
- passThroughDeltaMush : pdm (unicode) [query]
Sets the state of delta mush deformer pass through. Valid values are on, off, interactive.
- passThroughFlexors : pf (unicode) [query]
Sets the state of flexor pass through. Valid values are on, off, interactive.
- passThroughLattice : pl (unicode) [query]
Sets the state of lattice deformer pass through. Valid values are on, off, interactive.
- passThroughPaintEffects : pp (unicode) [query]
Sets the state of paint effects pass through. Valid values are on, off, interactive.
- passThroughSculpt : ps (unicode) [query]
Sets the state of sculpt deformer pass through. Valid values are on, off, interactive.
- passThroughWire : pw (unicode) [query]
Sets the state of wire deformer pass through. Valid values are on, off, interactive.
- skipHierarchyTraversal : sht (bool) [query]
When enabled, hierarchy traversal of invisible objects in the scene will be disabled in order to increase performance
however this has a side effect of performing redundant viewport refreshes on certain actions such as manipulations,
start/end of playback, idle refresh calls, etc.
- useClusterResolution : ucr (unicode) [query]
Sets the state of cluster deformer global resolution. This allows clusters to be calculated at a lower resolution.
Valid values are on, off, interactive.
- useLatticeResolution : ulr (unicode) [query]
Sets the state of lattice deformer global resolution. This allows lattices to be calculated at a lower resolution.
Valid values are on, off, interactive. Flag can have multiple arguments, passed either as a tuple or a
list.
Derived from mel command `maya.cmds.performanceOptions`
"""
pass
def color(*args, **kwargs):
"""
This command sets the dormant wireframe color of the specified objects to be their class color or if the -ud/userDefined
flag is specified, one of the user defined colors. The -rgb/rgbColor flags can be specified if the user requires
floating point RGB colors.
Flags:
- rgbColor : rgb (float, float, float) [create]
Specifies and rgb color to set the selected object to.
- userDefined : ud (int) [create]
Specifies the user defined color index to set selected object to. The valid range of numbers is [1-8].
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.color`
"""
pass
def transformLimits(*args, **kwargs):
"""
The transformLimits command allows us to set, edit, or query the limits of the transformation that can be applied to
objects. We can also turn any limits off which may have been previously set. When an object is first created, all the
transformation limits are off by default.Transformation limits allow us to control how much an object can be
transformed. This is most useful for joints, although it can be used any place we would like to limit the movement of an
object.Default values are:( -1, 1) for translation, ( -1, 1) for scaling, and (-45,45) for rotation. In query mode,
return type is based on queried flag.
Flags:
- enableRotationX : erx (bool, bool) [query]
enable/disable the lower and upper x-rotation limitsWhen queried, it returns boolean boolean
- enableRotationY : ery (bool, bool) [query]
enable/disable the lower and upper y-rotation limitsWhen queried, it returns boolean boolean
- enableRotationZ : erz (bool, bool) [query]
enable/disable the lower and upper z-rotation limitsWhen queried, it returns boolean boolean
- enableScaleX : esx (bool, bool) [query]
enable/disable the lower and upper x-scale limitsWhen queried, it returns boolean boolean
- enableScaleY : esy (bool, bool) [query]
enable/disable the lower and upper y-scale limitsWhen queried, it returns boolean boolean
- enableScaleZ : esz (bool, bool) [query]
enable/disable the lower and upper z-scale limitsWhen queried, it returns boolean boolean
- enableTranslationX : etx (bool, bool) [query]
enable/disable the ower and upper x-translation limitsWhen queried, it returns boolean boolean
- enableTranslationY : ety (bool, bool) [query]
enable/disable the lower and upper y-translation limitsWhen queried, it returns boolean boolean
- enableTranslationZ : etz (bool, bool) [query]
enable/disable the lower and upper z-translation limitsWhen queried, it returns boolean boolean
- remove : rm (bool) [create]
turn all the limits off and reset them to their default values
- rotationX : rx (float, float) [query]
set the lower and upper x-rotation limitsWhen queried, it returns angle angle
- rotationY : ry (float, float) [query]
set the lower and upper y-rotation limitsWhen queried, it returns angle angle
- rotationZ : rz (float, float) [query]
set the lower and upper z-rotation limitsWhen queried, it returns angle angle
- scaleX : sx (float, float) [query]
set the lower and upper x-scale limitsWhen queried, it returns float float
- scaleY : sy (float, float) [query]
set the lower and upper y-scale limitsWhen queried, it returns float float
- scaleZ : sz (float, float) [query]
set the lower and upper z-scale limitsWhen queried, it returns float float
- translationX : tx (float, float) [query]
set the lower and upper x-translation limitsWhen queried, it returns linear linear
- translationY : ty (float, float) [query]
set the lower and upper y-translation limitsWhen queried, it returns linear linear
- translationZ : tz (float, float) [query]
set the lower and upper z-translation limitsWhen queried, it returns linear linearFlag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.transformLimits`
"""
pass
def listSets(*args, **kwargs):
"""
The listSets command is used to get a list of all the sets an object belongs to. To get sets of a specific type for an
object use the type flag as well. To get a list of all sets in the scene then don't use an object in the command line
but use one of the flags instead.
Modifications:
- returns wrapped classes
- if called without arguments and keys works as with allSets=True
:rtype: `PyNode` list
Flags:
- allSets : allSets (bool) [create]
Returns all sets in the scene.
- extendToShape : ets (bool) [create]
When requesting a transform's sets also walk down to the shape immediately below it for its sets.
- object : o (PyNode) [create]
Returns all sets which this object is a member of.
- type : t (int) [create]
Returns all sets in the scene of the given type: 1 - all rendering sets2 - all deformer setsFlag can have multiple
arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.listSets`
"""
pass
def snapMode(*args, **kwargs):
"""
The snapMode command is used to control snapping. It toggles the snapping modes in effect and sets information used for
snapping.
Flags:
- curve : c (bool) [create,query]
Set curve snap mode
- distanceIncrement : dsi (float) [create,query]
Set the distance for the snapping to objects such as a lines or planes.
- edgeMagnet : em (int) [create,query]
Number of extra magnets to snap onto, regularly spaced along the edge.
- edgeMagnetTolerance : emt (float) [create,query]
Precision for edge magnet snapping.
- grid : gr (bool) [create,query]
Set grid snap mode
- liveFaceCenter : lfc (bool) [create,query]
While moving on live polygon objects, snap to its face centers.
- livePoint : lp (bool) [create,query]
While moving on live polygon objects, snap to its vertices.
- meshCenter : mc (bool) [create,query]
While moving, snap on the center of the mesh that intersect the line from the camera to the cursor.
- pixelCenter : pc (bool) [create,query]
Snap UV to the center of the pixel instead of the corner.
- pixelSnap : ps (bool) [create,query]
Snap UVs to the nearest pixel center or corner.
- point : p (bool) [create,query]
Set point snap mode
- tolerance : t (int) [create,query]
Tolerance defines the size of the square region in which points must lie in order to be snapped to. The tolerance value
is the distance from the cursor position to the boundary of the square (in all four directions).
- useTolerance : ut (bool) [create,query]
If useTolerance is set, then point snapping is limited to points that are within a square region surrounding the cursor
position. The size of the square is determined by the tolerance value.
- uvTolerance : uvt (int) [create,query]
uvTolerance defines the size of the square region in which points must lie in order to be snapped to, in the UV Editor.
The tolerance value is the distance from the cursor position to the boundary of the square (in all four directions).
- viewPlane : vp (bool) [create,query]
Set view-plane snap mode Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.snapMode`
"""
pass
def selectKey(*args, **kwargs):
"""
This command operates on a keyset. A keyset is defined as a group of keys within a specified time range on one or more
animation curves. The animation curves comprising a keyset depend on the value of the -animationflag: keysOrObjects: Any
active keys, when no target objects or -attribute flags appear on the command line, orAll animation curves connected to
all keyframable attributes of objects specified as the command line's targetList, when there are no active keys.keys:
Only act on active keys or tangents. If there are no active keys or tangents, don't do anything. objects: Only act on
specified objects. If there are no objects specified, don't do anything. Note that the -animationflag can be used to
override the curves uniquely identified by the multi-use -attributeflag, which takes an argument of the form
attributeName, such as translateX. Keys on animation curves are identified by either their time values or their indices.
Times and indices can be given individually or as part of a list or range. -time 10palmeans the key at frame 10 (PAL
format).-time 1.0sec -time 15ntsc -time 20means the keys at time 1.0 second, frame 15 (in NTSC format), and time 20 (in
the currently defined global time unit).-time 10:20means all keys in the range from 10 to 20, inclusive, in the current
time unit.Omitting one end of a range means go to infinity, as in the following examples: -time 10:means all keys from
time 10 (in the current time unit) onwards.-time :10means all keys up to (and including) time 10 (in the current time
unit).-time :is a short form to specify all keys.-index 0means the first key of each animation curve. (Indices are
0-based.)-index 2 -index 5 -index 7means the 3rd, 6th, and 8th keys.-index 1:5means the 2nd, 3rd, 4th, 5th, and 6th keys
of each animation curve.This command places keyframes and/or keyframe tangents on the active list.
Flags:
- addTo : add (bool) [create]
Add to the current selection of keyframes/tangents
- animation : an (unicode) [create]
Where this command should get the animation to act on. Valid values are objects,keys,and keysOrObjectsDefault:
keysOrObjects.(See Description for details.)
- attribute : at (unicode) [create]
List of attributes to select
- clear : cl (bool) [create]
Remove all keyframes and tangents from the active list.
- controlPoints : cp (bool) [create]
This flag explicitly specifies whether or not to include the control points of a shape (see -sflag) in the list of
attributes. Default: false. (Not valid for pasteKeycmd.)
- float : f (floatrange) [create]
value uniquely representing a non-time-based key (or key range) on a time-based animCurve. Valid floatRange include
single values (-f 10) or a string with a lower and upper bound, separated by a colon (-f 10:20
- hierarchy : hi (unicode) [create]
Hierarchy expansion options. Valid values are above,below,both,and none.(Not valid for pasteKeycmd.)
- inTangent : it (bool) [create]
Select in-tangents of keyframes in the specified time range
- includeUpperBound : iub (bool) [create]
When the -t/time or -f/float flags represent a range of keys, this flag determines whether the keys at the upper bound
of the range are included in the keyset. Default value: true. This flag is only valid when the argument to the -t/time
flag is a time range with a lower and upper bound. (When used with the pasteKeycommand, this flag refers only to the
time range of the target curve that is replaced, when using options such as replace,fitReplace,or scaleReplace.This flag
has no effect on the curve pasted from the clipboard.)
- index : index (int) [create]
index of a key on an animCurve
- keyframe : k (bool) [create]
select only keyframes (cannot be combined with -in/-out)
- outTangent : ot (bool) [create]
Select out-tangents of keyframes in the specified time range
- remove : rm (bool) [create]
Remove from the current selection of keyframes/tangents
- replace : r (bool) [create]
Replace the current selection of keyframes/tangents
- shape : s (bool) [create]
Consider attributes of shapes below transforms as well, except controlPoints. Default: true. (Not valid for
pasteKeycmd.)
- time : t (timerange) [create]
time uniquely representing a key (or key range) on a time-based animCurve. Valid timeRanges include single values (-t
10) or a string with a lower and upper bound, separated by a colon (-t 10:20
- toggle : tgl (bool) [create]
Toggle the picked state of the specified keyset
- unsnappedKeys : uk (float) [create]
Select only keys that have times that are not a multiple of the specified numeric value. Flag can have
multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.selectKey`
"""
pass
def listRelatives(*args, **kwargs):
"""
This command lists parents and children of DAG objects. The flags -c/children, -ad/allDescendents, -s/shapes, -p/parent
and -ap/allParents are mutually exclusive. Only one can be used in a command. When listing parents of objects directly
under the world, the command will return an empty parent list. Listing parents of objects directly under a shape
(underworld objects) will return their containing shape node in the list of parents. Listing parents of components of
objects will return the object. When listing children, shape nodes will return their underworld objects in the list of
children. Listing children of components of objects returns nothing. The -ni/noIntermediate flag works with the
-s/shapes flag. It causes any intermediate shapes among the descendents to be ignored.
Maya Bug Fix:
- allDescendents and shapes flags did not work in combination
- noIntermediate doesn't appear to work
Modifications:
- returns an empty list when the result is None
- returns an empty list when the arg is an empty list, tuple, set, or
frozenset, making it's behavior consistent with when None is passed, or
no args and nothing is selected (would formerly raise a TypeError)
- returns wrapped classes
- fullPath is forced on to ensure that all returned node paths are unique
:rtype: `DependNode` list
Flags:
- allDescendents : ad (bool) [create]
Returns all the children, grand-children etc. of this dag node. If a descendent is instanced, it will appear only once
on the list returned. Note that it lists grand-children before children.
- allParents : ap (bool) [create]
Returns all the parents of this dag node. Normally, this command only returns the parent corresponding to the first
instance of the object
- children : c (bool) [create]
List all the children of this dag node (default).
- fullPath : f (bool) [create]
Return full pathnames instead of object names.
- noIntermediate : ni (bool) [create]
No intermediate objects
- parent : p (bool) [create]
Returns the parent of this dag node
- path : pa (bool) [create]
Return a proper object name that can be passed to other commands.
- shapes : s (bool) [create]
List all the children of this dag node that are shapes (ie, not transforms)
- type : typ (unicode) [create]
List all relatives of the specified type. Flag can have multiple arguments, passed either as a tuple or
a list.
Derived from mel command `maya.cmds.listRelatives`
"""
pass
def license(*args, **kwargs):
"""
This command displays version information about the application if it is executed without flags. If one of the above
flags is specified then the specified version information is returned.
Flags:
- borrow : b (bool) [create]
This flag is obsolete and no longer supported.
- info : i (bool) [create]
This flag is obsolete and no longer supported.
- isBorrowed : ib (bool) [create]
This flag is obsolete and no longer supported.
- isExported : ie (bool) [create]
This flag is obsolete and no longer supported.
- isTrial : it (bool) [create]
This flag is obsolete and no longer supported.
- licenseMethod : lm (bool) [create]
This flag is obsolete and no longer supported.
- productChoice : pc (bool) [create]
This flag is obsolete and no longer supported.
- r : r (bool) [create]
This flag is obsolete and no longer supported.
- showBorrowInfo : sbi (bool) [create]
This flag is obsolete and no longer supported.
- showProductInfoDialog : spi (bool) [create]
Show the Product Information Dialog
- status : s (bool) []
- usage : u (bool) [create]
This flag is obsolete and no longer supported. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.license`
"""
pass
def matchTransform(*args, **kwargs):
"""
This command modifies the source object's transform to match the target object's transform. If no flags are specified
then the command will match position, rotation and scaling.
Flags:
- pivots : piv (bool) [create]
Match the source object(s) scale/rotate pivot positions to the target transform's pivot.
- position : pos (bool) [create]
Match the source object(s) position to the target object.
- rotation : rot (bool) [create]
Match the source object(s) rotation to the target object.
- scale : scl (bool) [create]
Match the source object(s) scale to the target transform. Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.matchTransform`
"""
pass
def inheritTransform(*args, **kwargs):
"""
This command toggles the inherit state of an object. If this flag is off the object will not inherit transformations
from its parent. In other words transformations applied to the parent node will not affect the object and it will act as
though it is under the world. If the -p flag is specified then the object's transformation will be modified to
compensate when changing the inherit flag so the object will not change its world-space location. In query mode, return
type is based on queried flag.
Flags:
- off : off (bool) []
- on : on (bool) []
- preserve : p (bool) [create,query]
preserve the objects world-space position by modifying the object(s) transformation matrix.
- toggle : tgl (bool) [create,query]
toggle the inherit state for the given object(s) (default if no flags are given) -on turn on inherit state for the given
object(s) -off turn off inherit state for the given object(s) Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.inheritTransform`
"""
pass
def attributeName(*args, **kwargs):
"""
This command takes one node.attribute-style specifier on the command line and returns either the attribute's long,
short, or nice name. (The nicename, or UI name, is the name used to display the attribute in Maya's interface, and may
be localized when running Maya in a language other than English.) If more than one node.attributespecifier is given on
the command line, only the first valid specifier is processed.
Flags:
- leaf : lf (bool) [create]
When false, shows parent multi attributes (like controlPoints[2].xValue). When true, shows only the leaf-level
attribute name (like xValue). Default is true. Note that for incomplete attribute strings, like a missing multi-parent
index (controlPoints.xValue) or an incorrectly named compound (cntrlPnts[2].xValue), this flag defaults to true and
provides a result as long as the named leaf-level attribute is defined for the node.
- long : l (bool) [create]
Returns names in long nameformat like translateX
- nice : n (bool) [create]
Returns names in nice nameformat like Translate X
- short : s (bool) [create]
Returns names in short nameformat like txFlag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.attributeName`
"""
pass
def containerPublish(*args, **kwargs):
"""
This is an accessory command to the container command which is used for some advanced publishing operations on the
container. For example, the publishConnectionsflag on the container will publish all the connections, but this command
can be used to publish just the inputs, outputs, or to collapse the shared inputs into a single attribute before
publishing. In query mode, return type is based on queried flag.
Flags:
- bindNode : bn (unicode, unicode) [create,query,edit]
Bind the specified node to the published node name.
- bindTemplateStandins : bts (bool) [create,query,edit]
This flag will create a temporary stand-in attribute for any attributes that exist in the template but are not already
bound. This enables you to set values for unbound attributes.
- inConnections : ic (bool) [create]
Specifies that the unpublished connections to nodes in the container from external nodes should be published.
- mergeShared : ms (bool) [create]
For use with the inConnections flag. Indicates that when an external attribute connects to multiple internal attributes
within the container, a single published attribute should be used to correspond to all of the internal attributes.
- outConnections : oc (bool) [create]
Specifies that the unpublished connections from nodes in the container to external nodes should be published.
- publishNode : pn (unicode, unicode) [create,query,edit]
Publish a name and type. When first published, nothing will be bound. To bind a node to the published name, use the
bindNode flag.
- unbindNode : ubn (unicode) [create,query,edit]
Unbind the node that is published with the name specified by the flag.
- unpublishNode : upn (unicode) [create,query,edit]
Unpublish the specified published node name. Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.containerPublish`
"""
pass
def condition(*args, **kwargs):
"""
This command creates a new named condition object whose true/false value is calculated by running a mel script. This new
condition can then be used for dimming, or controlling other scripts, or whatever. In query mode, return type is based
on queried flag.
Flags:
- delete : delete (bool) [create]
Deletes the condition.
- dependency : d (unicode) [create]
Each -dependency flag specifies another condition that the new condition will be dependent on. When any of these
conditions change, the new-state-script will run, and the state of this condition will be set accordingly. It is
possible to define infinite loops, but they will be caught and handled correctly at run-time.
- initialize : i (bool) [create]
Initializes the condition, by forcing it to run its script as soon as it is created. If this flag is not specified, the
script will not run until one of the dependencies is triggered.
- script : s (unicode) [create]
The script that determines the new state of the condition.
- state : st (bool) [create,query,edit]
Sets the state of the condition. This can be used to create a manually triggered condition: you could create a condition
without any dependencies and without a new-state-script. This condition would only change state in response to the
-st/state flag. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.condition`
"""
pass
def suitePrefs(*args, **kwargs):
"""
This command sets the mouse and keyboard interaction mode for Maya and other Suites applications (if Maya is part of a
Suites install).
Flags:
- applyToSuite : ats (unicode) [create]
Apply the mouse and keyboard interaction settings for the given application to all applications in the Suite (if Maya is
part of a Suites install). Valid values are Maya, 3dsMax, or undefined, which signifies that each app is to use their
own settings.
- installedAsSuite : ias (bool) [create]
Returns true if Maya is part of a Suites install, false otherwise.
- isCompleteSuite : ics (bool) [create]
Returns true if the Suites install contains all Entertainment Creation Suite products, false otherwise.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.suitePrefs`
"""
pass
def listFuture(*args, **kwargs):
"""
Modifications:
- returns an empty list when the result is None
- added a much needed 'type' filter
- added an 'exactType' filter (if both 'exactType' and 'type' are present, 'type' is ignored)
:rtype: `DependNode` list
"""
pass
def copyAttr(*args, **kwargs):
"""
Given two nodes, transfer the connections and/or the values from the first node to the second for all attributes whose
names and data types match. When values are transferred, they are transferred directly. They are not mapped or modified
in any way. The transferAttributes command can be used to transfer and remap some mesh attributes. The attributes flag
can be used to specify a list of attributes to be processed. If the attributes flag is unused, all attributes will be
processed. For dynamic attributes, the values and/or connections will only be transferred if the attributes names on
both nodes match. This command does not support geometry shape nodes such as meshes, subds and nurbs. This command does
not support transfer of multi-attribute values such as weight arrays. In query mode, return type is based on
queried flag.
Flags:
- attribute : at (unicode) [create]
The name of the attribute(s) for which connections and/or values will be transferred. If no attributes are specified,
then all attributes will be transferred.
- containerParentChild : cpc (bool) [create]
For use when copying from one container to another only. This option indicates that the published parent and/or child
relationships on the original container should be transferred to the target container if the published names match.
- inConnections : ic (bool) [create]
Indicates that incoming connections should be transferred.
- keepSourceConnections : ksc (bool) [create]
For use with the outConnections flag only. Indicates that the connections should be maintained on the first node, in
addition to making them to the second node. If outConnections is used and keepSourceConnections is not used, the out
connections on the source node will be broken and made to the target node.
- outConnections : oc (bool) [create]
Indicates that outgoing connections should be transferred.
- renameTargetContainer : rtc (bool) [create]
For use when copying from one container to another only. This option will rename the target container to the name of the
original container, and rename the original container to its old name + Orig. You would want to use this option if your
original container was referenced and edited, and you want those edits from the main scene to now apply to the new
container.
- values : v (bool) [create]
Indicates that values should be transferred. Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.copyAttr`
"""
pass
def containerView(*args, **kwargs):
"""
A container view defines the layout information for the published attributes of a particular container. Container views
can be selected from a set of built-in views or may be defined on an associated container template. This command queries
the view-related information for a container node. The information returned from this command will be based on the view-
related settings in force on the container node at the time of the query (i.e. the container's view mode, template name,
view name attributes). In query mode, return type is based on queried flag.
Flags:
- itemInfo : ii (unicode) [query]
Used in query mode in conjunction with the itemList flag. The command will return a list of information for each item in
the view, the information fields returned for each item are determined by this argument value. The information fields
will be listed in the string array returned. The order in which the keyword is specified will determine the order in
which the data will be returned by the command. One or more of the following keywords, separated by colons ':' are used
to specify the argument value. itemIndex : sequential item number (0-based)itemName : item name (string)itemLabel :
item display label (string)itemDescription : item description field (string)itemLevel : item hierarchy level
(0-n)itemIsGroup : (boolean 0 or 1) indicates whether or not this item is a groupitemIsAttribute : (boolean 0 or 1)
indicates whether or not this item is an attributeitemNumChildren: number of immediate children (groups or attributes)
of this itemitemAttrType : item attribute type (string)itemCallback : item callback field (string)
- itemList : il (bool) [query]
Used in query mode, the command will return a list of information for each item in the view. The viewName flag is used
to select the view to query. The information returned about each item is determined by the itemInfo argument value. For
efficiency, it is best to query all necessary item information at one time (to avoid recomputing the view information on
each call).
- viewDescription : vd (bool) [query]
Used in query mode, returns the description field associated with the selected view. If no description was defined for
this view, the value will be empty.
- viewLabel : vb (bool) [query]
Used in query mode, returns the display label associated with the view. An appropriate label suitable for the user
interface will be returned based on the selected view. Use of the view label is usually more suitable than the view
name for display purposes.
- viewList : vl (bool) [query]
Used in query mode, command will return a list of all views defined for the given target (container or template).
- viewName : vn (unicode) [query]
Used in query mode, specifies the name of the queried view when used in conjunction with a template target. When used in
conjunction with a container target, it requires no string argument, and returns the name of the currently active view
associated with the container; this value may be empty if the current view is not a valid template view or is generated
by one of the built-in views modes. For this reason, the view label is generally more suitable for display purposes. In
query mode, this flag can accept a value.Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.containerView`
"""
pass
def showHidden(*args, **kwargs):
"""
The showHiddencommand is used to make invisible objects visible. If no flags are specified, only the objects given to
the command will be made visible. If a parent of an object is invisible, the object will still be invisible.
Invisibility is inherited. To ensure the object becomes visible, use the -a/above flag. This forces all invisible
ancestors of the object(s) to be visible. If the -b/below flag is used, any invisible objects below the object will be
made visible. To make all objects visible, use the -all/allObjects flag. See also:hide
Flags:
- above : a (bool) [create]
Make objects and all their invisible ancestors visible.
- allObjects : all (bool) [create]
Make all invisible objects visible.
- below : b (bool) [create]
Make objects and all their invisible descendants visible.
- lastHidden : lh (bool) [create]
Show everything that was hidden with the last hide command. Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.showHidden`
"""
pass
def instance(*args, **kwargs):
"""
Instancing is a way of making the same object appear twice in the scene. This is accomplished by creation of a new
transform node that points to an exisiting object. Changes to the transform are independent but changes to the
instancedobject affect all instances since the node is shared. If no objects are given, then the selected list is
instanced. When an object is instanced a new transform node is created that points to the selected object. The smart
transform feature allows instance to transform newly instanced objects based on previous transformations between
instances. Example: Instance an object and move it to a new location. Instance it again with the smart transform flag.
It should have moved once again the distance you had previously moved it. Note: changing the selected list between smart
instances will cause the transform information to be deleted. It returns a list of the new objects created by the
instance operation. See also:duplicate
Modifications:
- returns a list of PyNode objects
Flags:
- leaf : lf (bool) [create]
Instances leaf-level objects. Acts like duplicate except leaf-level objects are instanced.
- name : n (unicode) [create]
Name to give new instance
- smartTransform : st (bool) [create]
Transforms instances item based on movements between transforms Flag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.instance`
"""
pass
def displayPref(*args, **kwargs):
"""
This command sets/queries the state of global display parameters. In query mode, return type is based on
queried flag.
Flags:
- activeObjectPivots : aop (bool) [create,query]
Sets the display state for drawing pivots for active objects.
- defaultFontSize : dfs (int) []
- displayAffected : da (bool) [create,query]
Turns on/off the special coloring of objects that are affected by the objects that are currently in the selection list.
If one of the curves in a loft were selected and this feature were turned on, then the lofted surface would be
highlighted because it is affected by the loft curve.
- displayGradient : dgr (bool) [create,query]
Set whether to display the background using a colored gradient as opposed to a constant background color.
- fontSettingMode : fm (int) []
- ghostFrames : gf (int, int, int) [create,query]
Sets the ghosting frame preferences: steps before, steps after and step size.
- lineWidth : lw (float) []
- materialLoadingMode : mld (unicode) [create,query]
Sets the material loading mode when loading the scene. Possible values for the string argument are immediate,
deferredand parallel.
- maxHardwareTextureResolution : mhr (bool) [query]
Query the maximum allowable hardware texture resolution available on the current video card. This maximum can vary
between different video cards and different operating systems.
- maxTextureResolution : mtr (int) [create,query]
Sets the maximum hardware texture resolution to be used when creating hardware textures for display. The maximum will be
clamped to the maximum allowable texture determined for the hardware at the time this command is invoked. Use the
-maxHardwareTextureResolution to retrieve this maximum value. Existing hardware textures are not affected. Only newly
created textures will be clamped to this maximum.
- purgeExistingTextures : pet (bool) [create]
Purge any existing hardware textures. This will force a re-evaluation of hardware textures used for display, and thus
may take some time to evaluate.
- regionOfEffect : roe (bool) [create,query]
Turns on/off the display of the region of curves/surfaces that is affected by changes to selected CVs and edit points.
- shadeTemplates : st (bool) [create,query]
Turns on/off the display of templated surfaces as shaded in shaded display mode. If its off, templated surfaces appear
in wireframe.
- smallFontSize : sfs (int) []
- textureDrawPixel : tdp (bool) [create,query]
Sets the display mode for drawing image planes. True for use of gltexture calls for perspective views. This flag should
not normally be needed. Image Planes may display faster on Windows but can result in some display artifacts.
- wireframeOnShadedActive : wsa (unicode) [create,query]
Sets the display state for drawing the wireframe on active shaded objects. Possible values for the string argument are
full, reducedand none. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.displayPref`
"""
pass
def _about(*args, **kwargs):
pass
def xformConstraint(*args, **kwargs):
"""
This command allows you to change the transform constraint used by the transform tools during component transforms.
In query mode, return type is based on queried flag.
Flags:
- alongNormal : n (int) [query,edit]
When set the transform constraint will first be applied along the vertex normals of the components being transformed.
When queried, returns the current state of this option.
- live : l (bool) [query]
Query-only flag that can be used to check whether the current live surface will be used as a transform constraint.
- type : t (unicode) [create,query,edit]
Set the type of transform constraint to use. When queried, returns the current transform constraint as a string. none -
no constraintsurface - constrain components to their surfaceedge - constrain components to surface edgesFlag can have
multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.xformConstraint`
"""
pass
def getClassification(*args):
"""
Returns the classification string for a given node type. Classification strings look like file pathnames
(shader/reflectiveor texture/2D, for example). Multiple classifications can be combined into a single compound
classification string by joining the individual classifications with ':'. For example, the classification string
shader/reflective:texture/2Dmeans that the node is both a reflective shader and a 2D texture. The classification string
is used to determine how rendering nodes are categorized in various UI, such as the Create Render Node and HyperShade
windows: CategoryClassification String2D Texturestexture/2d3D Texturestexture/3dEnv Texturestexture/environmentSurface
Materialsshader/surfaceVolumetric Materialsshader/volumeDisplacement Materialsshader/displacementLightslightGeneral
Utilitiesutility/generalColor Utilitiesutility/colorParticle Utilitiesutility/particleImage
PlanesimageplaneGlowpostprocess/opticalFXThe classification string is also used to determine how Viewport 2.0 will
interpret the node. CategoryClassification StringGeometrydrawdb/geometryTransformdrawdb/geometry/transformSub-Scene
Objectdrawdb/subsceneShaderdrawdb/shaderSurface Shaderdrawdb/shader/surface
Modifications:
- previously returned a list with a single colon-separated string of classifications. now returns a list of classifications
:rtype: `unicode` list
Flags:
- satisfies : sat (unicode) [create]
Returns true if the given node type's classification satisfies the classification string which is passed with the flag.
A non-compound classification string A is said to satisfy a non-compound classification string B if A is a
subclassification of B (for example, shaders/reflectivesatisfies shaders). A compound classification string A satisfies
a compound classification string B iff: every component of A satisfies at least one component of B and every component
of B is satisfied by at least one component of AHence, shader/reflective/phong:texturesatisfies shader:texture, but
shader/reflective/phongdoes not satisfy shader:texture. Flag can have multiple arguments, passed either
as a tuple or a list.
Derived from mel command `maya.cmds.getClassification`
"""
pass
def selectMode(*args, **kwargs):
"""
The selectModecommand is used to change the selection mode. Object, component, root, leaf and template modes are
mutually exclusive.
Flags:
- component : co (bool) [create,query]
Set component selection on. Component selection mode allows filtered selection based on the component selection mask.
The component selection mask is the set of selection masks related to objects that indicate which components are
selectable.
- hierarchical : h (bool) [create,query]
Set hierarchical selection on. There are three types of hierarchical selection: root, leaf and template. Hierarchical
mode is set if root, leaf or template mode is set. Setting to hierarchical mode will set the mode to whichever of root,
leaf, or template was last on.
- leaf : l (bool) [create,query]
Set leaf selection mode on. This mode allows the leaf level objects to be selected. It is similar to object selection
mode but ignores the object selection mask.
- object : o (bool) [create,query]
Set object selection on. Object selection mode allows filtered selection based on the object selection mask. The object
selection mask is the set of selection masks related to objects that indicate which objects are selectable. The masks
are controlled by the selectTypecommand. Object selection mode selects the leaf level objects.
- preset : p (bool) [create,query]
Allow selection of anything with the mask set, independent of it being an object or a component.
- root : r (bool) [create,query]
Set root selection mode on. This mode allows the root of a hierarchy to be selected by selecting any of its
descendents. It ignores the object selection mask.
- template : t (bool) [create,query]
Set template selection mode on. This mode allows selection of templated objects. It selects the templated object
closest to the root of the hierarchy. Flag can have multiple arguments, passed either as a tuple or a
list.
Derived from mel command `maya.cmds.selectMode`
"""
pass
def setToolTo(*args, **kwargs):
"""
This command switches control to the named context.
Derived from mel command `maya.cmds.setToolTo`
"""
pass
def editDisplayLayerMembers(*args, **kwargs):
"""
This command is used to query and edit membership of display layers. No equivalent 'remove' command is necessary since
all objects must be in exactly one display layer. Removing an object from a layer can be accomplished by adding it to a
different layer.
Flags:
- fullNames : fn (bool) [query]
(Query only.) If set then return the full DAG paths of the objects in the layer. Otherwise return just the name of the
object.
- noRecurse : nr (bool) [create,query]
If set then only add selected objects to the display layer. Otherwise all descendants of the selected objects will also
be added. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.editDisplayLayerMembers`
"""
pass
def sets(*args, **kwargs):
"""
This command is used to create a set, query some state of a set, or perform operations to update the membership of a
set. A set is a logical grouping of an arbitrary collection of objects, attributes, or components of objects. Sets are
dependency nodes. Connections from objects to a set define membership in the set. Sets are used throughout Maya in a
multitude of ways. They are used to define an association of material properties to objects, to define an association of
lights to objects, to define a bookmark or named collection of objects, to define a character, and to define the
components to be deformed by some deformation operation. Sets can be connected to any number of partitions. A partition
is a node which enforces mutual exclusivity amoung the sets in the partition. That is, if an object is in a set which is
in a partition, that object cannot be a member of any other set that is in the partition. Without any flags, the
setscommand will create a set with a default name of set#(where # is an integer). If no items are specified on the
command line, the currently selected items are added to the set. The -em/empty flag can be used to create an empty set
and not have the selected items added to the set. Sets can be created to have certain restrictions on membership. There
can be renderablesets which only allow renderable objects (such as nurbs geometry or polymesh faces) to be members of
the set. There can also be vertex (or control point), edit point, edge, or face sets which only allow those types of
components to be members of a set. Note that for these sets, if an object with a valid type of component is to be added
to a set, the components of the object are added to the set instead. Sets can have an associated color which is only of
use when creating vertex sets. The color can be one of the eight user defined colors defined in the color preferences.
This color can be used, for example to distinguish which vertices are being deformed by a particular deformation.
Objects, components, or attributes can be added to a set using one of three flags. The -add/addElement flag will add the
objects to a set as long as this won't break any mutual exclusivity constraints. If there are any items which can't be
added, the command will fail. The -in/include flag will only add those items which can be added and warn of those which
can't. The -fe/forceElement flag will add all the items to the set but will also remove any of those items that are in
any other set which is in the same partition as the set. There are several operations on sets that can be performed with
the setscommand. Membership can be queried. Tests for whether an item is in a set or whether two sets share the same
item can be performed. Also, the union, intersection and difference of sets can be performed which returns a list of
members of the sets which are a result of the operation.
Modifications
- resolved confusing syntax: operating set is always the first and only arg:
>>> from pymel.core import *
>>> f=newFile(f=1) #start clean
>>>
>>> shdr, sg = createSurfaceShader( 'blinn' )
>>> shdr
nt.Blinn(u'blinn1')
>>> sg
nt.ShadingEngine(u'blinn1SG')
>>> s,h = polySphere()
>>> s
nt.Transform(u'pSphere1')
>>> sets( sg, forceElement=s ) # add the sphere
nt.ShadingEngine(u'blinn1SG')
>>> sets( sg, q=1) # check members
[nt.Mesh(u'pSphereShape1')]
>>> sets( sg, remove=s )
nt.ShadingEngine(u'blinn1SG')
>>> sets( sg, q=1)
[]
- returns wrapped classes
Flags:
- addElement : add (PyNode) [edit]
Adds the list of items to the given set. If some of the items cannot be added to the set because they are in another
set which is in the same partition as the set to edit, the command will fail.
- afterFilters : af (bool) [edit]
Default state is false. This flag is valid in edit mode only. This flag is for use on sets that are acted on by
deformers such as sculpt, lattice, blendShape. The default edit mode is to edit the membership of the group acted on by
the deformer. If you want to edit the group but not change the membership of the deformer, set the flag to true.
- clear : cl (PyNode) [edit]
An operation which removes all items from the given set making the set empty.
- color : co (int) [create,query,edit]
Defines the hilite color of the set. Must be a value in range [-1, 7] (one of the user defined colors). -1 marks the
color has being undefined and therefore not having any affect. Only the vertices of a vertex set will be displayed in
this color.
- copy : cp (PyNode) [create]
Copies the members of the given set to a new set. This flag is for use in creation mode only.
- edges : eg (bool) [create,query]
Indicates the new set can contain edges only. This flag is for use in creation or query mode only. The default value is
false.
- editPoints : ep (bool) [create,query]
Indicates the new set can contain editPoints only. This flag is for use in creation or query mode only. The default
value is false.
- empty : em (bool) [create]
Indicates that the set to be created should be empty. That is, it ignores any arguments identifying objects to be added
to the set. This flag is only valid for operations that create a new set.
- facets : fc (bool) [create,query]
Indicates the new set can contain facets only. This flag is for use in creation or query mode only. The default value is
false.
- flatten : fl (PyNode) [edit]
An operation that flattens the structure of the given set. That is, any sets contained by the given set will be replaced
by its members so that the set no longer contains other sets but contains the other sets' members.
- forceElement : fe (PyNode) [edit]
For use in edit mode only. Forces addition of the items to the set. If the items are in another set which is in the same
partition as the given set, the items will be removed from the other set in order to keep the sets in the partition
mutually exclusive with respect to membership.
- include : include (PyNode) [edit]
Adds the list of items to the given set. If some of the items cannot be added to the set, a warning will be issued.
This is a less strict version of the -add/addElement operation.
- intersection : int (PyNode) [create]
An operation that returns a list of items which are members of all the sets in the list.
- isIntersecting : ii (PyNode) [create]
An operation which tests whether the sets in the list have common members.
- isMember : im (PyNode) [create]
An operation which tests whether all the given items are members of the given set.
- layer : l (bool) [create]
OBSOLETE. DO NOT USE.
- name : n (unicode) [create]
Assigns string as the name for a new set. This flag is only valid for operations that create a new set.
- noSurfaceShader : nss (bool) [create]
If set is renderable, do not connect it to the default surface shader. Flag has no meaning or effect for non renderable
sets. This flag is for use in creation mode only. The default value is false.
- noWarnings : nw (bool) [create]
Indicates that warning messages should not be reported such as when trying to add an invalid item to a set. (used by UI)
- nodesOnly : no (bool) [query]
This flag is usable with the -q/query flag but is ignored if used with another queryable flags. This flag modifies the
results of the set membership query such that when there are attributes (e.g. sphere1.tx) or components of nodes
included in the set, only the nodes will be listed. Each node will only be listed once, even if more than one attribute
or component of the node exists in the set.
- remove : rm (PyNode) [edit]
Removes the list of items from the given set.
- renderable : r (bool) [create,query]
This flag indicates that a special type of set should be created. This type of set (shadingEngine as opposed to
objectSet) has certain restrictions on its membership in that it can only contain renderable elements such as lights and
geometry. These sets are referred to as shading groups and are automatically connected to the renderPartitionnode when
created (to ensure mutual exclusivity of the set's members with the other sets in the partition). This flag is for use
in creation or query mode only. The default value is false which means a normal set is created.
- size : s (bool) [query]
Use the size flag to query the length of the set.
- split : sp (PyNode) [create]
Produces a new set with the list of items and removes each item in the list of items from the given set.
- subtract : sub (PyNode) [create]
An operation between two sets which returns the members of the first set that are not in the second set.
- text : t (unicode) [create,query,edit]
Defines an annotation string to be stored with the set.
- union : un (PyNode) [create]
An operation that returns a list of all the members of all sets listed.
- vertices : v (bool) [create,query]
Indicates the new set can contain vertices only. This flag is for use in creation or query mode only. The default value
is false. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.sets`
"""
pass
def deleteAttr(*args, **kwargs):
"""
This command is used to delete a dynamic attribute from a node or nodes. The attribute can be specified by using either
the long or short name. Only one dynamic attribute can be deleted at a time. Static attributes cannot be deleted.
Children of a compound attribute cannot be deleted. You must delete the complete compound attribute. This command has no
edit capabilities. The only query ability is to list all the dynamic attributes of a node. In query mode, return type is
based on queried flag.
Flags:
- attribute : at (unicode) [create]
Specify either the long or short name of the attribute.
- name : n (unicode) [create]
The name of the node. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.deleteAttr`
"""
pass
def paramLocator(*args, **kwargs):
"""
The command creates a locator in the underworld of a NURBS curve or NURBS surface at the specified parameter value. If
no object is specified, then a locator will be created on the first valid selected item (either a curve point or a
surface point).
Flags:
- position : p (bool) [create]
Whether to set the locator position in normalized space. Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.paramLocator`
"""
pass
def transformCompare(*args, **kwargs):
"""
Compares two transforms passed as arguments. If they are the same, returns 0. If they are different, returns 1. If no
transforms are specified in the command line, then the transforms from the active list are used.
Flags:
- root : r (bool) [create]
Compare the root only, rather than the entire hierarchy below the roots. Flag can have multiple
arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.transformCompare`
"""
pass
def listTransforms(*args, **kwargs):
"""
Modifications:
- returns wrapped classes
:rtype: `Transform` list
"""
pass
def parent(*args, **kwargs):
"""
This command parents (moves) objects under a new group, removes objects from an existing group, or adds/removes parents.
If the -w flag is specified all the selected or specified objects are parented to the world (unparented first). If the
-rm flag is specified then all the selected or specified instances are removed. If there are more than two objects
specified all the objects are parented to the last object specified. If the -add flag is specified, the objects are not
reparented but also become children of the last object specified. If there is only a single object specified then the
selected objects are parented to that object. If an object is parented under a different group and there is an object in
that group with the same name then this command will rename the parented object.
Modifications:
- if parent is `None`, world=True is automatically set
- if the given parent is the current parent, don't error (similar to mel)
Flags:
- absolute : a (bool) [create]
preserve existing world object transformations (overall object transformation is preserved by modifying the objects
local transformation) If the object to parent is a joint, it will alter the translation and joint orientation of the
joint to preserve the world object transformation if this suffices. Otherwise, a transform will be inserted between the
joint and the parent for this purpose. In this case, the transformation inside the joint is not altered. [default]
- addObject : add (bool) [create]
preserve existing local object transformations but don't reparent, just add the object(s) under the parent. Use -world
to add the world as a parent of the given objects.
- noConnections : nc (bool) [create]
The parent command will normally generate new instanced set connections when adding instances. (ie. make a connection to
the shading engine for new instances) This flag suppresses this behaviour and is primarily used by the file format.
- noInvScale : nis (bool) [create]
The parent command will normally connect inverseScale to its parent scale on joints. This is used to compensate scale on
joint. The connection of inverseScale will occur if both child and parent are joints and no connection is present on
child's inverseScale. In case of a reparenting, the old inverseScale will only get broken if the old parent is a joint.
Otherwise connection will remain intact. This flag suppresses this behaviour.
- relative : r (bool) [create]
preserve existing local object transformations (relative to the parent node)
- removeObject : rm (bool) [create]
Remove the immediate parent of every object specified. To remove only a single instance of a shape from a parent, the
path to the shape should be specified. Note: if there is a single parent then the object is effectively deleted from the
scene. Use -world to remove the world as a parent of the given object.
- shape : s (bool) [create]
The parent command usually only operates on transforms. Using this flags allows a shape that is specified to be
directly parented under the given transform. This is used to instance a shape node. (ie. parent -add -shapeis
equivalent to the instancecommand). This flag is primarily used by the file format.
- world : w (bool) [create]
unparent given object(s) (parent to world) Flag can have multiple arguments, passed either as a tuple
or a list.
Derived from mel command `maya.cmds.parent`
"""
pass
def _MObjectIn(x):
pass
def move(*args, **kwargs):
"""
The move command is used to change the positions of geometric objects. The default behaviour, when no objects or flags
are passed, is to do a absolute move on each currently selected object in the world space. The value of the coordinates
are interpreted as being defined in the current linear unit unless the unit is explicitly mentioned. When using
-objectSpace there are two ways to use this command. If numbers are typed without units then the internal values of the
object are set to these values. If, on the other hand a unit is specified then the internal value is set to the
equivalent internal value that represents that world-space distance. The -localSpace flag moves the object in its parent
space. In this space the x,y,z values correspond directly to the tx, ty, tz channels on the object. The
-rotatePivotRelative/-scalePivotRelative flags can be used with the -absolute flag to translate an object so that its
pivot point ends up at the given absolute position. These flags will be ignored if components are specified. The
-worldSpaceDistance flag is a modifier flag that may be used in conjunction with the -objectSpace/-localSpace flags.
When this flag is specified the command treats the x,y,z values as world space units so the object will move the
specified world space distance but it will move along the axis specified by the -objectSpace/-localSpace flag. The
default behaviour, without this flag, is to treat the x,y,z values as units in object space or local space. In other
words, the worldspace distance moved will depend on the transformations applied to the object unless this flag is
specified.
Modifications:
- allows any iterable object to be passed as first argument::
move("pSphere1", [0,1,2])
NOTE: this command also reorders the argument order to be more intuitive, with the object first
Flags:
- absolute : a (bool) [create]
Perform an absolute operation.
- componentSpace : cs (bool) [create]
Move in component space
- constrainAlongNormal : xn (bool) [create]
When true, transform constraints are applied along the vertex normal first and only use the closest point when no
intersection is found along the normal.
- deletePriorHistory : dph (bool) [create]
If true then delete the history prior to the current operation.
- localSpace : ls (bool) [create]
Move in local space
- moveX : x (bool) [create]
Move in X direction
- moveXY : xy (bool) [create]
Move in XY direction
- moveXYZ : xyz (bool) [create]
Move in all directions (default)
- moveXZ : xz (bool) [create]
Move in XZ direction
- moveY : y (bool) [create]
Move in Y direction
- moveYZ : yz (bool) [create]
Move in YZ direction
- moveZ : z (bool) [create]
Move in Z direction
- objectSpace : os (bool) [create]
Move in object space
- orientJoint : oj (unicode) [create]
Default is xyz.
- parameter : p (bool) [create]
Move in parametric space
- preserveChildPosition : pcp (bool) [create]
When true, transforming an object will apply an opposite transform to its child transform to keep them at the same
world-space position. Default is false.
- preserveGeometryPosition : pgp (bool) [create]
When true, transforming an object will apply an opposite transform to its geometry points to keep them at the same
world-space position. Default is false.
- preserveUV : puv (bool) [create]
When true, UV values on translated components are projected along the translation in 3d space. For small edits, this
will freeze the world space texture mapping on the object. When false, the UV values will not change for a selected
vertices. Default is false.
- reflection : rfl (bool) [create]
To move the corresponding symmetric components also.
- reflectionAboutBBox : rab (bool) [create]
Sets the position of the reflection axis at the geometry bounding box
- reflectionAboutOrigin : rao (bool) [create]
Sets the position of the reflection axis at the origin
- reflectionAboutX : rax (bool) [create]
Specifies the X=0 as reflection plane
- reflectionAboutY : ray (bool) [create]
Specifies the Y=0 as reflection plane
- reflectionAboutZ : raz (bool) [create]
Specifies the Z=0 as reflection plane
- reflectionTolerance : rft (float) [create]
Specifies the tolerance to findout the corresponding reflected components
- relative : r (bool) [create]
Perform a operation relative to the object's current position
- rotatePivotRelative : rpr (bool) [create]
Move relative to the object's rotate pivot point.
- scalePivotRelative : spr (bool) [create]
Move relative to the object's scale pivot point.
- secondaryAxisOrient : sao (unicode) [create]
Default is xyz.
- symNegative : smn (bool) [create]
When set the component transformation is flipped so it is relative to the negative side of the symmetry plane. The
default (no flag) is to transform components relative to the positive side of the symmetry plane.
- worldSpace : ws (bool) [create]
Move in world space
- worldSpaceDistance : wd (bool) [create]
Move is specified in world space units
- xformConstraint : xc (unicode) [create]
Apply a transform constraint to moving components. none - no constraintsurface - constrain components to the surfaceedge
- constrain components to surface edgeslive - constraint components to the live surfaceFlag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.move`
"""
pass
def displayStats(*args, **kwargs):
"""
Flags:
- frameRate : fr (bool) []
Derived from mel command `maya.cmds.displayStats`
"""
pass
def listNodesWithIncorrectNames(*args, **kwargs):
"""
List all nodes with incorrect names in the Script Editor.
Derived from mel command `maya.cmds.listNodesWithIncorrectNames`
"""
pass
def isTrue(*args, **kwargs):
"""
This commmand returns the state of the named condition. If the condition is true, it returns 1. Otherwise it returns 0.
Derived from mel command `maya.cmds.isTrue`
"""
pass
def displayAffected(*args, **kwargs):
"""
Turns on/off the special coloring of objects that are affected by the objects that are currently in the selection list.
If one of the curves in a loft were selected and this feature were turned on, then the lofted surface would be
highlighted because it is affected by the loft curve.
Derived from mel command `maya.cmds.displayAffected`
"""
pass
def vnnPaste(*args, **kwargs):
"""
Paste the copied VNN nodes to target VNN compound. The first parameter is the full name of the DG node that contains the
VNN graph. The second parameter is the full path of the target VNN compound. A vnnCopymust be called before this command
is called.
Derived from mel command `maya.cmds.vnnPaste`
"""
pass
def selectionConnection(*args, **kwargs):
"""
This command creates a named selectionConnection object. This object is simply a shared selection list. It may be used
by editors to share their highlight data. For example, an outliner may attach its selected list to one of these objects,
and a graph editor may use the same object as a list source. Then, the graph editor would only display objects that are
selected in the outliner. Selection connections are UI objects which contain a list of model objects. Selection
connections are useful for specifying which objects are to be displayed within a particular editor. Editor's have three
plug socketswhere a selection connection may be attached. They are: mainListConnectionan inputsocket which contains a
list of objects that are to be displayed within the editorselectionConnectionan outputsocket which contains a list of
objects that are selectedwithin the editorhighlightConnectionan inputsocket which contains a list of objects that are to
be highlightedwithin the editorThere are several different types of selection connections that may be created. They
include: activeLista selection connection which contains a list of everything in the model which is active (which
includes geometry objects and keys)modelLista selection connection which contains a list of all the geometry (i.e.
excluding keys) objects that are currently activekeyframeLista selection connection which contains a list of all the
keys that are currently activeworldLista selection connection which contains a list of all the objects in the
worldobjectLista selection connection which contains one model object (which may be a set)listLista selection connection
which contains a list of selection connectionseditorLista selection connection which contains a list of objects that are
attached to the mainListConnection of the specified editorsetLista selection connection which contains a list of all the
sets in the worldcharacterLista selection connection which contains a list of all the characters in the
worldhighlightLista selection connection which contains a list of objects to be highlighted in some fashionBelow is an
example selectionConnection network between two editors. Editor 1 is setup to display objects on the activeList. Editor
2 is setup to display objects which are selected within Editor 1, and objects that are selected in Editor 2 are
highlighted within Editor 1: -- Editor 1-- -- Editor 2-- inputList--| main | | |-| main | | | |
sele |--| | | sele |--| |-| high | | | high | | | | ------------- ------------- |
|------------- fromEditor2 -------------| The following commands will establish this network: selectionConnection
-activeList inputList; selectionConnection fromEditor1; selectionConnection fromEditor2; editor -edit
-mainListConnection inputList Editor1; editor -edit -selectionConnection fromEditor1 Editor1; editor -edit
-mainListConnection fromEditor1 Editor2; editor -edit -selectionConnection fromEditor2 Editor2; editor -edit
-highlightConnection fromEditor2 Editor1; Note: to delete a selection connectionuse the deleteUI commandNote: commands
which expect objects may be given a selection connection instead, and the command will operate upon the objects wrapped
by the selection connectionNote: the graph editor and the dope sheet are the only editors which can use the editor
connection to the highlightConnection of another editorWARNING: some flag combinations may not behave as you expect.
The command is really intended for internal use for managing the outliner used by the various editors.
Flags:
- activeCacheList : atc (bool) [create]
Specifies that this connection should reflect the cache that objects on the active list belong to.
- activeCharacterList : acl (bool) [create]
Specifies that this connection should reflect the characters that objects on the active list belong to.
- activeList : act (bool) [create]
Specifies that this connection should reflect the active list (geometry objects and keys).
- addScript : addScript (script) [create,query,edit]
Specify a script to be called when something is added to the selection.
- addTo : add (unicode) [create,edit]
The name of a selection connection that should be added to this list of connections.
- characterList : cl (bool) [create]
Specifies that this connection should reflect all the characters in the world.
- clear : clr (bool) [create,edit]
Remove everything from the selection connection.
- connectionList : lst (bool) [create,query]
Specifies that this connection should contain a list of selection connections.
- defineTemplate : dt (unicode) [create]
Puts the command in a mode where any other flags and args are parsed and added to the command template specified in the
argument. They will be used as default arguments in any subsequent invocations of the command when templateName is set
as the current template.
- deselect : d (PyNode) [create,edit]
Remove something from the selection.
- editor : ed (unicode) [create,query,edit]
Specifies that this connection should reflect the -mainListConnection of the specified editor.
- exists : ex (bool) [create]
Returns whether the specified object exists or not. Other flags are ignored.
- filter : f (unicode) [create,query,edit]
Optionally specifies an itemFilter for this connection. An empty string () clears the current filter. If a filter is
specified, all the information going into the selectionConnection must first pass through the filter before being
accepted. NOTE: filters can only be attached to regular selectionConnections. They cannot be attached to any connection
created using the -act, -mdl, -key, -wl, -sl, -cl, -lst, -obj, or -ren flags. We strongly recommend that you do not
attach filters to a selectionConnection --- it is better to attach your filter to the editor that is using the
selectionConnection instead.
- findObject : fo (PyNode) [query]
Find a selection connection in this list that wraps the specified object.
- g : g (bool) [create,query,edit]
A global selection connection cannot be deleted by any script commands.
- highlightList : hl (bool) [create]
Specifies that this connection is being used as a highlight list.
- identify : id (bool) [query]
Find out what type of selection connection this is. May be: activeList | modelList | keyframeList | worldList |
objectList listList | editorList | connection | unknown
- keyframeList : key (bool) [create]
Specifies that this connection should reflect the animation portion of the active list.
- lock : lck (bool) [create,query,edit]
For activeList connections, locking the connection means that it will not listen to activeList changes.
- modelList : mdl (bool) [create]
Specifies that this connection should reflect the modeling (i.e. excluding keys) portion of the active list.
- object : obj (PyNode) [create,query,edit]
Specifies that this connection should wrap around the specified object (which may be a set). Query will return all the
members of the selection connection (if the connection wraps a set, the set members will be returned)
- parent : p (unicode) [create,query,edit]
The name of a UI object this should be attached to. When the parent is destroyed, the selectionConnection will auto-
delete. If no parent is specified, the connection is created in the current controlLayout.
- remove : rm (unicode) [create,edit]
The name of a selection connection that should be removed from this list of connections.
- removeScript : rs (script) [create,query,edit]
Specify a script to be called when something is removed from the selection.
- select : s (PyNode) [create,edit]
Add something to the selection. This does not replace the existing selection.
- setList : sl (bool) [create]
Specifies that this connection should reflect all the sets in the world.
- switch : sw (bool) [create,query]
Acts as a modifier to -connectionList which sets the list of objects to be the first non-empty selection connection.
selection connections are tested in the order in which they are added.
- useTemplate : ut (unicode) [create]
Forces the command to use a command template other than the current one.
- worldList : wl (bool) [create]
Specifies that this connection should reflect all objects in the world. Flag can have multiple
arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.selectionConnection`
"""
pass
def instancer(*args, **kwargs):
"""
This command is used to create a instancer node and set the proper attributes in the node.
Maya Bug Fix:
- name of newly created instancer was not returned
Flags:
- addObject : a (bool) [create,edit]
This flag indicates that objects specified by the -object flag will be added to the instancer node as instanced objects.
- cycle : c (unicode) [create,query,edit]
This flag sets or queries the cycle attribute for the instancer node. The options are noneor sequential. The default is
none.
- cycleStep : cs (float) [create,query,edit]
This flag sets or queries the cycle step attribute for the instancer node. This attribute indicates the size of the
step in frames or seconds (see cycleStepUnit).
- cycleStepUnits : csu (unicode) [create,query,edit]
This flag sets or queries the cycle step unit attribute for the instancer node. The options are framesor seconds. The
default is frames.
- index : i (int) [query]
This flag is used to query the name of the ith instanced object.
- levelOfDetail : lod (unicode) [create,query,edit]
This flag sets or queries the level of detail of the instanced objects. The options are geometry, boundingBox,
boundingBoxes. The default is geometry.
- name : n (unicode) [create,query]
This flag sets or queries the name of the instancer node.
- object : obj (unicode) [create,query,edit]
This flag indicates which objects will be add/removed from the list of instanced objects. The flag is used in
conjuction with the -add and -remove flags. If neither of these flags is specified on the command line then -add is
assumed.
- objectPosition : op (unicode) [query]
This flag queries the given objects position. This object can be any instanced object or sub-object.
- objectRotation : objectRotation (unicode) [query]
This flag queries the given objects rotation. This object can be any instanced object or sub-object.
- objectScale : os (unicode) [query]
This flag queries the given objects scale. This object can be any instanced object or sub-object.
- pointDataSource : pds (bool) [query]
This flag is used to query the source node supply the data for the input points.
- removeObject : rm (bool) [edit]
This flag indicates that objects specified by the -object flag will be removed from the instancer node as instanced
objects.
- rotationOrder : ro (unicode) [create,query,edit]
This flag specifies the rotation order associated with the rotation flag. The options are XYZ, XZY, YXZ, YZX, ZXY, or
ZYX. By default the attribute is XYZ.
- rotationUnits : ru (unicode) [create,query,edit]
This flag specifies the rotation units associated with the rotation flag. The options are degrees or radians. By
default the attribute is degrees.
- valueName : vn (unicode) [query]
This flag is used to query the value(s) of the array associated with the given name. If the -index flag is used in
conjuction with this flag then the ith value will be returned. Otherwise, the entire array will be returned.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.instancer`
"""
pass
def xform(*args, **kwargs):
"""
This command can be used query/set any element in a transformation node. It can also be used to query some values that
cannot be set directly such as the transformation matrix or the bounding box. It can also set both pivot points to
convenient values. All values are specified in transformation coordinates. (attribute-space) In addition, the attributes
are applied/returned in the order in which they appear in the flags section. (which corresponds to the order they appear
in the transformation matrix as given below) See also:move, rotate, scale where: [sp] = | 1 0 0 0 | =
scale pivot matrix | 0 1 0 0 | | 0 0 1 0 | | -spx -spy -spz 1 | [s] = |
sx 0 0 0 | = scale matrix | 0 sy 0 0 | | 0 0 sz 0 | | 0 0
0 1 | [sh] = | 1 0 0 0 | = shear matrix | xy 1 0 0 | | xz yz 1
0 | | 0 0 0 1 | -1 [sp] = | 1 0 0 0 | = scale pivot inverse matrix | 0 1
0 0 | | 0 0 1 0 | | spx spy spz 1 | [st] = | 1 0 0 0 | = scale
translate matrix | 0 1 0 0 | | 0 0 1 0 | | stx sty stz 1 | [rp] = |
1 0 0 0 | = rotate pivot matrix | 0 1 0 0 | | 0 0 1 0 | | -rpx
-rpy -rpz 1 | [ar] = | \* \* \* 0 | = axis rotation matrix | \* \* \* 0 |
(composite rotation, | \* \* \* 0 | see [rx], [ry], [rz] | 0 0 0 1 | below
for details) [rx] = | 1 0 0 0 | = rotate X matrix | 0 cos(x) sin(x) 0 | | 0 -sin(x)
cos(x) 0 | | 0 0 0 1 | [ry] = | cos(y) 0 -sin(y) 0 | = rotate Y matrix | 0 1 0
0 | | sin(y) 0 cos(y) 0 | | 0 0 0 1 | [rz] = | cos(z) sin(z) 0 0 | = rotate Z
matrix | -sin(z) cos(z) 0 0 | | 0 0 1 0 | | 0 0 0 1 | -1 [rp] = | 1
0 0 0 | = rotate pivot matrix | 0 1 0 0 | | 0 0 1 0 | | rpx rpy
rpz 1 | [rt] = | 1 0 0 0 | = rotate translate matrix | 0 1 0 0 | | 0 0
1 0 | | rtx rty rtz 1 | [t] = | 1 0 0 0 | = translation matrix | 0 1
0 0 | | 0 0 1 0 | | tx ty tz 1 | In query mode, return type is based on queried
flag.
Flags:
- absolute : a (bool) [create]
perform absolute transformation (default)
- boundingBox : bb (bool) [query]
Returns the bounding box of an object. The values returned are in the following order: xmin ymin zmin xmax ymax zmax.
- boundingBoxInvisible : bbi (bool) [query]
Returns the bounding box of an object. This includes the bounding boxes of all invisible children which are not included
using the boundingBox flag. The values returned are in following order: xmin ymin zmin xmax ymax zmax.
- centerPivots : cp (bool) [create]
Set pivot points to the center of the object's bounding box. (see -p flag)
- centerPivotsOnComponents : cpc (bool) [create]
Set pivot points to the center of the component's bounding box. (see -p flag)
- deletePriorHistory : dph (bool) [create]
If true then delete the construction history before the operation is performed.
- euler : eu (bool) [create]
modifer for -relative flag that specifies rotation values should be added to current XYZ rotation values.
- matrix : m (float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float) [create,query]
Sets/returns the composite transformation matrix. \*Note\* the matrix is represented by 16 double arguments that are
specified in row order.
- objectSpace : os (bool) [create,query]
treat values as object-space transformation values (only works for pivots, translations, rotation, rotation axis,
matrix, and bounding box flags)
- pivots : piv (float, float, float) [create,query]
convenience method that changes both the rotate and scale pivots simultaneously. (see -rp -sp flags for more info)
- preserve : p (bool) [create]
preserve overall transformation. used to prevent object from jumpingwhen changing pivots or rotation order. the default
value is true. (used with -sp, -rp, -roo, -cp, -ra)
- preserveUV : puv (bool) [create]
When true, UV values on rotated components are projected across the rotation in 3d space. For small edits, this will
freeze the world space texture mapping on the object. When false, the UV values will not change for a selected vertices.
Default is false.
- reflection : rfl (bool) [create]
To move the corresponding symmetric components also.
- reflectionAboutBBox : rab (bool) [create]
Sets the position of the reflection axis at the geometry bounding box
- reflectionAboutOrigin : rao (bool) [create]
Sets the position of the reflection axis at the origin
- reflectionAboutX : rax (bool) [create]
Specifies the X=0 as reflection plane
- reflectionAboutY : ray (bool) [create]
Specifies the Y=0 as reflection plane
- reflectionAboutZ : raz (bool) [create]
Specifies the Z=0 as reflection plane
- reflectionTolerance : rft (float) [create]
Specifies the tolerance to findout the corresponding reflected components
- relative : r (bool) [create]
perform relative transformation
- rotateAxis : ra (float, float, float) [create,query]
rotation axis orientation (when used with the -p flag the overall rotation is preserved by modifying the rotation to
compensate for the axis rotation)
- rotateOrder : roo (unicode) [create,query]
rotation order (when used with the -p flag the overall rotation is preserved by modifying the local rotation to be
quivalent to the old one) Valid values for this flag are xyz | yzx | zxy | xzy | yxz | zyx
- rotatePivot : rp (float, float, float) [create,query]
rotate pivot point transformation (when used with the -p flag the overall transformation is preserved by modifying the
rotation translation)
- rotateTranslation : rt (float, float, float) [create,query]
rotation translation
- rotation : ro (float, float, float) [create,query]
rotation transformation
- scale : s (float, float, float) [create,query]
scale transformation
- scalePivot : sp (float, float, float) [create,query]
scale pivot point transformation (when used with the -p flag the overall transformation is preserved by modifying the
scale translation)
- scaleTranslation : st (float, float, float) [create,query]
scale translation
- shear : sh (float, float, float) [create,query]
shear transformation. The values represent the shear xy,xz,yz
- translation : t (float, float, float) [create,query]
translation
- worldSpace : ws (bool) [create,query]
(works for pivots, translations, rotation, rotation axis, matrix, and bounding box flags). Note that, when querying the
scale, that this calculation is cumulative and is only valid if there are all uniform scales and no rotation. In a
hierarchy with non-uniform scale and rotation, this value may not correspond entirely with the perceived global scale.
- worldSpaceDistance : wd (bool) [create,query]
Values for -sp, -rp, -st, -rt, -t, -piv flags are treated as world space distances to move along the local axis. (where
the local axis depends on whether the command is operating in local-space or object-space. This flag has no effect for
world space.
- zeroTransformPivots : ztp (bool) [create]
reset pivot points and pivot translations without changing the overall matrix by applying these values into the
translation channel. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.xform`
"""
pass
def evalDeferred(*args, **kwargs):
"""
This command takes the string it is given and evaluates it during the next available idle time. It is useful for
attaching commands to controls that can change or delete the control.
Flags:
- evaluateNext : en (bool) []
- list : ls (bool) [create]
Return a list of the command strings that are currently pending on the idle queue. By default, it will return the list
of commands for all priorities. The -lowestPriority and -lowPriority can be used to restrict the list of commands to a
given priority level.
- lowPriority : low (bool) [create]
Specified that the command to be executed should be deferred with the low priority. That is, it will be executed
whenever Maya is idle.
- lowestPriority : lp (bool) [create]
Specified that the command to be executed should be deferred with the lowest priority. That is, it will be executed when
no other idle events are scheduled. Flag can have multiple arguments, passed either as a tuple or a
list.
Derived from mel command `maya.cmds.evalDeferred`
"""
pass
def commandEcho(*args, **kwargs):
"""
This command controls what is echoed to the command window. In query mode, return type is based on queried
flag.
Flags:
- addFilter : af (<type 'unicode'>, ...) [create]
This flag allows you to append filters to the current list of filtered commands when echo all commands is enabled. Just
like the filter flag, you can provide a partial command name, so all commands that start with a substring specified in
the addFilter entry will be filtered out.
- filter : f (<type 'unicode'>, ...) [create,query]
This flag allows you to filter out unwanted commands when echo all commands is enabled. You can provide a partial
command name, so all commands that start with a substring specified in filter entry will be filtered out. If filter is
empty, all commands are echoed to the command window.
- lineNumbers : ln (bool) [create,query]
If true then file name and line number information is provided in error and warning messages. If false then no file name
and line number information is provided in error and warning messages.
- state : st (bool) [create,query]
If true then all commands are echoed to the command window. If false then only relevant commands are echoed.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.commandEcho`
"""
pass
def toolHasOptions(*args, **kwargs):
"""
This command queries a tool to see if it has options. If it does, it returns true. Otherwise it returns false.
Derived from mel command `maya.cmds.toolHasOptions`
"""
pass
def vnnConnect(*args, **kwargs):
"""
Makes a connection between two VNN node ports. The first parameter is the full name of the DG node that contains the VNN
graph. The next two parameters are the full path of the ports from the root of the VNN container. This command can be
used for compound or node connections, and the parameters can be out-of-order.
Flags:
- disconnect : d (bool) [create]
delete the connection if it exists, rather than creating a new connection Flag can have multiple
arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.vnnConnect`
"""
pass
def _getParent(getter, obj, generations):
"""
If generations is None, then a list of all the parents is returned.
"""
pass
def setEnums(attr, enums):
"""
Set the enumerators for an enum attribute.
"""
pass
def colorManagementConvert(*args, **kwargs):
"""
This command can be used to convert rendering (a.k.a. working) space color values to display space color values. This is
useful if you create custom UI with colors painted to screen, where you need to handle color management yourself. The
current view transform set in the Color Management user preferences will be used.
Flags:
- toDisplaySpace : tds (float, float, float) [create]
Converts the given RGB value to display space. Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.colorManagementConvert`
"""
pass
def reorder(*args, **kwargs):
"""
This command reorders (moves) objects relative to their siblings. For relative moves, both positive and negative numbers
may be specified. Positive numbers move the object forward and negative numbers move the object backward amoung its
siblings. When an object is at the end (beginning) of the list of siblings, a relative move of 1 (-1) will put the
object at the beginning (end) of the list of siblings. That is, relative moves will wrap if necessary. If a shape is
specified and it is the only child then its parent will be reordered.
Flags:
- back : b (bool) [create]
Move object(s) to back of sibling list.
- front : f (bool) [create]
Move object(s) to front of sibling list.
- relative : r (int) [create]
Move object(s) relative to other siblings. Flag can have multiple arguments, passed either as a tuple
or a list.
Derived from mel command `maya.cmds.reorder`
"""
pass
def deleteExtension(*args, **kwargs):
"""
This command is used to delete an extension attribute from a node type. The attribute can be specified by using either
the long or short name. Only one extension attribute can be deleted at a time. Children of a compound attribute cannot
be deleted, you must delete the complete compound attribute. This command has no undo, edit, or query capabilities.
Flags:
- attribute : at (unicode) [create]
Specify either the long or short name of the attribute.
- forceDelete : fd (bool) [create]
If this flag is set and turned ON then data values for the extension attributes are all deleted without confirmation. If
it's set and turned OFF then any extension attributes that have non-default values set on any node will remain in place.
If this flag is not set at all then the user will be asked if they wish to preserve non-default values on this
attribute.
- nodeType : nt (unicode) [create]
The name of the node type. Flag can have multiple arguments, passed either as a tuple or
a list.
Derived from mel command `maya.cmds.deleteExtension`
"""
pass
def _deprecatePyNode():
pass
def spaceLocator(*args, **kwargs):
"""
The command creates a locator at the specified position in space. By default it is created at (0,0,0).
Modifications:
- returns a single Transform instead of a list with a single locator
Flags:
- absolute : a (bool) [create,edit]
If set, the locator's position is in world space.
- name : n (unicode) [create,edit]
Name for the locator.
- position : p (float, float, float) [create,query,edit]
Location in 3-dimensional space where locator is to be created.
- relative : r (bool) [create,edit]
If set, the locator's position is relative to its local space. The locator is created in relative mode by default.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.spaceLocator`
"""
pass
def vnn(*args, **kwargs):
"""
This command is used for operations that apply to a whole VNN runtime, for example Bifrost. The Create Node window uses
it to build its list of nodes.
Flags:
- flushProxies : fp (unicode) [create,query]
Flush proxies for the named VNN runtime, for example Bifrost. This is a flag used for developers to ask a given runtime
to release all of its proxy VNN nodes so that they can be re-created the next time they are requested. This is used to
verify that the VNN graph corresponds to the graph that is being virtualized, or proxied. The maya node editor or any
other UI that uses VNN should be closed before this called is made. Failure to do so will result in that UI failure to
recongnize changes made to the VNN graph, because the changes will be made on another set of proxies.
- libraries : lib (unicode) [create,query]
List of the libraries in runTime.
- listPortTypes : lpt (unicode) [create,query]
List all the possible port types for the given VNN runtime, for example Bifrost. The list of port types is not fixed and
could grow as new definitions are added to the runtime.
- nodes : nd (unicode, unicode) [create,query]
List of the nodes from the runTime library. First argument is the name of the runtime, like Bifrost, second is the name
of the library, obtained with -libraries
- runTimes : rt (bool) [create,query]
List all the runTimes registered with VNN. Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.vnn`
"""
pass
def connectionInfo(*args, **kwargs):
"""
The connectionInfocommand is used to get information about connection sources and destinations. Unlike the isConnected
command, this command needs only one end of the connection.
Flags:
- destinationFromSource : dfs (bool) [create]
If the specified plug (or its ancestor) is a source, this flag returns the list of destinations connected from the
source. (array of strings, empty array if none)
- getExactDestination : ged (bool) [create]
If the plug or its ancestor is connection destination, this returns the name of the plug that is the exact destination.
(empty string if there is no such connection).
- getExactSource : ges (bool) [create]
If the plug or its ancestor is a connection source, this returns the name of the plug that is the exact source. (empty
string if there is no such connection).
- getLockedAncestor : gla (bool) [create]
If the specified plug is locked, its name is returned. If an ancestor of the plug is locked, its name is returned. If
more than one ancestor is locked, only the name of the closest one is returned. If neither this plug nor any ancestors
are locked, an empty string is returned.
- isDestination : id (bool) [create]
Returns true if the plug (or its ancestor) is the destination of a connection, false otherwise.
- isExactDestination : ied (bool) [create]
Returns true if the plug is the exact destination of a connection, false otherwise.
- isExactSource : ies (bool) [create]
Returns true if the plug is the exact source of a connection, false otherwise.
- isLocked : il (bool) [create]
Returns true if this plug (or its ancestor) is locked
- isSource : isSource (bool) [create]
Returns true if the plug (or its ancestor) is the source of a connection, false otherwise.
- sourceFromDestination : sfd (bool) [create]
If the specified plug (or its ancestor) is a destination, this flag returns the source of the connection. (string, empty
if none) Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.connectionInfo`
"""
pass
def listAttr(*args, **kwargs):
"""
This command lists the attributes of a node. If no flags are specified all attributes are listed.
Modifications:
- returns an empty list when the result is None
Flags:
- array : a (bool) [create]
only list array (not multi) attributes
- caching : ca (bool) [create]
only show attributes that are cached internally
- category : ct (unicode) [create]
only show attributes belonging to the given category. Category string can be a regular expression.
- changedSinceFileOpen : cfo (bool) [create]
Only list the attributes that have been changed since the file they came from was opened. Typically useful only for
objects/attributes coming from referenced files.
- channelBox : cb (bool) [create]
only show non-keyable attributes that appear in the channelbox
- connectable : c (bool) [create]
only show connectable attributes
- extension : ex (bool) [create]
list user-defined attributes for all nodes of this type (extension attributes)
- fromPlugin : fp (bool) [create]
only show attributes that were created by a plugin
- hasData : hd (bool) [create]
list only attributes that have data (all attributes except for message attributes)
- hasNullData : hnd (bool) [create]
list only attributes that have null data. This will list all attributes that have data (see hasData flag) but the data
value is uninitialized. A common example where an attribute may have null data is when a string attribute is created but
not yet assigned an initial value. Similarly array attribute data is often null until it is initialized.
- inUse : iu (bool) [create]
only show attributes that are currently marked as in use. This flag indicates that an attribute affects the scene data
in some way. For example it has a non-default value or it is connected to another attribute. This is the general
concept though the precise implementation is subject to change.
- keyable : k (bool) [create]
only show attributes that can be keyframed
- leaf : lf (bool) [create]
Only list the leaf-level name of the attribute. controlPoints[44].xValue would be listed as xValue.
- locked : l (bool) [create]
list only attributes which are locked
- multi : m (bool) [create]
list each currently existing element of a multi-attribute
- output : o (bool) [create]
List only the attributes which are numeric or which are compounds of numeric attributes.
- ramp : ra (bool) [create]
list only attributes which are ramps
- read : r (bool) [create]
list only attributes which are readable
- readOnly : ro (bool) [create]
List only the attributes which are readable and not writable.
- scalar : s (bool) [create]
only list scalar numerical attributes
- scalarAndArray : sa (bool) [create]
only list scalar and array attributes
- settable : se (bool) [create]
list attribute which are settable
- shortNames : sn (bool) [create]
list short attribute names (default is to list long names)
- string : st (unicode) [create]
List only the attributes that match the other criteria AND match the string(s) passed from this flag. String can be a
regular expression.
- unlocked : u (bool) [create]
list only attributes which are unlocked
- usedAsFilename : uf (bool) [create]
list only attributes which are designated to be treated as filenames
- userDefined : ud (bool) [create]
list user-defined (dynamic) attributes
- visible : v (bool) [create]
only show visible or non-hidden attributes
- write : w (bool) [create]
list only attributes which are writable Flag can have multiple arguments, passed either as a tuple or a
list.
Derived from mel command `maya.cmds.listAttr`
"""
pass
def itemFilterType(*args, **kwargs):
"""
This command queries a named itemFilter object. This object can be attached to selectionConnection objects, or to
editors, in order to filter the item lists going through them. Using union and intersection filters, complex composite
filters can be created.
Flags:
- text : t (unicode) [query,edit]
Defines an annotation string to be stored with the filter
- type : typ (bool) [query]
Query the type of the filter object. Possible return values are: itemFilter, attributeFilter, renderFilter, or
unknownFilter. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.itemFilterType`
"""
pass
def _MPlugIn(x):
pass
def ls(*args, **kwargs):
"""
The lscommand returns the names (and optionally the type names) of objects in the scene. The most common use of lsis to
filter or match objects based on their name (using wildcards) or based on their type. By default lswill match any object
in the scene but it can also be used to filter or list the selected objects when used in conjunction with the -selection
flag. If type names are requested, using the showType flag, they will be interleaved with object names so the result
will be pairs of object, typevalues. Internal nodes (for example itemFilter nodes) are typically filtered so that only
scene objects are returned. However, using a wildcard will cause all the nodes matching the wild card to show up,
including internal nodes. For example, ls \*will list all nodes whether internal or not. When Maya is in relativeNames
mode, the lscommand will return names relativeto the current namespace and ls \*will list from the the current
namespace. For more details, please refer to the -relativeNamesflag of the namespacecommand. The command may also be
passed node UUIDs instead of names/paths, and can return UUIDs instead of names via the -uuid flag.
Modifications:
- Returns PyNode objects, not "names" - all flags which do nothing but modify
the string name of returned objects are ignored (ie, 'long'); note that
the 'allPaths' flag DOES have an effect, as PyNode objects are aware of
their dag paths (ie, two different instances of the same object will result
in two unique PyNodes)
- Added new keyword: 'editable' - this will return the inverse set of the readOnly flag. i.e. non-read-only nodes
- Added new keyword: 'regex' - pass a valid regular expression string, compiled regex pattern, or list thereof.
>>> group('top')
nt.Transform(u'group1')
>>> duplicate('group1')
[nt.Transform(u'group2')]
>>> group('group2')
nt.Transform(u'group3')
>>> ls(regex='group\d+\|top') # don't forget to escape pipes `|`
[nt.Transform(u'group1|top'), nt.Transform(u'group2|top')]
>>> ls(regex='group\d+\|top.*')
[nt.Transform(u'group1|top'), nt.Camera(u'group1|top|topShape'), nt.Transform(u'group2|top'), nt.Camera(u'group2|top|topShape')]
>>> ls(regex='group\d+\|top.*', cameras=1)
[nt.Camera(u'group2|top|topShape'), nt.Camera(u'group1|top|topShape')]
>>> ls(regex='\|group\d+\|top.*', cameras=1) # add a leading pipe to search for full path
[nt.Camera(u'group1|top|topShape')]
The regular expression will be used to search the full DAG path, starting from the right, in a similar fashion to how globs currently work.
Technically speaking, your regular expression string is used like this::
re.search( '(\||^)' + yourRegexStr + '$', fullNodePath )
:rtype: `PyNode` list
Flags:
- absoluteName : an (bool) [create]
This flag can be used in conjunction with the showNamespace flag to specify that the namespace(s) returned by the
command be in absolute namespace format. The absolute name of the namespace is a full namespace path, starting from the
root namespace :and including all parent namespaces. For example :ns:ballis an absolute namespace name while ns:ballis
not. The absolute namespace name is invariant and is not affected by the current namespace or relative namespace modes.
- allPaths : ap (bool) [create]
List all paths to nodes in DAG. This flag only works if -dagis also specified or if an object name is supplied.
- assemblies : assemblies (bool) [create]
List top level transform Dag objects
- cameras : ca (bool) [create]
List camera shapes.
- containerType : ct (unicode) [create]
List containers with the specified user-defined type. This flag cannot be used in conjunction with the type or exactType
flag.
- containers : con (bool) [create]
List containers. Includes both standard containers as well as other types of containers such as dagContainers.
- dagObjects : dag (bool) [create]
List Dag objects of any type. If object name arguments are passed to the command then this flag will list all Dag
objects below the specified object(s).
- defaultNodes : dn (bool) [create]
Returns default nodes. A default node is one that Maya creates automatically and does not get saved out with the scene,
although some of its attribute values may.
- dependencyNodes : dep (bool) [create]
List dependency nodes. (including Dag objects)
- exactType : et (unicode) [create]
List all objects of the specified type, but notobjects that are descendents of that type. This flag can appear multiple
times on the command line. Note: the type passed to this flag is the same type name returned from the showType flag.
This flag cannot be used in conjunction with the type or excludeType flag.
- excludeType : ext (unicode) [create]
List all objects that are not of the specified type. This flag can appear multiple times on the command line. Note: the
type passed to this flag is the same type name returned from the showType flag. This flag cannot be used in conjunction
with the type or exactType flag.
- flatten : fl (bool) [create]
Flattens the returned list of objects so that each component is identified individually.
- geometry : g (bool) [create]
List geometric Dag objects.
- ghost : gh (bool) [create]
List ghosting objects.
- head : hd (int) [create]
This flag specifies the maximum number of elements to be returned from the beginning of the list of items. Note: each
type flag will return at most this many items so if multiple type flags are specified then the number of items returned
can be greater than this amount.
- hilite : hl (bool) [create]
List objects that are currently hilited for component selection.
- intermediateObjects : io (bool) [create]
List only intermediate dag nodes.
- invisible : iv (bool) [create]
List only invisible dag nodes.
- leaf : lf (bool) [create]
List all leaf nodes in Dag. This flag is a modifier and must be used in conjunction with the -dag flag.
- lights : lt (bool) [create]
List light shapes.
- live : lv (bool) [create]
List objects that are currently live.
- lockedNodes : ln (bool) [create]
Returns locked nodes, which cannot be deleted or renamed. However, their status may change.
- long : l (bool) [create]
Return full path names for Dag objects. By default the shortest unique name is returned.
- materials : mat (bool) [create]
List materials or shading groups.
- modified : mod (bool) [create]
When this flag is set, only nodes modified since the last save will be returned.
- noIntermediate : ni (bool) [create]
List only non intermediate dag nodes.
- nodeTypes : nt (bool) [create]
Lists all registered node types.
- objectsOnly : o (bool) [create]
When this flag is set only object names will be returned and components/attributes will be ignored.
- orderedSelection : os (bool) [create]
List objects and components that are currently selected in their order of selection. This flag depends on the value of
the -tso/trackSelectionOrder flag of the selectPref command. If that flag is not enabled than this flag will return the
same thing as the -sl/selection flag would.
- partitions : pr (bool) [create]
List partitions.
- persistentNodes : pn (bool) [create]
Returns persistent nodes, which are nodes that stay in the Maya session after a file new. These are a special class of
default nodes that do not get reset on file new. Ex: itemFilter and selectionListOperator nodes.
- planes : pl (bool) [create]
List construction plane shapes.
- preSelectHilite : psh (bool) [create]
List components that are currently hilited for pre-selection.
- readOnly : ro (bool) [create]
Returns referenced nodes. Referenced nodes are read only. NOTE: Obsolete. Please use -referencedNodes.
- recursive : r (bool) [create]
When set to true, this command will look for name matches in all namespaces. When set to false, this command will only
look for matches in namespaces that are requested (e.g. by specifying a name containing the ':'... ns1:pSphere1).
- referencedNodes : rn (bool) [create]
Returns referenced nodes. Referenced nodes are read only.
- references : rf (bool) [create]
List references associated with files. Excludes special reference nodes such as the sharedReferenceNode and unknown
reference nodes.
- renderGlobals : rg (bool) [create]
List render globals.
- renderQualities : rq (bool) [create]
List named render qualities.
- renderResolutions : rr (bool) [create]
List render resolutions.
- renderSetups : rs (bool) [create]
Alias for -renderGlobals.
- selection : sl (bool) [create]
List objects that are currently selected.
- sets : set (bool) [create]
List sets.
- shapes : s (bool) [create]
List shape objects.
- shortNames : sn (bool) [create]
Return short attribute names. By default long attribute names are returned.
- showNamespace : sns (bool) [create]
Show the namespace of each object after the object name. This flag cannot be used in conjunction with the showType flag.
- showType : st (bool) [create]
List the type of each object after its name.
- tail : tl (int) [create]
This flag specifies the maximum number of elements to be returned from the end of the list of items. Note: each type
flag will return at most this many items so if multiple type flags are specified then the number of items returned can
be greater than this amount
- templated : tm (bool) [create]
List only templated dag nodes.
- textures : tex (bool) [create]
List textures.
- transforms : tr (bool) [create]
List transform objects.
- type : typ (unicode) [create]
List all objects of the specified type. This flag can appear multiple times on the command line. Note: the type passed
to this flag is the same type name returned from the showType flag. Note: some selection items in Maya do not have a
specific object/data type associated with them and will return untypedwhen listed with this flag. This flag cannot be
used in conjunction with the exactType or excludeType flag.
- undeletable : ud (bool) [create]
Returns nodes that cannot be deleted (which includes locked nodes). These nodes also cannot be renamed.
- untemplated : ut (bool) [create]
List only un-templated dag nodes.
- uuid : uid (bool) [create]
Return node UUIDs instead of names. Note that there are no UUID paths- combining this flag with e.g. the -long flag will
not result in a path formed of node UUIDs.
- visible : v (bool) [create]
List only visible dag nodes. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.ls`
"""
pass
def contextInfo(*args, **kwargs):
"""
This command allows you to get information on named contexts.
Flags:
- apiImage1 : ip1 (unicode) []
- c : c (bool) [create]
Return the class type of the named context.
- escapeContext : esc (bool) [create]
Return the command string that will allow you to exit the current tool.
- exists : ex (bool) [create]
Return true if the context exists, false if it does not exists (or is internal and therefore untouchable)
- image1 : i1 (bool) [create]
Returns the name of an xpm associated with the named context.
- image2 : i2 (bool) [create]
Returns the name of an xpm associated with the named context.
- image3 : i3 (bool) [create]
Returns the name of an xpm associated with the named context.
- title : t (bool) [create]
Return the title string of the named context. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.contextInfo`
"""
pass
def displaySurface(*args, **kwargs):
"""
This command toggles display options on the specified or active surfaces. Typically this command applies to NURBS or
poly mesh surfaces and ignores other type of objects.
Flags:
- flipNormals : flp (bool) [query]
flip normal direction on the surface
- twoSidedLighting : two (bool) [query]
toggle if the surface should be considered two-sided. If it's single-sided, drawing and rendering may use single sided
lighting and back face cull to improve performance.
- xRay : x (bool) [query]
toggle X ray mode (make surface transparent) Flag can have multiple arguments, passed either as a tuple
or a list.
Derived from mel command `maya.cmds.displaySurface`
"""
pass
def select(*args, **kwargs):
"""
This command is used to put objects onto or off of the active list. If none of the five flags [-add, -af, -r, -d, -tgl]
are specified, the default is to replace the objects on the active list with the given list of objects. When selecting a
set as in select set1, the behaviour is for all the members of the set to become selected instead of the set itself. If
you want to select a set, the -ne/noExpandflag must be used. With the advent of namespaces, selection by name may be
confusing. To clarify, without a qualified namespace, name lookup is limited to objects in the root namespace :. There
are really two parts of a name: the namespace and the name itself which is unique within the namespace. If you want to
select objects in a specific namespace, you need to include the namespace separator :. For example, 'select -r foo\*' is
trying to look for an object with the fooprefix in the root namespace. It is not trying to look for all objects in the
namespace with the fooprefix. If you want to select all objects in a namespace (foo), use 'select foo:\*'. Note: When
the application starts up, there are several dependency nodes created by the system which must exist. These objects are
not deletable but are selectable. All objects (dag and dependency nodes) in the scene can be obtained using the
lscommand without any arguments. When using the -all, adn/allDependencyNodesor -ado/allDagObjectsflags, only the
deletable objects are selected. The non deletable object can still be selected by explicitly specifying their name as
in select time1;.
Modifications:
- passing an empty list no longer causes an error.
instead, the selection is cleared if the selection mod is replace (the default);
otherwise, it does nothing
Flags:
- add : add (bool) [create]
Indicates that the specified items should be added to the active list without removing existing items from the active
list.
- addFirst : af (bool) [create]
Indicates that the specified items should be added to the front of the active list without removing existing items from
the active list.
- all : all (bool) [create]
Indicates that all deletable root level dag objects and all deletable non-dag dependency nodes should be selected.
- allDagObjects : ado (bool) [create]
Indicates that all deletable root level dag objects should be selected.
- allDependencyNodes : adn (bool) [create]
Indicates that all deletable dependency nodes including all deletable dag objects should be selected.
- clear : cl (bool) [create]
Clears the active list. This is more efficient than select -d;. Also select -d;will not remove sets from the active
list unless the -neflag is also specified.
- containerCentric : cc (bool) [create]
Specifies that the same selection rules as apply to selection in the main viewport will also be applied to the select
command. In particular, if the specified objects are members of a black-boxed container and are not published as nodes,
Maya will not select them. Instead, their first parent valid for selection will be selected.
- deselect : d (bool) [create]
Indicates that the specified items should be removed from the active list if they are on the active list.
- hierarchy : hi (bool) [create]
Indicates that all children, grandchildren, ... of the specified dag objects should also be selected.
- noExpand : ne (bool) [create]
Indicates that any set which is among the specified items should not be expanded to its list of members. This allows
sets to be selected as opposed to the members of sets which is the default behaviour.
- replace : r (bool) [create]
Indicates that the specified items should replace the existing items on the active list.
- symmetry : sym (bool) [create]
Specifies that components should be selected symmetrically using the current symmetricModelling command settings. If
symmetric modeling is not enabled then this flag has no effect.
- symmetrySide : sys (int) [create]
Indicates that components involved in the current symmetry object should be selected, according to the supplied
parameter. Valid values for the parameter are: -1 : Select components in the unsymmetrical region. 0 : Select components
on the symmetry seam. 1 : Select components on side 1. 2 : Select components on side 2. If symmetric modeling is not
enabled then this flag has no effect. Note: currently only works for topological symmetry.
- toggle : tgl (bool) [create]
Indicates that those items on the given list which are on the active list should be removed from the active list and
those items on the given list which are not on the active list should be added to the active list.
- visible : vis (bool) [create]
Indicates that of the specified items only those that are visible should be affected. Flag can have
multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.select`
"""
pass
def itemFilter(*args, **kwargs):
"""
This command creates a named itemFilter object. This object can be attached to selectionConnection objects, or to
editors, in order to filter the item lists going through them. Using union, intersection and difference filters,
complex composite filters can be created.
Flags:
- byBin : bk (unicode) [create,query,edit]
The filter will only pass items whose bin list contains the given string as a bin name.This is a multi-use flag.If more
than one occurance of this flag is used in a single command, the filter will accept a node if it matches at least one of
the given bins (in other words, a union or logical or of all given bins.
- byName : bn (unicode) [create,query,edit]
The filter will only pass items whose names match the given regular expression string. This string can contain the
special characters \* and ?. '?' matches any one character, and '\*' matches any substring.
- byScript : bs (unicode) [create,query,edit]
The filter will run a MEL script named by the given string on each item name. Items will pass the filter if the script
returns a non-zero value. The script name string must be the name of a proc whose signature is:global proc int procName(
string $name )or def procName(\*args, \*\*keywordArgs)if -pym/pythonModuleis specified. Note that if -secondScript is
also used, it will always take precedence.
- byType : bt (unicode) [create,query,edit]
The filter will only pass items whose typeName matches the given string. The typeName of an object can be found using
the nodeTypecommand. This is a multi-use flag. If more than one occurance of this flag is used in a single command, the
filter will accept a node if it matches at least one of the given types (in other words, a union or logical or of all
given types.
- category : cat (unicode) [create,query,edit]
A string for categorizing the filter.
- classification : cls (unicode) [create,query,edit]
Indicates whether the filter is a built-in or user filter. The string argument must be either builtInor user. The
otherclassification is deprecated. Use userinstead. Filters will not be deleted by a file new, and filter nodes will be
hidden from the UI (ex: Attribute Editor, Hypergraph etc) and will not be accessible from the command-line.
- clearByBin : cbk (bool) [create,edit]
This flag will clear any existing bins associated with this filter.
- clearByType : cbt (bool) [create,edit]
This flag will clear any existing typeNames associated with this filter.
- difference : di (unicode, unicode) [create,query,edit]
The filter will consist of the set difference of two other filters, whose names are the given strings. Items will pass
this filter if and only if they pass the first filter but not the second filter.
- exists : ex (bool) [create]
Returns true|false depending upon whether the specified object exists. Other flags are ignored.
- intersect : intersect (unicode, unicode) [create,query,edit]
The filter will consist of the intersection of two other filters, whose names are the given strings. Items will pass
this filter if and only if they pass both of the contained filters.
- listBuiltInFilters : lbf (bool) [query]
Returns an array of all item filters with classification builtIn.
- listOtherFilters : lof (bool) [query]
The otherclassification is deprecated. Use userinstead. Returns an array of all item filters with classification other.
- listUserFilters : luf (bool) [query]
Returns an array of all item filters with classification user.
- negate : neg (bool) [create,query,edit]
This flag can be used to cause the filter to invert itself, and reverse what passes and what fails.
- parent : p (unicode) [create,query,edit]
Optional. If specified, the filter's life-span is linked to that of the parent. When the parent goes out of scope, so
does the filter. If not specified, the filter will exist until explicitly deleted.
- pythonModule : pym (unicode) [create,query,edit]
Treat -bs/byScriptand -ss/secondScriptas Python functions located in the specified module.
- secondScript : ss (unicode) [create,query,edit]
Cannot be used in conjunction with the -bs flag. The second script is for filtering whole lists at once, rather than
individually. Its signature must be:global proc string[] procName( string[] $name )or def procName(\*args,
\*\*keywordArgs)if -pym/pythonModuleis specified. It should take in a list of items, and return a filtered list of
items.
- text : t (unicode) [create,query,edit]
Defines an annotation string to be stored with the filter
- union : un (unicode, unicode) [create,query,edit]
The filter will consist of the union of two other filters, whose names are the given strings. Items will pass this
filter if they pass at least one of the contained filters.
- uniqueNodeNames : unn (bool) [create,query,edit]
Returns unique node names to script filters so there are no naming conflicts. Flag can have multiple
arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.itemFilter`
"""
pass
def addAttr(*args, **kwargs):
"""
This command is used to add a dynamic attribute to a node or nodes. Either the longName or the shortName or both must be
specified. If neither a dataType nor an attributeType is specified, a double attribute will be added. The dataType flag
can be specified more than once indicating that any of the supplied types will be accepted (logical-or). To add a non-
double attribute the following criteria can be used to determine whether the dataType or the attributeType flag is
appropriate. Some types, such as double3can use either. In these cases the -dtflag should be used when you only wish to
access the data as an atomic entity (eg. you never want to access the three individual values that make up a double3).
In general it is best to use the -atin these cases for maximum flexibility. In most cases the -dtversion will not
display in the attribute editor as it is an atomic type and you are not allowed to change individual parts of it. All
attributes flagged as (compound)below or the compound attribute itself are not actually added to the node until all of
the children are defined (using the -pflag to set their parent to the compound being created). See the EXAMPLES section
for more details. Type of attribute Flag and argument to use boolean
-at bool 32 bit integer -at long 16 bit
integer -at short 8 bit integer -at
byte char -at char enum
-at enum (specify the enum names using the enumName flag) float -at
float(use quotes since float is a mel keyword)
double -at double angle value
-at doubleAngle linear value -at doubleLinear string
-dt string(use quotes since string is a mel
keyword) array of strings -dt stringArray compound
-at compound message (no data) -at message time
-at time 4x4 double matrix -dt matrix(use quotes
since matrix is a mel keyword) 4x4 float matrix -at fltMatrix reflectance
-dt reflectanceRGBreflectance (compound) -at reflectance spectrum
-dt spectrumRGB spectrum (compound) -at spectrum 2 floats
-dt float2 2 floats (compound) -at float2 3 floats
-dt float3 3 floats (compound) -at float3 2 doubles
-dt double2 2 doubles (compound) -at double2 3 doubles
-dt double3 3 doubles (compound) -at double3 2 32-bit integers
-dt long2 2 32-bit integers (compound) -at long2 3 32-bit integers
-dt long3 3 32-bit integers (compound) -at long3 2 16-bit integers
-dt short2 2 16-bit integers (compound) -at short2 3 16-bit integers
-dt short3 3 16-bit integers (compound) -at short3 array of doubles
-dt doubleArray array of floats -dt floatArray array of 32-bit ints
-dt Int32Array array of vectors -dt vectorArray nurbs curve
-dt nurbsCurve nurbs surface -dt nurbsSurface polygonal mesh
-dt mesh lattice -dt lattice array of
double 4D points -dt pointArray In query mode, return type is based on queried flag.
Modifications:
- allow python types to be passed to set -at type
str string
float double
int long
bool bool
Vector double3
- when querying dataType, the dataType is no longer returned as a list
- when editing hasMinValue, hasMaxValue, hasSoftMinValue, or hasSoftMaxValue the passed boolean value was ignored
and the command instead behaved as a toggle. The behavior is now more intuitive::
>>> addAttr('persp', ln='test', at='double', k=1)
>>> addAttr('persp.test', query=1, hasMaxValue=True)
False
>>> addAttr('persp.test', edit=1, hasMaxValue=False)
>>> addAttr('persp.test', query=1, hasMaxValue=True)
False
>>> addAttr('persp.test', edit=1, hasMaxValue=True)
>>> addAttr('persp.test', query=1, hasMaxValue=True)
True
- allow passing a list or dict instead of a string for enumName
- allow user to pass in type and determine whether it is a dataType or
attributeType. Types that may be both, such as float2, float3, double2,
double3, long2, long3, short2, and short3 are all treated as
attributeTypes. In addition, as a convenience, since these attributeTypes
are actually treated as compound attributes, the child attributes are
automatically created, with X/Y/Z appended, unless usedAsColor is set, in
which case R/G/B is added. Alternatively, the suffices can explicitly
specified with childSuffixes:
>>> addAttr('persp', ln='autoDouble', type='double', k=1)
>>> addAttr('persp.autoDouble', query=1, attributeType=1)
u'double'
>>> addAttr('persp.autoDouble', query=1, dataType=1)
u'TdataNumeric'
>>> addAttr('persp', ln='autoMesh', type='mesh', k=1)
>>> addAttr('persp.autoMesh', query=1, attributeType=1)
u'typed'
>>> addAttr('persp.autoMesh', query=1, dataType=1)
u'mesh'
>>> addAttr('persp', ln='autoDouble3Vec', type='double3', k=1)
>>> [x.attrName() for x in PyNode('persp').listAttr() if 'autoDouble3' in x.name()]
[u'autoDouble3Vec', u'autoDouble3VecX', u'autoDouble3VecY', u'autoDouble3VecZ']
>>> addAttr('persp', ln='autoFloat3Col', type='float3', usedAsColor=1)
>>> [x.attrName() for x in PyNode('persp').listAttr() if 'autoFloat3' in x.name()]
[u'autoFloat3Col', u'autoFloat3ColR', u'autoFloat3ColG', u'autoFloat3ColB']
>>> addAttr('persp', ln='autoLong2', type='long2', childSuffixes=['_first', '_second'])
>>> [x.attrName() for x in PyNode('persp').listAttr() if 'autoLong2' in x.name()]
[u'autoLong2', u'autoLong2_first', u'autoLong2_second']
Flags:
- attributeType : at (unicode) [create,query]
Specifies the attribute type, see above table for more details. Note that the attribute types float, matrixand stringare
also MEL keywords and must be enclosed in quotes.
- binaryTag : bt (unicode) [create,query]
This flag is obsolete and does not do anything any more
- cachedInternally : ci (bool) [create,query]
Whether or not attribute data is cached internally in the node. This flag defaults to true for writable attributes and
false for non-writable attributes. A warning will be issued if users attempt to force a writable attribute to be
uncached as this will make it impossible to set keyframes.
- category : ct (unicode) [create,query,edit]
An attribute category is a string associated with the attribute to identify it. (e.g. the name of a plugin that created
the attribute, version information, etc.) Any attribute can be associated with an arbitrary number of categories however
categories can not be removed once associated.
- dataType : dt (unicode) [create,query]
Specifies the data type. See setAttrfor more information on data type names.
- defaultValue : dv (float) [create,query,edit]
Specifies the default value for the attribute (can only be used for numeric attributes).
- disconnectBehaviour : dcb (int) [create,query]
defines the Disconnect Behaviour 2 Nothing, 1 Reset, 0 Delete
- enumName : en (unicode) [create,query,edit]
Flag used to specify the ui names corresponding to the enum values. The specified string should contain a colon-
separated list of the names, with optional values. If values are not specified, they will treated as sequential integers
starting with 0. For example: -enumName A:B:Cwould produce options: A,B,C with values of 0,1,2; -enumName
zero:one:two:thousand=1000would produce four options with values 0,1,2,1000; and -enumName
solo=1:triplet=3:quintet=5would produce three options with values 1,3,5. (Note that there is a current limitation of
the Channel Box that will sometimes incorrectly display an enumerated attribute's pull-down menu. Extra menu items can
appear that represent the numbers inbetween non-sequential option values. To avoid this limitation, specify sequential
values for the options of any enumerated attributes that will appear in the Channel Box. For example:
solo=1:triplet=2:quintet=3.)
- exists : ex (bool) [create,query]
Returns true if the attribute queried is a user-added, dynamic attribute; false if not.
- fromPlugin : fp (bool) [create,query]
Was the attribute originally created by a plugin? Normally set automatically when the API call is made - only added here
to support storing it in a file independently from the creating plugin.
- hasMaxValue : hxv (bool) [create,query,edit]
Flag indicating whether an attribute has a maximum value. (can only be used for numeric attributes).
- hasMinValue : hnv (bool) [create,query,edit]
Flag indicating whether an attribute has a minimum value. (can only be used for numeric attributes).
- hasSoftMaxValue : hsx (bool) [create,query]
Flag indicating whether a numeric attribute has a soft maximum.
- hasSoftMinValue : hsn (bool) [create,query]
Flag indicating whether a numeric attribute has a soft minimum.
- hidden : h (bool) [create,query]
Will this attribute be hidden from the UI?
- indexMatters : im (bool) [create,query]
Sets whether an index must be used when connecting to this multi-attribute. Setting indexMatters to false forces the
attribute to non-readable.
- internalSet : internalSet (bool) [create,query]
Whether or not the internal cached value is set when this attribute value is changed. This is an internal flag used for
updating UI elements.
- keyable : k (bool) [create,query]
Is the attribute keyable by default?
- longName : ln (unicode) [create,query]
Sets the long name of the attribute.
- maxValue : max (float) [create,query,edit]
Specifies the maximum value for the attribute (can only be used for numeric attributes).
- minValue : min (float) [create,query,edit]
Specifies the minimum value for the attribute (can only be used for numeric attributes).
- multi : m (bool) [create,query]
Makes the new attribute a multi-attribute.
- niceName : nn (unicode) [create,query,edit]
Sets the nice name of the attribute for display in the UI. Setting the attribute's nice name to a non-empty string
overrides the default behaviour of looking up the nice name from Maya's string catalog. (Use the MEL commands
attributeNiceNameand attributeQuery -niceNameto lookup an attribute's nice name in the catalog.)
- numberOfChildren : nc (int) [create,query]
How many children will the new attribute have?
- parent : p (unicode) [create,query]
Attribute that is to be the new attribute's parent.
- proxy : pxy (unicode) [create,query]
Proxy another node's attribute. Proxied plug will be connected as source. The UsedAsProxy flag is automatically set in
this case.
- readable : r (bool) [create,query]
Can outgoing connections be made from this attribute?
- shortName : sn (unicode) [create,query]
Sets the short name of the attribute.
- softMaxValue : smx (float) [create,query,edit]
Soft maximum, valid for numeric attributes only. Specifies the upper default limit used in sliders for this attribute.
- softMinValue : smn (float) [create,query,edit]
Soft minimum, valid for numeric attributes only. Specifies the upper default limit used in sliders for this attribute.
- storable : s (bool) [create,query]
Can the attribute be stored out to a file?
- usedAsColor : uac (bool) [create,query]
Is the attribute to be used as a color definition? Must have 3 DOUBLE or 3 FLOAT children to use this flag. The
attribute type -atshould be double3or float3as appropriate. It can also be used to less effect with data types -dtas
double3or float3as well but some parts of the code do not support this alternative. The special attribute types/data
spectrumand reflectancealso support the color flag and on them it is set by default.
- usedAsFilename : uaf (bool) [create,query]
Is the attribute to be treated as a filename definition? This flag is only supported on attributes with data type -dtof
string.
- usedAsProxy : uap (bool) [create,query]
Set if the specified attribute should be treated as a proxy to another attributes.
- writable : w (bool) [create,query]
Can incoming connections be made to this attribute? Flag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.addAttr`
"""
pass
def makeIdentity(*args, **kwargs):
"""
The makeIdentity command is a quick way to reset the selected transform and all of its children down to the shape level
by the identity transformation. You can also specify which of transform, rotate or scale is applied down from the
selected transform. The identity transformation means: translate = 0, 0, 0rotate = 0, 0, 0scale = 1, 1, 1shear = 1, 1,
1If a transform is a joint, then the translateattribute may not be 0, but will be used to position the joints so that
they preserve their world space positions. The translate flag doesn't apply to joints, since joints must preserve their
world space positions. Only the rotate and scale flags are meaningful when applied to joints. If the -a/apply flag is
true, then the transforms that are reset are accumulated and applied to the all shapes below the modified transforms, so
that the shapes will not move. The pivot positions are recalculated so that they also will not move in world space. If
this flag is false, then the transformations are reset to identity, without any changes to preserve position.
Flags:
- apply : a (bool) [create]
If this flag is true, the accumulated transforms are applied to the shape after the transforms are made identity, such
that the world space positions of the transforms pivots are preserved, and the shapes do not move. The default is false.
- jointOrient : jo (bool) [create]
If this flag is set, the joint orient on joints will be reset to align with worldspace.
- normal : n (int) [create]
If this flag is set to 1, the normals on polygonal objects will be frozen. This flag is valid only when the -apply flag
is on. If this flag is set to 2, the normals on polygonal objects will be frozen only if its a non-rigid transformation
matrix. ie, a transformation that does not contain shear, skew or non-proportional scaling. The default behaviour is not
to freeze normals.
- preserveNormals : pn (bool) [create]
If this flag is true, the normals on polygonal objects will be reversed if the objects are negatively scaled
(reflection). This flag is valid only when the -apply flag is on.
- rotate : r (bool) [create]
If this flag is true, only the rotation is applied to the shape. The rotation will be changed to 0, 0, 0. If neither
translate nor rotate nor scale flags are specified, then all (t, r, s) are applied.
- scale : s (bool) [create]
If this flag is true, only the scale is applied to the shape. The scale factor will be changed to 1, 1, 1. If neither
translate nor rotate nor scale flags are specified, then all (t, r, s) are applied.
- translate : t (bool) [create]
If this flag is true, only the translation is applied to the shape. The translation will be changed to 0, 0, 0. If
neither translate nor rotate nor scale flags are specified, then all (t, r, s) are applied. (Note: the translate flag
is not meaningful when applied to joints, since joints are made to preserve their world space position. This flag will
have no effect on joints.) Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.makeIdentity`
"""
pass
def polySplitCtx2(*args, **kwargs):
"""
Create a new context to split facets on polygonal objects In query mode, return type is based on queried
flag.
Flags:
- adjustEdgeFlow : aef (float) []
- constrainToEdges : cte (bool) [create,query,edit]
Enable/disable snapping to edge. If enabled any click in the current face will snap to the closest valid edge. If there
is no valid edge, the click will be ignored. NOTE: This is different from magnet snapping, which causes the click to
snap to certain points along the edge.
- detachEdges : de (bool) []
- edgeMagnets : em (int) [create,query,edit]
number of extra magnets to snap onto, regularly spaced along the edge
- exists : ex (bool) []
- highlightPointColor : hpc (float, float, float) []
- image1 : i1 (unicode) []
- image2 : i2 (unicode) []
- image3 : i3 (unicode) []
- insertWithEdgeFlow : ief (bool) []
- snapTolerance : st (float) [create,query,edit]
precision for custom magnet snapping. Range[0,1]. Value 1 means any click on an edge will snap to either extremities or
magnets. Flag can have multiple arguments, passed either as a tuple or a list.
- snappedToEdgeColor : sec (float, float, float) []
- snappedToFaceColor : sfc (float, float, float) []
- snappedToMagnetColor : smc (float, float, float) []
- snappedToVertexColor : svc (float, float, float) []
- snappingTolerance : st (float) []
- splitLineColor : slc (float, float, float) []
Derived from mel command `maya.cmds.polySplitCtx2`
"""
pass
def _getPymelTypeFromObject(obj, name):
pass
def objectType(*args, **kwargs):
"""
This command returns the type of elements. Warning: This command is incomplete and may not be supported by all object
types.
Flags:
- convertTag : ct (unicode) []
- isAType : isa (unicode) [create]
Returns true if the object is the specified type or derives from an object that is of the specified type. This flag will
only work with dependency nodes.
- isType : i (unicode) [create]
Returns true if the object is exactly of the specified type. False otherwise.
- tagFromType : tgt (unicode) [create]
Returns the type tag given a type name.
- typeFromTag : tpt (int) [create]
Returns the type name given an integer type tag.
- typeTag : tt (bool) [create]
Returns an integer tag that is unique for that object type. Not all object types will have tags. This is the unique
4-byte value that is used to identify nodes of a given type in the binary file format. Flag can have
multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.objectType`
"""
pass
def getEnums(attr):
"""
Get the enumerators for an enum attribute.
:rtype: `util.enum.EnumDict`
>>> addAttr( "persp", ln='numbers', at='enum', enumName="zero:one:two:thousand=1000:three")
>>> numbers = Attribute('persp.numbers').getEnums()
>>> sorted(numbers.items())
[(u'one', 1), (u'thousand', 1000), (u'three', 1001), (u'two', 2), (u'zero', 0)]
>>> numbers[1]
u'one'
>>> numbers['thousand']
1000
"""
pass
def removeMultiInstance(*args, **kwargs):
"""
Removes a particular instance of a multiElement. This is only useful for input attributes since outputs will get
regenerated the next time the node gets executed. This command will remove the instance and optionally break all
incoming and outgoing connections to that instance. If the connections are not broken (with the -b true) flag, then the
command will fail if connections exist.
Flags:
- b : b (bool) [create]
If the argument is true, all connections to the attribute will be broken before the element is removed. If false, then
the command will fail if the element is connected. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.removeMultiInstance`
"""
pass
def bakePartialHistory(*args, **kwargs):
"""
This command is used to bake sections of the construction history of a shape node when possible. A typical usage would
be on a shape that has both modelling operations and deformers in its history. Using this command with the
-prePostDeformers flag will bake the modeling portions of the graph, so that only the deformers remain. Note that not
all modeling operations can be baked such that they create exactly the same effect after baking. For example, imagine
the history contains a skinning operation followed by a smooth. Before baking, the smooth operation is performed each
time the skin deforms, so it will smooth differently depending on the output of the skin. When the smooth operation is
baked into the skinning, the skin will be reweighted based on the smooth points to attempt to approximate the original
behavior. However, the skin node does not perform the smooth operation, it merely performs skinning with the newly
calculated weights and the result will not be identical to before the bake. In general, modeling operations that occur
before deformers can be baked precisely. Those which occur after can only be approximated. The -pre and -post flags
allow you to control whether only the operations before or after the deformers are baked. When the command is used on an
object with no deformers, the entire history will be deleted.
Flags:
- allShapes : all (bool) [create,query]
Specifies that the bake operation should be performed on all shapes in the entire scene. By default, only selected
objects are baked. If this option is specified and there are no shapes in the scene, then this command will do nothing
and end successfully.
- postSmooth : nps (bool) [create,query]
Specifies whether or not a smoothing operation should be done on skin vertices. This smoothing is only done on vertices
that are found to deviate largely from other vertex values. The default is false.
- preCache : pc (bool) [create,query]
Specifies baking of any history operations that occur before the caching operation, including deformers. In query mode,
returns a list of the nodes that will be baked.
- preDeformers : pre (bool) [create,query]
Specifies baking of any modeling operations in the history that occur before the deformers. In query mode, returns a
list of the nodes that will be baked.
- prePostDeformers : ppt (bool) [create,query]
Specifies baking of all modeling operations in the history whether they are before or after the deformers in the
history. If neither the -prePostDeformers nor the -preDeformers flag is specified, prePostDeformers will be used as the
default. In query mode, returns a list of the nodes that will be baked. Flag can have
multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.bakePartialHistory`
"""
pass
def relationship(*args, **kwargs):
"""
This is primarily for use with file IO. Rather than write out the specific attributes/connections required to maintain a
relationship, a description of the related nodes/plugs is written instead. The relationship must have an owner node, and
have a specific type. During file read, maya will make the connections and/or set the data necessary to represent the
realtionship in the dependency graph. In query mode, return type is based on queried flag.
Flags:
- b : b (bool) [create,query,edit]
Break the specified relationship instead of creating it
- relationshipData : rd (unicode) [create,query,edit]
Provide relationship data to be used when creating the relationship. Flag can have
multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.relationship`
"""
pass
def toolDropped(*args, **kwargs):
"""
This command builds and executes the commands necessary to recreate the specified tool button. It is invoked when a
tool is dropped on the shelf.
Derived from mel command `maya.cmds.toolDropped`
"""
pass
def colorManagementPrefs(*args, **kwargs):
"""
This command allows querying and editing the color management global data in a scene. It also allows for setting the
view transform and rendering space which automatically configures the color processing in the enabled views.
In query mode, return type is based on queried flag.
Flags:
- cmConfigFileEnabled : cfe (bool) [query,edit]
Turn on or off applying an OCIO configuration file. If set, the color management configuration set in the preferences
is used.
- cmEnabled : cme (bool) [query,edit]
Turn on or off color management in general. If set, the color management configuration set in the preferences is used.
- colorManagePots : cmp (bool) [query,edit]
Turn on or off color management of color pots in the UI. If set, colors in color pots are taken to be in rendering
space, and are displayed after being transformed by the view transform set in the preferences.
- colorManagedNodes : cmn (bool) [query,edit]
Gets the names of all nodes that apply color management to bring pixels from an input color space to the rendering
space. Examples include file texture node.
- colorManagementSDKVersion : cmv (unicode) [query,edit]
Obtain the version of the color management SDK used by Maya.
- configFilePath : cfp (unicode) [query,edit]
The configuration file to be used, if color management is enabled.
- defaultInputSpaceName : din (unicode) [query,edit]
This flag is obsolete. See the colorManagementFileRules command for more information.
- equalsToPolicyFile : etp (unicode) [query,edit]
Query if the current loaded policy settings is the same with the settings described in the policy file which is the
argument of the command.
- exportPolicy : epy (unicode) [create,query,edit]
Export the color management parameters to policy file
- inputSpaceNames : iss (bool) [query,edit]
Returns the list of available input color spaces. Used to populate the input color spaces UI popup.
- loadPolicy : lpy (unicode) [create,query,edit]
Load the color management policy file. This file overides the color management settings.
- loadedDefaultInputSpaceName : ldn (unicode) [query,edit]
This flag is obsolete.
- loadedOutputTransformName : lon (unicode) [query,edit]
Gets the loaded output transform. Used by file open, import, and reference to check for missing color spaces or
transforms.
- loadedRenderingSpaceName : lrn (unicode) [query,edit]
Gets the loaded rendering space. Used by file open, import, and reference to check for missing color spaces or
transforms.
- loadedViewTransformName : lvn (unicode) [query,edit]
Gets the loaded view transform. Used by file open, import, and reference to check for missing color spaces or
transforms.
- missingColorSpaceNodes : mcn (bool) [query,edit]
Gets the names of the nodes that have color spaces not defined in the selected transform collection.
- ocioRulesEnabled : ore (bool) [query,edit]
Turn on or off the use of colorspace assignment rules from the OCIO library.
- outputTarget : ott (unicode) [query,edit]
Indicates to which output the outputTransformEnabled or the outputTransformName flags are to be applied. Valid values
are rendereror playblast.
- outputTransformEnabled : ote (bool) [query,edit]
Turn on or off applying the output transform for out of viewport renders. If set, the output transform set in the
preferences is used.
- outputTransformName : otn (unicode) [query,edit]
The output transform to be applied for out of viewport renders. Disables output use view transform mode.
- outputTransformNames : ots (bool) [query,edit]
Returns the list of available output transforms.
- outputUseViewTransform : ovt (bool) [query,edit]
Turns use view transform mode on. In this mode, the output transform is set to match the view transform. To turn the
mode off, set an output transform using the outputTransformName flag.
- policyFileName : pfn (unicode) [query,edit]
Set the policy file name
- popupOnError : poe (bool) [query,edit]
Turn on or off displaying a modal popup on error (as well as the normal script editor reporting of the error), for this
invocation of the command. Default is off.
- renderingSpaceName : rsn (unicode) [query,edit]
The color space to be used during rendering. This is the source color space to the viewing transform, for color managed
viewers and color managed UI controls, and the destination color space for color managed input pixels.
- renderingSpaceNames : rss (bool) [query,edit]
Returns the list of available rendering spaces. Used to populate the color management preference UI popup.
- restoreDefaults : rde (bool) [create,query,edit]
Restore the color management settings to their default value.
- viewTransformName : vtn (unicode) [query,edit]
The view transform to be applied by color managed viewers and color managed UI controls.
- viewTransformNames : vts (bool) [query,edit]
Returns the list of available view transforms. Used to populate the color management preference UI popup.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.colorManagementPrefs`
"""
pass
def displayCull(*args, **kwargs):
"""
This command is responsible for setting the display culling property of back faces of surfaces. In query mode, return
type is based on queried flag.
Flags:
- backFaceCulling : bfc (bool) [create,query]
Enable/disable culling of back faces. Flag can have multiple arguments, passed either as a tuple or a
list.
Derived from mel command `maya.cmds.displayCull`
"""
pass
def pixelMove(*args, **kwargs):
"""
The pixelMove command moves objects by what appears as pixel units based on the current view. It takes two integer
arguments which specify the direction in screen space an object should appear to move. The vector between the center
pixel of the view and the specified offset is mapped to some world space vector which defines the relative amount to
move the selected objects. The mapping is dependent upon the view.
Derived from mel command `maya.cmds.pixelMove`
"""
pass
def upAxis(*args, **kwargs):
"""
The upAxis command changes the world up direction. Current implementation provides only two choices of axis (the Y-axis
or the Z-axis) as the world up direction.By default, the ground plane in Maya is on the XY plane. Hence, the default up-
direction is the direction of the positive Z-axis.The -ax flag is mandatory. In conjunction with the -ax flag, when the
-rv flag is specified, the camera of currently active view is revolved about the X-axis such that the position of the
groundplane in the view will remain the same as before the the up direction is changed.The screen update is applied to
all cameras of all views.In query mode, return type is based on queried flag.
Flags:
- axis : ax (unicode) [query]
This flag specifies the axis as the world up direction. The valid axis are either yor z.When queried, it returns a
string.
- rotateView : rv (bool) [create]
This flag specifies to rotate the view as well. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.upAxis`
"""
pass
def selectType(*args, **kwargs):
"""
The selectTypecommand is used to change the set of allowable types of objects that can be selected when using the select
tool. It accepts no other arguments besides the flags. There are basically two different types of items that are
selectable when interactively selecting objects in the 3D views. They are classified as objects (entire objects) or
components (parts of objects). The objectand componentcommand flags control which class of objects are selectable. It
is possible to select components while in the object selection mode. To set the components which are selectable in
object selection mode you must use the -ocm flag when specifying the component flags.
Flags:
- allComponents : alc (bool) [create,query]
Set all component selection masks on/off
- allObjects : alo (bool) [create,query]
Set all object selection masks on/off
- animBreakdown : abd (bool) [create,query]
Set animation breakdown selection mask on/off.
- animCurve : ac (bool) [create,query]
Set animation curve selection mask on/off.
- animInTangent : ait (bool) [create,query]
Set animation in-tangent selection mask on/off.
- animKeyframe : ak (bool) [create,query]
Set animation keyframe selection mask on/off.
- animOutTangent : aot (bool) [create,query]
Set animation out-tangent selection mask on/off.
- byName : bn (unicode, bool) [create]
Set the specified user-defined selection mask on/off. (object flag)
- camera : ca (bool) [create,query]
Set camera selection mask on/off. (object flag)
- cluster : cl (bool) [create,query]
Set cluster selection mask on/off. (object flag)
- collisionModel : clm (bool) [create,query]
Set collision model selection mask on/off. (object flag)
- controlVertex : cv (bool) [create,query]
Set control vertex selection mask on/off. (component flag)
- curve : c (bool) [create,query]
Set curve selection mask on/off. (object flag)
- curveKnot : ck (bool) [create,query]
Set curve knot selection mask on/off. (component flag)
- curveOnSurface : cos (bool) [create,query]
Set curve-on-surface selection mask on/off. (object flag)
- curveParameterPoint : cpp (bool) [create,query]
Set curve parameter point selection mask on/off. (component flag)
- dimension : dim (bool) [create,query]
Set dimension shape selection mask on/off. (object flag)
- dynamicConstraint : dc (bool) [create,query]
Set dynamicConstraint selection mask on/off. (object flag)
- edge : eg (bool) [create,query]
Set mesh edge selection mask on/off. (component flag)
- editPoint : ep (bool) [create,query]
Set edit-point selection mask on/off. (component flag)
- emitter : em (bool) [create,query]
Set emitter selection mask on/off. (object flag)
- facet : fc (bool) [create,query]
Set mesh face selection mask on/off. (component flag)
- field : fi (bool) [create,query]
Set field selection mask on/off. (object flag)
- fluid : fl (bool) [create,query]
Set fluid selection mask on/off. (object flag)
- follicle : fo (bool) [create,query]
Set follicle selection mask on/off. (object flag)
- hairSystem : hs (bool) [create,query]
Set hairSystem selection mask on/off. (object flag)
- handle : ha (bool) [create,query]
Set object handle selection mask on/off. (object flag)
- hull : hl (bool) [create,query]
Set hull selection mask on/off. (component flag)
- ikEndEffector : iee (bool) [create,query]
Set ik end effector selection mask on/off. (object flag)
- ikHandle : ikh (bool) [create,query]
Set ik handle selection mask on/off. (object flag)
- imagePlane : ip (bool) [create,query]
Set image plane selection mask on/off. (component flag)
- implicitGeometry : ig (bool) [create,query]
Set implicit geometry selection mask on/off. (object flag)
- isoparm : iso (bool) [create,query]
Set surface iso-parm selection mask on/off. (component flag)
- joint : j (bool) [create,query]
Set ik handle selection mask on/off. (object flag)
- jointPivot : jp (bool) [create,query]
Set joint pivot selection mask on/off. (component flag)
- lattice : la (bool) [create,query]
Set lattice selection mask on/off. (object flag)
- latticePoint : lp (bool) [create,query]
Set lattice point selection mask on/off. (component flag)
- light : lt (bool) [create,query]
Set light selection mask on/off. (object flag)
- localRotationAxis : ra (bool) [create,query]
Set local rotation axis selection mask on/off. (component flag)
- locator : lc (bool) [create,query]
Set locator (all types) selection mask on/off. (object flag)
- locatorUV : luv (bool) [create,query]
Set uv locator selection mask on/off. (object flag)
- locatorXYZ : xyz (bool) [create,query]
Set xyz locator selection mask on/off. (object flag)
- meshComponents : mc (bool) []
- meshUVShell : msh (bool) [create,query]
Set uv shell component mask on/off.
- motionTrailPoint : mtp (bool) [create,query]
Set motion point selection mask on/off.
- motionTrailTangent : mtt (bool) [create,query]
Set motion point tangent mask on/off.
- nCloth : ncl (bool) [create,query]
Set nCloth selection mask on/off. (object flag)
- nParticle : npr (bool) [create,query]
Set nParticle point selection mask on/off. (component flag)
- nParticleShape : nps (bool) [create,query]
Set nParticle shape selection mask on/off. (object flag)
- nRigid : nr (bool) [create,query]
Set nRigid selection mask on/off. (object flag)
- nonlinear : nl (bool) [create,query]
Set nonlinear selection mask on/off. (object flag)
- nurbsCurve : nc (bool) [create,query]
Set nurbs-curve selection mask on/off. (object flag)
- nurbsSurface : ns (bool) [create,query]
Set nurbs-surface selection mask on/off. (object flag)
- objectComponent : ocm (bool) [create,query]
Component flags apply to object mode.
- orientationLocator : ol (bool) [create,query]
Set orientation locator selection mask on/off. (object flag)
- particle : pr (bool) [create,query]
Set particle point selection mask on/off. (component flag)
- particleShape : ps (bool) [create,query]
Set particle shape selection mask on/off. (object flag)
- plane : pl (bool) [create,query]
Set sketch plane selection mask on/off. (object flag)
- polymesh : p (bool) [create,query]
Set poly-mesh selection mask on/off. (object flag)
- polymeshEdge : pe (bool) [create,query]
Set poly-mesh edge selection mask on/off. (component flag)
- polymeshFace : pf (bool) [create,query]
Set poly-mesh face selection mask on/off. (component flag)
- polymeshFreeEdge : pfe (bool) [create,query]
Set poly-mesh free-edge selection mask on/off. (component flag)
- polymeshUV : puv (bool) [create,query]
Set poly-mesh UV point selection mask on/off. (component flag)
- polymeshVertex : pv (bool) [create,query]
Set poly-mesh vertex selection mask on/off. (component flag)
- polymeshVtxFace : pvf (bool) [create,query]
Set poly-mesh vertexFace selection mask on/off. (component flag)
- queryByName : qbn (unicode) [query]
Query the specified user-defined selection mask. (object flag)
- rigidBody : rb (bool) [create,query]
Set rigid body selection mask on/off. (object flag)
- rigidConstraint : rc (bool) [create,query]
Set rigid constraint selection mask on/off. (object flag)
- rotatePivot : rp (bool) [create,query]
Set rotate pivot selection mask on/off. (component flag)
- scalePivot : sp (bool) [create,query]
Set scale pivot selection mask on/off. (component flag)
- sculpt : sc (bool) [create,query]
Set sculpt selection mask on/off. (object flag)
- selectHandle : sh (bool) [create,query]
Set select handle selection mask on/off. (component flag)
- spring : spr (bool) [create,query]
Set spring shape selection mask on/off. (object flag)
- springComponent : spc (bool) [create,query]
Set individual spring selection mask on/off. (component flag)
- stroke : str (bool) [create,query]
Set the Paint Effects stroke selection mask on/off. (object flag)
- subdiv : sd (bool) [create,query]
Set subdivision surfaces selection mask on/off. (object flag)
- subdivMeshEdge : sme (bool) [create,query]
Set subdivision surfaces mesh edge selection mask on/off. (component flag)
- subdivMeshFace : smf (bool) [create,query]
Set subdivision surfaces mesh face selection mask on/off. (component flag)
- subdivMeshPoint : smp (bool) [create,query]
Set subdivision surfaces mesh point selection mask on/off. (component flag)
- subdivMeshUV : smu (bool) [create,query]
Set subdivision surfaces mesh UV map selection mask on/off. (component flag)
- surfaceEdge : se (bool) [create,query]
Set surface edge selection mask on/off. (component flag)
- surfaceFace : sf (bool) [create,query]
Set surface face selection mask on/off. (component flag)
- surfaceKnot : sk (bool) [create,query]
Set surface knot selection mask on/off. (component flag)
- surfaceParameterPoint : spp (bool) [create,query]
Set surface parameter point selection mask on/off. (component flag)
- surfaceRange : sr (bool) [create,query]
Set surface range selection mask on/off. (component flag)
- surfaceUV : suv (bool) [create,query]
Set surface uv selection mask on/off. (component flag)
- texture : tx (bool) [create,query]
Set texture selection mask on/off. (object flag)
- vertex : v (bool) [create,query]
Set mesh vertex selection mask on/off. (component flag) Flag can have multiple arguments, passed either
as a tuple or a list.
Derived from mel command `maya.cmds.selectType`
"""
pass
def webView(*args, **kwargs):
"""
This command allows the user to bring up a web page view
Flags:
- urlAddress : url (unicode) [create]
Bring up webView on given URL
- windowHeight : wh (int) [create]
Set the window height
- windowWidth : ww (int) [create]
Set the window width Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.webView`
"""
pass
def selected(**kwargs):
"""
ls -sl
"""
pass
def ungroup(*args, **kwargs):
"""
This command ungroups the specified objects. The objects will be placed at the same level in the hierarchy the group
node occupied unless the -w flag is specified, in which case they will be placed under the world. If an object is
ungrouped and there is an object in the new group with the same name then this command will rename the ungrouped object.
See also:group, parent, instance, duplicate
Flags:
- absolute : a (bool) [create]
preserve existing world object transformations (overall object transformation is preserved by modifying the objects
local transformation) [default]
- parent : p (unicode) [create]
put the ungrouped objects under the given parent
- relative : r (bool) [create]
preserve existing local object transformations (don't modify local transformation)
- world : w (bool) [create]
put the ungrouped objects under the world Flag can have multiple arguments, passed either as a tuple or
a list.
Derived from mel command `maya.cmds.ungroup`
"""
pass
def artAttrTool(*args, **kwargs):
"""
The artAttrTool command manages the list of tool types which are used for attribute painting. This command
supports querying the list contents as well as adding new tools to the list. Note that there is a set of
built-in tools. The list of built-ins can be queried by starting Maya and doing an artAttrTool -q. The tools
which are managed by this command are all intended for attribute painting via Artisan: when you create a new
context via artAttrCtx you specify the tool name via artAttrCtx's -whichToolflag. Typically the user may wish to
simply use one of the built-in tools. However, if you need to have custom Properties and Values sheets
asscociated with your tool, you will need to define a custom tool via artAttrTool -add toolName. For an example
of a custom attribute painting tool, see the devkit example customtoolPaint.mel. In query mode, return
type is based on queried flag.
Flags:
- add : string (Adds the named tool to the internal list of tools.) [create]
- exists : ex (unicode) [create,query]
Checks if the named tool exists, returning true if found, and false otherwise.
- remove : rm (unicode) [create]
Removes the named tool from the internal list of tools. Flag can have multiple
arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.artAttrTool`
"""
pass
def hasAttr(pyObj, attr, checkShape='True'):
"""
convenience function for determining if an object has an attribute.
If checkShape is enabled, the shape node of a transform will also be checked for the attribute.
:rtype: `bool`
"""
pass
def _objectError(objectName):
pass
def timeCode(*args, **kwargs):
"""
Use this command to query and set the time code information in the file
Flags:
- mayaStartFrame : msf (float) [create,query,edit]
Sets the Maya start time of the time code, in frames. In query mode, returns the Maya start frame of the time code.
- productionStartFrame : psf (float) [create,query,edit]
Sets the production start time of the time code, in terms of frames. In query mode, returns the sub-second frame of
production start time.
- productionStartHour : psh (float) [create,query,edit]
Sets the production start time of the time code, in terms of hours. In query mode, returns the hour of production start
time.
- productionStartMinute : psm (float) [create,query,edit]
Sets the production start time of the time code, in terms of minutes. In query mode, returns the minute of production
start time.
- productionStartSecond : pss (float) [create,query,edit]
Sets the production start time of the time code, in terms of seconds. In query mode, returns the second of production
start time. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.timeCode`
"""
pass
def applyAttrPattern(*args, **kwargs):
"""
Take the attribute structure described by a pre-defined pattern and apply it either to a node (as dynamic attributes) or
a node type (as extension attributes). The same pattern can be applied more than once to different nodes or node types
as the operation duplicates the attribute structure described by the pattern. See the 'createAttrPatterns' command for
a description of how to create a pattern.
Flags:
- nodeType : nt (unicode) [create]
Name of the node type to which the attribute pattern is to be applied. This flag will cause a new extension attribute
tree to be created, making the new attributes available on all nodes of the given type. If it is not specified then
either a node name must be specified or a node must be selected for application of dynamic attributes.
- patternName : pn (unicode) [create]
The name of the pattern to apply. The pattern with this name must have been previously created using the
createAttrPatterns command. Flag can have multiple arguments, passed either as a tuple or
a list.
Derived from mel command `maya.cmds.applyAttrPattern`
"""
pass
def renameAttr(*args, **kwargs):
"""
Renames the given user-defined attribute to the name given in the string argument. If the new name conflicts with an
existing name then this command will fail. Note that it is not legal to rename an attribute to the empty string.
Derived from mel command `maya.cmds.renameAttr`
"""
pass
def setAttr(attr, *args, **kwargs):
"""
Sets the value of a dependency node attribute. No value for the the attribute is needed when the -l/-k/-s flags are
used. The -type flag is only required when setting a non-numeric attribute. The following chart outlines the syntax of
setAttr for non-numeric data types: TYPEbelow means any number of values of type TYPE, separated by a space[TYPE]means
that the value of type TYPEis optionalA|Bmeans that either of Aor Bmay appearIn order to run its examples, first execute
these commands to create the sample attribute types:sphere -n node; addAttr -ln short2Attr -at short2; addAttr -ln
short2a -p short2Attr -at short; addAttr -ln short2b -p short2Attr -at short; addAttr -ln short3Attr -at short3; addAttr
-ln short3a -p short3Attr -at short; addAttr -ln short3b -p short3Attr -at short; addAttr -ln short3c -p short3Attr -at
short; addAttr -ln long2Attr -at long2; addAttr -ln long2a -p long2Attr -at long; addAttr -ln long2b -p long2Attr -at
long; addAttr -ln long3Attr -at long3; addAttr -ln long3a -p long3Attr -at long; addAttr -ln long3b -p long3Attr -at
long; addAttr -ln long3c -p long3Attr -at long; addAttr -ln float2Attr -at float2; addAttr -ln float2a -p float2Attr -at
float; addAttr -ln float2b -p float2Attr -at float; addAttr -ln float3Attr -at float3; addAttr -ln float3a -p float3Attr
-at float; addAttr -ln float3b -p float3Attr -at float; addAttr -ln float3c -p float3Attr -at float; addAttr -ln
double2Attr -at double2; addAttr -ln double2a -p double2Attr -at double; addAttr -ln double2b -p double2Attr -at double;
addAttr -ln double3Attr -at double3; addAttr -ln double3a -p double3Attr -at double; addAttr -ln double3b -p double3Attr
-at double; addAttr -ln double3c -p double3Attr -at double; addAttr -ln int32ArrayAttr -dt Int32Array; addAttr -ln
doubleArrayAttr -dt doubleArray; addAttr -ln pointArrayAttr -dt pointArray; addAttr -ln vectorArrayAttr -dt vectorArray;
addAttr -ln stringArrayAttr -dt stringArray; addAttr -ln stringAttr -dt string; addAttr -ln matrixAttr -dt matrix;
addAttr -ln sphereAttr -dt sphere; addAttr -ln coneAttr -dt cone; addAttr -ln meshAttr -dt mesh; addAttr -ln latticeAttr
-dt lattice; addAttr -ln spectrumRGBAttr -dt spectrumRGB; addAttr -ln reflectanceRGBAttr -dt reflectanceRGB; addAttr -ln
componentListAttr -dt componentList; addAttr -ln attrAliasAttr -dt attributeAlias; addAttr -ln curveAttr -dt nurbsCurve;
addAttr -ln surfaceAttr -dt nurbsSurface; addAttr -ln trimFaceAttr -dt nurbsTrimface; addAttr -ln polyFaceAttr -dt
polyFaces; -type short2Array of two short integersValue Syntaxshort shortValue Meaningvalue1 value2Mel ExamplesetAttr
node.short2Attr -type short2 1 2;Python Examplecmds.setAttr('node.short2Attr',1,2,type='short2')-type short3Array of
three short integersValue Syntaxshort short shortValue Meaningvalue1 value2 value3Mel ExamplesetAttr node.short3Attr
-type short3 1 2 3;Python Examplecmds.setAttr('node.short3Attr',1,2,3,type='short3')-type long2Array of two long
integersValue Syntaxlong longValue Meaningvalue1 value2Mel ExamplesetAttr node.long2Attr -type long2 1000000
2000000;Python Examplecmds.setAttr('node.long2Attr',1000000,2000000,type='long2')-type long3Array of three long
integersValue Syntaxlong long longValue Meaningvalue1 value2 value3Mel ExamplesetAttr node.long3Attr -type long3 1000000
2000000 3000000;Python Examplecmds.setAttr('node.long3Attr',1000000,2000000,3000000,type='long3')-type
Int32ArrayVariable length array of long integersValue SyntaxValue MeaningMel ExamplesetAttr node.int32ArrayAttr -type
Int32Array 2 12 75;Python Examplecmds.setAttr('node.int32ArrayAttr',[2,12,75],type='Int32Array')-type float2Array of two
floatsValue Syntaxfloat floatValue Meaningvalue1 value2Mel ExamplesetAttr node.float2Attr -type float2 1.1 2.2;Python
Examplecmds.setAttr('node.float2Attr',1.1,2.2,type='float2')-type float3Array of three floatsValue Syntaxfloat float
floatValue Meaningvalue1 value2 value3Mel ExamplesetAttr node.float3Attr -type float3 1.1 2.2 3.3;Python
Examplecmds.setAttr('node.float3Attr',1.1,2.2,3.3,type='float3')-type double2Array of two doublesValue Syntaxdouble
doubleValue Meaningvalue1 value2Mel ExamplesetAttr node.double2Attr -type double2 1.1 2.2;Python
Examplecmds.setAttr('node.double2Attr',1.1,2.2,type='double2')-type double3Array of three doublesValue Syntaxdouble
double doubleValue Meaningvalue1 value2 value3Mel ExamplesetAttr node.double3Attr -type double3 1.1 2.2 3.3;Python
Examplecmds.setAttr('node.double3Attr',1.1,2.2,3.3,type='double3')-type doubleArrayVariable length array of doublesValue
SyntaxValue MeaningMel ExamplesetAttr node.doubleArrayAttr -type doubleArray 2 3.14159 2.782;Python Examplecmds.setAttr(
node.doubleArrayAttr, (2, 3.14159, 2.782,), type=doubleArray)-type matrix4x4 matrix of doublesValue Syntaxdouble double
double doubledouble double double doubledouble double double doubledouble double double doubleValue Meaningrow1col1
row1col2 row1col3 row1col4row2col1 row2col2 row2col3 row2col4row3col1 row3col2 row3col3 row3col4row4col1 row4col2
row4col3 row4col4Alternate Syntaxstring double double doubledouble double doubleintegerdouble double doubledouble double
doubledouble double doubledouble double doubledouble double doubledouble double doubledouble double double doubledouble
double double doubledouble double doublebooleanAlternate MeaningxformscaleX scaleY scaleZrotateX rotateY
rotateZrotationOrder (0=XYZ, 1=YZX, 2=ZXY, 3=XZY, 4=YXZ, 5=ZYX)translateX translateY translateZshearXY shearXZ
shearYZscalePivotX scalePivotY scalePivotZscaleTranslationX scaleTranslationY scaleTranslationZrotatePivotX rotatePivotY
rotatePivotZrotateTranslationX rotateTranslationY rotateTranslationZrotateOrientW rotateOrientX rotateOrientY
rotateOrientZjointOrientW jointOrientX jointOrientY jointOrientZinverseParentScaleX inverseParentScaleY
inverseParentScaleZcompensateForParentScale Mel ExamplesetAttr node.matrixAttr -type matrix1 0 0 0 0 1 0 0 0 0 1 0 2 3 4
1;setAttr node.matrixAttr -type matrixxform1 1 1 0 0 0 0 2 3 4 0 0 00 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 0
false;Python Examplecmds.setAttr('node.matrixAttr',(1,0,0,0,0,1,0,0,0,0,1,0,2,3,4,1),type='matrix')cmds.setAttr('node.ma
trixAttr','xform',(1,1,1),(0,0,0),0,(2,3,4),(0,0,0),(0,0,0),(0,0,0),(0,0,0),(0,1,1),(0,0,1,0),(1,0,1,0),(1,2,3),False,ty
pe=matrix)-type pointArrayVariable length array of pointsValue SyntaxValue MeaningMel ExamplesetAttr node.pointArrayAttr
-type pointArray 2 1 1 1 1 2 2 2 1;Python
Examplecmds.setAttr('node.pointArrayAttr',2,(1,1,1,1),(2,2,2,1),type='pointArray')-type vectorArrayVariable length array
of vectorsValue SyntaxValue MeaningMel ExamplesetAttr node.vectorArrayAttr -type vectorArray 2 1 1 1 2 2 2;Python
Examplecmds.setAttr('node.vectorArrayAttr',2,(1,1,1),(2,2,2),type='vectorArray')-type stringCharacter stringValue
SyntaxstringValue MeaningcharacterStringValueMel ExamplesetAttr node.stringAttr -type stringblarg;Python
Examplecmds.setAttr('node.stringAttr',blarg,type=string)-type stringArrayVariable length array of stringsValue
SyntaxValue MeaningMel ExamplesetAttr node.stringArrayAttr -type stringArray 3 abc;Python
Examplecmds.setAttr('node.stringArrayAttr',3,a,b,c,type='stringArray')-type sphereSphere dataValue SyntaxdoubleValue
MeaningsphereRadiusExamplesetAttr node.sphereAttr -type sphere 5.0;-type coneCone dataValue Syntaxdouble doubleValue
MeaningconeAngle coneCapMel ExamplesetAttr node.coneAttr -type cone 45.0 5.0;Python
Examplecmds.setAttr('node.coneAttr',45.0,5.0,type='cone')-type reflectanceRGBReflectance dataValue Syntaxdouble double
doubleValue MeaningredReflect greenReflect blueReflectMel ExamplesetAttr node.reflectanceRGBAttr -type reflectanceRGB
0.5 0.5 0.1;Python Examplecmds.setAttr('node.reflectanceRGBAttr',0.5,0.5,0.1,type='reflectanceRGB')-type
spectrumRGBSpectrum dataValue Syntaxdouble double doubleValue MeaningredSpectrum greenSpectrum blueSpectrumMel
ExamplesetAttr node.spectrumRGBAttr -type spectrumRGB 0.5 0.5 0.1;Python
Examplecmds.setAttr('node.spectrumRGBAttr',0.5,0.5,0.1,type='spectrumRGB')-type componentListVariable length array of
componentsValue SyntaxValue MeaningMel ExamplesetAttr node.componentListAttr -type componentList 3 cv[1] cv[12]
cv[3];Python Examplecmds.setAttr('node.componentListAttr',3,'cv[1]','cv[12]','cv[3]',type='componentList')-type
attributeAliasString alias dataValue Syntaxstring stringValue MeaningnewAlias currentNameMel ExamplesetAttr
node.attrAliasAttr -type attributeAliasGoUp, translateY, GoLeft, translateX;Python
Examplecmds.setAttr('node.attrAliasAttr',(GoUp, translateY,GoLeft, translateX),type='attributeAlias')-type
nurbsCurveNURBS curve dataValue SyntaxValue MeaningMel Example// degree is the degree of the curve(range 1-7)// spans is
the number of spans // form is open (0), closed (1), periodic (2)// dimension is 2 or 3, depending on the dimension of
the curve// isRational is true if the curve CVs contain a rational component // knotCount is the size of the knot list//
knotValue is a single entry in the knot list// cvCount is the number of CVs in the curve// xCVValue,yCVValue,[zCVValue]
[wCVValue] is a single CV.// zCVValue is only present when dimension is 3.// wCVValue is only present when isRational
is true.//setAttr node.curveAttr -type nurbsCurve 3 1 0 no 36 0 0 0 1 1 14 -2 3 0 -2 1 0 -2 -1 0 -2 -3 0;-type
nurbsSurfaceNURBS surface dataValue Syntaxint int int int bool Value MeaninguDegree vDegree uForm vForm
isRationalTRIM|NOTRIMExample// uDegree is degree of the surface in U direction (range 1-7)// vDegree is degree of the
surface in V direction (range 1-7)// uForm is open (0), closed (1), periodic (2) in U direction// vForm is open (0),
closed (1), periodic (2) in V direction// isRational is true if the surface CVs contain a rational component//
uKnotCount is the size of the U knot list// uKnotValue is a single entry in the U knot list// vKnotCount is the size of
the V knot list// vKnotValue is a single entry in the V knot list// If TRIMis specified then additional trim
information is expected// If NOTRIMis specified then the surface is not trimmed// cvCount is the number of CVs in the
surface// xCVValue,yCVValue,zCVValue [wCVValue]is a single CV.// zCVValue is only present when dimension is 3.//
wCVValue is only present when isRational is true//setAttr node.surfaceAttr -type nurbsSurface 3 3 0 0 no 6 0 0 0 1 1 16
0 0 0 1 1 116 -2 3 0 -2 1 0 -2 -1 0 -2 -3 0-1 3 0 -1 1 0 -1 -1 0 -1 -3 01 3 0 1 1 0 1 -1 0 1 -3 03 3 0 3 1 0 3 -1 0 3 -3
0;-type nurbsTrimfaceNURBS trim face dataValue SyntaxValue MeaningExample// flipNormal if true turns the surface inside
out// boundaryCount: number of boundaries// boundaryType: // tedgeCountOnBoundary : number of edges in a boundary//
splineCountOnEdge : number of splines in an edge in// edgeTolerance : tolerance used to build the 3d edge//
isEdgeReversed : if true, the edge is backwards// geometricContinuity : if true, the edge is tangent
continuous// splineCountOnPedge : number of splines in a 2d edge// isMonotone : if true, curvature is
monotone// pedgeTolerance : tolerance for the 2d edge//-type polyFacePolygon face dataValue SyntaxfhmfmhmufcValue
MeaningfhmfmhmufcExample// This data type (polyFace) is meant to be used in file I/O// after setAttrs have been written
out for vertex position// arrays, edge connectivity arrays (with corresponding start// and end vertex descriptions),
texture coordinate arrays and// color arrays. The reason is that this data type references// all of its data through
ids created by the former types.//// fspecifies the ids of the edges making up a face -// negative value if the edge
is reversed in the face// hspecifies the ids of the edges making up a hole -// negative value if the edge is
reversed in the face// mfspecifies the ids of texture coordinates (uvs) for a face.// This data type is obsolete as
of version 3.0. It is replaced by mu.// mhspecifies the ids of texture coordinates (uvs) for a hole// This data type
is obsolete as of version 3.0. It is replaced by mu.// muThe first argument refers to the uv set. This is a zero-
based// integer number. The second argument refers to the number of vertices (n)// on the face which have valid
uv values. The last n values are the uv// ids of the texture coordinates (uvs) for the face. These indices// are
what used to be represented by the mfand mhspecification.// There may be more than one muspecification, one for each
unique uv set.// fcspecifies the color index values for a face//setAttr node.polyFaceAttr -type polyFaces f3 1 2 3 fc3 4
4 6;-type meshPolygonal meshValue SyntaxValue Meaningvvn[vtesmooth|hard]Example// vspecifies the vertices of the
polygonal mesh// vnspecifies the normal of each vertex// vtis optional and specifies a U,V texture coordinate for each
vertex// especifies the edge connectivity information between vertices//setAttr node.meshAttr -type mesh v3 0 0 0 0 1 0
0 0 1vn3 1 0 0 1 0 0 1 0 0vt3 0 0 0 1 1 0e3 0 1 hard1 2 hard2 0 hard;-type latticeLattice dataValue SyntaxValue
MeaningsDivisionCount tDivisionCount uDivisionCountExample// sDivisionCount is the horizontal lattice division count//
tDivisionCount is the vertical lattice division count// uDivisionCount is the depth lattice division count// pointCount
is the total number of lattice points// pointX,pointY,pointZ is one lattice point. The list is// specified varying
first in S, then in T, last in U so the// first two entries are (S=0,T=0,U=0) (s=1,T=0,U=0)//setAttr node.latticeAttr
-type lattice 2 5 2 20-2 -2 -2 2 -2 -2 -2 -1 -2 2 -1 -2 -2 0 -22 0 -2 -2 1 -2 2 1 -2 -2 2 -2 2 2 -2-2 -2 2 2 -2 2 -2 -1
2 2 -1 2 -2 0 22 0 2 -2 1 2 2 1 2 -2 2 2 2 2 2;In query mode, return type is based on queried flag.
Maya Bug Fix:
- setAttr did not work with type matrix.
Modifications:
- No need to set type, this will automatically be determined
- Adds support for passing a list or tuple as the second argument for datatypes such as double3.
- When setting stringArray datatype, you no longer need to prefix the list with the number of elements - just pass a list or tuple as with other arrays
- Added 'force' kwarg, which causes the attribute to be added if it does not exist.
- if no type flag is passed, the attribute type is based on type of value being set (if you want a float, be sure to format it as a float, e.g. 3.0 not 3)
- currently does not support compound attributes
- currently supported python-to-maya mappings:
============ ===========
python type maya type
============ ===========
float double
------------ -----------
int long
------------ -----------
str string
------------ -----------
bool bool
------------ -----------
Vector double3
------------ -----------
Matrix matrix
------------ -----------
[str] stringArray
============ ===========
>>> addAttr( 'persp', longName= 'testDoubleArray', dataType='doubleArray')
>>> setAttr( 'persp.testDoubleArray', [0,1,2])
>>> setAttr( 'defaultRenderGlobals.preMel', 'sfff')
- Added ability to set enum attributes using the string values; this may be
done either by setting the 'asString' kwarg to True, or simply supplying
a string value for an enum attribute.
Flags:
- alteredValue : av (bool) [create]
The value is only the current value, which may change in the next evalution (if the attribute has an incoming
connection). This flag is only used during file I/O, so that attributes with incoming connections do not have their data
overwritten during the first evaluation after a file is opened.
- caching : ca (bool) [create]
Sets the attribute's internal caching on or off. Not all attributes can be defined as caching. Only those attributes
that are not defined by default to be cached can be made caching. As well, multi attribute elements cannot be made
caching. Caching also affects child attributes for compound attributes.
- capacityHint : ch (int) [create]
Used to provide a memory allocation hint to attributes where the -size flag cannot provide enough information. This flag
is optional and is primarily intended to be used during file I/O. Only certain attributes make use of this flag, and the
interpretation of the flag value varies per attribute. This flag is currently used by (node.attribute): mesh.face -
hints the total number of elements in the face edge lists
- channelBox : cb (bool) [create]
Sets the attribute's display in the channelBox on or off. Keyable attributes are always display in the channelBox
regardless of the channelBox settting.
- clamp : c (bool) [create]
For numeric attributes, if the value is outside the range of the attribute, clamp it to the min or max instead of
failing
- keyable : k (bool) [create]
Sets the attribute's keyable state on or off.
- lock : l (bool) [create]
Sets the attribute's lock state on or off.
- size : s (int) [create]
Defines the size of a multi-attribute array. This is only a hint, used to help allocate memory as efficiently as
possible.
- type : typ (unicode) [create]
Identifies the type of data. If the -type flag is not present, a numeric type is assumed. Flag can
have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.setAttr`
"""
pass
def displaySmoothness(*args, **kwargs):
"""
This command is responsible for setting the display smoothness of NURBS curves and surfaces to either predefined or
custom values. It also sets display modes for smoothness such as hulls and the hull simplification factors. At present,
this command is NOT un-doable. In query mode, return type is based on queried flag.
Flags:
- all : all (bool) [create,query]
Change smoothness for all curves and surfaces
- boundary : bn (bool) [create,query]
Display wireframe surfaces using only the boundaries of the surface Not fully implemented yet
- defaultCreation : dc (bool) [create,query]
The default values at creation (applies only -du, -dv, -pw, -ps)
- divisionsU : du (int) [create,query]
Number of isoparm divisions per span in the U direction. The valid range of values is [0,64].
- divisionsV : dv (int) [create,query]
Number of isoparm divisions per span in the V direction. The valid range of values is [0,64].
- full : f (bool) [create,query]
Display surface at full resolution - the default.
- hull : hl (bool) [create,query]
Display surface using the hull (control points are drawn rather than surface knot points). This mode is a useful display
performance improvement when modifying a surface since it doesn't require evaluating points on the surface.
- pointsShaded : ps (int) [create,query]
Number of points per surface span in shaded mode. The valid range of values is [1,64].
- pointsWire : pw (int) [create,query]
Number of points per surface isoparm span or the number of points per curve span in wireframe mode. The valid range of
values is [1,128]. Note: This is the only flag that also applies to nurbs curves.
- polygonObject : po (int) [create,query]
Display the polygon objects with the given resolution
- renderTessellation : rt (bool) [create,query]
Display using render tesselation parameters when in shaded mode.
- simplifyU : su (int) [create,query]
Number of spans to skip in the U direction when in hull display mode.
- simplifyV : sv (int) [create,query]
Number of spans to skip in the V direction when in hull display mode. Flag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.displaySmoothness`
"""
pass
def containerProxy(*args, **kwargs):
"""
Creates a new container with the same published interface, dynamic attributes and attribute values as the specified
container but with fewer container members. This proxy container can be used as a reference proxy so that values can be
set on container attributes without loading in the full container. The proxy container will contain one or more locator
nodes. The first locator has dynamic attributes that serve as stand-ins for the original published attributes. The
remaining locators serve as stand-ins for any dag nodes that have been published as parent or as child and will be
placed at the world space location of the published parent/child nodes. The expected usage of container proxies is to
serve as a reference proxy for a referenced container. For automated creation, export and setup of the proxy see the
doExportContainerProxy.mel script which is invoked by the Export Container Proxymenu item. In query
mode, return type is based on queried flag.
Flags:
- fromTemplate : ft (unicode) [create]
Specifies the name of a template file which will be used to create the new container proxy. Stand-in attributes will be
created and published for all the numeric attributes on the proxy.
- type : typ (unicode) [create]
Specifies the type of container node to use for the proxy. This flag is only valid in conjunction with the fromTemplate
flag. When creating a proxy for an existing container, the type created will always be identical to that of the source
container. The default value for this flag is 'container'. Flag can have multiple
arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.containerProxy`
"""
pass
def assignCommand(*args, **kwargs):
"""
This command allows the user to assign hotkeys and manipulate the internal array of named command objects. Each object
in the array has an 1-based index which is used for referencing. Under expected usage you should not need to use this
command directly as the Hotkey Editor may be used to assign hotkeys. This command is obsolete for setting new hotkeys,
instead please use the hotkeycommand. In query mode, return type is based on queried flag.
Flags:
- addDivider : ad (unicode) [edit]
Appends an annotated divideritem to the end of the list of commands.
- altModifier : alt (bool) [edit]
This flag specifies if an alt modifier is used for the key.
- annotation : ann (unicode) [query,edit]
The string is the english name describing the command.
- command : c (script) [query,edit]
This is the command that is executed when this object is mapped to a key or menuItem.
- commandModifier : cmd (bool) [edit]
This flag specifies if a command modifier is used for the key. This is only available on systems which support a
separate command key.
- ctrlModifier : ctl (bool) [edit]
This flag specifies if a ctrl modifier is used for the key.
- data1 : da1 (unicode) [query,edit]
Optional, user-defined data strings may be attached to the nameCommand objects.
- data2 : da2 (unicode) [query,edit]
Optional, user-defined data strings may be attached to the nameCommand objects.
- data3 : da3 (unicode) [query,edit]
Optional, user-defined data strings may be attached to the nameCommand objects.
- delete : d (int) [edit]
This tells the Manager to delete the object at position index.
- dividerString : ds (unicode) [query]
If the passed index corresponds to a divideritem, then the divider's annotation is returned. Otherwise, a null string
is returned.
- enableCommandRepeat : ecr (bool) []
- factorySettings : fs (bool) [edit]
This flag sets the manager back to factory settings.
- index : i (int) [edit]
The index of the object to operate on. The index value ranges from 1 to the number of name command objects.
- keyArray : ka (bool) []
- keyString : k (unicode) [query,edit]
This specifies a key to assign a command to in edit mode. In query mode this flag returns the key string, modifiers and
indicates if the command is mapped to keyUp or keyDown.
- keyUp : kup (bool) [edit]
This flag specifies if the command is executed on keyUp or keyDown.
- name : n (bool) [query]
The name of the command object.
- numDividersPreceding : ndp (int) [query]
If the index of a namedCommand object Cis passed in, then this flag returns the number of divideritems preceding Cwhen
the namedCommands are sorted by category.
- numElements : num (bool) [query]
This command returns the number of namedCommands in the system. This flag doesn't require the index to be specified.
- optionModifier : opt (bool) [edit]
This flag specifies if an option modifier is used for the key.
- sortByKey : sbk (bool) [query,edit]
This key tells the manager to sort by key or by order of creation.
- sourceUserCommands : suc (bool) [edit]
This command sources the user named command file. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.assignCommand`
"""
pass
def validComponentIndexType(argObj, allowDicts='True', componentIndexTypes='None'):
"""
True if argObj is of a suitable type for specifying a component's index.
False otherwise.
Dicts allow for components whose 'mel name' may vary - ie, a single
isoparm component may have, u, v, or uv elements; or, a single pivot
component may have scalePivot and rotatePivot elements. The key of the
dict would indicate the 'mel component name', and the value the actual
indices.
Thus:
{'u':3, 'v':(4,5), 'uv':ComponentIndex((1,4)) }
would represent single component that contained:
.u[3]
.v[4]
.v[5]
.uv[1][4]
Derived classes should implement:
_dimLength
"""
pass
def vnnNode(*args, **kwargs):
"""
The vnnNodecommand is used to operate vnnNode and query its port and connections. The first argument is the full name of
the DG node that the VNN node is in. The second argument is the name of the full path of the VNN node.
Flags:
- connected : c (bool) [create]
Used with listPortsto query the connected or unconnected ports.
- connectedTo : ct (unicode) [create]
Used with listConnectedNodesto query the nodes that are connected to the specified ports.
- listConnectedNodes : lcn (bool) [create]
Used to list nodes which are connected to the specified node. The returned result is a list of node names.
- listPortChildren : lpc (unicode) [create]
List the children of specified port.
- listPorts : lp (bool) [create]
List ports on the specified node. Can be used with connectedto determine if the returned ports have connections.
- portDefaultValue : pdv (unicode, unicode) [create]
Set the default value to a node port The port cannot be connected.
- queryAcceptablePortDataTypes : qat (unicode) [create]
Get the list of acceptable types for the given port of an unresolved node. The acceptable types are based on the
overloads that match the current defined ports of the node.
- queryIsUnresolved : qiu (bool) [create]
Query if the node is unresolved. A node is considered unresolved if it is part of overload set, and have at least one
port that is both unconnected and has an undefined type.
- queryPortDataType : qpt (unicode) [create]
Query the data type of a specified port.
- queryPortDefaultValue : qpv (unicode) [create]
Query the default value of a node port
- queryTypeName : qtn (bool) [create]
Used to query the fundamental type of a node such as runtimeName,libraryName,typeName
- setPortDataType : spt (unicode, unicode) [create]
Set the data type of a specified port. Flag can have multiple arguments, passed either as a tuple or a
list.
Derived from mel command `maya.cmds.vnnNode`
"""
pass
def _nodeAddedCallback(list_):
pass
def about(*args, **kwargs):
"""
This command displays version information about the application if it is executed without flags. If one of the above
flags is specified then the specified version information is returned.
Flags:
- apiVersion : api (bool) [create]
Returns the api version.
- application : a (bool) [create]
Returns the application name string.
- batch : b (bool) [create]
Returns true if application is in batch mode.
- buildDirectory : bd (bool) [create]
Returns the build directory string.
- buildVariant : bv (bool) [create]
Returns the build variant string.
- codeset : cs (bool) [create]
Returns a string identifying the codeset (codepage) of the locale that Maya is running in. Example return values include
UTF-8, ISO-8859-1, 1252. Note that the codeset values and naming conventions are highly platform dependent. They may
differ in format even if they have the same meaning (e.g. utf8vs. UTF-8).
- compositingManager : cm (bool) [create]
On Linux, returns true if there is a compositing manager running; on all other platforms, it always returns true.
- connected : cnt (bool) [create]
Return whether the user is connected or not to the Internet.
- ctime : cti (bool) [create]
Returns the current time in the format Wed Jan 02 02:03:55 1980\n\0
- currentDate : cd (bool) [create]
Returns the current date in the format yyyy/mm/dd, e.g. 2003/05/04.
- currentTime : ct (bool) [create]
Returns the current time in the format hh:mm:ss, e.g. 14:27:53.
- cutIdentifier : c (bool) [create]
Returns the cut string.
- date : d (bool) [create]
Returns the build date string.
- environmentFile : env (bool) [create]
Returns the location of the application defaults file.
- evalVersion : ev (bool) [create]
This flag is now deprecated. Always returns false, as the eval version is no longer supported.
- file : f (bool) [create]
Returns the file version string.
- fontInfo : foi (bool) [create]
Returns a string of the specifications of the fonts requested, and the specifications of the fonts that are actually
being used.
- helpDataDirectory : hdd (bool) [create]
Returns the help data directory.
- installedVersion : iv (bool) [create]
Returns the product version string.
- irix : ir (bool) [create]
Returns true if the operating system is Irix. Always false with support for Irix removed.
- is64 : x64 (bool) [create]
Returns true if the application is 64 bit.
- languageResources : lr (bool) [create]
Returns a string array of the currently installed language resources. Each string entry consists of three elements
delimited with a colon (':'). The first token is the locale code (ISO 639-1 language code followed by ISO 3166-1 country
code). The second token is the language name in English. This third token is the alpha-3 code (ISO 639-2). For example
English is represented as en_US:English:enu.
- linux : li (bool) [create]
Returns true if the operating system is Linux.
- linux64 : l64 (bool) [create]
Returns true if the operating system is Linux 64 bit.
- liveUpdate : lu (bool) [create]
Returns Autodesk formatted product information.
- localizedResourceLocation : lrl (bool) [create]
Returns the path to the top level of the localized resource directory, if we are running in an alternate language.
Returns an empty string if we are running in the default language.
- ltVersion : lt (bool) [create]
Returns true if this is the Maya LT version of the application.
- macOS : mac (bool) [create]
Returns true if the operating system is Macintosh.
- macOSppc : ppc (bool) [create]
Returns true if the operating system is a PowerPC Macintosh.
- macOSx86 : x86 (bool) [create]
Returns true if the operating system is an Intel Macintosh.
- ntOS : nt (bool) [create]
Returns true if the operating system is Windows.
- operatingSystem : os (bool) [create]
Returns the operating system type. Valid return types are nt, win64, mac, linuxand linux64
- operatingSystemVersion : osv (bool) [create]
Returns the operating system version. on Linux this returns the equivalent of uname -srvm
- preferences : pd (bool) [create]
Returns the location of the preferences directory.
- product : p (bool) [create]
Returns the license product name.
- qtVersion : qt (bool) [create]
Returns Qt version string.
- tablet : tab (bool) [create]
Windows only. Returns true if the PC is a Tablet PC.
- tabletMode : tm (bool) [create]
Windows 8 (and above) only. If your device is a Tablet PC, then the convertible mode the device is currently running
in. Returns either: tablet or laptop (keyboard attached). See the tabletflag.
- uiLanguage : uil (bool) [create]
Returns the language that Maya's running in. Example return values include en_USfor English and ja_JPfor Japanese.
- uiLanguageForStartup : uis (bool) [create]
Returns the language that is used for Maya's next start up. This is read from config file and is rewritten after setting
ui language in preference.
- uiLanguageIsLocalized : uii (bool) [create]
Returns true if we are running in an alternate language, not the default (English).
- uiLocaleLanguage : ull (bool) [create]
Returns the language locale of the OS. English is default.
- version : v (bool) [create]
Returns the version string.
- win64 : w64 (bool) [create]
Returns true if the operating system is Windows x64 based.
- windowManager : wm (bool) [create]
Returns the name of the Window Manager that is assumed to be running.
- windows : win (bool) [create]
Returns true if the operating system is Windows based. Flag can have multiple arguments, passed either
as a tuple or a list.
Derived from mel command `maya.cmds.about`
"""
pass
def partition(*args, **kwargs):
"""
This command is used to create, query or add/remove sets to a partition. If a partition name needs to be specified, it
is the first argument, other arguments represent the set names. Without any flags, the command will create a partition
with a default name. Any sets which are arguments to the command will be added to the partition. A set can be added to
a partition only if none of its members are in any of the other sets in the partition. If the -re/render flag is
specified when the partition is created, only 'renderable' sets can be added to the partition. Sets can be added and
removed from a partition by using the -addSet or -removeSet flags. Note:If a set is already selected, and the partition
command is executed, the set will be added to the created partition.
Flags:
- addSet : add (PyNode) [create]
Adds the list of sets to the named partition.
- name : n (unicode) [create]
Assigns the given name to new partition. Valid only for create mode.
- removeSet : rm (PyNode) [create]
Removes the list of sets from the named partition.
- render : re (bool) [create,query]
New partition can contain render sets. For use in creation mode only. Default is false. Can also be used with query
flag - returns boolean. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.partition`
"""
pass
def affects(*args, **kwargs):
"""
This command returns the list of attributes on a node or node type which affect the named attribute.
Flags:
- by : boolean (Show attributes that are affected by the given one rather than the
ones that affect it.) [create]
- type : t (unicode) [create]
static node type from which to get 'affects' information Flag can have multiple
arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.affects`
"""
pass
def createDisplayLayer(*args, **kwargs):
"""
Create a new display layer. The display layer number will be assigned based on the first unassigned number not less
than the base index number found in the display layer global parameters. Normally all objects and their descendants
will be added to the new display layer but if the '-nr' flag is specified then only the objects themselves will be
added.
Modifications:
- returns a PyNode object
Flags:
- empty : e (bool) [create]
If set then create an empty display layer. ie. Do not add the selected items to the new display layer.
- makeCurrent : mc (bool) [create]
If set then make the new display layer the current one.
- name : n (unicode) [create]
Name of the new display layer being created.
- noRecurse : nr (bool) [create]
If set then only add selected objects to the display layer. Otherwise all descendants of the selected objects will also
be added.
- number : num (int) [create]
Number for the new display layer being created. Flag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.createDisplayLayer`
"""
pass
def currentUnit(*args, **kwargs):
"""
This command allows you to change the units in which you will work in Maya. There are three types of units: linear,
angular and time. The current unit affects how all commands in Maya interpret their numeric values. For example, if the
current linear unit is cm, then the command: move 5 -2 3; sphere -radius 4; will be interpreted as moving 5cm in X, -2cm
in Y, 3cm in Z, and as creating a sphere with radius 4cm. Similarly, if the current time unit is Film (24 frames per
second), then the command: currentTime 6; will be interpreted as setting the current time to frame 6 in the Film unit,
which is 6/24 or 0.25 seconds. You can always override the unit of a particular numeric value to a command be specifying
it one the command. For example, using the above examples: move 5m -2mm 3cm; sphere -radius 4inch; currentTime 6ntsc;
would move the object 5 meters in X, -2 millimeters in Y, 3 centimeters in Z, create a sphere of radius 4 inches, and
change the current time to 6 frames in the NTSC unit, which would be 0.2 seconds, or 4.8 frames in the current (Film)
unit.
Flags:
- angle : a (unicode) [create,query]
Set the current angular unit. Valid strings are: [deg | degree | rad | radian] When queried, returns a string which is
the current angular unit
- fullName : f (bool) [query]
A query only flag. When specified in conjunction with any of the -linear/-angle/-time flags, will return the long form
of the unit. For example, mmand millimeterare the same unit, but the former is the short form of the unit name, and the
latter is the long form of the unit name.
- linear : l (unicode) [create,query]
Set the current linear unit. Valid strings are: [mm | millimeter | cm | centimeter | m | meter | km | kilometer | in |
inch | ft | foot | yd | yard | mi | mile] When queried, returns a string which is the current linear unit
- time : t (unicode) [create,query]
Set the current time unit. Valid strings are: [hour | min | sec | millisec | game | film | pal | ntsc | show | palf |
ntscf] When queried, returns a string which is the current time unit Note that there is no long form for any of the time
units. The non-seconds based time units are interpreted as the following frames per second: game: 15 fpsfilm: 24 fpspal:
25 fpsntsc: 30 fpsshow: 48 fpspalf: 50 fpsntscf: 60 fps
- updateAnimation : ua (bool) [create]
An edit only flag. When specified in conjunction with the -time flag indicates that times for keys are not updated. By
default when the current time unit is changed, the times for keys are modified so that playback timing is preserved.
For example a key set a frame 12film is changed to frame 15ntsc when the current time unit is changed to ntsc, since
they both represent a key at a time of 0.5 seconds. Specifying -updateAnimation false would leave the key at frame
12ntsc. Default is -updateAnimation true. Flag can have multiple arguments, passed either as a tuple or
a list.
Derived from mel command `maya.cmds.currentUnit`
"""
pass
def vnnCopy(*args, **kwargs):
"""
Copy a set of VNN nodes to clipper board. The first parameter is the full name of the DG node that contains the VNN
graph. The second parameter is the full path of the parent VNN compound. The source VNN nodes must be set by the flag
-sourceNode.
Flags:
- sourceNode : src (unicode) [create]
Set the source node to copy. This node should be a child of the specified parent compound. This command should be used
with vnnPastecommand. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.vnnCopy`
"""
pass
def assembly(*args, **kwargs):
"""
Command to register assemblies for the scene assembly framework, to create them, and to edit and query them. Assembly
nodes are DAG nodes, and are therefore shown in the various DAG editors (Outliner, Hypergraph, Node Editor). At assembly
creation time, the node name defaults to the node type name. The assembly command can create any node that is derived
from the assembly node base class. It also acts as a registry of these types, so that various scripting callbacks can
be defined and registered with the assembly command. These callbacks are invoked by Maya during operations on assembly
nodes, and can be used to customize behavior. In query mode, return type is based on queried flag.
Flags:
- active : a (unicode) [query,edit]
Set the active representation by name, or query the name of the active representation. Edit mode can be applied to more
than one assembly. Query mode will return a single string when only a single assembly is specified, and will return an
array of strings when multiple assemblies are specified. Using an empty string as name means to inactivate the currently
active representation.
- activeLabel : al (unicode) [query,edit]
Set the active representation by label, or query the label of the active representation. Edit mode can be applied to
more than one assembly. Query mode will return a single string when only a single assembly is specified, and will return
an array of strings when multiple assemblies are specified.
- canCreate : cc (unicode) [query]
Query the representation types the specific assembly can create.
- createOptionBoxProc : cob (script) [query,edit]
Set or query the option box menu procedure for a specific assembly type. The assembly type will be the default type,
unless the -type flag is used to specify an explicit assembly type.
- createRepresentation : cr (unicode) [edit]
Create and add a specific type of representation for an assembly. If the representation type needs additional
parameters, they must be specified using the inputflag. For example, the Maya scene assembly reference implementation
Cache and Scene representations need an input file.
- defaultType : dt (unicode) [query,edit]
Set or query the default type of assembly. When the assembly command is used to perform an operation on an assembly
type rather than on an assembly object, it will be performed on the default type, unless the -type flag is used to
specify an explicit assembly type.
- deleteRepresentation : dr (unicode) [edit]
Delete a specific representation from an assembly.
- deregister : d (unicode) [edit]
Deregister a registered assembly type. If the deregistered type is the default type, the default type will be set to the
empty string.
- input : input (unicode) [edit]
Specify the additional parameters of representation creation procedure when creating a representation. This flag must be
used with createRepresentation flag.
- isAType : isa (unicode) [query]
Query whether the given object is of an assembly type.
- isTrackingMemberEdits : ite (unicode) [query]
Query whether the given object is tracking member edits.
- label : lbl (unicode) [query,edit]
Set or query the label for an assembly type. Assembly type is specified with flag type. If no type specified, the
default type is used.
- listRepTypes : lrt (bool) [query]
Query the supported representation types for a given assembly type. The assembly type will be the default type, unless
the -type flag is used to specify an explicit assembly type.
- listRepTypesProc : lrp (script) [query,edit]
Set or query the procedure that provides the representation type list which an assembly type supports. This procedure
takes no argument, and returns a string array of representation types that represents the full set of representation
types this assembly type can create. The assembly type for which this procedure applies will be the default type,
unless the type flag is used to specify an explicit assembly type.
- listRepresentations : lr (bool) [query]
Query the created representations list for a specific assembly. The -repType flag can be used to filter the list and
return representations for a single representation type. If the -repType flag is not used, all created representations
will be returned.
- listTypes : lt (bool) [query]
Query the supported assembly types.
- name : n (unicode) [create]
Specify the name of the assembly when creating it.
- newRepLabel : nrl (unicode) [edit]
Specify the representation label to set on representation label edit.
- postCreateUIProc : aoc (script) [query,edit]
Set or query the UI post-creation procedure for a given assembly type. This procedure will be invoked by Maya
immediately after an assembly of the specified type is created from the UI, but not through scripting. It can be used
to invoke a dialog, to obtain and set initial parameters on a newly-created assembly. The assembly type will be the
default type, unless the -type flag is used to specify an explicit assembly type.
- proc : prc (script) [edit]
Specify the procedure when setting the representation UI post- or pre-creation procedure, for a given assembly type.
The assembly type will be the default type, unless the -type flag is used to specify an explicit assembly type.
- renameRepresentation : rnr (unicode) [edit]
Renames the representation that is the argument to this flag. The repName flag must be used to provide the new name.
- repLabel : rl (unicode) [query,edit]
Query or edit the label of the representation that is the argument to this flag, for a given assembly. In both query
and edit modes, the -repLabel flag specifies the name of the representation. In edit mode, the -newRepLabel flag must
be used to specify the new representation label.
- repName : rnm (unicode) [edit]
Specify the representation name to set on representation creation or rename. This flag is optional with the
createRepresentation flag: if omitted, the assembly will name the representation. It is mandatory with the
renameRepresentation flag.
- repNamespace : rns (unicode) [query]
Query the representation namespace of this assembly node. The value returned is used by Maya for creating the namespace
where nodes created by the activation of a representation will be added. If a name clash occurs when the namespace is
added to its parent namespace, Maya will update repNamespace with the new name. Two namespaces are involved when dealing
with an assembly node: the namespace of the assembly node itself (which this flag does not affect or query), and the
namespace of its representations. The representation namespace is a child of its assembly node's namespace. The assembly
node's namespace is set by its containing assembly, if it is nested, or by the top-level file. Either the assembly
node's namespace, or the representation namespace, or both, can be the empty string. It should be noted that if the
assembly node is nested, the assembly node's namespace will be (by virtue of its nesting) the representation namespace
of its containing assembly.
- repPostCreateUIProc : poc (unicode) [query,edit]
Set or query the UI post-creation procedure for a specific representation type, and for a specific assembly type. This
procedure takes two arguments, the first the DAG path to the assembly, and the second the name of the representation.
It returns no value. It will be invoked by Maya immediately after a representation of the specified type is created
from the UI, but not through scripting. It can be used to invoke a dialog, to obtain and set initial parameters on a
newly-created representation. The representation type is the argument of this flag. The -proc flag must be used to
specify the procedure name. The assembly type will be the default type, unless the -type flag is used to specify an
explicit assembly type.
- repPreCreateUIProc : pec (unicode) [query,edit]
Set or query the UI pre-creation procedure for a specific representation type, and for a specific assembly type. This
procedure takes no argument, and returns a string that is passed as an argument to the -input flag when Maya invokes the
assembly command with the -createRepresentation flag. The representation pre-creation procedure is invoked by Maya
immediately before creating a representation of the specified type from the UI, but not through scripting. It can be
used to invoke a dialog, to obtain the creation argument for a new representation. The representation type is the
argument of this flag. The -proc flag must be used to specify the procedure name. The assembly type will be the
default type, unless the -type flag is used to specify an explicit assembly type.
- repType : rt (unicode) [query]
Specify a representation type to use as a filter for the -listRepresentations query. The representation type is the
argument to this flag.
- repTypeLabel : rtl (unicode) [query]
Query the label of the specific representation type.
- repTypeLabelProc : rtp (script) [query,edit]
Set or query the procedure that provides the representation type label, for a given assembly type. The procedure takes
the representation type as its sole argument, and returns a localized representation type label. The assembly type for
which this procedure applies will be the default type, unless the -type flag is used to specify an explicit assembly
type.
- type : typ (unicode) [create,query,edit]
Set or query properties for the specified registered assembly type. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.assembly`
"""
pass
def objectCenter(*args, **kwargs):
"""
This command returns the coordinates of the center of the bounding box of the specified object. If one coordinate only
is specified, it will be returned as a float. If no coordinates are specified, an array of floats is returned,
containing x, y, and z. If you specify multiple coordinates, only one will be returned.
Flags:
- gl : gl (bool) [create]
Return positional values in global coordinates (default).
- local : l (bool) [create]
Return positional values in local coordinates.
- x : x (bool) [create]
Return X value only
- y : y (bool) [create]
Return Y value only
- z : z (bool) [create]
Return Z value only Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.objectCenter`
"""
pass
def listAttrPatterns(*args, **kwargs):
"""
Attribute patterns are plain text descriptions of an entire Maya attribute forest. (forestbecause there could be an
arbitrary number of root level attributes, it's not restricted to having a single common parent though in general that
practice is a good idea.) This command lists the various pattern types available, usually created via plugin, as well as
any specific patterns that have already been instantiated. A pattern type is a thing that knows how to take some textual
description of an attribute tree, e.g. XML or plaintext, and convert it into an attribute pattern that can be applied to
any node or node type in Maya.
Flags:
- patternType : pt (bool) [create]
If turned on then show the list of pattern types rather than actual instantiated patterns.
- verbose : v (bool) [create]
If turned on then show detailed information about the patterns or pattern types. The same list of instance or pattern
names is returned as for the non-verbose case. Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.listAttrPatterns`
"""
pass
def addExtension(*args, **kwargs):
"""
This command is used to add an extension attribute to a node type. Either the longName or the shortName or both must be
specified. If neither a dataType nor an attributeType is specified, a double attribute will be added. The dataType flag
can be specified more than once indicating that any of the supplied types will be accepted (logical-or). To add a non-
double attribute the following criteria can be used to determine whether the dataType or the attributeType flag is
appropriate. Some types, such as double3can use either. In these cases the -dtflag should be used when you only wish to
access the data as an atomic entity (eg. you never want to access the three individual values that make up a double3).
In general it is best to use the -atin these cases for maximum flexibility. In most cases the -dtversion will not
display in the attribute editor as it is an atomic type and you are not allowed to change individual parts of it. All
attributes flagged as (compound)below or the compound attribute itself are not actually added to the node until all of
the children are defined (using the -pflag to set their parent to the compound being created). See the EXAMPLES section
for more details. Type of attribute Flag and argument to use boolean
-at bool 32 bit integer -at long 16 bit
integer -at short 8 bit integer -at
byte char -at char enum
-at enum (specify the enum names using the enumName flag) float -at
float(use quotes since float is a mel keyword)
double -at double angle value
-at doubleAngle linear value -at doubleLinear string
-dt string(use quotes since string is a mel
keyword) array of strings -dt stringArray compound
-at compound message (no data) -at message time
-at time 4x4 double matrix -dt matrix(use quotes
since matrix is a mel keyword) 4x4 float matrix -at fltMatrix reflectance
-dt reflectanceRGBreflectance (compound) -at reflectance spectrum
-dt spectrumRGB spectrum (compound) -at spectrum 2 floats
-dt float2 2 floats (compound) -at float2 3 floats
-dt float3 3 floats (compound) -at float3 2 doubles
-dt double2 2 doubles (compound) -at double2 3 doubles
-dt double3 3 doubles (compound) -at double3 2 32-bit integers
-dt long2 2 32-bit integers (compound) -at long2 3 32-bit integers
-dt long3 3 32-bit integers (compound) -at long3 2 16-bit integers
-dt short2 2 16-bit integers (compound) -at short2 3 16-bit integers
-dt short3 3 16-bit integers (compound) -at short3 array of doubles
-dt doubleArray array of floats -dt floatArray array of 32-bit ints
-dt Int32Array array of vectors -dt vectorArray nurbs curve
-dt nurbsCurve nurbs surface -dt nurbsSurface polygonal mesh
-dt mesh lattice -dt lattice array of
double 4D points -dt pointArray
Flags:
- attributeType : at (unicode) [create,query]
Specifies the attribute type, see above table for more details. Note that the attribute types float, matrixand stringare
also MEL keywords and must be enclosed in quotes.
- binaryTag : bt (unicode) [create,query]
This flag is obsolete and does not do anything any more
- cachedInternally : ci (bool) [create,query]
Whether or not attribute data is cached internally in the node. This flag defaults to true for writable attributes and
false for non-writable attributes. A warning will be issued if users attempt to force a writable attribute to be
uncached as this will make it impossible to set keyframes.
- category : ct (unicode) [create,query,edit]
An attribute category is a string associated with the attribute to identify it. (e.g. the name of a plugin that created
the attribute, version information, etc.) Any attribute can be associated with an arbitrary number of categories however
categories can not be removed once associated.
- dataType : dt (unicode) [create,query]
Specifies the data type. See setAttrfor more information on data type names.
- defaultValue : dv (float) [create,query,edit]
Specifies the default value for the attribute (can only be used for numeric attributes).
- disconnectBehaviour : dcb (int) [create,query]
defines the Disconnect Behaviour 2 Nothing, 1 Reset, 0 Delete
- enumName : en (unicode) [create,query,edit]
Flag used to specify the ui names corresponding to the enum values. The specified string should contain a colon-
separated list of the names, with optional values. If values are not specified, they will treated as sequential integers
starting with 0. For example: -enumName A:B:Cwould produce options: A,B,C with values of 0,1,2; -enumName
zero:one:two:thousand=1000would produce four options with values 0,1,2,1000; and -enumName
solo=1:triplet=3:quintet=5would produce three options with values 1,3,5. (Note that there is a current limitation of
the Channel Box that will sometimes incorrectly display an enumerated attribute's pull-down menu. Extra menu items can
appear that represent the numbers inbetween non-sequential option values. To avoid this limitation, specify sequential
values for the options of any enumerated attributes that will appear in the Channel Box. For example:
solo=1:triplet=2:quintet=3.)
- exists : ex (bool) [create,query]
Returns true if the attribute queried is a user-added, dynamic attribute; false if not.
- fromPlugin : fp (bool) [create,query]
Was the attribute originally created by a plugin? Normally set automatically when the API call is made - only added here
to support storing it in a file independently from the creating plugin.
- hasMaxValue : hxv (bool) [create,query,edit]
Flag indicating whether an attribute has a maximum value. (can only be used for numeric attributes).
- hasMinValue : hnv (bool) [create,query,edit]
Flag indicating whether an attribute has a minimum value. (can only be used for numeric attributes).
- hasSoftMaxValue : hsx (bool) [create,query]
Flag indicating whether a numeric attribute has a soft maximum.
- hasSoftMinValue : hsn (bool) [create,query]
Flag indicating whether a numeric attribute has a soft minimum.
- hidden : h (bool) [create,query]
Will this attribute be hidden from the UI?
- indexMatters : im (bool) [create,query]
Sets whether an index must be used when connecting to this multi-attribute. Setting indexMatters to false forces the
attribute to non-readable.
- internalSet : internalSet (bool) [create,query]
Whether or not the internal cached value is set when this attribute value is changed. This is an internal flag used for
updating UI elements.
- keyable : k (bool) [create,query]
Is the attribute keyable by default?
- longName : ln (unicode) [create,query]
Sets the long name of the attribute.
- maxValue : max (float) [create,query,edit]
Specifies the maximum value for the attribute (can only be used for numeric attributes).
- minValue : min (float) [create,query,edit]
Specifies the minimum value for the attribute (can only be used for numeric attributes).
- multi : m (bool) [create,query]
Makes the new attribute a multi-attribute.
- niceName : nn (unicode) [create,query,edit]
Sets the nice name of the attribute for display in the UI. Setting the attribute's nice name to a non-empty string
overrides the default behaviour of looking up the nice name from Maya's string catalog. (Use the MEL commands
attributeNiceNameand attributeQuery -niceNameto lookup an attribute's nice name in the catalog.)
- nodeType : nt (unicode) [create,edit]
Specifies the type of node to which the attribute will be added. See the nodeType command for the names of different
node types.
- numberOfChildren : nc (int) [create,query]
How many children will the new attribute have?
- parent : p (unicode) [create,query]
Attribute that is to be the new attribute's parent.
- proxy : pxy (unicode) [create,query]
Proxy another node's attribute. Proxied plug will be connected as source. The UsedAsProxy flag is automatically set in
this case.
- readable : r (bool) [create,query]
Can outgoing connections be made from this attribute?
- shortName : sn (unicode) [create,query]
Sets the short name of the attribute.
- softMaxValue : smx (float) [create,query,edit]
Soft maximum, valid for numeric attributes only. Specifies the upper default limit used in sliders for this attribute.
- softMinValue : smn (float) [create,query,edit]
Soft minimum, valid for numeric attributes only. Specifies the upper default limit used in sliders for this attribute.
- storable : s (bool) [create,query]
Can the attribute be stored out to a file?
- usedAsColor : uac (bool) [create,query]
Is the attribute to be used as a color definition? Must have 3 DOUBLE or 3 FLOAT children to use this flag. The
attribute type -atshould be double3or float3as appropriate. It can also be used to less effect with data types -dtas
double3or float3as well but some parts of the code do not support this alternative. The special attribute types/data
spectrumand reflectancealso support the color flag and on them it is set by default.
- usedAsFilename : uaf (bool) [create,query]
Is the attribute to be treated as a filename definition? This flag is only supported on attributes with data type -dtof
string.
- usedAsProxy : uap (bool) [create,query]
Set if the specified attribute should be treated as a proxy to another attributes.
- writable : w (bool) [create,query]
Can incoming connections be made to this attribute? Flag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.addExtension`
"""
pass
def disconnectAttr(source, destination='None', inputs='None', outputs='None', **kwargs):
"""
Disconnects two connected attributes. First argument is the source attribute, second is the destination.
Modifications:
- If no destination is passed, then all inputs will be disconnected if inputs
is True, and all outputs will be disconnected if outputs is True; if
neither are given (or both are None), both all inputs and all outputs
will be disconnected
Flags:
- nextAvailable : na (bool) [create]
If the destination multi-attribute has set the indexMatters to be false, the command will disconnect the first matching
connection. No index needs to be specified. Flag can have multiple arguments, passed either as a tuple
or a list.
Derived from mel command `maya.cmds.disconnectAttr`
"""
pass
def isConnected(*args, **kwargs):
"""
The isConnectedcommand is used to check if two plugs are connected in the dependency graph. The return value is falseif
they are not and trueif they are. The first string specifies the source plug to check for connection. The second one
specifies the destination plug to check for connection.
Flags:
- ignoreUnitConversion : iuc (bool) [create]
In looking for connections, skip past unit conversion nodes. Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.isConnected`
"""
pass
def softSelect(*args, **kwargs):
"""
This command allows you to change the soft modelling options. Soft modelling is an option that allows for reflection of
basic manipulator actions such as move, rotate, and scale. In query mode, return type is based on queried flag.
Flags:
- compressUndo : cu (int) [create,query,edit]
Controls how soft selection settings behave in undo: 0 means all changes undo individually1 means all consecutive
changes undo as a group2 means only interactive changes undo as a groupWhen queried, returns an int indicating the
current undo behaviour.
- enableFalseColor : efc (int) [create,query,edit]
Set soft select color feedback on or off. When queried, returns an int indicating whether color feedback is currently
enabled.
- softSelectColorCurve : scc (unicode) [create,query,edit]
Sets the color ramp used to display false color feedback for soft selected components in the viewport. The color curve
is encoded as a string of comma separated floating point values representing the falloff curve CVs. Each CV is
represented by 5 successive values: 3 RGB values (the color to use), an input value (the selection weight), and a curve
interpolation type. When queried, returns a string containing the encoded CVs of the current color feedback curve.
- softSelectCurve : ssc (unicode) [create,query,edit]
Sets the falloff curve used to calculate selection weights for components within the falloff distance. The curve is
encoded as a string of comma separated floating point values representing the falloff curve CVs. Each CV is represented
by 3 successive values: an output value (the selection weight at this point), an input value (the normalised falloff
distance) and a curve interpolation type. When queried, returns a string containing the encoded CVs of the current
falloff curve.
- softSelectDistance : ssd (float) [create,query,edit]
Sets the falloff distance (radius) used for world and object space soft selection. When queried, returns a float
indicating the current falloff distance.
- softSelectEnabled : sse (int) [create,query,edit]
Sets soft selection based modeling on or off. When queried, returns an int indicating the current state of the option.
- softSelectFalloff : ssf (int) [create,query,edit]
Sets the falloff mode: 0 for volume based falloff1 for surface based falloff2 for global falloffWhen queried, returns an
int indicating the falloff mode.
- softSelectReset : ssr (bool) [create,edit]
Resets soft selection to its default settings.
- softSelectUVDistance : sud (float) [create,query,edit]
Sets the falloff distance (radius) used for UV space soft selection. When queried, returns a float indicating the
current falloff distance. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.softSelect`
"""
pass
def symmetricModelling(*args, **kwargs):
"""
This command allows you to change the symmetric modelling options. Symmetric modelling is an option that allows for
reflection of basic manipulator actions such as move, rotate, and scale. In query mode, return type is based on queried
flag.
Flags:
- about : a (unicode) [create,query,edit]
Set the space in which symmetry should be calculated (object or world or topo). When queried, returns a string which is
the current space being used.
- allowPartial : ap (bool) [create,query,edit]
Specifies whether partial symmetry should be allowed when enabling topological symmetry.
- axis : ax (unicode) [create,query,edit]
Set the current axis to be reflected over. When queried, returns a string which is the current axis.
- preserveSeam : ps (int) [create,query,edit]
Controls whether selection or symmetry should take priority on the plane of symmetry. When queried, returns an int for
the option.
- reset : r (bool) [create,edit]
Reset the redo information before starting.
- seamFalloffCurve : sf (unicode) [create,query,edit]
Set the seam's falloff curve, used to control the seam strength within the seam tolerance. The string is a comma
separated list of sets of 3 values for each curve point. When queried, returns a string which is the current space being
used.
- seamTolerance : st (float) [create,query,edit]
Set the seam tolerance used for reflection. When preserveSeam is enabled, this tolerance controls the width of the
enforced seam. When queried, returns a float of the seamTolerance.
- symmetry : s (int) [create,query,edit]
Set the symmetry option on or off. When queried, returns an int for the option.
- tolerance : t (float) [create,query,edit]
Set the tolerance of reflection. When queried, returns a float of the tolerance.
- topoSymmetry : ts (bool) [create,query,edit]
Enable/disable topological symmetry. When enabled, the supplied component/active list will be used to define the
topological symmetry seam. When queried, returns the name of the active topological symmetry object.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.symmetricModelling`
"""
pass
def editDisplayLayerGlobals(*args, **kwargs):
"""
Edit the parameter values common to all display layers. Some of these paremeters, eg. baseId and mergeType, are stored
as preferences and some, eg. currentDisplayLayer, are stored in the file.
Flags:
- baseId : bi (int) [create,query]
Set base layer ID. This is the number at which new layers start searching for a unique ID.
- currentDisplayLayer : cdl (PyNode) [create,query]
Set current display layer; ie. the one that all new objects are added to.
- mergeType : mt (int) [create,query]
Set file import merge type. Valid values are 0, none, 1, by number, and 2, by name.
- useCurrent : uc (bool) [create,query]
Set whether or not to enable usage of the current display layer as the destination for all new nodes.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.editDisplayLayerGlobals`
"""
pass
def curveRGBColor(*args, **kwargs):
"""
This command creates, changes or removes custom curve colors, which are used to draw the curves in the Graph Editor. The
custom curve names may contain the wildcards ?, which marches a single character, and \*, which matches any number of
characters. These colors are part of the UI and not part of the saved data for a model. This command is not undoable.
Flags:
- hueSaturationValue : hsv (bool) [create,query]
Indicates that rgb values are really hsv values.
- list : l (bool) [create]
Writes out a list of all curve color names and their values.
- listNames : ln (bool) [create]
Returns an array of all curve color names.
- remove : r (bool) [create]
Removes the named curve color.
- resetToFactory : rf (bool) [create]
Resets all the curve colors to their factory defaults.
- resetToSaved : rs (bool) [create]
Resets all the curve colors to their saved values. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.curveRGBColor`
"""
pass
def createNode(*args, **kwargs):
"""
This command creates a new node in the dependency graph of the specified type.
Flags:
- name : n (unicode) [create]
Sets the name of the newly-created node. If it contains namespace path, the new node will be created under the specified
namespace; if the namespace doesn't exist, we will create the namespace.
- parent : p (unicode) [create]
Specifies the parent in the DAG under which the new node belongs.
- shared : s (bool) [create]
This node is shared across multiple files, so only create it if it does not already exist.
- skipSelect : ss (bool) [create]
This node is not to be selected after creation, the original selection will be preserved. Flag can have
multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.createNode`
"""
pass
def toggleAxis(*args, **kwargs):
"""
Toggles the state of the display axis. Note: the display of the axis in the bottom left corner has been rendered
obsolete by the headsUpDisplay command.
Flags:
- origin : o (bool) [create,query]
Turns display of the axis at the origin of the ground plane on or off.
- view : v (bool) [create,query]
Turns display of the axis at the bottom left of each view on or off. (Obsolete - refer to the headsUpDisplay command)
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.toggleAxis`
"""
pass
def hide(*args, **kwargs):
"""
The hidecommand is used to make objects invisible. If no flags are used, the objects specified, or the active objects if
none are specified, will be made invisible.
Flags:
- allObjects : all (bool) [create]
Make everything invisible (top level objects).
- clearLastHidden : clh (bool) []
- clearSelection : cs (bool) [create]
Clear selection after the operation.
- invertComponents : ic (bool) [create]
Hide components that are not specified.
- returnHidden : rh (bool) [create]
Hide objects, but also return list of hidden objects.
- testVisibility : tv (bool) [create]
Do not change visibility, just test it (returns 1 is invisible, 2 if visible, 3 if partially visible).
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.hide`
"""
pass
def hilite(*args, **kwargs):
"""
Hilites/Unhilites the specified object(s). Hiliting an object makes it possible to select the components of the object.
If no objects are specified then the selection list is used.
Flags:
- replace : r (bool) [create]
Hilite the specified objects. Any objects previously hilited will no longer be hilited.
- toggle : tgl (bool) [create]
Toggle the hilite state of the specified objects.
- unHilite : u (bool) [create]
Remove the specified objects from the hilite list. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.hilite`
"""
pass
def attributeQuery(*args, **kwargs):
"""
attributeQuery returns information about the configuration of an attribute. It handles both boolean flags, returning
true or false, as well as other return values. Specifying more than one boolean flag will return the logical andof all
the specified boolean flags. You may not specify any two flags when both do not provide a boolean return type. (eg.
-internal -hiddenis okay but -range -hiddenor -range -softRangeis not.)
Flags:
- affectsAppearance : aa (bool) [create]
Return true if the attribute affects the appearance of the node
- affectsWorldspace : aws (bool) [create]
Return the status of the attribute flag marking attributes affecting worldspace
- attributeType : at (bool) [create]
Return the name of the attribute type (will be the same type names as described in the addAttr and addExtension
commands).
- cachedInternally : ci (bool) [create]
Return whether the attribute is cached within the node as well as in the datablock
- categories : ct (bool) [create]
Return the categories to which the attribute belongs or an empty list if it does not belong to any.
- channelBox : ch (bool) [create]
Return whether the attribute should show up in the channelBox or not
- connectable : c (bool) [create]
Return the connectable status of the attribute
- enum : e (bool) [create]
Return true if the attribute is a enum attribute
- exists : ex (bool) [create]
Return true if the attribute exists
- hidden : h (bool) [create]
Return the hidden status of the attribute
- indeterminant : idt (bool) [create]
Return true if this attribute might be used in evaluation but it's not known for sure until evaluation time
- indexMatters : im (bool) [create]
Return the indexMatters status of the attribute
- internal : i (bool) [create]
Return true if the attribute is either internalSet or internalGet
- internalGet : ig (bool) [create]
Return true if the attribute come from getCachedValue
- internalSet : internalSet (bool) [create]
Return true if the attribute must be set through setCachedValue
- keyable : k (bool) [create]
Return the keyable status of the attribute
- listChildren : lc (bool) [create]
Return the list of children attributes of the given attribute.
- listDefault : ld (bool) [create]
Return the default values of numeric and compound numeric attributes.
- listEnum : le (bool) [create]
Return the list of enum strings for the given attribute.
- listParent : lp (bool) [create]
Return the parent of the given attribute.
- listSiblings : ls (bool) [create]
Return the list of sibling attributes of the given attribute.
- longName : ln (bool) [create]
Return the long name of the attribute.
- maxExists : mxe (bool) [create]
Return true if the attribute has a hard maximum. A min does not have to be present.
- maximum : max (bool) [create]
Return the hard maximum of the attribute's value
- message : msg (bool) [create]
Return true if the attribute is a message attribute
- minExists : mne (bool) [create]
Return true if the attribute has a hard minimum. A max does not have to be present.
- minimum : min (bool) [create]
Return the hard minimum of the attribute's value
- multi : m (bool) [create]
Return true if the attribute is a multi-attribute
- niceName : nn (bool) [create]
Return the nice name (or UI name) of the attribute.
- node : n (PyNode) [create]
Use all attributes from node named NAME
- numberOfChildren : nc (bool) [create]
Return the number of children the attribute has
- range : r (bool) [create]
Return the hard range of the attribute's value
- rangeExists : re (bool) [create]
Return true if the attribute has a hard range. Both min and max must be present.
- readable : rd (bool) [create]
Return the readable status of the attribute
- renderSource : rs (bool) [create]
Return whether this attribute is marked as a render source or not
- shortName : sn (bool) [create]
Return the short name of the attribute.
- softMax : smx (bool) [create]
Return the soft max (slider range) of the attribute's value
- softMaxExists : sxe (bool) [create]
Return true if the attribute has a soft maximum. A min does not have to be present.
- softMin : smn (bool) [create]
Return the soft min (slider range) of the attribute's value
- softMinExists : sme (bool) [create]
Return true if the attribute has a soft minimum. A max does not have to be present.
- softRange : s (bool) [create]
Return the soft range (slider range) of the attribute's value
- softRangeExists : se (bool) [create]
Return true if the attribute has a soft range. Both min and max must be present.
- storable : st (bool) [create]
Return true if the attribute is storable
- type : typ (unicode) [create]
Use static attributes from nodes of type TYPE. Includes attributes inherited from parent class nodes.
- typeExact : tex (unicode) [create]
Use static attributes only from nodes of type TYPE. Does not included inherited attributes.
- usedAsColor : uac (bool) [create]
Return true if the attribute should bring up a color picker
- usedAsFilename : uaf (bool) [create]
Return true if the attribute should bring up a file browser
- usesMultiBuilder : umb (bool) [create]
Return true if the attribute is a multi-attribute and it uses the multi-builder to handle its data
- worldspace : ws (bool) [create]
Return the status of the attribute flag marking worldspace attribute
- writable : w (bool) [create]
Return the writable status of the attribute Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.attributeQuery`
"""
pass
def toggle(*args, **kwargs):
"""
The toggle command is used to toggle the display of various object features for objects which have these components. For
example, CV and edit point display may be toggled for those listed NURB curves or surfaces. Note: This command is
not undoable.
Flags:
- above : a (bool) [create]
Toggle state for all objects above listed objects.
- below : b (bool) [create]
Toggle state for all objects below listed objects.
- boundary : bn (bool) [create,query]
Toggle boundary display of listed mesh objects.
- boundingBox : box (bool) [create,query]
Toggle or query the bounding box display of listed objects.
- controlVertex : cv (bool) [create,query]
Toggle CV display of listed curves and surfaces.
- doNotWrite : dnw (bool) [create,query]
Toggle the this should be written to the filestate.
- editPoint : ep (bool) [create,query]
Toggle edit point display of listed curves and surfaces.
- extent : et (bool) [create,query]
Toggle display of extents of listed mesh objects.
- facet : f (bool) [create,query]
For use with normalflag. Set the normal display style to facet display.
- geometry : g (bool) [create,query]
Toggle geometry display of listed objects.
- gl : gl (bool) [create]
Toggle state for all objects
- highPrecisionNurbs : hpn (bool) [create,query]
Toggle high precision display for Nurbs
- hull : hl (bool) [create,query]
Toggle hull display of listed curves and surfaces.
- latticePoint : lp (bool) [create,query]
Toggle point display of listed lattices
- latticeShape : ls (bool) [create,query]
Toggle display of listed lattices
- localAxis : la (bool) [create,query]
Toggle local axis display of listed objects.
- newCurve : nc (bool) [create,query]
Set component display state of new curve objects
- newPolymesh : np (bool) [create,query]
Set component display state of new polymesh objects
- newSurface : ns (bool) [create,query]
Set component display state of new surface objects
- normal : nr (bool) [create,query]
Toggle display of normals of listed surface and mesh objects.
- origin : o (bool) [create,query]
Toggle origin display of listed surfaces.
- point : pt (bool) [create,query]
For use with normal flag. Set the normal display style to vertex display.
- pointDisplay : pd (bool) [create,query]
Toggle point display of listed surfaces.
- pointFacet : pf (bool) [create,query]
For use with normalflag. Set the normal display style to vertex and face display.
- rotatePivot : rp (bool) [create,query]
Toggle rotate pivot display of listed objects.
- scalePivot : sp (bool) [create,query]
Toggle scale pivot display of listed objects.
- selectHandle : sh (bool) [create,query]
Toggle select handle display of listed objects.
- state : st (bool) [create]
Explicitly set the state to true or false instead of toggling the state. Can not be queried.
- surfaceFace : sf (bool) [create,query]
Toggle surface face handle display of listed surfaces.
- template : te (bool) [create,query]
Toggle template state of listed objects
- uvCoords : uv (bool) [create,query]
Toggle display uv coords of listed mesh objects.
- vertex : vt (bool) [create,query]
Toggle vertex display of listed mesh objects. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.toggle`
"""
pass
def threadCount(*args, **kwargs):
"""
This command sets the number of threads to be used by Maya in regions of code that are multithreaded. By default the
number of threads is equal to the number of logical CPUs, not the number of physical CPUs. Logical CPUs are different
from physical CPUs in the following ways:A physical CPU with hyperthreading counts as two logical CPUsA dual-core CPU
counts as two logical CPUsWith some workloads, using one thread per logical CPU may not perform well. This is sometimes
the case with hyperthreading. It is worth experimenting with different numbers of threads to see which gives the best
performance. Note that having more threads can mean Maya uses more memory. Setting a value of zero means the number of
threads used will equal the number of logical processors in the system. In query mode, return type is based on queried
flag.
Flags:
- numberOfThreads : n (int) [create,query]
Sets the number of threads to use Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.threadCount`
"""
pass
def shapeCompare(*args, **kwargs):
"""
Compares two shapes. If no shapes are specified in the command line, then the shapes from the active list are used.
Derived from mel command `maya.cmds.shapeCompare`
"""
pass
def _MPlugOut(self, x):
pass
def containerTemplate(*args, **kwargs):
"""
A container template is a description of a container's published interface. This command provides the ability to create
and save a template file for a container or load an existing template file. Once a template exists, the user can query
the template information. In query mode, return type is based on queried flag.
Flags:
- addBindingSet : abs (unicode) [create,edit]
This argument is used to add a new binding set with the given name to a template. A default binding set will be created.
If the binding set already exists, the force flag must be used to replace the existing binding set. When used with the
fromContainer option, default bindings will be entered based on the current bindings of the designated container. When
used without a reference container, the binding set will be made with placeholder entries. The template must be saved
before the new binding set is permanently stored with the template file.
- addNames : an (bool) [edit]
In edit mode, when used with the fromContainer flag, any published name on the container not present as an attribute on
the template will be added to the template.
- addView : av (unicode) [create,edit]
This argument is used to add a new view with the given name to a template. By default a view containing a flat list of
all template attributes will be created. The layoutMode flag provides more layout options. The template must be saved
before the new view is permanently stored with the template file.
- allKeyable : ak (bool) [create,edit]
Used when the fromSelection flag is true and fromContainer is false. If true we will use all keyable attributes to
define the template or the view, if false we use the attributes passed in with the attribute flag.
- attribute : at (unicode) [create,edit]
If fromSelection is true and allKeyable is false, this attribute name will be used to create an attribute item in the
template file.
- attributeList : al (unicode) [create,query,edit]
Used in query mode, returns a list of attributes contained in the template definition.
- baseName : bn (unicode) [create,query]
Used in query mode, returns the base name of the template. The basename is the template name with any package qualifiers
stripped off.
- bindingSetList : bsl (unicode) [create,query]
Used in query mode, returns a list of all binding sets defined on the template.
- childAnchor : can (bool) [create,query]
This flag can be optionally specified when querying the publishedNodeList. The resulting list will contain only
childAnchor published nodes.
- delete : d (bool) [create]
Delete the specified template and its file. All objects that are associated with this template or contained in the same
template file will be deleted. To simply unload a template without permanently deleting its file, use unload instead.
- exists : ex (bool) [query]
Returns true or false depending upon whether the specified template exists. When used with the matchFile argument, the
query will return true if the template exists and the filename it was loaded from matches the filename given.
- expandCompounds : ec (bool) [create,edit]
This argument is used to determine how compound parent attributes and their children will be added to generated views
when both are published to the container. When true, the compound parent and all compound child attributes published to
the container will be included in the view. When false, only the parent attribute is included in the view. Note: if only
the child attributes are published and not the parent, the children will be included in the view, this flag is only used
in the situation where both parent and child attributes are published to the container. The default value is false.
- fileName : fn (unicode) [create,query]
Specifies the filename associated with the template. This argument can be used in conjunction with load, save or query
modes. If no filename is associated with a template, a default file name based on the template name will be used. It is
recommended but not required that the filename and template name correspond.
- force : f (bool) [create]
This flag is used with some actions to allow them to proceed with an overwrite or destructive operation. When used with
load, it will allow an existing template to be reloaded from a file. When used in create mode, it will allow an
existing template to be recreated (for example when using fromContainer argument to regenerate a template).
- fromContainer : fc (unicode) [create]
This argument is used in create or edit mode to specify a container node to be used for generating the template
contents. In template creation mode, the template definition will be created based on the list of published attributes
in the specified container. In edit mode, when used with the addNames flag or with no other flag, any published name on
the container not present as an attribute on the template will be added to the template. This flag is also used in
conjunction with flags such as addView.
- fromSelection : fs (bool) [create,edit]
If true, we will use the active selection list to create the template or the view. If allKeyable is also true then we
will create the template from all keyable attributes in the selection, otherwise we will create the template using the
attributes specified with the attribute flag.
- layoutMode : lm (int) [create]
This argument is used to specify the layout mode when creating a view. Values correspond as follows: 0: layout in flat
list (default when not creating view from container) 1: layout grouped by node (default if creating view from container)
The fromContainer or fromSelection argument is required to provide the reference container or selection for layout modes
that require node information. Note that views can only refer to defined template attributes. This means that when
using the fromContainer or from Selection flag to add a view to an existing template, only attributes that are defined
on both the template and the container or the current selection will be included in the view (i.e. published attributes
on the container that are not defined in the template will be ignored).
- load : l (bool) []
Load an existing template from a file. If a filename is specified for the template, the entire file (and all templates
in it) will be loaded. If no file is specified, a default filename will be assumed, based on the template name.
- matchFile : mf (unicode) [query]
Used in query mode in conjunction with other flags this flag specifies an optional file name that is to be matched as
part of the query operation.
- matchName : mn (unicode) [query]
Used in query mode in conjunction with other flags this flag specifies an optional template name that is to be matched
as part of the query operation. The base template name is used for matching, any template with the same basename will be
matched even across different packages.
- parentAnchor : pan (bool) [create,query]
This flag can be optionally specified when querying the publishedNodeList. The resulting list will contain only
parentAnchor published nodes.
- publishedNodeList : pnl (unicode) [create,query,edit]
Used in query mode, returns a list of published nodes contained in the template definition. By default all published
nodes on the template will be returned. The list of published nodes can be limited to only include certain types of
published nodes using one of the childAnchor, parentAnchor or rootTransform flags. If an optional flag is are specified,
only nodes of the specified type will be returned.
- removeBindingSet : rbs (unicode) [create,edit]
This argument is used to remove the named binding set from the template. The template must be saved before the binding
set is permanently removed from the template file.
- removeView : rv (unicode) [create,edit]
This argument is used to remove the named view from the template. The template must be saved before the view is
permanently removed from the template file.
- rootTransform : rtn (bool) [create,query]
This flag can be optionally specified when querying the publishedNodeList. The resulting list will contain only
rootTransform published nodes.
- save : s (bool) [create]
Save the specified template to a file. If a filename is specified for the template, the entire file (and all templates
associated with it) will be saved. If no file name is specified, a default filename will be assumed, based on the
template name.
- searchPath : sp (unicode) [query,edit]
The template searchPath is an ordered list of all locations that are being searched to locate template files (first
location searched to last location searched). The template search path setting is stored in the current workspace and
can also be set and queried as the file rule entry for 'templates' (see the workspace command for more information). In
edit mode, this flag allows the search path setting to be customized. When setting the search path value, the list
should conform to a path list format expected on the current platform. This means that paths should be separated by a
semicolon (;) on Windows and a colon (:) on Linux and MacOSX. Environment variables can also be used. Additional built-
in paths may be added automatically by maya to the customized settings. In query mode, this flag returns the current
contents of the search path; all paths, both customized and built-in, will be included in the query return value.
- silent : si (bool) [create,query,edit]
Silent mode will suppress any error or warning messages that would normally be reported from the command execution. The
return values are unaffected.
- templateList : tl (unicode) [query]
Used in query mode, returns a list of all loaded templates. This query can be used with optional matchFile and matchName
flags. When used with the matchFile flag, the list of templates will be restricted to those associated with the
specified file. When used with the matchName flag, the list of templates will be restricted to those matching the
specified template name.
- unload : u (bool) [create]
Unload the specified template. This action will not delete the associated template file if one exists, it merely
removes the template definition from the current session.
- updateBindingSet : ubs (unicode) [create,edit]
This argument is used to update an existing binding set with new bindings. When used with the fromContainer argument
binding set entries with be replaced or merged in the binding set based on the bindings of the designated container. If
the force flag is used, existing entries in the binding set are replaced with new values. When force is not used, only
new entries are merged into the binding set, any existing entries will be left as-is. When used without a reference
container, the binding set will be updated with placeholder entries. The template must be saved before the new binding
set is permanently stored with the template file.
- useHierarchy : uh (bool) [create,edit]
If true, and the fromSelection flag is set, the selection list will expand to include it's hierarchy also.
- viewList : vl (unicode) [create,query]
Used in query mode, returns a list of all views defined on the template. Flag can have
multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.containerTemplate`
"""
pass
def createAttrPatterns(*args, **kwargs):
"""
Create a new instance of an attribute pattern given a pattern type (e.g. XML) and a string or data file containing the
description of the attribute tree in the pattern's format.
Flags:
- patternDefinition : pd (unicode) [create]
Hardcoded string containing the pattern definition, for simpler formats that don't really need a separate file for
definition.
- patternFile : pf (unicode) [create]
File where the pattern information can be found
- patternType : pt (unicode) [create]
Name of the pattern definition type to use in creating this instance of the pattern. Flag
can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.createAttrPatterns`
"""
pass
def _toEnumStr(enums):
pass
def distanceDimension(*args, **kwargs):
"""
This command is used to create a distance dimension to display the distance between two specified points.
Modifications:
- returns a PyNode object
Flags:
- endPoint : ep (float, float, float) [create]
Specifies the point to measure distance to, from the startPoint.
- startPoint : sp (float, float, float) [create]
Specifies the point to start measuring distance from. Flag can have multiple arguments, passed either
as a tuple or a list.
Derived from mel command `maya.cmds.distanceDimension`
"""
pass
def commandLogging(*args, **kwargs):
"""
This command controls logging of Maya commands, in memory and on disk. Note that if commands are logged in memory, they
will be available to the crash reporter and appear in crash logs. In query mode, return type is based on
queried flag.
Flags:
- historySize : hs (int) [create,query]
Sets the number of entries in the in-memory command history.
- logCommands : lc (bool) [create,query]
Enables or disables the on-disk logging of commands.
- logFile : lf (unicode) [create,query]
Sets the filename to use for the on-disk log. If logging is active, the current file will be closed before the new one
is opened.
- recordCommands : rc (bool) [create,query]
Enables or disables the in-memory logging of commands.
- resetLogFile : rl (bool) [create,query]
Reset the log filename to the default ('mayaCommandLog.txt' in the application folder, alongside 'Maya.env' and the
default projects folder). Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.commandLogging`
"""
pass
def instanceable(*args, **kwargs):
"""
Flags one or more DAG nodes so that they can (or cannot) be instanced. This command sets an internal state on the
specified DAG nodes which is checked whenever Maya attempts an instancing operation. If no node names are provided on
the command line then the current selection list is used. Sets are automatically expanded to their constituent objects.
Nodes which are already instanced (or have children which are already instanced) cannot be marked as non-instancable.
Flags:
- allow : a (bool) [create,query]
Specifies the new instanceable state for the node. Specify true to allow the node to be instanceable, and false to
prevent it from being instanced. The default is true (i.e. nodes can be instanced by default).
- recursive : r (bool) [create]
Can be specified with the -allow flag in create or edit mode to recursively apply the -allow setting to all non-shape
children of the selected node(s). To also affect shapes, also specify the -shape flag along with -recursive.
- shape : s (bool) [create]
Can be specified with the -allow flag in create or edit mode to apply the -allow setting to all shape children of the
selected node(s). This flag can be specified in conjunction with the -recursive flag.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.instanceable`
"""
pass
def makePaintable(*args, **kwargs):
"""
Make attributes of nodes paintable to Attribute Paint Tool. This command is used to register new attributes to the
Attribute Paint tool as paintable. Once registered the attributes will be recognized by the Attribute Paint tool and the
user will be able to paint them. In query mode, return type is based on queried flag.
Flags:
- activate : ac (bool) [create,query]
Activate / deactivate the given paintable attribute. Used to filter out some nodes in the attribute paint tool.
- activateAll : aca (bool) [create,query]
Activate / deactivate all the registered paintable attributes. Used to filter out some nodes in the attribute paint
tool.
- altAttribute : aa (unicode) [create,query]
Define an alternate attribute which will also receive the same values. There can be multiple such flags.
- attrType : at (unicode) [create,query]
Paintable attribute type. Supported types: intArray, doubleArray, vectorArray, multiInteger, multiFloat, multiDouble,
multiVector.
- clearAll : ca (bool) [create,query]
Removes all paintable attribute definitions.
- remove : rm (bool) [create,query]
Make the attribute not paintable any more.
- shapeMode : sm (unicode) [create,query]
This flag controls how Artisan correlates the paintable node to a corresponding shape node. It is used for attributes
of type multi of multi, where the first multi dimension corresponds to the shape index (i.e. cluster nodes). At present,
only one value of this flag is supported: deformer. By default this flag is an empty string, which means that there is a
direct indexing (no special mapping required) of the attribute with respect to vertices on the shape.
- uiName : ui (unicode) [create,query]
UI name. Default is the attribute name. Flag can have multiple arguments, passed
either as a tuple or a list.
Derived from mel command `maya.cmds.makePaintable`
"""
pass
def objExists(*args, **kwargs):
"""
This command simply returns true or false depending on whether an object with the given name exists.
Derived from mel command `maya.cmds.objExists`
"""
pass
def colorManagementCatalog(*args, **kwargs):
"""
This non-undoable action performs additions and removals of custom color transforms from the Autodesk native color
transform catalog. Once a custom color transform has been added to the catalog, it can be used in the same way as the
builtin Autodesk native color transforms.
Flags:
- addTransform : adt (unicode) [create]
Add transform to collection.
- editUserTransformPath : eut (unicode) [create]
Edit the user transform directory. By changing the directory, all custom transforms currently added could be changed,
and new ones could appear.
- listSupportedExtensions : lse (bool) [create]
List the file extensions that are supported by add transform. This list is valid for all transform types, and therefore
this flag does not require use of the type flag.
- listTransformConnections : ltc (bool) [create]
List the transforms that can be used as source (for viewand outputtypes) or destination (for inputand rendering
spacetypes) to connect a custom transform to the rest of the transform collection.
- path : pth (unicode) [create]
In addTransform mode, the path to the transform data file.
- queryUserTransformPath : qut (bool) [create]
Query the user transform directory.
- removeTransform : rmt (unicode) [create]
Remove transform from collection.
- transformConnection : tcn (unicode) [create]
In addTransform mode, an existing transform to which the added transform will be connected. For an input transform or
rendering space transform, this will be a destination. For a view or output transform, this will be a source.
- type : typ (unicode) [create]
The type of transform added, removed, or whose transform connections are to be listed. Must be one of view, rendering
space, input, or output. Flag can have multiple arguments, passed either as a tuple or a
list.
Derived from mel command `maya.cmds.colorManagementCatalog`
"""
pass
def reorderContainer(*args, **kwargs):
"""
This command reorders (moves) objects relative to their siblings in a container. For relative moves, both positive and
negative numbers may be specified. Positive numbers move the object forward and negative numbers move the object
backward amoung its siblings. When an object is at the end (beginning) of the list of siblings, a relative move of 1
(-1) will put the object at the beginning (end) of the list of siblings. That is, relative moves will wrap if
necessary. Only nodes within one container can be moved at a time. Note: The container command's -nodeList flag will
return a sorted list of contained nodes. To see the effects of reordering, use the -unsortedOrder flag in conjunction
with the -nodeList flag. In query mode, return type is based on queried flag.
Flags:
- back : b (bool) [create,query,edit]
Move object(s) to back of container contents list
- front : f (bool) [create,query,edit]
Move object(s) to front of container contents list
- relative : r (int) [create,query,edit]
Move object(s) relative to other container contents Flag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.reorderContainer`
"""
pass
def stringArrayIntersector(*args, **kwargs):
"""
The stringArrayIntersector command creates and edits an object which is able to efficiently intersect large string
arrays. The intersector object maintains a sense of the intersection so far, and updates the intersection when new
string arrays are provided using the -i/intersect flag. Note that the string intersector object may be deleted using the
deleteUI command.
Flags:
- allowDuplicates : ad (bool) [create]
Should the intersector allow duplicates in the input arrays (true), or combine all duplicate entries into a single,
unique entry (false). This flag must be used when initially creating the intersector. Default is 'false'.
- defineTemplate : dt (unicode) [create]
Puts the command in a mode where any other flags and args are parsed and added to the command template specified in the
argument. They will be used as default arguments in any subsequent invocations of the command when templateName is set
as the current template.
- exists : ex (bool) [create]
Returns whether the specified object exists or not. Other flags are ignored.
- intersect : i (<type 'unicode'>, ...) [create,edit]
Intersect the specified string array with the current intersection being maintained by the intersector.
- reset : r (bool) [edit]
Reset the intersector to begin a new intersection.
- useTemplate : ut (unicode) [create]
Forces the command to use a command template other than the current one. Flag can have multiple
arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.stringArrayIntersector`
"""
pass
def saveToolSettings(*args, **kwargs):
"""
This command causes all the tools not on the shelf to save their settings as optionVars. This is called automatically
by the system when Maya exits.
Derived from mel command `maya.cmds.saveToolSettings`
"""
pass
def delete(*args, **kwargs):
"""
This command is used to delete selected objects, or all objects, or objects specified along with the command. Flags are
available to filter the type of objects that the command acts on. At times, more than just specified items will be
deleted. For example, deleting two CVs in the same rowon a NURBS surface will delete the whole row.
Modifications:
- the command will not fail on an empty list
Flags:
- all : all (bool) [create]
Remove all objects of specified kind, in the scene. This flag is to be used in conjunction with the following flags.
- attribute : at (unicode) [create]
List of attributes to select
- channels : c (bool) [create]
Remove animation channels in the scene. Either all channels can be removed, or the scope can be narrowed down by
specifying some of the above mentioned options.
- constraints : cn (bool) [create]
Remove selected constraints and constraints attached to the selected nodes, or remove all constraints in the scene.
- constructionHistory : ch (bool) [create]
Remove the construction history on the objects specified or selected.
- controlPoints : cp (bool) [create]
This flag explicitly specifies whether or not to include the control points of a shape (see -sflag) in the list of
attributes. Default: false. (Not valid for pasteKeycmd.)
- expressions : e (bool) [create]
Remove expressions in the scene. Either all expressions can be removed, or the scope can be narrowed down by specifying
some of the above mentioned options.
- hierarchy : hi (unicode) [create]
Hierarchy expansion options. Valid values are above,below,both,and none.(Not valid for pasteKeycmd.)
- inputConnectionsAndNodes : icn (bool) [create]
Break input connection to specified attribute and delete all unconnected nodes that are left behind. The graph will be
traversed until a node that cannot be deleted is encountered.
- motionPaths : mp (bool) []
- shape : s (bool) [create]
Consider attributes of shapes below transforms as well, except controlPoints. Default: true. (Not valid for
pasteKeycmd.)
- staticChannels : sc (bool) [create]
Remove static animation channels in the scene. Either all static channels can be removed, or the scope can be narrowed
down by specifying some of the above mentioned options.
- timeAnimationCurves : tac (bool) [create]
Modifies the -c/channels and -sc/staticChannels flags. When true, only channels connected to time-input animation curves
(for instance, those created by 'setKeyframe' will be deleted. When false, no time-input animation curves will be
deleted. Default: true.
- unitlessAnimationCurves : uac (bool) [create]
Modifies the -c/channels and -sc/staticChannels flags. When true, only channels connected to unitless-input animation
curves (for instance, those created by 'setDrivenKeyframe' will be deleted. When false, no unitless-input animation
curves will be deleted. Default: true. Flag can have multiple arguments, passed either as a tuple or a
list.
Derived from mel command `maya.cmds.delete`
"""
pass
def deleteAttrPattern(*args, **kwargs):
"""
After a while the list of attribute patterns could become cluttered. This command provides a way to remove patterns from
memory so that only the ones of interest will show.
Flags:
- allPatterns : all (bool) [create]
If specified it means delete all known attribute patterns.
- patternName : pn (unicode) [create]
The name of the pattern to be deleted.
- patternType : pt (unicode) [create]
Delete all patterns of the given type. Flag can have multiple arguments, passed either as a
tuple or a list.
Derived from mel command `maya.cmds.deleteAttrPattern`
"""
pass
def group(*args, **kwargs):
"""
This command groups the specified objects under a new group and returns the name of the new group. If the -em flag is
specified, then an empty group (with no objects) is created. If the -w flag is specified then the new group is placed
under the world, otherwise if -p is specified it is placed under the specified node. If neither -w or -p is specified
the new group is placed under the lowest common group they have in common. (or the world if no such group exists) If an
object is grouped with another object that has the same name then one of the objects will be renamed by this command.
Modifications
- if no objects are passed or selected, the empty flag is automatically set
Maya Bug Fix:
- corrected to return a unique name
Flags:
- absolute : a (bool) [create]
preserve existing world object transformations (overall object transformation is preserved by modifying the objects
local transformation) [default]
- empty : em (bool) [create]
create an empty group (with no objects in it)
- name : n (unicode) [create]
Assign given name to new group node.
- parent : p (unicode) [create]
put the new group under the given parent
- relative : r (bool) [create]
preserve existing local object transformations (relative to the new group node)
- useAsGroup : uag (unicode) [create]
Use the specified node as the group node. The specified node must be derived from the transform node and must not have
any existing parents or children.
- world : w (bool) [create]
put the new group under the world Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.group`
"""
pass
def rename(obj, newname, **kwargs):
"""
Renames the given object to have the new name. If only one argument is supplied the command will rename the (first)
selected object. If the new name conflicts with an existing name, the object will be given a unique name based on the
supplied name. It is not legal to rename an object to the empty string. When a transform is renamed then any shape nodes
beneath the transform that have the same prefix as the old transform name are renamed. For example, rename nurbsSphere1
ballwould rename nurbsSphere1|nurbsSphereShape1to ball|ballShape. If the new name ends in a single '#' then the rename
command will replace the trailing '#' with a number that ensures the new name is unique.
Modifications:
- if the full path to an object is passed as the new name, the shortname of the object will automatically be used
Flags:
- ignoreShape : ignoreShape (bool) [create]
Indicates that renaming of shape nodes below transform nodes should be prevented.
- uuid : uid (bool) [create]
Indicates that the new name is actually a UUID, and that the command should change the node's UUID. (In which case its
name remains unchanged.) Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.rename`
"""
pass
def colorIndex(*args, **kwargs):
"""
The index specifies a color index in the color palette. The r, g, and b values (between 0-1) specify the RGB values (or
the HSV values if the -hsv flag is used) for the color.
Flags:
- hueSaturationValue : hsv (bool) [create,query]
Indicates that rgb values are really hsv values. Upon query, returns the HSV valuses as an array of 3 floats.
- resetToFactory : rf (bool) [create]
Resets all color index palette entries to their factory defaults.
- resetToSaved : rs (bool) [create]
Resets all color palette entries to their saved values. Flag can have multiple arguments, passed either
as a tuple or a list.
Derived from mel command `maya.cmds.colorIndex`
"""
pass
def _formatSlice(sliceObj):
pass
def itemFilterAttr(*args, **kwargs):
"""
This command creates a named itemFilterAttr object. This object can be attached to editors, in order to filter the
attributes going through them. Using union and intersection filters, complex composite filters can be created.
Flags:
- byName : bn (unicode) [create,query,edit]
The filter will only pass items whose names match the given regular expression string. This string can contain the
special characters \* and ?. '?' matches any one character, and '\*' matches any substring. This flag cannot be used in
conjunction with the -byScript or -secondScript flags.
- byNameString : bns (unicode) [create,query,edit]
The filter will only pass items whose names match the given string. This is a multi-use flag which allows the user to
specify several strings. The filter will pass items that match any of the strings. This flag cannot be used in
conjunction with the -byScript or -secondScript flags.
- byScript : bs (unicode) [create,query,edit]
The filter will run a MEL script named by the given string on each attribute name. Attributes will pass the filter if
the script returns a non-zero value. The script name string must be the name of a proc whose signature is:global proc
int procName( string $nodeName string $attrName )This flag cannot be used in conjunction with the -byName or
-byNameString flags.
- classification : cls (unicode) [create,query,edit]
Indicates whether the filter is a built-in or user filter. The string argument must be either builtInor user. The
otherfilter classification is deprecated. Use userinstead. Filters created by Maya should be classified as builtIn.
Filters created by plugins or user scripts should be classified as user. Filters will not be deleted by a file new.
Filter nodes will be hidden from the UI (ex: Attribute Editor, Hypergraph etc) and will not be accessible from the
command-line.
- dynamic : dy (bool) []
- exists : ex (bool) []
- hasCurve : hc (bool) [create,query,edit]
The filter will only pass attributes that are driven by animation curves.
- hasDrivenKey : hdk (bool) [create,query,edit]
The filter will only pass attributes that are driven by driven keys
- hasExpression : he (bool) [create,query,edit]
The filter will only pass attributes that are driven by expressions
- hidden : h (bool) [create,query,edit]
The filter will only pass attributes that are hidden to the user
- intersect : intersect (unicode, unicode) [create,query,edit]
The filter will consist of the intersection of two other filters, whose names are the given strings. Attributes will
pass this filter if and only if they pass both of the contained filters.
- keyable : k (bool) [create,query,edit]
The filter will only pass attributes that are keyable
- listBuiltInFilters : lbf (bool) [query]
Returns an array of all attribute filters with classification builtIn.
- listOtherFilters : lof (bool) [query]
The otherclassification has been deprecated. Use userinstead. Returns an array of all attribute filters with
classification other.
- listUserFilters : luf (bool) [query]
Returns an array of all attribute filters with classification user.
- negate : neg (bool) [create,query,edit]
This flag can be used to cause the filter to invert itself, and reverse what passes and what fails.
- parent : p (unicode) []
This flag is no longer supported.
- published : pub (bool) [create,query,edit]
The filter will only pass attributes that are published on the container.
- readable : r (bool) [create,query,edit]
The filter will only pass attributes that are readable (outputs)
- scaleRotateTranslate : srt (bool) [create,query,edit]
The filter will show only SRT attributes: scale, rotate, translate and their children
- secondScript : ss (unicode) [create,query,edit]
Can be used in conjunction with the -bs flag. The second script is for filtering whole lists at once, rather than
individually. Its signature must be:global proc string[] procName( string[] $nodeName string[] $attrName )It should
take in a list of attributes, and return a filtered list of attributes. This flag cannot be used in conjunction with the
-byName or -byNameString flags.
- text : t (unicode) [create,query,edit]
Defines an annotation string to be stored with the filter
- union : un (unicode, unicode) [create,query,edit]
The filter will consist of the union of two other filters, whose names are the given strings. Attributes will pass this
filter if they pass at least one of the contained filters.
- writable : w (bool) [create,query,edit]
The filter will only pass attributes that are writable (inputs) Flag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.itemFilterAttr`
"""
pass
def getAttr(attr, default='None', **kwargs):
"""
This command returns the value of the named object's attribute. UI units are used where applicable. Currently, the types
of attributes that can be displayed are: numeric attributesstring attributesmatrix attributesnumeric compound attributes
(whose children are all numeric)vector array attributesdouble array attributesint32 array attributespoint array
attributesdata component list attributesOther data types cannot be retrieved. No result is returned if the attribute
contains no data.
Maya Bug Fix:
- maya pointlessly returned vector results as a tuple wrapped in a list ( ex. '[(1,2,3)]' ). This command unpacks the vector for you.
Modifications:
- casts double3 datatypes to `Vector`
- casts matrix datatypes to `Matrix`
- casts vectorArrays from a flat array of floats to an array of Vectors
- when getting a multi-attr, maya would raise an error, but pymel will return a list of values for the multi-attr
- added a default argument. if the attribute does not exist and this argument is not None, this default value will be returned
- added support for getting message attributes
Flags:
- asString : asString (bool) [create]
This flag is only valid for enum attributes. It allows you to get the attribute values as strings instead of integer
values. Note that the returned string value is dependent on the UI language Maya is running in (about -uiLanguage).
- caching : ca (bool) [create]
Returns whether the attribute is set to be cached internally
- channelBox : cb (bool) [create]
Returns whether the attribute is set to show in the channelBox. Keyable attributes also show in the channel box.
- expandEnvironmentVariables : x (bool) [create]
Expand any environment variable and (tilde characters on UNIX) found in string attributes which are returned.
- keyable : k (bool) [create]
Returns the keyable state of the attribute.
- lock : l (bool) [create]
Returns the lock state of the attribute.
- multiIndices : mi (bool) [create]
If the attribute is a multi, this will return a list containing all of the valid indices for the attribute.
- settable : se (bool) [create]
Returns 1 if this attribute is currently settable by setAttr, 0 otherwise. An attribute is settable if it's not locked
and either not connected, or has only keyframed animation.
- silent : sl (bool) [create]
When evaluating an attribute that is not a numeric or string value, suppress the error message saying that the data
cannot be displayed. The attribute will be evaluated even though its data cannot be displayed. This flag does not
suppress all error messages, only those that are benign.
- size : s (bool) [create]
Returns the size of a multi-attribute array. Returns 1 if non-multi.
- time : t (time) [create]
Evaluate the attribute at the given time instead of the current time.
- type : typ (bool) [create]
Returns the type of data currently in the attribute. Attributes of simple types such as strings and numerics always
contain data, but attributes of complex types (arrays, meshes, etc) may contain no data if none has ever been assigned
to them. When this happens the command will return with no result: not an empty string, but no result at all. Attempting
to directly compare this non-result to another value or use it in an expression will result in an error, but you can
assign it to a variable in which case the variable will be set to the default value for its type (e.g. an empty string
for a string variable, zero for an integer variable, an empty array for an array variable). So to be safe when using
this flag, always assign its result to a string variable, never try to use it directly. Flag can have
multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.getAttr`
"""
pass
def rotate(obj, *args, **kwargs):
"""
The rotate command is used to change the rotation of geometric objects. The rotation values are specified as Euler
angles (rx, ry, rz). The values are interpreted based on the current working unit for Angular measurements. Most often
this is degrees. The default behaviour, when no objects or flags are passed, is to do a absolute rotate on each
currently selected object in the world space.
Modifications:
- allows any iterable object to be passed as first argument::
rotate("pSphere1", [0,1,2])
NOTE: this command also reorders the argument order to be more intuitive, with the object first
Flags:
- absolute : a (bool) [create]
Perform an absolute operation.
- centerPivot : cp (bool) [create]
Let the pivot be the center of the bounding box of all objects
- constrainAlongNormal : xn (bool) [create]
When true, transform constraints are applied along the vertex normal first and only use the closest point when no
intersection is found along the normal.
- deletePriorHistory : dph (bool) [create]
If true then delete the history prior to the current operation.
- euler : eu (bool) [create]
Modifer for -relative flag that specifies rotation values should be added to current XYZ rotation values.
- forceOrderXYZ : fo (bool) [create]
When true, euler rotation value will be understood in XYZ rotation order not per transform node basis.
- objectCenterPivot : ocp (bool) [create]
Let the pivot be the center of the bounding box of each object
- objectSpace : os (bool) [create]
Perform rotation about object-space axis.
- orientAxes : oa (float, float, float) []
- pivot : p (float, float, float) [create]
Define the pivot point for the transformation
- preserveChildPosition : pcp (bool) [create]
When true, transforming an object will apply an opposite transform to its child transform to keep them at the same
world-space position. Default is false.
- preserveGeometryPosition : pgp (bool) [create]
When true, transforming an object will apply an opposite transform to its geometry points to keep them at the same
world-space position. Default is false.
- preserveUV : puv (bool) [create]
When true, UV values on rotated components are projected across the rotation in 3d space. For small edits, this will
freeze the world space texture mapping on the object. When false, the UV values will not change for a selected vertices.
Default is false.
- reflection : rfl (bool) [create]
To move the corresponding symmetric components also.
- reflectionAboutBBox : rab (bool) [create]
Sets the position of the reflection axis at the geometry bounding box
- reflectionAboutOrigin : rao (bool) [create]
Sets the position of the reflection axis at the origin
- reflectionAboutX : rax (bool) [create]
Specifies the X=0 as reflection plane
- reflectionAboutY : ray (bool) [create]
Specifies the Y=0 as reflection plane
- reflectionAboutZ : raz (bool) [create]
Specifies the Z=0 as reflection plane
- reflectionTolerance : rft (float) [create]
Specifies the tolerance to findout the corresponding reflected components
- relative : r (bool) [create]
Perform a operation relative to the object's current position
- rotateX : x (bool) [create]
Rotate in X direction
- rotateXY : xy (bool) [create]
Rotate in X and Y direction
- rotateXYZ : xyz (bool) [create]
Rotate in all directions (default)
- rotateXZ : xz (bool) [create]
Rotate in X and Z direction
- rotateY : y (bool) [create]
Rotate in Y direction
- rotateYZ : yz (bool) [create]
Rotate in Y and Z direction
- rotateZ : z (bool) [create]
Rotate in Z direction
- symNegative : smn (bool) [create]
When set the component transformation is flipped so it is relative to the negative side of the symmetry plane. The
default (no flag) is to transform components relative to the positive side of the symmetry plane.
- translate : t (bool) [create]
When true, the command will modify the node's translate attribute instead of its rotateTranslate attribute, when
rotating around a pivot other than the object's own rotate pivot.
- worldSpace : ws (bool) [create]
Perform rotation about global world-space axis.
- xformConstraint : xc (unicode) [create]
Apply a transform constraint to moving components. none - no constraintsurface - constrain components to the surfaceedge
- constrain components to surface edgeslive - constraint components to the live surfaceFlag can have multiple arguments,
passed either as a tuple or a list.
Derived from mel command `maya.cmds.rotate`
"""
pass
def _pathFromMObj(mObj, fullPath='False'):
"""
Return a unique path to an mObject
"""
pass
def baseView(*args, **kwargs):
"""
A view defines the layout information for the attributes of a particular node type or container. Views can be selected
from a set of built-in views or may be defined on an associated container template. This command queries the view-
related information for a container node or for a given template. The information returned from this command will be
based on the view-related settings in force on the container node at the time of the query (i.e. the container's view
mode, template name, view name attributes), when applicable. In query mode, return type is based on
queried flag.
Flags:
- itemInfo : ii (unicode) [query]
Used in query mode in conjunction with the itemList flag. The command will return a list of information for each item in
the view, the information fields returned for each item are determined by this argument value. The information fields
will be listed in the string array returned. The order in which the keyword is specified will determine the order in
which the data will be returned by the command. One or more of the following keywords, separated by colons ':' are used
to specify the argument value. itemIndex : sequential item number (0-based)itemName : item name (string)itemLabel :
item display label (string)itemDescription : item description field (string)itemLevel : item hierarchy level
(0-n)itemIsGroup : (boolean 0 or 1) indicates whether or not this item is a groupitemIsAttribute : (boolean 0 or 1)
indicates whether or not this item is an attributeitemNumChildren: number of immediate children (groups or attributes)
of this itemitemAttrType : item attribute type (string)itemCallback : item callback field (string)
- itemList : il (bool) [query]
Used in query mode, the command will return a list of information for each item in the view. The viewName flag is used
to select the view to query. The information returned about each item is determined by the itemInfo argument value. For
efficiency, it is best to query all necessary item information at one time (to avoid recomputing the view information on
each call).
- viewDescription : vd (bool) [query]
Used in query mode, returns the description field associated with the selected view. If no description was defined for
this view, the value will be empty.
- viewLabel : vb (bool) [query]
Used in query mode, returns the display label associated with the view. An appropriate label suitable for the user
interface will be returned based on the selected view. Use of the view label is usually more suitable than the view
name for display purposes.
- viewList : vl (bool) [query]
Used in query mode, command will return a list of all views defined for the given target (container or template).
- viewName : vn (unicode) [query]
Used in query mode, specifies the name of the queried view when used in conjunction with a template target. When used in
conjunction with a container target, it requires no string argument, and returns the name of the currently active view
associated with the container; this value may be empty if the current view is not a valid template view or is generated
by one of the built-in views modes. For this reason, the view label is generally more suitable for display purposes. In
query mode, this flag can accept a value.Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.baseView`
"""
pass
def nodeCast(*args, **kwargs):
"""
Given two nodes, a source node of type A and a target node of type B, where type A is either type B or a sub-type of B,
this command will replace the target node with the source node. That is, all node connections, DAG hierarchy and
attribute values on the target node will be removed from the target node and placed on the source node. This operation
will fail if either object is referenced, locked or if the nodes do not share a common sub-type. This operation is
atomic. If the given parameters fail, then the source and target nodes will remain in their initial state prior to
execution of the command. IMPORTANT: the command will currently ignore instance connections and instance objects. It
will also ignore reference nodes.
Flags:
- copyDynamicAttrs : cda (bool) [create]
If the target node contains any dynamic attributes that are not defined on the source node, then create identical
dynamic attricutes on the source node and copy the values and connections from the target node into them.
- disableAPICallbacks : dsa (bool) [create]
add comment
- disableScriptJobCallbacks : dsj (bool) [create]
add comment
- disconnectUnmatchedAttrs : dua (bool) [create]
If the node that is being swapped out has any connections that do not exist on the target node, then indicate if the
connection should be disconnected. By default these connections are not removed because they cannot be restored if the
target node is swapped back with the source node.
- force : f (bool) [create]
Forces the command to do the node cast operation even if the nodes do not share a common base object. When this flag is
specified the command will try to do the best possible attribute matching when swapping the command. It is
notrecommended to use the '-swapValues/sv' flag with this flag.
- swapNames : sn (bool) [create]
Swap the names of the nodes. By default names are not swapped.
- swapValues : sv (bool) [create]
Indicates if the commands should exchange attributes on the common attributes between the two nodes. For example, if
the nodes are the same base type as a transform node, then rotate, scale, translate values would be copied over.
Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.nodeCast`
"""
pass
def _MDagPathIn(x):
pass
CHECK_ATTR_BEFORE_LOCK = False
deprecated_str_methods = []
_logger = None
with_statement = None
SCENE = Scene()
| UTF-8 | Python | false | false | 640,863 | py | 400 | general.py | 391 | 0.603691 | 0.599613 | 0 | 14,197 | 44.140311 | 590 |
martinosspa/warframe-market | 10,995,116,288,519 | 42dad4dd48e4780549bea8662ac59fe423d3071e | 4bd73761f36a9e21b74bafd328a0707d9892cdd5 | /wilib2/wilib2.py | 3eeb94f8fd25807c9c4e9376c114e6d39dd6879a | []
| no_license | https://github.com/martinosspa/warframe-market | 45e8792d0c9524a2e77505605d32a68630fcc74e | 14652758f97c2cd7dcde5eafa6b2dc370aa9084e | refs/heads/master | 2020-03-20T21:26:34.586920 | 2019-11-08T13:57:33 | 2019-11-08T13:57:33 | 137,738,978 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from urllib.request import urlopen, Request
from pprint import pprint
import json
import time
import numpy as np
import aiohttp
import asyncio
import threading
_api_base_url = 'https://api.warframe.market/v1/items'
_drop_url = 'http://drops.warframestat.us'
global _relic_tier0
_relic_tier0 = 'Intact'
_relic_tier1 = 'Exceptional'
_relic_tier2 = 'Flawless'
_relic_tier3 = 'Radiant'
def _filter_order(order):
order.pop('creation_date')
order.pop('id')
order.pop('last_update')
order.pop('visible')
order['user'].pop('avatar')
order['user'].pop('id')
order['user'].pop('last_seen')
order['user'].pop('reputation')
order['user'].pop('reputation_bonus')
return order
def _encode(str):
splitted = str.split(' ')
if len(splitted) == 4 and 'Blueprint' in splitted:
# warframe blueprint, need to remove 'Blueprint' from str
space = ' '
splitted.remove('Blueprint')
str = space.join(splitted)
return str.lower().replace(' ', '_')
def filter_order(orders, _type='sell'):
orders = list(map(_filter_order, orders))
orders = list(filter(lambda order: order['order_type'] == _type , orders))
orders = list(filter(lambda order: order['platform'] == 'pc', orders))
orders = list(filter(lambda order: order['user']['status'] == 'ingame', orders))
return orders
#prices = list(map(lambda order: order['platinum'], orders))
async def fetch_drop_data(session, endpoint):
async with session.get(f'{_drop_url}/data/{endpoint}') as resp:
r = await resp.json()
return r
# GETS MIN BUY PRICE
async def fetch_order_sell_price(session, item_name):
orders = (await fetch_orders(session, item_name))['orders']
#t = threading.Thread(target=filter_order, argBNBs=orders)
#t.start()
orders = filter_order(orders)
prices = list(map(lambda x: x['platinum'], orders))
if len(prices) > 0:
pos = np.argmin(prices)
price = prices[pos]
return {'price' : price,
'customer' : {'name' : orders[pos]['user']['ingame_name'],
'region': orders[pos]['region']}}
else:
pos = None
price = 0
return {'price' : 0,
'customer' : None }
# GETS MAX SELL PRICE
async def fetch_order_buy_price(session, item_name):
orders = (await fetch_orders(session, item_name))['orders']
#t = threading.Thread(target=filter_order, args=orders)
#t.start()
orders = filter_order(orders, _type='buy')
prices = list(map(lambda order: order['platinum'], orders))
pos = np.argmax(prices)
price = prices[pos]
name = orders[pos]['user']['ingame_name']
region = orders[pos]['user']['region']
#pprint(orders)
return {'item_name' : item_name,
'price' : price,
'user_name' : name,
'user_region': region}
async def fetch_info(session, item_name):
async with session.get(f'{_api_base_url}/{item_name}') as response:
json = await response.json()
return json['payload']
async def fetch_stats(session, item_name):
async with session.get(f'{_api_base_url}/{item_name}/statistics') as response:
json = await response.json()
return {'item_name' : item_name,
'stats' : json['payload']}
async def fetch_orders(session, item_name):
async with session.get(f'{_api_base_url}/{item_name}/orders') as response:
json = await response.json()
#print(item_name)
if 'orders' in json['payload']:
return {'item_name' : item_name,
'orders' : json['payload']['orders']}
else:
return None
async def fetch_all_buy_prices(session, item_names):
results = await asyncio.gather(*[asyncio.create_task(fetch_order_buy_price(session, item_name))
for item_name in item_names])
return results
async def fetch_all_sell_prices(session, item_names):
results = await asyncio.gather(*[asyncio.create_task(fetch_order_sell_price(session, item_name))
for item_name in item_names])
return results
async def fetch_all_orders(session, item_names):
results = await asyncio.gather(*[asyncio.create_task(fetch_orders(session, item_name))
for item_name in item_names])
return results
async def fetch_all_stats(session, item_names):
results = await asyncio.gather(*[asyncio.create_task(fetch_stats(session, item_name))
for item_name in item_names])
return results
async def fetch_all_info(session, item_names):
results = await asyncio.gather(*[asyncio.create_task(fetch_info(session, item_name))
for item_name in item_names])
return results
async def get_average_relic_price(session, era, name, tier=_relic_tier0):
resp = await fetch_drop_data(session, f'relics/{era}/{name}.json')
resp = resp['rewards'][tier]
resp = list(filter(lambda item: not item['itemName'] == 'Forma Blueprint', resp))
item_names = [_encode(item['itemName']) for item in resp]
chances = [item['chance'] for item in resp]
l = await fetch_all_sell_prices(session, item_names)
prices = [item['price'] for item in l]
return sum(np.multiply(prices, chances)) / 100
async def load_missions(session, planet_name):
resp = await fetch_drop_data(session, 'missionRewards.json')
return resp['missionRewards'][planet_name]
async def main():
async with aiohttp.ClientSession() as session:
# get all items and parse them into url names
#resp = await session.get(f'{_api_base_url}')
#all_items = await resp.json()
#all_items = all_items['payload']['items']['en']
#items = [item['url_name'] for item in all_items]
#test_item = ['tigris_prime_set']
#htmls = await fetch_all_orders(session, test_item)
test = await get_average_relic_price(session, 'Neo R2 Relic')
print(test)
#for item in htmls:
#print(item['item_name'])
#with open('all-items-json/{}.json'.format(item['item_name']), 'w+') as f:
#json.dump(item, f)
if __name__ == '__main__':
asyncio.run(main()) | UTF-8 | Python | false | false | 5,647 | py | 14 | wilib2.py | 13 | 0.683903 | 0.681247 | 0 | 183 | 29.863388 | 97 |
puxin0526/Study_project | 5,987,184,445,352 | 8b54409c6adbd182daa9892c7bfe9cc6ae4ac0f5 | 67713e37863c06741e5aec5c7b074520b55f98c4 | /homework_appium/page/base_page.py | 871b53c82904c57d1daaf98752c441ab9f884cfb | []
| no_license | https://github.com/puxin0526/Study_project | 843d9644e935a6959388d1ce88db54d3591506b3 | 56123f32bb764bb4015980cb588d9f4fe772b561 | refs/heads/main | 2023-06-09T17:05:40.909018 | 2021-07-05T15:21:04 | 2021-07-05T15:21:04 | 356,801,790 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # 基类,完成底层封装,比如常用的一些方法,初始化,driver,find
from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException
class BasePage:
def __init__(self, driver: WebDriver = None):
self.driver = driver
def find(self, by, value):
return self.driver.find_element(by, value)
def swipe_find(self, text, num=3):
for i in range(0, num):
if i == num - 1:
raise NoSuchElementException(f'找了{num}次没有找到元素')
try:
return self.find(MobileBy.XPATH, f"//*[@text='{text}']")
except:
print('未找到,滑动')
size = self.driver.get_window_size()
width = size['width']
height = size['height']
startx = width / 2
starty = height * 0.8
endx = startx
endy = height * 0.3
duration = 2000 # 2s
self.driver.swipe(startx, starty, endx, endy)
| UTF-8 | Python | false | false | 1,143 | py | 11 | base_page.py | 9 | 0.547507 | 0.535278 | 0 | 33 | 31.212121 | 72 |
yildirimege/FileTransferSystem | 60,129,590,924 | 049d0874ccb393d3bc9ebc14a6f48604a5819785 | 7efb72d82d6eeee9e86d09dc2d66083648c3595e | /Service_Listener.py | 10cad4236239b2ad89046b97d5058b8672396682 | []
| no_license | https://github.com/yildirimege/FileTransferSystem | 34a359a17ebf8183a7aec5233c38fe68abe26546 | 9b10ed1861366c30d18a0bdf7f016f89b65e29f6 | refs/heads/master | 2022-09-07T06:27:38.284138 | 2020-05-29T21:19:33 | 2020-05-29T21:19:33 | 267,957,119 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import socket
import json
print("Listening for files...")
port = 6000
listenerSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #UDP Socket for listener.
listenerSocket.bind(('', port))
while True:
rec = listenerSocket.recvfrom(1024)
data = json.loads(rec[0].decode('utf-8'))
print(f"Username: {str(data['username'])}, Files: {str(data['files'])} ") #Displaying username and files keys.
| UTF-8 | Python | false | false | 439 | py | 2 | Service_Listener.py | 2 | 0.656036 | 0.633257 | 0 | 15 | 26.466667 | 114 |
Wy2160640/sanger-sequencing | 1,949,915,196,844 | 4385753852be4770f0e695d433c6ad3d8a8ec859 | 21b95e6c28acc4428cdefb991e0bb97e7fcdad31 | /src/sanger_sequencing/model/plasmid_report.py | 26de5bca1eb5dfc51976f090d91414d30a52826e | [
"Apache-2.0"
]
| permissive | https://github.com/Wy2160640/sanger-sequencing | 98fb25b80ab58952874171d61fd272a8ac73002e | eefedd79b625062f919910e4b3df8a4c428662c7 | refs/heads/master | 2022-04-01T21:28:09.910278 | 2020-02-11T00:21:39 | 2020-02-11T00:21:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Copyright (c) 2019-2020 Novo Nordisk Foundation Center for Biosustainability,
# Technical University of Denmark.
#
# 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Summarize results for an entire plasmid."""
import typing
from pydantic import BaseModel, Field
from .sample_report import SampleReport, SampleReportInternal
__all__ = ("PlasmidReport", "PlasmidReportInternal")
class BasePlasmidReport(BaseModel):
"""Define attributes for a base plasmid report."""
id: str = Field(..., description="The given identifier for the plasmid.")
name: str = Field(..., description="A human readable name for the plasmid.")
class Config:
"""Configure the base plasmid report behavior."""
description = "Summarize results for an entire plasmid."
class PlasmidReport(BasePlasmidReport):
"""Define attributes for a plasmid report used in external communication."""
samples: typing.List[SampleReport] = Field(
(), description="A collection of individual sample (read) reports."
)
class Config(BasePlasmidReport.Config):
"""Configure the plasmid report behavior."""
allow_population_by_field_name = True
orm_mode = True
class PlasmidReportInternal(BasePlasmidReport):
"""Define attributes for an internal plasmid report."""
samples: typing.List[SampleReportInternal] = Field(
(), description="A collection of individual internal sample (read) reports."
)
class Config(BasePlasmidReport.Config):
"""Configure the internal plasmid report behavior."""
validate_all = True
validate_assignment = True
| UTF-8 | Python | false | false | 2,132 | py | 33 | plasmid_report.py | 18 | 0.718574 | 0.712946 | 0 | 67 | 30.820896 | 84 |
MagpieRook/Kvasaheim-Django | 10,625,749,136,542 | 46edb0d8ac180a909bcd0997dc470b07adfa5e5c | 6994b8da8ee0c3e6efbf7d01d5ac916cfa314565 | /kvasaheim/migrations/0012_auto_20180720_1819.py | e2c5a6ff20b33934bc99ea0a737954d83b215800 | []
| no_license | https://github.com/MagpieRook/Kvasaheim-Django | ad05f1eb2006c0392b4f0971e223c5c09426abdb | 50a042c7fa3e8d3ff1f867a7126c02d2bd8db0c9 | refs/heads/master | 2022-12-22T01:04:31.371675 | 2022-08-02T19:06:59 | 2022-08-02T19:06:59 | 138,333,573 | 0 | 2 | null | false | 2022-12-09T07:20:14 | 2018-06-22T18:06:16 | 2022-01-07T20:30:30 | 2022-12-09T07:20:12 | 503 | 0 | 2 | 2 | Python | false | false | # Generated by Django 2.0.7 on 2018-07-20 22:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kvasaheim', '0011_remove_problem_spread'),
]
operations = [
migrations.RemoveField(
model_name='twolistproblem',
name='second_spread',
),
migrations.AddField(
model_name='categoricalproblem',
name='num_categories_high',
field=models.IntegerField(default=10),
preserve_default=False,
),
migrations.AddField(
model_name='categoricalproblem',
name='num_categories_low',
field=models.IntegerField(default=1),
preserve_default=False,
),
]
| UTF-8 | Python | false | false | 778 | py | 35 | 0012_auto_20180720_1819.py | 25 | 0.577121 | 0.548843 | 0 | 29 | 25.827586 | 52 |
arjunmitra/RecipeBlog | 1,494,648,619,605 | 08c450e626b2fc6a574f07a6a8dcda209bb50340 | 8bc16d327a5bc2aad0497fa17c58036041fa42e1 | /Blog/post/views.py | b5493382d6b635981a1058be6bf0af5b096a3449 | []
| no_license | https://github.com/arjunmitra/RecipeBlog | 0a5b5a072f0c0653ca237cfa1ba02c91abcccb9c | 8986a7ba857f9253632772624ec67943a8a3b31d | refs/heads/main | 2023-07-07T08:27:30.315935 | 2021-08-06T13:01:23 | 2021-08-06T13:01:23 | 385,526,579 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render, get_object_or_404,redirect,reverse
from django.db.models import Count, Q
from django.conf import settings
from .models import Post, Category, Author, PostView
from .forms import CommentForm, PostForm
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.authtoken.models import Token
from io import StringIO
from html.parser import HTMLParser
import os
# Helper class to strip whitespace from strings
class MLStripper(HTMLParser):
def __init__(self):
super().__init__()
self.reset()
self.strict = False
self.convert_charrefs= True
self.text = StringIO()
def handle_data(self, d):
self.text.write(d)
def get_data(self):
return self.text.getvalue()
# functions to remove whitespace from strings
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
class PostInfo(APIView):
permission_classes = (IsAuthenticated,)
def get(self,request, *args, **kwargs):
# retrieve all posts
queryset = Post.objects.all()
# dictionary containing information about each post
payload = {}
for i in range(len(queryset)):
# fields we will share through API
fields = ['title', 'overview', 'body', 'categories','thumbnail','view_count','comment_count','author','timestamp']
item = {}
for field in fields:
item[field] = ""
item[fields[0]] = queryset[i].title
item[fields[1]] = queryset[i].overview
#removing html tags and whitespaces
item[fields[2]] = ' '.join(strip_tags(queryset[i].body).split())
item[fields[3]] = []
categories = queryset[i].categories.all()
for category in categories:
#categories is a list
item[fields[3]].append(category.title)
item[fields[4]] = queryset[i].thumbnail.url
item[fields[5]] = queryset[i].view_count
item[fields[6]] = queryset[i].comment_count
item[fields[7]] = queryset[i].author.user.username
item[fields[8]] = queryset[i].timestamp
# inserting into paylaod with key title and value post item
payload[queryset[i].title] = item
return Response(payload)
@login_required
def favourite_list(request):
queryset = Post.objects.filter(favourites=request.user)
if len(queryset) ==0:
empty = True
else:
empty = False
context = {'object_list':queryset, "isEmpty":empty}
return render(request,'favourites.html',context)
@login_required
def favourite_update(request,id):
post = get_object_or_404(Post,id=id)
if post.favourites.filter(id=request.user.id).exists():
post.favourites.remove(request.user)
else:
post.favourites.add(request.user)
return redirect(reverse('post-detail',args=(id,)))
# method to get other object
def get_author(user):
qs= Author.objects.filter(user=user.id)
if qs.exists():
return qs[0]
return None
# searching by specific category
def category_search(request):
query = request.GET.get('category') # name of category
category = Category.objects.filter(title = query)
queryset = Post.objects.filter(categories = category[0])# filtering by category title
return general_blog(request,queryset)
def search(request):
queryset = Post.objects.all()
query = request.GET.get('q')# search parameter user passed in
if query:
# filtering by checking if query is contained in post title or overview
queryset = queryset.filter(
Q(title__icontains=query) |
Q(overview__icontains=query)
).distinct() # not to double count if the query appears in both title and overview
return general_blog(request,queryset)
def general_blog(request,queryset):
category_count = get_category_count() # getting all categories and the count of posts within the category
most_recent = Post.objects.order_by("-timestamp")[:3] # getting latest 3 posts
paginator = Paginator(queryset, 4) # setting up pagination
page_request_var = 'page'
page = request.GET.get(page_request_var)
try:
paginated_queryset = paginator.page(page)
except PageNotAnInteger:
paginated_queryset = paginator.page(1)
except EmptyPage:
paginated_queryset = paginator.page(paginator.num_pages)
context = {
'queryset': paginated_queryset,
'most_recent': most_recent,
'page_request_var': page_request_var,
'category_count': category_count
}
return render(request, "blog.html", context)
def get_category_count():
# mapping from category title to count of posts within that category
queryset = Post.objects.values('categories__title').annotate(Count('categories__title'))
return queryset
# home page
def index(request):
if request.user.is_authenticated:
# Token.objects.get_or_create(user=request.user)
if not Token.objects.filter(user=request.user).exists():
Token.objects.create(user=request.user)
print("creating")
else:
print('existed')
featured = Post.objects .filter(featured = True) # retrieving posts that we want to feature
latest = Post.objects.order_by('-timestamp')[0:3]
context = {
'object_list': featured,
'latest' : latest
}
return render(request,"index.html",context)
# displays all posts
def blog(request):
queryset = Post.objects.all()
return general_blog(request,queryset)
# specific post page
def post(request,id):
post = get_object_or_404(Post, id=id)# retrieving post object
if post.favourites.filter(id=request.user.id).exists():
favourite = True
else:
favourite = False
most_recent = Post.objects.order_by("-timestamp")[:3] # getting latest 3 posts
category_count = get_category_count() # getting category and post counts
if request.user.is_authenticated:
PostView.objects.get_or_create(user=request.user,post=post) # if user is authenticated, incrementing view for that post if not viewed before
form = CommentForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.instance.user = request.user
form.instance.post = post
form.save()# saving new post
return redirect('post-detail', id=id)
context = {
'post' : post,
'most_recent': most_recent,
'category_count': category_count,
'favourite': favourite,
'form' : form
}
return render(request,"post.html",context )
# create link, only viewable to admin and staff
@login_required
def post_create(request ):
title="Create"
form = PostForm(request.POST or None, request.FILES or None )
author = get_author(request.user)
if request.method == "POST":
if form.is_valid():
form.instance.author = get_author(author) # setting author of post
form.save() # saving post
return redirect(reverse("post-detail",kwargs={
'id' : form.instance.id
}))
else:
print(form.errors)# checking for errors
context = {
'title':title,
'form':form
}
return render(request,"post_create.html" , context)
@login_required
def post_update(request,id):
title = "Update"
post = get_object_or_404(Post, id=id)
form = PostForm(request.POST or None, request.FILES or None, instance=post)# pre loading form with created post
author = get_author(request.user)
if request.method == "POST":
if form.is_valid():
form.instance.author = get_author(author)
form.save()
return redirect(reverse("post-detail", kwargs={
'id': form.instance.id
}))
else:
print(form.errors)
context = {
'title' : title,
'form': form
}
return render(request, "post_create.html", context)
@login_required
def post_delete(request,id):
post = get_object_or_404(Post,id=id)
post.delete()# deleting post
os.remove(settings.MEDIA_ROOT + '/' + str(post.thumbnail)) # deleting img associated with post
return redirect(reverse("post-list"))
| UTF-8 | Python | false | false | 8,581 | py | 4 | views.py | 3 | 0.645612 | 0.641417 | 0 | 245 | 34.020408 | 148 |
rgsngdha/PaddlePaddle-OCR | 13,640,816,152,347 | 148b9f89d290311837e78cf50e7e8189dc934ccc | 4c70124c9b2c73f776c4e21ec9ef6e28c03c4b8d | /train.py | cbe20a8e62e3bf8955dca3ee9879013a070dad40 | [
"Apache-2.0"
]
| permissive | https://github.com/rgsngdha/PaddlePaddle-OCR | ef0e13fa8fba8f8e31a1644cdd2f0def9be3ede3 | 469319996541f59b3f9cddb4082e8c57e6c0f501 | refs/heads/master | 2023-04-01T09:52:32.794710 | 2021-04-02T15:55:00 | 2021-04-02T15:55:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
import time
import numpy as np
import paddle.fluid as fluid
import config as cfg
from nets.attention_model import attention_train_net
from nets.crnn_ctc_model import ctc_train_net
from utils import data_reader
from utils.utility import get_ctc_feeder_data, get_attention_feeder_data
def main():
"""OCR training"""
if cfg.use_model == "crnn_ctc":
train_net = ctc_train_net
get_feeder_data = get_ctc_feeder_data
else:
train_net = attention_train_net
get_feeder_data = get_attention_feeder_data
# define network
sum_cost, error_evaluator, inference_program, model_average = train_net(cfg, cfg.data_shape, cfg.num_classes)
# data reader
train_reader = data_reader.train(batch_size=cfg.batch_size,
prefix_path=cfg.train_prefix,
cycle=cfg.total_step > 0,
model=cfg.use_model)
test_reader = data_reader.test(prefix_path=cfg.test_prefix, model=cfg.use_model)
# prepare environment
place = fluid.CUDAPlace(0) if cfg.use_gpu else fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
# 加载初始化模型
if cfg.init_model:
fluid.load(program=fluid.default_main_program(),
model_path=cfg.init_model,
executor=exe,
var_list=fluid.io.get_program_parameter(fluid.default_main_program()))
print("Init model from: %s." % cfg.init_model)
train_exe = exe
error_evaluator.reset(exe)
if cfg.parallel:
train_exe = fluid.ParallelExecutor(use_cuda=cfg.use_gpu, loss_name=sum_cost.name)
fetch_vars = [sum_cost] + error_evaluator.metrics
def train_one_batch(data):
var_names = [var.name for var in fetch_vars]
if cfg.parallel:
results = train_exe.run(var_names,
feed=get_feeder_data(data, place))
results = [np.array(r).sum() for r in results]
else:
results = exe.run(program=fluid.default_main_program(),
feed=get_feeder_data(data, place),
fetch_list=fetch_vars)
results = [r[0] for r in results]
return results
def test():
error_evaluator.reset(exe)
for data in test_reader():
exe.run(inference_program, feed=get_feeder_data(data, place))
_, test_seq_error = error_evaluator.eval(exe)
return test_seq_error[0]
def save_model():
if not os.path.exists(cfg.model_path):
os.makedirs(cfg.model_path)
fluid.save(program=fluid.default_main_program(),
model_path=os.path.join(cfg.model_path, "model"))
print("Saved model to: %s" % cfg.model_path)
iter_num = 0
stop = False
while not stop:
total_loss = 0.0
total_seq_error = 0.0
# train a pass
for data in train_reader():
if cfg.total_step < iter_num:
stop = True
break
result = train_one_batch(data)
total_loss += result[0]
total_seq_error += result[2]
iter_num += 1
# training log
if iter_num % cfg.log_period == 0:
print("[%s] - Iter[%d]; Avg loss: %.3f; Avg seq err: %.3f"
% (time.asctime(time.localtime(time.time())), iter_num,
total_loss / (cfg.log_period * cfg.batch_size),
total_seq_error / (cfg.log_period * cfg.batch_size)))
total_loss = 0.0
total_seq_error = 0.0
# evaluate
if iter_num % cfg.eval_period == 0:
if model_average:
with model_average.apply(exe):
test_seq_error = test()
else:
test_seq_error = test()
print("\n[%s] - Iter[%d]; Test seq error: %.3f\n" %
(time.asctime(time.localtime(time.time())), iter_num, test_seq_error))
# save model
if iter_num % cfg.save_model_period == 0:
if model_average:
with model_average.apply(exe):
save_model()
else:
save_model()
if __name__ == "__main__":
main()
| UTF-8 | Python | false | false | 4,443 | py | 12 | train.py | 10 | 0.537593 | 0.532626 | 0 | 122 | 35.303279 | 113 |
zyong/GameServer | 10,780,367,935,136 | 5e559a5ded0c5bbc3beb0d88813d39fe2b8fc7b2 | 1c2711d8cfaf5da9340ce53bb0dd8348cf60f1a8 | /logic/mesh/__init__.py | 0c469f02a583fc247a29db282e6ffc604f954e3f | []
| no_license | https://github.com/zyong/GameServer | 2bf362162f1988dcc95f52539f90a3a77dea1e41 | 9f47473b4467db37d970fdff40b4a860ccf57887 | refs/heads/master | 2017-12-22T01:02:19.852477 | 2016-11-26T04:07:43 | 2016-11-26T04:07:43 | 76,151,313 | 1 | 0 | null | true | 2016-12-11T03:13:19 | 2016-12-11T03:13:19 | 2016-11-26T03:31:02 | 2016-11-26T04:08:46 | 5,958 | 0 | 0 | 0 | null | null | null | #-*-coding:utf-8-*-
#作者:马昭@曹县闫店楼镇
#这个文件是空的,但是也必须保留. | UTF-8 | Python | false | false | 101 | py | 1,580 | __init__.py | 1,295 | 0.641509 | 0.622642 | 0 | 3 | 16.333333 | 19 |
maguileracanon/SummerOfCode | 4,707,284,160,696 | eb108a0d86986270e24bf2a3d71db7a193c747ba | 09c269f9bf46007bf03914ab8f741a1746686e52 | /Week1/HackatonD1.py | 6de021652707aeb8031223eebc4311c6ed1bc614 | [
"MIT"
]
| permissive | https://github.com/maguileracanon/SummerOfCode | d2836beb61daf2190436185fb3a8d6b4839cb566 | 8a8e1b9d5ceb5a37d4c68dd50a8744bde706537c | refs/heads/master | 2020-03-23T07:28:51.921695 | 2018-08-27T21:18:54 | 2018-08-27T21:18:54 | 141,274,111 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #Week1 Hackaton
from random import choice
# O for sea and x for land
choices = ['o','X']
num_of_continents = int(0)
size_continents = []
continen_counter=1
worldSize = input("How big do you want your world to be?")
worldSize = int(worldSize)
world = []
neighboorFound = True
for i in range (0,worldSize):
world.append([" "] * worldSize)
for j in range (0,worldSize):
world[i][j] = choice(choices)
world[0][0] = '1'
def print_world(a_world):
print("'X' represents land in the map")
print("")
for row in a_world:
print (" ".join(row))
#world[1][8] = '♥' # es fila - columna
print_world(world)
#THis is a super nested method :( sorry
for num_of_continents in range(1,4):
for amp in range (1,worldSize):
for k in range(0,amp+1):
if world[amp][k] =='X': #Find if there are already identified nighbohrs
#Evaluate neiboohrs
for in_i in range (amp-1,amp+2):
index_i = max(min(in_i,worldSize-1),0) #Clip value to prevent error in corners
for in_j in range(k-1,k+2):
index_j = max(min(in_j,worldSize-1),0)
if world[index_i][index_j].isdigit():
#print("Digit found")
world[amp][k] = world[index_i][index_j]
continen_counter=continen_counter+1
#and then we fill the neighbors
for in_i in range (amp-1,amp+2): #Range does not include maximum
index_i = max(min(in_i,worldSize-1),0) #Clip value to prevent error in corners
for in_j in range(k-1,k+2):
index_j = max(min(in_j,worldSize-1),0)
if world[index_i][index_j] =='X':
world[index_i][index_j] = world[amp][k]
continen_counter=continen_counter+1
#neighboorFound=True
break
else :
continue
break
if neighboorFound==False:
if world[amp][k]=='X':
world[amp][k]=str(num_of_continents)
continen_counter=continen_counter+1
for in_i in range (amp-1,amp+2): #Range does not include maximum
index_i = max(min(in_i,worldSize-1),0) #Clip value to prevent error in corners
for in_j in range(k-1,k+2):
index_j = max(min(in_j,worldSize-1),0)
if world[index_i][index_j] =='X':
world[index_i][index_j] = world[amp][k]
continen_counter=continen_counter+1
neighboorFound=True
elif world[amp][k] == str(num_of_continents):
#and then we fill the neighbors
for in_i in range (amp-1,amp+2): #Range does not include maximum
index_i = max(min(in_i,worldSize-1),0) #Clip value to prevent error in corners
for in_j in range(k-1,k+2):
index_j = max(min(in_j,worldSize-1),0)
if world[index_i][index_j] =='X':
world[index_i][index_j] = world[amp][k]
continen_counter=continen_counter+1
for k in range(amp,-1,-1):
if world[k][amp] =='X': #Find if there are already identified nighbohrs
#Evaluate neiboohrs
neighboorFound=False
for in_i in range (k-1,k+2):
index_i = max(min(in_i,worldSize-1),0) #Clip value to prevent error in corners
for in_j in range(amp-1,amp+2):
index_j = max(min(in_j,worldSize-1),0)
if world[index_i][index_j].isdigit():
#print("Digit found")
world[k][amp] = world[index_i][index_j]
continen_counter=continen_counter+1
for in_i in range (k-1,k+2): #Range does not include maximum
index_i = max(min(in_i,worldSize-1),0) #Clip value to prevent error in corners
for in_j in range(amp-1,amp+2):
index_j = max(min(in_j,worldSize-1),0)
if world[index_i][index_j] =='X':
world[index_i][index_j] = world[k][amp]
continen_counter=continen_counter+1
#neighboorFound=True
break
else :
continue
break
if neighboorFound==False:
if world[k][amp] =='X':
world[k][amp] = str(num_of_continents)
continen_counter=continen_counter+1
for in_i in range (k-1,k+2): #Range does not include maximum
index_i = max(min(in_i,worldSize-1),0) #Clip value to prevent error in corners
for in_j in range(amp-1,amp+2):
index_j = max(min(in_j,worldSize-1),0)
if world[index_i][index_j] =='X':
world[index_i][index_j] = world[k][amp]
continen_counter=continen_counter+1
neighboorFound=True
elif world[k][amp]==str(num_of_continents):
for in_i in range (k-1,k+2): #Range does not include maximum
index_i = max(min(in_i,worldSize-1),0) #Clip value to prevent error in corners
for in_j in range(amp-1,amp+2):
index_j = max(min(in_j,worldSize-1),0)
if world[index_i][index_j] =='X':
world[index_i][index_j] = world[k][amp]
continen_counter=continen_counter+1
neighboorFound=False
size_continents.append(continen_counter)
continen_counter=0
print_world(world)
#print(len(size_continents))
for z in range (0,len(size_continents)):
print('Continent ' + str(z+1) + ' size: ' +str(size_continents[z]))
| UTF-8 | Python | false | false | 5,006 | py | 41 | HackatonD1.py | 21 | 0.608513 | 0.589728 | 0 | 141 | 34.361702 | 87 |
notelba/midi-remote-scripts | 4,990,752,006,286 | 0605c3695411a3932e76383643f6fc35da8e8dc8 | ddd35c693194aefb9c009fe6b88c52de7fa7c444 | /Live 10.1.18/APC20/BackgroundComponent.py | cd4f3871dafc31b655919161016b668d483551c2 | []
| no_license | https://github.com/notelba/midi-remote-scripts | 819372d9c22573877c7912091bd8359fdd42585d | e3ec6846470eed7da8a4d4f78562ed49dc00727b | refs/heads/main | 2022-07-30T00:18:33.296376 | 2020-10-04T00:00:12 | 2020-10-04T00:00:12 | 301,003,961 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # uncompyle6 version 3.7.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.8.5 (default, Aug 12 2020, 00:00:00)
# [GCC 10.2.1 20200723 (Red Hat 10.2.1-1)]
# Embedded file name: c:\Jenkins\live\output\Live\win_64_static\Release\python-bundle\MIDI Remote Scripts\APC20\BackgroundComponent.py
# Compiled at: 2020-05-05 13:23:28
from __future__ import absolute_import, print_function, unicode_literals
from _Framework.BackgroundComponent import BackgroundComponent as BackgroundComponentBase
from _Framework.Util import nop
class BackgroundComponent(BackgroundComponentBase):
def _clear_control(self, name, control):
if control:
control.add_value_listener(nop)
elif name in self._control_map:
self._control_map[name].remove_value_listener(nop)
super(BackgroundComponent, self)._clear_control(name, control)
# okay decompiling /home/deniz/data/projects/midiremote/Live 10.1.18/APC20/BackgroundComponent.pyc
| UTF-8 | Python | false | false | 967 | py | 409 | BackgroundComponent.py | 408 | 0.746639 | 0.676319 | 0 | 19 | 49.894737 | 134 |
MayankKharbanda/MSc | 5,772,436,066,483 | 4fce6b0aeacefe0c429bfa83055e9356173e0d40 | 65c221829e60a858106dd469436b883b0a8edf1c | /Artificial Intelligence/time table/chromosome.py | 1318675df9081e0ef3d257914df81503493c71ae | []
| no_license | https://github.com/MayankKharbanda/MSc | c54642a1566aa0f6909edc8d2f1bf903a0336996 | 3b0c0bee767511eedf237439689cf0dc87b64397 | refs/heads/master | 2020-04-03T01:24:37.277938 | 2019-04-02T06:43:39 | 2019-04-02T06:43:39 | 154,929,708 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from gene import Gene
import copy
import csv
import os
class Chromosome:
'''
It has an object containing all the time tables of the courses
'''
def __init__(self, timetables):
self.fitness = 1
self.genes = []
for timetable in timetables:
gene = Gene(timetable)
gene.permutate()
self.genes.append(gene)
def calculate_fitness(self):
'''
This function calculate the fitness of the chromosome.
constraint - 1
lectures and practicals of a class on "same" day should be together
constraint - 2
teacher takes only one class in a slot across all timetables
'''
#to avoid divide by zero error
self.fitness = 1
#C-1
slots_per_day = self.genes[0].timetable.num_of_slots_per_day
'''
partitioning the slots in days
eliminating none
then checking longest streak and adding it to fitness
'''
for gene in self.genes:
slots_in_a_day__n = [gene.timetable.slots[i:i+slots_per_day] for i in range (0,len(gene.timetable.slots),slots_per_day)]
slots_in_a_day__n = [[i for i in x if i.subject is not None] for x in slots_in_a_day__n]
lectures_day_list__n = [[i.subject.id for i in slot] for slot in slots_in_a_day__n]
lectures_day_set__n = []
for subjects in lectures_day_list__n:
lectures_day_set__n.append(set(subjects))
for i, lectures_day_list in enumerate(lectures_day_list__n):
lectures_day_set = lectures_day_set__n[i]
for subject in lectures_day_set:
appearance = [0]
streak = False
count = 0
for subject_list in lectures_day_list:
if subject_list == subject and streak:
count += 1
elif subject_list == subject and not streak:
streak = True
count += 1
elif subject_list != subject and streak:
streak = False
appearance.append(count)
count = 0
if subject_list == lectures_day_list[len(lectures_day_list) - 1] and streak:
appearance.append(count)
self.fitness += max(appearance)
#C-2
no_of_slots = len(self.genes[0].timetable.slots)
no_of_conflicts = 0
respective_slots = list(zip(*[t.timetable.slots for t in self.genes]))
for i, timeslot in enumerate(respective_slots):
#if timeslots in a tuple are none
if all(v is None for v in timeslot):
continue
#if timeslots in a tuple are not none
timeslot_without_none = [x for x in timeslot if x is not None]
teachers_list = [x.subject.teacher.id
for x in timeslot_without_none if x.subject is not None]
teachers_set = set(teachers_list)
if len(teachers_list) != len(teachers_set):
no_of_conflicts += 1
self.fitness += no_of_slots - no_of_conflicts
'''
crossover
- just copies the chromosome as it is from parent to child
mutate
- it mutates every gene of chromosome with a given rate
output
- displays output in a csv file
'''
def crossover(self):
return copy.copy(self)
def mutate(self, mutation_rate):
for gene in self.genes:
gene.mutate(mutation_rate)
def output(self, directory):
dirPath = os.path.join(directory, "timetables")
os.makedirs(dirPath, exist_ok=True)
print("Writing data to separate files in",dirPath)
for gene in self.genes:
tt_slots = gene.timetable.slots
filePath = os.path.join(dirPath, tt_slots[0].course.name + ".csv")
dataList = [slot.subject.name+"-"+slot.subject.teacher.name
if slot.subject is not None else "Empty"
for slot in tt_slots ]
slotsPerDay = gene.timetable.num_of_slots_per_day
dataListByDay = [dataList[i:i+slotsPerDay]
for i in range(0, len(dataList), slotsPerDay)]
with open(filePath, 'w') as f:
writer = csv.writer(f)
writer.writerows(dataListByDay)
#todo: theory and practical class should be written
| UTF-8 | Python | false | false | 4,807 | py | 30 | chromosome.py | 18 | 0.522363 | 0.518411 | 0 | 145 | 32.144828 | 156 |
ApacheIsDead/vulnbytemenu | 10,075,993,278,139 | 18fe1e0aead9a6ece3a254565df9210463ad952d | 9414e0da533a694a64aecaaa458c7aa1da9e705a | /hub-progress.py | 05186a736794d0d2f63342b41180538feddd3ea2 | []
| no_license | https://github.com/ApacheIsDead/vulnbytemenu | 25180f6b0e3236645085491a5e50e8e654f7e4e1 | c0de5de73e44a5ff99d62e5fada76157df0685b3 | refs/heads/master | 2020-03-18T17:36:55.232053 | 2019-04-02T03:21:23 | 2019-04-02T03:21:23 | 135,039,340 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # aplesmash module hub
import sys
import subprocess
import socket
import time
import os
import sys
sys.setrecursionlimit(10000)
# mainCall - calls everything and does important shit
def mainCall():
userChoice()
# gets users choice
def userChoice():
hName = socket.gethostname()
menuItem = ("Ap1esmash Modules:\n{1} - De-Authenticate Network\n{2} - Advanced Scanning\n{3} - Set up HTA server\n{4} - Auto Modules\n" + "apple@"+ hName + " $ ")
if menuItem == "1":
tyranny()
elif menuItem == "2":
scanning()
elif menuItem == "3":
htaServer()
elif menuItem == "4":
otherItems = int(input("Ap1esmash Others:\n{1} Link Coolness\n{2} Base_64 Decode\n{3} Bruteforce Hash\n" + hName + " > "))
if otherItems == "1":
webShit()
elif otherItems == "2":
baseDecode()
elif otherItems == "3":
bruteForce()
else:
print("[!] Invalid input")
else:
print("[!] Invalid input")
mainCall()
# modules
def tyranny():
tyrannyBanner()
time.sleep(1)
tyrannyHandler()
# Automated NET Handling script
def tyrannyBanner():
print("""
+=+=+=+=+=++=+=+=+=+=++=+=+=+=+=++=+=+=+=+=++=+=+=+=+=++=+=+=+=+=+
Tyranny
+=+=+=+=+=++=+=+=+=+=++=+=+=+=+=++=+=+=+=+=++=+=+=+=+=++=+=+=+=+=+
""")
def tyrannyHandler():
print("Starting Tyranny")
tyrannyBanner()
time.sleep(1)
vector = str(input("[1] - Mac\n[2] - Wifi\n[3] - Ifconfig\n$ "))
if vector == "1":
# Change Mac Address
changeMac = "macchanger -r"
subprocess.call(changeMac, shell=True).read()
tyrannyHandler()
elif vector == "2":
airessid = str(input("Enter BSSID: "))
airechannel = str(input("Enter Channel: "))
airethreads = str(input("Enter Thread Count: "))
airecmd = "aireplay-ng -0 -a " + airessid + " " + airethreads + " -c " + airechannel + " wlan0"
time.sleep(2)
print("[!] De-Authing Now")
subprocess.call(airecmd, shell=True)
tyrannyHandler()
elif vector == "3":
print("NET Config")
netVector = input("[1] - Change Channel\n[2] - Ifconfig\n[3] - traceroute\n[4] - ICMP Echo Request\n[5] - Start NET services\n$ ")
if netVector == "1":
channelName = str(input("Channel Number: "))
iwconfig = "iwconfig channel " + channelName
subprocess.call(iwconfig, shell=True)
main()
elif netVector == "2":
subprocess.call("ifconfig", shell=True)
main()
elif netVector == "3":
ip = str(input("Enter an ip: "))
traceroute = "traceroute " + ip
subprocess.call(ip, shell=True)
tyrannyHandler()
def scanning():
scanType = int(input("Aplesmash Scans:\n{1} Network\n{2} NSE\n{3} Port Scan\n{4} Tor/Proxied Scan\n"))
if scanType == "1":
# Network Mapping Scan Here
print("[!] Mapping Network -- ")
elif scanType == "2":
# NSE Script Scans Here
print("[?] SELECT NSE --")
def htaServer():
cmd = "msfconsole;use exploit/windows/misc/hta_server;set SRVHOST " + htaListener + ";set URIPATH " + uriPath + ";exploit;"
os.system(cmd)
def automation():
print('here')
def webShit():
print('here')
def baseDecode():
print('here')
def bruteForce():
print('here')
userChoice()
| UTF-8 | Python | false | false | 3,904 | py | 9 | hub-progress.py | 8 | 0.48207 | 0.469775 | 0 | 106 | 35.830189 | 170 |
vdenPython/python_training | 5,729,486,378,619 | 6cecdff0163382d1a26d4164867d7b58f3ec3fe7 | af1ec7d879344277e395b9ad8696e9c7429c1872 | /test/test_modify_group.py | ff8715f750ac63a9588ca03c37d250baa8dd2dfe | [
"Apache-2.0"
]
| permissive | https://github.com/vdenPython/python_training | fd9c837ef5b9cbceeb0efe0b1d4b31970ecf0238 | 56f11d18ea9099064153c6ea19e672a23ba0bc15 | refs/heads/master | 2020-05-28T01:44:24.453071 | 2015-10-03T11:44:50 | 2015-10-03T11:44:50 | 39,999,167 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | __author__ = 'vden'
from model.group import Group
import random
def test_modify_group_name(app, db, check_ui):
if app.group.count() == 0:
app.group.create(Group(name="test"))
old_groups = db.get_group_list()
group = random.choice(old_groups)
group_id = group.id
group = Group(name="New group")
app.group.modify_group_by_id(group_id, group)
new_groups = db.get_group_list()
index = 0
for m in old_groups:
if m.id == group_id:
return index
index = index+1
old_groups[index] = group
assert old_groups == new_groups
if check_ui:
assert sorted(db.get_group_list(True), key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)
| UTF-8 | Python | false | false | 741 | py | 7 | test_modify_group.py | 7 | 0.620783 | 0.616734 | 0 | 23 | 31.086957 | 126 |
mare5x/Backuper | 4,458,176,057,283 | 62fc67756ea530e1f08992d121e461536bf0b0a7 | 1c25073e00324311a578a7395f448736ff9b4f81 | /backuper.py | c3234f7b08489d627e86766ab3d088ca37db10b3 | []
| no_license | https://github.com/mare5x/Backuper | f11368929f7aae71818b240bab80a1d124fe17ad | b4cc3340088b8e7c6b40379a9d58bf9cbf6fca51 | refs/heads/master | 2020-07-01T19:17:58.675034 | 2019-08-14T14:09:35 | 2019-08-14T14:09:35 | 201,270,436 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import argparse
import logging
from pytools import filetools as ft
from backuper import backuper
def main(log=True):
if log:
# One log file for each day. Running the program multiple times
# a day will append to the same file.
name = "Backuper_{}.log".format(ft.get_current_date_string())
ft.init_log_file(name, overwrite=True, mode="a")
parser = argparse.ArgumentParser()
class _FullFolderSyncAction(argparse.Action):
help_str = "Fully sync folder_id with local_path. Usage: -ffs FOLDER_ID LOCAL_PATH [dry/sync]"
options = ("dry", "sync")
def __init__(self, *args, nargs=None, metavar=None, **kwargs):
super().__init__(*args, nargs='*', help=self.help_str, metavar=("folder_id local_path", "dry"), **kwargs)
def __call__(self, parser, namespace, values, option_string):
n = len(values)
if n < 2 or n > 3: return parser.error("Invalid number of arguments for -ffs!")
# Dry run if 'dry' or left out. If 'sync' sync, otherwise raise error.
if n == 2:
values.append(self.options[0])
elif n == 3:
if values[2] not in self.options:
return parser.error("Unknown argument for -ffs!")
setattr(namespace, self.dest, values)
class _MirrorAction(argparse.Action):
help_str = "Mirror all sync_dirs (settings.ini) onto Google Drive. Usage: -mir [fast/full] [dry/sync] (default: fast dry)"
options1 = ("fast", "full")
options2 = ("dry", "sync")
def __init__(self, *args, nargs=None, metavar=None, **kwargs):
super().__init__(*args, nargs='*', help=self.help_str, metavar=("fast/full", "dry/sync"), **kwargs)
def __call__(self, parser, namespace, values, option_string):
options1, options2 = self.options1, self.options2
n = len(values)
if n == 0:
values.append(options1[0])
values.append(options2[0])
else:
if values[0] not in options1:
return parser.error("Invalid option 1 for -mir!")
if n == 1:
values.append(options2[0])
elif n == 2:
if values[1] not in options2:
return parser.error("Invalid option 2 for -mir!")
else:
return parser.error("Too many arguments for -mir!")
setattr(namespace, self.dest, values)
parser.add_argument("-uc", nargs='?', const="list", choices=["list", "sync"], help="Upload changes listed by 'list' (see settings.ini).")
parser.add_argument("-dc", nargs='?', const="list", choices=["list", "sync"], help="Download changes listed by 'list'.")
parser.add_argument("-tree", action="store_true", help="Upload 'trees' of directories (see settings.ini).")
parser.add_argument("-rem", nargs='?', const="list", choices=["list", "blacklist", "remove"], help="List synced files that were removed from Google Drive.")
parser.add_argument("-ffs", action=_FullFolderSyncAction)
parser.add_argument("-mir", action=_MirrorAction)
parser.add_argument("-nolog", action="store_false", help="DON'T create a pretty log file of all I/O operations.")
parser.add_argument("-init", action="store_true", help="Initialize program for first time use.")
args = parser.parse_args()
# Check if any option is actually set.
exclude = ["nolog"]
if not any(getattr(args, key) for key in filter(lambda key: key not in exclude, vars(args))):
parser.print_help()
return -1
with backuper.Backuper(pretty_log=args.nolog) as b:
if args.init:
b._init()
if args.rem:
opt = args.rem
if opt == "list":
b.list_removed_from_gd()
elif opt == "blacklist":
b.blacklist_removed_from_gd()
elif opt == "remove":
b.remove_db_removed_from_gd()
if args.mir:
_type, dry_run = args.mir
b.mirror_all(fast=(_type == "fast"), dry_run=(dry_run == "dry"))
if args.ffs:
folder_id, local_path, dry_run = args.ffs
b.full_folder_sync(folder_id, local_path, dry_run=(dry_run == "dry"))
if args.uc:
opt = args.uc
if opt == "list":
b.list_upload_changes()
elif opt == "sync":
b.upload_changes()
if args.dc:
b.download_changes(dry_run=(args.dc == "list"))
if args.tree:
b.upload_tree_logs_zip()
if __name__ == "__main__":
main()
| UTF-8 | Python | false | false | 4,740 | py | 19 | backuper.py | 17 | 0.55654 | 0.550633 | 0 | 113 | 40.946903 | 160 |
kenchose/Python | 18,219,251,299,556 | c5a6c141da87e32847c49bfe90a614d918b57102 | 7e7a5892d5ac5b084e26bb534ef550f33854c7ce | /Django/Django Info/Django App/apps/blog_app/views.py | 5bcfb4f6d445872ee8659918e2392dfd13ad3a59 | []
| no_license | https://github.com/kenchose/Python | 8f8a2d528d9c31a7e47177764a67976a5f2d9e98 | b147b81c2a61021dd7d7d12e1621ff3e8426e0a7 | refs/heads/master | 2020-04-10T22:00:16.866195 | 2019-01-05T04:01:57 | 2019-01-05T04:01:57 | 161,312,528 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
# Create your views here.
def index(request):
return HttpResponse('Placeholder to later display all the list of blogs')
def new(request):
return HttpResponse('Placeholder to display a new form to create a new blog')
def create(request):
return redirect('/')
def show(request,number):
return HttpResponse("Placeholder to display blog {}".format(number))
def edit(request, word):
return HttpResponse('Placeholder to edit blog {}'.format(word))
def destroy(request):
return redirect('/') | UTF-8 | Python | false | false | 640 | py | 84 | views.py | 40 | 0.723438 | 0.721875 | 0 | 24 | 25.708333 | 81 |
avilevis/manage_interviews | 10,909,216,942,486 | ee06d2e775c90096aaced5f0e3c49f1a630381cd | 41d94f87c0b399fa5e263c9f744459a5167e0af4 | /agents_app/apps.py | b2204a6a4a88facf0b2fab68aaacc5cd9d086898 | []
| no_license | https://github.com/avilevis/manage_interviews | 96df64c665766d420d31c64b605098ac9bd7ed8c | 1bc629caa7357528889e1c26a75aeae88ab2754b | refs/heads/main | 2023-02-06T06:44:46.910346 | 2020-12-31T11:44:16 | 2020-12-31T11:44:16 | 325,786,703 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.apps import AppConfig
class AguntsConfig(AppConfig):
name = 'agents_app'
| UTF-8 | Python | false | false | 91 | py | 29 | apps.py | 21 | 0.747253 | 0.747253 | 0 | 5 | 17.2 | 33 |
TomaskoKnaze/IOT_Facefilms | 6,167,573,065,281 | c8239428471aeae009c42a48254fa5860fd335a1 | 720a98f01e7dd467cac05cb0e18fb8fc2ef7caf7 | /client/functions.py | c6023bfa41070892c73374b9b5a236cb601ea055 | []
| no_license | https://github.com/TomaskoKnaze/IOT_Facefilms | 5603a9e93503001acf0e0474c34d224de96688c5 | 6a720c89998722d2186b1eb2c60a81080505fecb | refs/heads/main | 2023-02-16T15:18:13.912471 | 2021-01-14T15:59:19 | 2021-01-14T15:59:19 | 329,577,069 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import pymongo
import numpy as np
from pymongo import MongoClient
import pandas as pd
import imdb
emotion_labels = ["Angry", "Happy", "Neutral", "Sad", "Surprised", "None"]
def get_dataframe(collection_list,db):
film_names = []
df = pd.DataFrame()
for collection in collection_list:
col = db[collection]
for doc in col.find():
current_doc = doc
length = len(doc['emotions'])
id_number = doc['_id']
name_film = doc['name']
emotion_index_list = doc['emotions']
id_list = []
film_name_list = []
emotion_name_list = []
for m in range(length):
id_list.append(id_number)
film_name_list.append(name_film)
for emotion in emotion_index_list:
emotion_name_list.append(emotion_labels[emotion])
current_doc['emotions'] = emotion_name_list
current_doc['_id'] = id_list
current_doc['name'] = film_name_list
df_temp = pd.DataFrame.from_dict(current_doc)
#print(df_temp)
df = df.append(df_temp)
df.reset_index(drop=True, inplace=True)
film_names.append(name_film)
results = df
return results
def if_movement_section(index, rel_movement_list, no_movement, some_movement, lot_movement):
rating_list = []
if rel_movement_list[index] < 2.3:
rating_list.append(no_movement)
elif rel_movement_list[index] >= 2.3 and rel_movement_list[index] <= 4.3:
rating_list.append(some_movement)
elif rel_movement_list[index] > 4.3:
rating_list.append(lot_movement)
return rating_list
def all_same(items):
return all(x == items[0] for x in items)
def get_dataframe2(collection_list,db):
df_list = []
for collection in collection_list:
df = pd.DataFrame()
col = db[collection]
for doc in col.find():
current_doc = doc
length = len(doc['emotions'])
id_number = doc['_id']
name_film = doc['name']
emotion_index_list = doc['emotions']
id_list = []
film_name_list = []
emotion_name_list = []
for m in range(length):
id_list.append(id_number)
film_name_list.append(name_film)
for emotion in emotion_index_list:
emotion_name_list.append(emotion_labels[emotion])
current_doc['emotions'] = emotion_name_list
current_doc['_id'] = id_list
current_doc['name'] = film_name_list
df_temp = pd.DataFrame.from_dict(current_doc)
#print(df_temp)
df = df.append(df_temp)
df.reset_index(drop=True, inplace=True)
df_list.append(df)
#results = df
return df_list
def cummulative_rating_calculator(dataframe_list,film_name_list):
results = []
updated_dataframe_list = []
for h in range(len(film_name_list)):
film = film_name_list[h]
result = []
dataframe = dataframe_list[h]
rating_seconds = dataframe['rating_seconds'].tolist()
cummulative_score = 50
cummulative_rating = []
for k in rating_seconds:
cummulative_score += k
cummulative_rating.append(cummulative_score)
dataframe['cummulative_rating'] = cummulative_rating
results.append([film, dataframe])
return results
def rating_calculator(dataframe_list,film_name_list):
results = []
updated_dataframe_list = []
for h in range(len(film_name_list)):
film = film_name_list[h]
result = []
dataframe = dataframe_list[h]
rating_seconds = []
base_rating = 50
relevant_emotions = dataframe['emotions'].tolist()
relevant_timestamp = dataframe['timestamp'].tolist()
relevant_movement = dataframe['movement'].tolist()
multiplier = 5400/len(relevant_emotions)
movement_delta = []
for j in range (len(relevant_emotions)):
buffer = []
buffer.append(relevant_emotions[j])
if relevant_emotions[j] == 'Angry':
rating_seconds.extend(if_movement_section(j, relevant_movement, 0.00370, 0.00185, -0.00556 ))
elif relevant_emotions[j] == 'Happy':
rating_seconds.extend(if_movement_section(j, relevant_movement, 0.01963, 0.01556, 0.00750 ))
elif relevant_emotions[j] == 'Neutral':
rating_seconds.extend(if_movement_section(j, relevant_movement, 0.00128, 0.00093, -0.00570 ))
elif relevant_emotions[j] == 'Sad':
rating_seconds.extend(if_movement_section(j, relevant_movement, 0.00750, 0.01163, 0.00185 ))
elif relevant_emotions[j] == 'Surprised':
rating_seconds.extend(if_movement_section(j, relevant_movement, 0.02186, 0.02370, 0.00750 ))
elif relevant_emotions[j] == 'None':
rating_seconds.extend(if_movement_section(j, relevant_movement, -0.00093, -0.00185, 0.00278 ))
if len(buffer) == 4:
if all_same(buffer) == True:
if buffer[2] == 'Angry':
rating_seconds[j] = 0.008
rating_seconds[j-1] = 0.008
rating_seconds[j-2] = 0.008
rating_seconds[j-3] = 0.008
rating_seconds[j-4] = 0.008
elif buffer[2] == 'Sad':
rating_seconds[j] = 0.09
rating_seconds[j-1] = 0.09
rating_seconds[j-2] = 0.09
rating_seconds[j-3] = 0.09
rating_seconds[j-4] = 0.09
elif buffer[2] == 'Surprised':
rating_seconds[j] = 0.01
rating_seconds[j-1] = 0.01
rating_seconds[j-2] = 0.01
rating_seconds[j-3] = 0.01
rating_seconds[j-4] = 0.01
elif buffer[2] == 'Happy':
rating_seconds[j] = 0.007
rating_seconds[j-1] = 0.007
rating_seconds[j-2] = 0.007
rating_seconds[j-3] = 0.007
rating_seconds[j-4] = 0.007
elif buffer[2] == 'None':
rating_seconds[j] = -0.005
rating_seconds[j-1] = -0.005
rating_seconds[j-2] = -0.005
rating_seconds[j-3] = -0.005
rating_seconds[j-4] = -0.005
else:
None
else:
buffer.pop(0)
rating_seconds[j] = rating_seconds[j]*multiplier
if j == 0:
movement_delta.append(0)
else:
movement_delta.append(relevant_movement[j] - relevant_movement[j-1])
if abs(movement_delta[j]) > 3 and relevant_emotions[j] == 'Angry':
rating_seconds[j] = 0.012
elif abs(movement_delta[j]) > 4 and relevant_emotions[j] == 'Happy':
rating_seconds[j] = 0.011
elif abs(movement_delta[j]) > 4.5 and relevant_emotions[j] == 'Surprised':
rating_seconds[j] = 0.013
else:
None
base_rating += rating_seconds[j]
dataframe['rating_seconds'] = rating_seconds
dataframe['movement_delta'] = movement_delta
#updated_dataframe_list.append(dataframe)
results.append([film,base_rating, dataframe])
return results
def get_favourite_section(dataframe_list, film_name_list):
results = []
for h in range(len(film_name_list)):
film = film_name_list[h]
favourite_section_start = 0
previous_rolling_sum = 0
dataframe = dataframe_list[h]
rating_list = dataframe['rating_seconds'].tolist()
lines = dataframe['text'].tolist()
rolling_list = []
text_list = []
for o in range(len(rating_list)):
rating_second = rating_list[o]
rolling_list.append(rating_second)
if len(rolling_list) == 20:
rolling_list.pop(0)
rolling_sum = sum(rolling_list)
if rolling_sum > previous_rolling_sum:
previous_rolling_sum = rolling_sum
favourite_section_start = o-19
else:
None
for p in range(19):
text_list.append(lines[favourite_section_start+p])
result = [film, favourite_section_start, text_list]
results.append(result)
return results
def get_predominant_emotion(dataframe_list, film_name_list):
results = []
for g in range(len(film_name_list)):
film = film_name_list[g]
dataframe = dataframe_list[g]
all_emotions = []
happy = ['happy']
sad = ['sad']
surprised = ['surprised']
angry = ['angry']
emotions_list = dataframe['emotions'].tolist()
for emotion in emotions_list:
if emotion == 'Happy':
happy.append(1)
elif emotion == 'Sad':
sad.append(1)
elif emotion == 'Surprised':
surprised.append(1)
elif emotion == 'Angry':
angry.append(1)
else:
None
all_emotions.append(happy)
all_emotions.append(sad)
all_emotions.append(surprised)
all_emotions.append(angry)
sorted_emotions = sorted(all_emotions, key = len, reverse = True)
first = sorted_emotions[0][0]
second = sorted_emotions[1][0]
third = sorted_emotions[2][0]
#frequency_list = dataframe.emotions.value_counts()
result = [film,[first, second, third]]
results.append(result)
return results
def get_leaderboards_dataframe(rating_list):
film_unordered = []
ratings = []
df = pd.DataFrame()
for couple in rating_list:
film_unordered.append(couple[0])
ratings.append(couple[1])
df['name'] = film_unordered
df['rating'] = ratings
sorted_df = df.sort_values(by=['rating'], ascending=False)
return sorted_df
def get_imdb_score(film_name):
try:
ia = imdb.IMDb()
name = film_name.replace('_' , ' ')
movies = ia.search_movie(name)
movie_id = movies[0].movieID
film_object = ia.get_movie(movie_id)
rating = film_object.data['rating']
#synopsis = film_object.data['synopsis']
cast = film_object.data['cast']
director = film_object.data['director']
director1 = director[0]
director2 = director1['name']
actors = cast[:5]
parsed_actors = ""
for actor in actors:
actor_name = actor['name']
parsed_actors += str(actor_name)
parsed_actors += str(', ')
link = ia.get_imdbURL(film_object)
result = [film_name, rating, director2, parsed_actors, link ]
except KeyError:
result = [film_name, 'No rating Found', 'No director info found', 'Information on actors was not found', 'No link :(' ]
return result
def get_average_movement(dataframe_list, film_name_list):
results = []
for h in range(len(film_name_list)):
film_name = film_name_list[h]
dataframe = dataframe_list[h]
movement_list = dataframe['movement'].tolist()
average_movement = sum(movement_list)/len(movement_list)
result = [film_name,average_movement]
results.append(result)
return results
def get_distraction_time(dataframe_list, film_name_list):
results = []
for h in range(len(film_name_list)):
film_name = film_name_list[h]
dataframe = dataframe_list[h]
emotions_list = dataframe['emotions'].tolist()
no_attention_list = []
for emotion in emotions_list:
if emotion == 'None':
no_attention_list.append(1)
else:
None
distracted_time = len(no_attention_list)
result = [film_name, distracted_time]
results.append(result)
return results
def get_total_watchtime(dataframe_list, film_name_list):
total_time = 0
for index in range(len(film_name_list)):
dataframe = dataframe_list[index]
sec_list = dataframe['timestamp'].tolist()
total_time += len(sec_list)
return total_time
def get_average_rating(rating_list):
sum_all = 0
for couple in rating_list:
sum_all += couple[1]
average = sum_all/len(rating_list)
return average | UTF-8 | Python | false | false | 13,068 | py | 7 | functions.py | 4 | 0.533364 | 0.510866 | 0 | 389 | 32.596401 | 127 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.