Example #1
0
def main():
    if '-help' in sys.argv[1:]:
        help()
    check_version()
    if len(sys.argv) == 1:
        print "Usage: norme.py <files_to_scan>"
        sys.exit()
    moulin = norme()
    files = get_files(sys.argv)
    if '-verbose' in sys.argv[1:]:
        moulin.verbose = 1
    if '-comment' in sys.argv[1:]:
        moulin.comment = 0
    if '-nocheat' in sys.argv[1:]:
        moulin.cheat = 0
    if '-score' in sys.argv[1:]:
        moulin.score = 1
    if '-libc' in sys.argv[1:]:
        moulin.libc = 0
    if '-printline' in sys.argv[1:]:
        moulin.printline = 1
    if '-return' in sys.argv[1:]:
        moulin.creturn = 0
    if moulin.cheat == 1:
        moulin.get_user()
    try:
        moulin.scan_files(files)
    except NameError:
        print "Usage: norme.py <files_to_scan>"
    if moulin.score:
        print "Note:",-moulin.note,
def simGeoLoad(score):
    print "Loading configuration for scenario", options.tag , options.version ,"...\n"
    if score == "Run1":
       #process.load("Geometry.VeryForwardGeometry.geometryRP_cfi")
       process.load("Configuration.Geometry.geometry_CTPPS_cfi")
       #process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi")

    elif score == "2015":
       process.load("Geometry.CMSCommonData.cmsExtendedGeometry2015XML_cfi")

    elif score == "2015dev":
       process.load("Geometry.CMSCommonData.cmsExtendedGeometry2015devXML_cfi")

    elif score == "2017":
       process.load("Geometry.CMSCommonData.cmsExtendedGeometry2017XML_cfi")
       
    elif score == "2017Muon":
       process.load("Geometry.CMSCommonData.cmsExtendedGeometry2017MuonXML_cfi")

    elif score == "2019":
       process.load("Geometry.CMSCommonData.cmsExtendedGeometry2019XML_cfi")

    elif score == "2023":
       versionCheck(options.version)
       process.load("Geometry.CMSCommonData.cmsExtendedGeometry2023" + options.version + "XML_cfi")
 
    else:
      help()
Example #3
0
def command_line(veb, ra, ov, pr):
	l = len(sys.argv)
	for i in xrange(1, l):
		if not is_switch(sys.argv[i]):
			break

	for j in xrange(i, l): # Start with the first non-switch
		if j != i: # Pretty printing
			print
		response = sys.argv[j]
		if valid_input(response):
			response = response.replace('^', '**')
			try:
				n = eval(response)
				int(n)
			except (SyntaxError, TypeError, ValueError):
				help()
		else:
			help()

		print	'Factoring %d:' % n
		if n < 0:
			print	-1
			n = -n
		if n == 0:
			print	'0 does not have a well-defined factorization.'
			continue
		elif n == 1:
			print	1
			continue

		if ov == DUMMY:
			ov = 2*math.log(math.log(n))
		for factor in factors(n, veb, ra, ov, pr):
			print factor
Example #4
0
    def raw_input(self, *args):
        line = InteractiveConsole.raw_input(self, *args)
        if len(line) < 1:
            return line
        if line == EDIT_CMD:
            fd, tmpfl = mkstemp('.py')
            os.write(fd, b'\n'.join(self.last_buffer))
            os.close(fd)
            os.system('%s %s' % (EDITOR, tmpfl))
            line = open(tmpfl).read()
            os.unlink(tmpfl)
            tmpfl = ''
            lines = line.split('\n')
            for i in range(len(lines) - 1):
                self.push(lines[i])
            line = lines[-1]
        elif line[0] == RAW_CMD:
            os.system(line[1:])
            return ""
        elif line[0] == DIR_CMD:
            return str(dir(eval(line[1:])))
        elif line[0] == HELP_CMD:
            help(eval(line[1:]))
            return ""

        return line
Example #5
0
def main():
	'''
	Run help if called directly
	'''
	
	import __main__
	help(__main__)
Example #6
0
def test_clr_addreference():
    sys.stdout = stdout_reader()
    help(clr.AddReference)
    x = sys.stdout.text
    sys.stdout = sys.__stdout__
    
    Assert(x.find("Adds a reference to a .NET assembly.") != -1)
Example #7
0
 def wrapped(*args, **kwargs):
     try:
         f(*args, **kwargs)
     except TypeError:
         # TODO TypeError is probably too broad here.
         sys.stderr.write('Wrong number of arguements.  Usage:\n')
         help(f.__name__)
Example #8
0
def test_methoddescriptor():
    sys.stdout = stdout_reader()
    help(list.append)
    x = sys.stdout.text
    sys.stdout = sys.__stdout__
    
    Assert(x.find('append(...)') != -1)
Example #9
0
def test_str():
    sys.stdout = stdout_reader()
    help('abs')
    x = sys.stdout.text
    sys.stdout = sys.__stdout__
    
    Assert(x.find('Return the absolute value of the argument.') != -1)
Example #10
0
def main():
    if len(sys.argv) == 1:
        help()
    env = sys.argv[1];

    cprint("PUSH_TO_ENVIRONMENT  Input Environment: "+ env, bcolors.HEADER)

    orig_file = ".env"
    env_file = ".env." + env
    backup_file = ".env_backups/.env.backup." + str(datetime.datetime.now().strftime("%A_%d_%B_%Y_%I_%M_%p"))
    cprint("Env File: " + env_file, bcolors.OKBLUE)
    if check_diff(env_file):
        cprint( "Backup File: " + backup_file, bcolors.OKBLUE)
        call(["cp", orig_file, backup_file])
        call(["cp", env_file, orig_file])
    else:
        cprint( "No diff found", bcolors.OKBLUE)

    if not mappings.has_key(env):
        print "create heroku"

    call(["gulp"])
    if env == "local":
        call(["php", "-S", "localhost:8000", "-t", "public/"])
    else:
        call(["build/try.sh"])
        call(["git", "reset", "HEAD" , backup_file])
        call(["git", "reset", "HEAD" , orig_file])
Example #11
0
def test_builtinfunction():
    sys.stdout = stdout_reader()
    help(abs)
    x = sys.stdout.text
    sys.stdout = sys.__stdout__
    
    Assert(x.find('Return the absolute value of the argument') != -1)
Example #12
0
def main(argv = None):
    if argv == None:
        argv = sys.argv

    (o, a) = makeOptionParser(argv)
    if o.debug: pdb.set_trace()
    
    if o.help:
        help()

    verbose(o.verbose, True)
    if verbose():
        dump_options(o)

    if o.tarball != '' and o.copy != '':
        raise Exception('--pkg and --copy are not compatible')
    elif o.tarball != '' and o.copy == '':
        package(sys.argv[0], o.tarball)
    elif o.tarball == '' and o.copy != '':
        copy_me(sys.argv[0], o.copy)

    try:
        (start, end) = interpret_options(o)
    except Exception, e:
        print str(e)
        sys.exit(1)
def illumina2sangerFq(inputfile):
    
    print help(SeqIO.convert)
    
    filename = inputfile[:-3]+'.fastq'
    
    SeqIO.convert(inputfile, "fastq-illumina", filename, "fastq")
Example #14
0
def getdoc(thing, title='Help on %s', forceload=0):

    #g.trace(thing)

    if 1: # Both seem to work.

        # Redirect stdout to a "file like object".
        old_stdout = sys.stdout
        sys.stdout = fo = g.fileLikeObject()
        # Python's builtin help function writes to stdout.
        help(str(thing))
        # Restore original stdout.
        sys.stdout = old_stdout
        # Return what was written to fo.
        return fo.get()

    else:
        # Similar to doc function from pydoc module.
        from pydoc import resolve, describe, inspect, text, plain
        object, name = resolve(thing, forceload)
        desc = describe(object)
        module = inspect.getmodule(object)
        if name and '.' in name:
            desc += ' in ' + name[:name.rfind('.')]
        elif module and module is not object:
            desc += ' in module ' + module.__name__
        doc = title % desc + '\n\n' + text.document(object, name)
        return plain(doc)
def main():
  help()
  ### Get args
  if len(sys.argv) != 4 and len(sys.argv) != 3:
    usage()
    sys.exit(1)

  if len(sys.argv) == 4:
    VIEW_TO_USE = int(sys.argv[1])
    INPUT_FILE = sys.argv[2]
    OUTPUT_FILE = sys.argv[3]
  else:
    INPUT_FILE = sys.argv[1]
    OUTPUT_FILE = sys.argv[2]
    views = guess_view(INPUT_FILE)
    VIEW_TO_USE = most_likely_view(views)
    print "Guessing you want view id %s" % VIEW_TO_USE

  expr = re.compile('.*Received new cluster view.*\|%s. \[(.*)\].*' % VIEW_TO_USE)
  find(INPUT_FILE, expr)

  with open(INPUT_FILE) as f_in:
    with open(OUTPUT_FILE, 'w+') as f_out:
      for l in f_in:
        for c in addresses.keys():
          l = l.replace(c, addresses[c])
        f_out.write(l)

  print "Processed %s and generated %s.  The following replacements were made: " % (INPUT_FILE, OUTPUT_FILE)	
  sorted_keys = new_addresses.keys()
  sorted_keys.sort()
  for a in sorted_keys:
    print "  %s --> %s" % (new_addresses[a], a)
def load_inports(insert_nurses=False, insert_turnuses=False, insert_vacations=False, insert_workplaces=False, insert_scheduling_units=False, insert_employment_types=False, insert_titles=False, insert_turnus_types=False, insert_roles=False, print_help=True):
  
  if print_help:
    help()
    return
  try:
    if insert_turnus_types:
      data.input.input_turnus_types()
    
    if insert_turnuses:
      data.input.input_turnuses()
      
    if insert_vacations:
      data.input.input_vacations()
      
    if insert_workplaces:
      data.input.input_workplaces()
      
    if insert_roles:
      data.input.input_roles()
      
    if insert_titles:
      data.input.input_titles()
      
    if insert_scheduling_units:
      data.input.input_scheduling_units()
      
    if insert_employment_types:
      data.input.input_employment_types()
      
    if insert_nurses:
      data.input.input_nurses()
    
  except IOError as e:
    print '\n\nManjka datoteka: ' + str(e.filename)
Example #17
0
def as_main():
    import os, sys
    def help():
        print __doc__ % (__author__, __date__)

    from getopt import getopt
    opts, files = getopt(sys.argv[1:], 'hk:d:',
                         ['help', 'kindle=', 'alf='])
    serial = None
    alfdir = None
    for (opt, val) in opts:
        if   opt == '-h' or opt == '--help':
            help()
            sys.exit(1)
        elif opt == '-k' or opt == '--kindle':
            serial = val
        elif opt == '-d' or opt == '--alf':
            alfdir = val

    if not serial:
        print "** Won't be able to clean up without a kindle serial number."
        sys.exit(1)

    cl = Cleanup(serial, alfdir, outdir='')
    for fname in files:
        print cl.decrypt(fname)
Example #18
0
def main():
    help()
    animals = json_decoder('animals.json')

    while True:
        choice = input('Enter a command> ')
        if choice.lower() == 'quit':
            exit()

        elif choice.lower() == 'show_animals':
            # pass
            print(str(animals))

        elif choice.lower().startswith('accommodate'):
            if len(choice.split()) != 5:
                help()
            pass

        elif choice.lower().startswith('move_to_habitat'):
            if len(choice.split()) != 3:
                help()
            pass

        elif choice.lower().startswith('simulate'):
            if len(choice.split()) != 3:
                help()
            pass

        else:
            help()
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hs:67f:n:")
    except Exception, e:
        print e
        help()
        sys.exit(2)
Example #20
0
def parse_cmdline():
  parser = OptionParser()
  #parser.add_option("-l", "--limit", action="store", type="int", 
  #  dest="total_file_size_limit", default=10000000,
  #  help="change total file size in each separate job")
  #parser.add_option("-t", "--type", action="store", type="string", 
  #  dest="bond_type", default="nuclear",
  #  help="specify hydrogen bond length for clashes (nuclear or ecloud)")
  opts, args = parser.parse_args()
  #if opts.total_file_size_limit < 5000000:
  #  sys.stderr.write("\n**ERROR: -limit cannot be less than 5000000 (5M)\n")
  #  sys.exit(parser.print_help())
  #if not (opts.bond_type == "nuclear" or opts.bond_type == "ecloud"):
  #  sys.stderr.write("\n**ERROR: -type must be ecloud or nuclear\n")
  #  sys.exit(parser.print_help())
  if len(args) < 2:
    sys.stderr.write("\n**ERROR: User must specify input and output directory\n")
    sys.exit(help())
  else:  
    indir = args[0]
    outdir = args[1]
    if (os.path.isdir(indir) and os.path.isdir(outdir)):
      return opts, indir, outdir
    else:
      sys.stderr.write("\n**ERROR: First two arguments must be directories!\n")
      sys.exit(help())
Example #21
0
def main():
    if len(sys.argv) == 1:
        print "Usage: norme.py <dir_to_scan>"
        sys.exit()
    moulin = norme()
    if '-verbose' in sys.argv[1:]:
        moulin.verbose = 1
    if '-comment' in sys.argv[1:]:
        moulin.comment = 0
    if '-nocheat' in sys.argv[1:]:
        moulin.cheat = 0
    if '-score' in sys.argv[1:]:
        moulin.score = 1
    if '-libc' in sys.argv[1:]:
        moulin.libc = 0
    if '-malloc' in sys.argv[1:]:
        moulin.malloc = 0
    if '-printline' in sys.argv[1:]:
        moulin.printline = 1
    if '-return' in sys.argv[1:]:
        moulin.creturn = 0
    if '-help' in sys.argv[1:]:
        help()
    if sys.argv[1][-1:] != '/':
        sys.argv[1] = sys.argv[1] + '/'
    if moulin.cheat == 1:
        moulin.get_user()
    try:
        moulin.scandir(sys.argv[1])
    except NameError:
        print "Usage: norme.py <dir_to_scan>"
    if moulin.score:
        print "Vous avez fait",moulin.note,"fautes de norme"
Example #22
0
def PARSE(fname):
    """ """
    print("\n"*10)
    i = 1 # line counter
#    i_replace = 0 # line for replacement referencer
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    # regex settings for finding the PTX line

#    oneNote = "(\[\].*\n)[\[|#]"
#    reLine = ("%s") % (oneNote,)

#    regexLine = re.compile(reLine)
    # first insert dates into individual notes - as regex has no memory to do it later

    # ____________________________________________________
    # READ it
    txt = READ(fname)
    # ____________________________________________________
    # Preprocess
    txt = PREPROCESS(txt)
    # ____________________________________________________
    # parse individual notes
    regexLine = re.compile(strParsedNote , re.MULTILINE|re.UNICODE|re.DOTALL)
    r = regexLine.search(txt)
    rgs = r.groups()

    print(help(txt.splitlines))
    rgs = txt.splitlines(True).split(SN)
    
    # multiline split
    for note in rgs:
        
        print("\n".join([ "~"*80, note, "\n" * 3 ]) )
        
    print(help(txt.split))
Example #23
0
def run_action(name, args=[]):
    a = find_action(name)
    if a:
        a(*args)
    else:
        print >> sys.stderr, 'unknown command', name
        help()
Example #24
0
def executeCommand(userName, escapedUserCommand, userCommand):
    if re.search('^\\\\!book', escapedUserCommand):
        book(userName, userCommand)
        return 0
    if re.search('^\\\\!config', escapedUserCommand):
        config(userName, userCommand)
        return 0
    if re.search('^\\\\!changelevel', escapedUserCommand):
        map(userName, userCommand)
        return 0
    if re.search('^\\\\!kick', escapedUserCommand):
        kick(userName, userCommand)
        return 0
    if re.search('^\\\\!man', escapedUserCommand):
        help()
        return 0
    if re.search('^\\\\!map', escapedUserCommand):
        map(userName, userCommand)
        return 0
    if re.search('^\\\\!mumble', escapedUserCommand):
        mumble()
        return 0
    if re.search('^\\\\!prototype', escapedUserCommand):
        prototype()
        return 0
    if re.search('^\\\\!servers', escapedUserCommand):
        book(userName, '!book')
        return 0
    if re.search('^\\\\!whattimeisit', escapedUserCommand):
        send("PRIVMSG " + channel + " :\x038,01* \x039,01Hammertime \x038,01*")
        return 0
Example #25
0
def main(my_argv):
    inputfile = ''
    revision = None

    if (len(my_argv) == 0):
    	print 'Usage: Wikiwho.py -i <inputfile> [-rev <revision_id>]\n'
    	exit(2)
    elif (len(my_argv) <= 2):
        try:
            opts, args = getopt.getopt(my_argv,"i:",["ifile="])
        except getopt.GetoptError:
            print 'Usage: Wikiwho.py -i <inputfile> [-r <revision_id>]\n'
            exit(2)
    else:
        try:
            opts, args = getopt.getopt(my_argv,"i:r:",["ifile=","revision="])
        except getopt.GetoptError:
            print 'Usage: Wikiwho.py -i <inputfile> [-r <revision_id>]\n'
            exit(2)
    
    for opt, arg in opts:
        if opt in ('-h', "--help"):
            help()
            exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-r", "--revision"):
            revision = arg
         
    return (inputfile,revision)
Example #26
0
def readNext(bot,update):
    global readIndex,cur
    dp.removeTelegramMessageHandler(readNext)
    text = update.message.text
    if (text == read_options[0][0]):
        cur.execute('CALL GetPoemForReading(%d)'%readIndex)
        result = cur.fetchall()
        cur.close()
        cur = db.cursor() 
        if(len(result) != 0):
            readIndex = readIndex+1
            text = "\n محبوبیت %d درصد||%d امتیاز از %d رای \n"%(int(result[0][4]*100) ,int(result[0][2]), int(result[0][3]) )
            bot.sendMessage(update.message.chat_id,result[0][1] + text)
            msg = "ادامه میدی؟"
            params = urllib.urlencode({'chat_id': str(update.message.chat_id),
            'text': msg.encode('utf-8'),
            'reply_markup': read_reply_markup,
            'disable_web_page_preview': 'true',
            # 'reply_to_message_id': str(message_id),
            })
            urllib2.urlopen(BASE_URL + 'sendMessage', params).read()
            dp.addTelegramMessageHandler(readNext)    
        else:
            bot.sendMessage(update.message.chat_id,'اشعار تمام شده است')
            
    else:
        bot.sendMessage(update.message.chat_id,'شما از بخش خواندن اشعار خارج شدید')
        dp.removeTelegramMessageHandler(readNext)
        help(bot,update)
Example #27
0
def main():
	try:
		opts, args = getopt.getopt(sys.argv[1:], "ahvi:p:P:", ["about", "help", "verbose", "ip=", "port=", "password="])
	except getopt.GetoptError, err:
		print err
		help()
		sys.exit()
Example #28
0
def usage():
    if __name__ == '__main__':
        import pydoc
        #FIXME: literally displayed '__main__'
        print(pydoc.help(__name__))
    else:
        help(str(os.path.basename(sys.argv[0]).split('.')[0]))
Example #29
0
def main():
    import cli
    usagestr = "Usage: %prog [OPTIONS] <command> [args]"
    PARSER = OptionParser(usage=usagestr)
    PARSER.add_option("-H", "--host", dest="host",
                      type="string", default="127.0.0.1",
                      help="ip address of api host")
    PARSER.add_option("-p", "--port", dest="port",
                      type="int", default=9696, help="api poort")
    PARSER.add_option("-s", "--ssl", dest="ssl",
                      action="store_true", default=False, help="use ssl")
    PARSER.add_option("-v", "--verbose", dest="verbose",
                      action="store_true", default=False,
                      help="turn on verbose logging")
    PARSER.add_option("-f", "--logfile", dest="logfile",
                      type="string", default="syslog", help="log file path")
    PARSER.add_option(
        '--version', default=DEFAULT_QUANTUM_VERSION,
        help='Accepts 1.1 and 1.0, defaults to env[QUANTUM_VERSION].')
    options, args = PARSER.parse_args()

    if options.verbose:
        LOG.setLevel(logging.DEBUG)
    else:
        LOG.setLevel(logging.WARN)

    if options.logfile == "syslog":
        LOG.addHandler(logging.handlers.SysLogHandler(address='/dev/log'))
    else:
        LOG.addHandler(logging.handlers.WatchedFileHandler(options.logfile))
        os.chmod(options.logfile, 0644)

    version = options.version
    if len(args) < 1:
        PARSER.print_help()
        qcli.help(version)
        help()
        sys.exit(1)

    CMD = args[0]
    if CMD in qcli.commands['1.1'].keys():
        qcli.main()
        sys.exit(1)
    if CMD not in COMMANDS.keys():
        LOG.error("Unknown command: %s" % CMD)
        qcli.help(version)
        help()
        sys.exit(1)

    args = build_args(CMD, COMMANDS[CMD]["args"], args[1:])

    LOG.info("Executing command \"%s\" with args: %s" % (CMD, args))

    HOST = options.host
    PORT = options.port
    USE_SSL = options.ssl
    COMMANDS[CMD]["func"](*args)

    LOG.info("Command execution completed")
    sys.exit(0)
def parse_options():
    try:
        long_options = ['split-args', 'help']
        opts, args = getopt.getopt(sys.argv[1:], "shp:w:", long_options)
    except getopt.GetoptError, e:
        print help()
        sys.exit(3)
Example #31
0
def suma(a, b):
    """Suma dos valores a y b

  param int a cualquier entero
  param int b cualquier entero

  returns la sumatoria de a y b
  """
    total = a + b
    return total


help(suma)
#Topic:Linear Model - Steps
#-----------------------------
#libraries

#S1- libraries
import numpy as np
from sklearn.linear_model import LinearRegression
help(np)
np
#S2 - data
x = np.array([5, 15, 25, 35, 45, 55]).reshape((-1, 1))  #making 2 dim
x  #IV
y = np.array([5, 20, 14, 32, 22, 38])  #1 dim
y  #DV #(y can 2 dim also : y.reshape((-1,1)))
y.shape
x.shape
x.ndim
y.ndim
#S3 - Model
model = LinearRegression()  #create blank model
#other options- fit_intercept (y/N), normalise i/p var
model.fit(
    x, y
)  #find optimal values of weights b0, b1 using x & y, .fit() fits the model

model = LinearRegression().fit(x, y)  #another way  #2 lines into 1

#S4 - Results
r_sq = model.score(x, y)
r_sq  #coeff of determination : > .6 is good #71% of variation in y is explained by x
model.intercept_  #bo
Example #33
0
list1 = [1, 2, 3, 3, 4, 5]
print(list1.index(3, 3))
help(list.index)
Example #34
0
"""
######################################################

# Suppose you have created a Cantera object and want to know what
# methods are available for it, and get help on using the methods.
from Cantera import *
g = GRI30()

# The first thing you need to know is the Python class that object g
# belongs to. In Python, the class an object belongs to is stored in
# data member __class__:

print g.__class__

# To get help on this class, type
help(g.__class__)

# You can also use the Python module browser to view this same
# information in a web browser.  Under Windows, on the Start menu
# select
#   Start
#       |---Programs
#                  |---Python2.x
#                              |---Module Docs
#
# On unix, linux, or Mac OSX, at a shell prompt type
#
#   pydoc -g
#
# A small pop-up window will appear. Enter 'Cantera' in the search
# box, or else simply click on 'open browser', then navigate to the
Example #35
0
def setup(bot):
    bot.add_cog(help(bot))
Example #36
0
    print("  -s=, --sample=[VALUE]      Samples. Number of iterations")
    print("  -h,  --help                Provide this help information.")
    print("  -d,  --debug               Provide additional information \n"
          "                             during program development.")
    # print("  -i=, --input=[FILE]        Input file")
    print("  -o=, --output=[FILE]       Comma seperated values file")
    print("  -l=, --log=[FILE]          Provide a filename for logging.")
    print("")
    print("Copyright: {}\n".format(_copyright_))


if __name__ == "__main__":
    # Get command line options from sys.argv list
    for index, option in enumerate(sys.argv):
        if "-h" in option:
            help()
            sys.exit()

        if "-d" in option:
            debug = not debug

        # Collect string data from command line interface (cli) sys.argv list
        # -s = total_sample
        if "-s" in option:
            sample_list = sys.argv[index].split("=")
            if len(sample_list) > 1:
                sample = sample_list[1]

        if "-e" in option:
            edge_list = sys.argv[index].split("=")
            if len(edge_list) > 1:
Example #37
0
is_empty = None
print(help(is_empty))

if is_empty is not None:
    print("None!")

print(1 == True)
print(1 is True)
print(True is True)
print(None is None)

a = 1
b = 2

print(a is b)
print(a == b)
Example #38
0
# 内省
class MyClass(object):
    def __init__(self):
        pass

    def __del__(self):
        pass

    def foo(self):
        print 'in foo'

    def __str__(self):
        return 'myclass str'


mycls = MyClass()
print id(mycls)
print str(mycls)
print dir(mycls)
print help(mycls)
print type(mycls)
print hasattr(mycls, 'foo')
print getattr(mycls, 'foo')
print isinstance(mycls, MyClass)
print isinstance(mycls, object)




# np.random.uniform(start,stop,size) will generate array of real numbers with size = size

#### another way to split data into train and test

from sklearn.model_selection import train_test_split
train, test = train_test_split(Fraud_Data, test_size=0.2)
test
test.shape  # (120, 7)
train
train.shape  #(480, 7)

##############  Decision Tree Model building ###############

from sklearn.tree import DecisionTreeClassifier
help(DecisionTreeClassifier)

model = DecisionTreeClassifier(criterion='entropy')

model.fit(train[predictors], train[target])

preds = model.predict(test[predictors])

preds

from sklearn import metrics  #Import scikit-learn metrics module for accuracy calculation
print("Accuracy:", metrics.accuracy_score(test[target], preds))
#Accuracy: 0.9916666666666667

pd.Series(preds).value_counts()
#moderate    43
    else:
        plan = "有没有人一起出去玩"

    return plan  # 返回plan的值


my_plan_5 = what_to_go(dow=5)
my_plan_6 = what_to_go(dow=6)
my_plan_7 = what_to_go(dow=7)
print("周五的计划是", my_plan_5)
print("周六的计划是", my_plan_6)
print("周日的计划是", my_plan_7)

# 标准库
import math  # 导入math数学库

print("pi的值是", math.pi)
print("求sin90度", math.sin(math.pi / 2))
help(math.sin)  # 查看文档

# 写出数据到文本文件
file = open('./output/mytext.txt', 'w')  # w 声明写出模式
mytext = "今天吃什么"
file.write(mytext)  # 将字符串mytext写出至mytext.txt
file.close()  # 关闭文件

# 从文件读取
file = open('./output/mytext.txt', 'r')  # r 声明读取模式
text_load = file.read()
print(text_load)
Example #41
0
print (b)

def show_names(*names):      # *一星元组
    for name in names:
        print('名字是:'+name)

show_names('manba','zengjun','fzq','123')

def show_my_info(**infos):   # ** 两星字典
    '''展示信息'''
    print (infos)
    for k,v in infos.items():
        print('我的{}是: {}. '.format(k, v))
show_my_info(name='manba', age=18, weight='90kg',sex='男')
print(show_my_info.__doc__)
help(show_my_info)

'''作用域'''
#Python中, def, class(我们后面会讲),会改变变量的作用域
#if, else, elif, while, for, try (我们后面会讲)不会改变变量的作用域
for i in range(0, 10):
    print (i)
print(i)  #即使出了for循环语句块,变量i仍然能访问到i变量.

def func():
    x=1
    print (x)
print(x)  #出了def的函数语句块,就不再能访问到x变量了.

'''文档字符串'''
#写注释对于提升程序的可读性有很大的帮助.前面我们介绍了#来表示单行注释.
def print_max(x, y):
    '''Print the max number of tow numbers

    The tow numbers must be integer'''

    x = int(x)
    y = int(y)

    if x > y:
        print(x)
    else:
        print(y)


print_max(3.1, 5.4)
#print(print_max.__doc__)
help(print_max)
def escrevar(msg):
    '''escrever adptador ao tamanho da letra, coloque escrevar('quaque coisa aqui') ele escreve com a linha do mesmo tamanho do texto'''

    tam = len(msg)
    print('-' * tam)
    print(msg)
    print('-' * tam)


escrevar('ola mundo')
escrevar('curso em video')

help(escrevar)
Example #44
0
y = data['entry1']['default']['y'][...]   # The […] extracts the lazy loaded data.
dnp.plot.line(x,y)                

scan sg -1.0 1.0 0.1
data2 = dnp.io.load("<File name from the beginning of the scan>")
y2=data2['entry1']['default']['y'][...]
dnp.plot.line(x,[y,y2])

ds = y - y2
ds.max()
ds.min()
dnp.plot.line(x,ds)

dnp.plot.line(x,[y-y2])

help(dnp)
help(dnp.plot)

scan sg -1.0 1.0 .1 sg1 -1.0 1.0 0.1

data3 = dnp.io.load("<File name from the beginning of the scan>")
data3
image = data3['entry1']['default']['y'][...]
image
image.shape=[21,21]
image

dnp.plot.image(image)

dnp.plot.line(image[0,:])
dnp.plot.line(image[:,0])
Example #45
0
import psycopg2
help(psycopg2)
dir() """ Short for 'directory """

# builtins = coleção de objetos comuns
dir(_builtins_)
""" ex - pow """
help(pow)
pow(2, 10)

# also we can search for modules: doc / name / package 

# modules

help(modules)

""" é necessário importar os módulos """

import math

dir()

help(math.radians)

math.radians(180)
Example #47
0
File: cls.py Project: snuky/School
def main():
    """Main."""
    parsed = parseCommandLine(sys.argv[1:])
    keys = parsed.keys()
    if ("help" in keys):
        if (len(keys) != 1):
            error("Kombinovat --help a ine argumenty sa nepatri", 1)
        help()
    if ("input" not in keys):
        inputStream = sys.stdin
    else:
        try:
            inputStream = open(parsed["input"], "r")
        except:
            error("Input file is not valid or readable", 2)
    inputContent = inputStream.read()
    parsedClasses = parseClasses(inputContent)
    parsedClasses = makeClassesComplete(parsedClasses)
    if ('conflicts' not in parsed.keys() and
       [c for c in parsedClasses.keys() if parsedClasses[c][4]]):
        error("Conflict", 21)

    if ('pretty-xml' in parsed.keys()):
        pretty = 4 if not parsed['pretty-xml'] else int(parsed['pretty-xml'])
    else:
        pretty = 4

    if ('details' not in parsed.keys()):
        top = Element('model')
        base = [c for c in parsedClasses.keys() if parsedClasses[c][0] == {}]
        for b in base:
            getXMLHierarchy(b, parsedClasses, top)
    else:
        if (parsed['details']):
            top = []
            if (parsed['details'] in parsedClasses.keys()):
                top = getXMLClassDetails(parsed['details'],
                                         parsedClasses[parsed['details']], False)
        else:  # all the classes
            top = Element('model')
            for cl in parsedClasses.keys():
                getXMLClassDetails(cl, parsedClasses[cl], top)
        if ('search' in parsed.keys()):
            r = top.xpath(parsed['search'])
            top = Element('result')
            toWrite = ""
            if r:
                for item in sorted(r):
                    if (isinstance(item, str)):
                        toWrite += "\n" + pretty * " " + item
                    else:
                        top.append(item)
                top.text = toWrite+"\n"
            else:
                pass  # TODO len hlavicka alebo tak volako
    final = prettify(top, pretty)
    if ("output" not in keys):
        outputStream = sys.stdout
    else:
        try:
            outputStream = open(parsed["output"], "w")
        except:
            error("Output file is not valid or writable", 3)
    outputStream.write(final)
Example #48
0
print("====__builtins__====")
items = dir(__builtins__)
for item in items:
    print(item)

print(help(max))        

import math
print("====dir(math)====")
for item in dir(math):
    print(item)    

print(help(math.asin))

print(math.__doc__)

class Demo:
    """
Demo - 
        learning Python class..."""
 
    def __init__(self, i):
        self.i = i
     
    def __str__(self):
        return str(self.i)
          
    def hello(self):
        """This is a function that say hello"""
        print("hello", self.i)
from scipy import integrate

help(integrate.quad)
a = lambda x, y: x * y ** 2
b = lambda x: 1
c = lambda x: -1
print(integrate.quad(a, 0, 1,1))

print(integrate.dblquad(a,0,2,b,c))
Example #50
0
from ie_mbdbl2018_monestarazi import datareader_doc

print(help(datareader_doc))

print(datareader_doc())
Example #51
0
argCount = len(sys.argv)
for i in range(1, argCount):
    token = sys.argv[i]

    # if this is a number, it must be a value to push to the stack
    if number_recognition.isDecimal(token):
        opstack.push(token)
        continue

    # if we're here, it must be an operator to try to carry it out
    try:
        opfunc = opmap[token][0]
        opfunc(opstack)
    except IndexError:
        print("empty stack")
        sys.exit(1)

    except Exception as e:
        print("invalid operator " + token)
        print("OS error: {0}".format(e))
        help(opstack)
        sys.exit(1)

# get the final value off the stack
finalValue = opstack.pop()
print("  Answer = " + str(finalValue))

# sanity check that the stack is empty
if not opstack.isEmpty():
    print("(warning: stack not empty so maybe you missed something)")
Example #52
0
def main(argv):
    try:
        logging_est()
        global time_start
        time_start = time.time()
        engine_ip = ""
        engine_pass = ""
        dg = ""
        dns_servers = ""
        try:
            opts, args = getopt.getopt(argv, "e:n:g:d:p:hv")
        except getopt.GetoptError:
            help()
        for opt, arg in opts:
            if opt == '-h':
                help()
            elif opt == '-e':
                engine_ip = arg
            elif opt == '-p':
                engine_pass = arg
            elif opt == '-n':
                new_engine_cidr = arg
            elif opt == '-g':
                dg = arg
            elif opt == '-d':
                dns_servers = arg
            elif opt == '-v':
                version()

        if (engine_ip == "" or engine_pass == "" or new_engine_cidr == "" or \
            dg == "" or dns_servers == "") :
            help()

        sys_server = system_serversess(engine_ip, "sysadmin", engine_pass)

        #Configure Static IP
        primary_interface = network.interface.get_all(sys_server)[0].reference
        print_debug("Primary interface identified as " + primary_interface)
        ni_obj = NetworkInterface()
        if_obj = InterfaceAddress()
        if_obj.address = new_engine_cidr
        if_obj.address_type = "STATIC"
        #if_obj.addressType = "DHCP"
        ni_obj.addresses = [if_obj]
        #print_debug(str(ni_obj))
        try:
            print_debug(
                "Changing the IP address. This operation can take up to 60 seconds to complete"
            )
            network.interface.update(sys_server, primary_interface, ni_obj)
        except socket_error as e:
            if e.errno == errno.ETIMEDOUT:
                print_debug("IP address changed")
            else:
                raise e
        #if we made it this far, we need to operate on the new IP.
        engine_ip = new_engine_cidr.split('/')[0]
        print_debug("ENGINE IP: " + engine_ip)
        #Now re-establish the server session
        sys_server = system_serversess(engine_ip, "sysadmin", engine_pass)

        #configure DNS
        print_debug("Setting DNS")
        dns_obj = DNSConfig()
        dns_obj.servers = dns_servers.split(",")
        dns_obj.domain = []
        service.dns.set(sys_server, dns_obj)

        #configure hostname
        print_debug("Setting hostname")
        system_info = SystemInfo()
        system_info.hostname = "LandsharkEngine"
        system.set(sys_server, system_info)

        #configue default gateway
        print_debug("Setting default gateway")
        de_routes = network.route.get_all(sys_server)
        print_debug("Current routes: ")
        print_debug(str(de_routes))
        default_gateway = NetworkRoute()
        default_gateway.destination = "default"
        default_gateway.out_interface = primary_interface
        #Check to see if a DG already exists. If so, delete it.
        for de_route in de_routes:
            if de_route.destination == 'default':
                print_debug("Found an existing DG. Deleting it")
                default_gateway.gateway = dg
                network.route.delete(sys_server, default_gateway)
        default_gateway.gateway = dg
        print_debug("Adding new route")
        network.route.add(sys_server, default_gateway)
        de_routes = network.route.get_all(sys_server)
        print_debug("New routes: ")
        print_debug(str(de_routes))

    except SystemExit as e:
        sys.exit(e)
    except HttpError as e:
        print_error("Connection failed to the Delphix Engine")
        print_error("Please check the ERROR message below")
        print_error(e.message)
        sys.exit(2)
    except JobError as e:
        print_error("A job failed in the Delphix Engine")
        print_error(e.job)
        elapsed_minutes = time_elapsed()
        print_info("Prime took " + str(elapsed_minutes) + \
            " minutes to get this far.")
        sys.exit(2)
    except KeyboardInterrupt:
        print_debug("You sent a CTRL+C to interrupt the process")
        elapsed_minutes = time_elapsed()
        print_info("Prime took " + str(elapsed_minutes) + \
            " minutes to get this far.")
        sys.exit(2)
    except socket_error as e:
        print_error("Connection failed to the Delphix Engine")
        print_error("Please check the ERROR message below")
        if e.errno == errno.ETIMEDOUT:
            print_debug("Connection timed out trying to connect to " \
                + engine_ip)
        else:
            print_error(e.message)
        sys.exit(2)
    except:
        print_error(sys.exc_info()[0])
        print_error(traceback.format_exc())
        elapsed_minutes = time_elapsed()
        print_info("Prime took " + str(elapsed_minutes) + \
            " minutes to get this far.")
        sys.exit(2)
Example #53
0
        inner(emp)
        print('=' * 35)
    return inner

@outer_deco
def sol_exam03(emp):
    for e in emp :
        if e[2] == min_p :
            print('최고 급여 : {}, 이름 : {}'.format(e[2], e[1]))
        elif e[2] == max_p :
            print('최저 급여 : {}, 이름 : {}'.format(e[2], e[1]))
        else :
            pass

print(sol_exam03(emp))
'''

help(enumerate)
print('관측치 :', len(ePay))
emean = ePay.mean()
print('전체 평균 급여 :', emean)
min_p = min(ePay)
max_p = max(ePay)

print('=' * 30)
for i, p in enumerate(ePay):  # index, pay
    if p == min_p:
        print(f'최저 급여 : {p}, 이름 : {eName[i]}')
    if p == max_p:
        print(f'최고 급여 : {p}, 이름 : {eName[i]}')
print('=' * 30)
Example #54
0
 def run(self, config, options, args, help=None):
     if help:
         return help()
Example #55
0
 
radius = 5
print("The diameter of the circle is", radius * 2, "cm.")
# The diameter of the circle is 10 cm.

 

# By default, the arguments are separated by a space, 
# as in the sep argument and ends with a newline, 
# as in the end argument. 
# If you want to change these, supply different values
# to those arguments. 

 
help(print)
# Help on built-in function print in module builtins:

# print(...)
#     print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

#     Prints the values to a stream, or to sys.stdout by default.
#     Optional keyword arguments:
#     file:  a file-like object (stream); defaults to the current sys.stdout.
#     sep:   string inserted between values, default a space.
#     end:   string appended after the last value, default a newline.
#     flush: whether to forcibly flush the stream.
# print('a', 'b', 'c')  # The separator is a space by default
# a b c
# print('a', 'b', 'c', sep=', ')
# a, b, c
## Data Excercise 1
# Read the data in gapminder_gdp_americas.csv (which should be in the same directory as gapminder_gdp_oceania.csv) into a variable called americas and display its summary statistics.

## Data Excercise 2
After reading the data for the Americas, use help(americas.head) and help(americas.tail)
to find out what DataFrame.head and DataFrame.tail do.

# Display the first three rows of this data

# Display the last three columns of this data?
# (Hint: you may need to change your view of the data.)

## Data Excercise 3
As well as the read_csv function for reading data from a file, Pandas provides a
 to_csv function to write dataframes to files. Applying what you’ve learned
 about reading from files, write one of your dataframes to a file called
 processed.csv. You can use help to get information on how to use to_csv.
Example #57
0
with lock:
   print 'Critical section 1'
   print 'Critical section 2'

# Ignore specific error type:
with ignored(OSError):
   os.remove('somefile.tmp')

@contextmanager
def ignored(*exceptions):
   try:
      yield
   except exceptions:
      pass

# redirect temporary contexts:
with open('somefile.txt', 'w') as f:
   with redirect_stout(f):
      help(pow)

@ contextmanager
def redirect_stdout(fileobj):
   oldstdout = sys.stdout
   sys.stdout = fileobj
   try:
      yeld fieldobj
   finally:
      sys.stdout = oldstout

# Convert No to String
my_string_number = str(my_number)
print(my_string_number)
#Converting a string into integer using int keyword
print( int("123"))
#ID used to for hecking id of the object
print(id(my_string))

#String are object in python
#String have methods also like uppercase,lowercase
print(my_string.upper())
print(my_string.lower())
print(my_string.strip())
#All string methods can be shown using dir
print(dir(my_string))
print(help(my_string.capitalize))
#checking data tyoe of 
print(type(my_string))
#String Slicing application
print(my_string[:1])
print(my_string[0:12])
print(my_string[0:13])
print(my_string[0:14])
print(my_string[0:-5])
print(my_string[:])
print(my_string[2:])
print(my_string[0])
#String formatting or Substitution application
string_1 ="I like %s" %"Python" #%s is a string variable and %"Python" is variable data to store
print(string_1)
var = "cookies"
Example #59
0
#return [6,7,8,9,10]
print fun (a,5)

def fun(arg):
    if arg > 3:
        return True
    else:
        return False
print filter(fun, a)

print filter(lambda arg:True if arg > 3 else False, a)
print filter(lambda arg: arg>3,a)

a= [1,2,3,4,5,6,7,8,9,10]

help(map)
def fun(arg):
    return arg*2

print map(fun, a)

#a= [1,2,3,4,5]
#def fun (lst):
   # pass

#120
#print fun(a)

"""
1*2=2
2*3=6
Example #60
0
import nuke.rotopaint

curves = nuke.toNode('RotoPaint1')['curves']
shape = curves.toElement('Shape2')
attrs = shape.getAttributes()
print help(attrs)
r = 0.7
g = 0.4
b = 0.8
a = 1
attrs.set(attrs.kRedOverlayAttribute, r)
attrs.set(attrs.kGreenOverlayAttribute, g)
attrs.set(attrs.kBlueOverlayAttribute, b)
attrs.set(attrs.kAlphaOverlayAttribute, a)