text:
<file_sep>

      <title>Sumiya yeasmin labannya</title>

Sumiya yeasmin labannya

ID:011192001

I'm a student of UIU. I live in Sayednagar.

        My home district is in Rajshahi.

I've completed my SSC from Cantonment Board High School Jahangirabd.

     Here's the facebook link to our school:Cantonment Board High School Jahangirabad

After SSC,I got admitted in Bogura Cantonment Public School And College for complete my HSC.

      Here's the facebook link to our college:

Bogura Cantonment Public School And College

Why do i choose to study in CSE?

Computer Engineers theorize,design,develop and apply the software and hardware for the programmes we use day in day out.Such a creative field it is,Studing Computer engineering helps you widen your  creative horizon and provide solutions to the problems people haven't thought about yet.

    Go to page2

branch_name: refs/heads/master

repo_language: HTML


text:
<repo_name>umairabbasDev/payment<file_sep>/src/components/MbileAccount.js
import React,{useRef} from "react";
import axios from "axios";
import { sha256 } from 'js-sha256';

function MbileAccount() {

  function hndle() {
  var d = new Date();
  d = new Date(d.getTime() - 3000000);
  var date_format_str = d.getFullYear().toString()+((d.getMonth()+1).toString().length==2?(d.getMonth()+1).toString():"0"+(d.getMonth()+1).toString())+(d.getDate().toString().length==2?d.getDate().toString():"0"+d.getDate().toString())+(d.getHours().toString().length==2?d.getHours().toString():"0"+d.getHours().toString())+((parseInt(d.getMinutes()/5)*5).toString().length==2?(parseInt(d.getMinutes()/5)*5).toString():"0"+(parseInt(d.getMinutes()/5)*5).toString());
  console.log(date_format_str);

   var mydata = {

        pp_Version: "1.1",
        pp_TxnType: "MWALLET",
        pp_Language : "EN",
        pp_MerchantID: "MC12607",
        pp_SubMerchantID: "",
        pp_Password: "<PASSWORD>",
        pp_BankID: "",
        pp_ProductID: "",
        pp_TxnRefNo: "T20201112025442",
        pp_Amount: "1000",
        pp_TxnCurrency: "PKR",
        pp_TxnDateTime: "20201112185500",
        pp_BillReference: "billRef",
        pp_Description: "Description",
        pp_TxnExpiryDateTime: "20201113185500",
        pp_ReturnURL: "http://ideotech-ma.com/",
        pp_SecureHash: "1AC78B753E935EC864255830BA5EFAD1EC44223DFCCAD6D1F84500EFC90D6571",
        ppmpf_1: "03123456789",

    }

  const url ="hhttps://sandbox.jazzcash.com.pk/ApplicationAPI/API/Payment/DoTransaction";

  axios
    .post(url,mydata)
    .then((response) => {
        console.log('working,', response);
    })
    .catch((err) => {
      console.log(`😱 request failed: ${err}`);
    });

}

//   function intosh(mydata) {

//     var str ='';
//    Object.entries(mydata).forEach(entry => {
//   const [key, value] = entry;
//       str = str +'&'+value;
//       // console.log(`${key}: ${value}`);
//     })
//     var ssh = sha256.hmac('y914g075s3', str);
//     return ssh
//   }

    // console.log(textInput.current.value);

  return (

     <input
            onClick={hndle}
            type="button"
            name="pp_TxnType"
            value="click to send request"
          />
          {/* <input
            // ref={pp_Language}
            // onChange={(event) => setpp_Language(event.target.value)}
            type="text"
            name="pp_Language"
            value="EN"
          /> */}

  );
}

export default MbileAccount;

{
  /*

 */
}
<file_sep>/src/components/Voucher.js
import React from 'react'

function Voucher() {
    return (

by Voucher

JazzCash HTTP POST (Page Redirection) Testing

<form name="jsform" method="post" action="https://sandbox.jazzcash.com.pk/CustomerPortal/transactionmanagement/merchantform/">
    <input type="hidden" name="pp_Version" value="1.1"/>
    <input type="hidden" name="pp_TxnType" value="OTC"/>
    <input type="hidden" name="pp_Language" value="EN"/>
    <input type="hidden" name="pp_MerchantID" value="MC12607"/>
    <input type="hidden" name="pp_SubMerchantID" value=""/>
    <input type="hidden" name="pp_Password" value="<PASSWORD>"/>
    <input type="hidden" name="pp_BankID" value="TBANK"/>
    <input type="hidden" name="pp_ProductID" value="RETL"/>

        pp_TxnRefNo:
        <input type="text" name="pp_TxnRefNo" id="pp_TxnRefNo" value="T20201109235902"/>

        pp_Amount:
        <input type="text" name="pp_Amount" value="1000"/>

    <input type="hidden" name="pp_TxnCurrency" value="PKR"/>
    <input type="hidden" name="pp_TxnDateTime" value="20201109235902"/>

        pp_BillReference:
        <input type="text" name="pp_BillReference" value="billRef"/>

        pp_Description:
        <input type="text" name="pp_Description" value="Description of transaction"/>

    <input type="hidden" name="pp_TxnExpiryDateTime" value="20201110235902"/>

        pp_ReturnURL:
        <input type="text" name="pp_ReturnURL" value="ideotech-ma.com"/>

    <input type="hidden" name="pp_SecureHash" value=""/>
    <input type="hidden" name="ppmpf_1" value="1"/>
    <input type="hidden" name="ppmpf_2" value="2"/>
    <input type="hidden" name="ppmpf_3" value="3"/>
    <input type="hidden" name="ppmpf_4" value="4"/>
    <input type="hidden" name="ppmpf_5" value="5"/>
    <button type="button" onclick="submitForm()">Submit</button>
</form>

{/* y914g075s3 */}

    Hash values string:
    <input type="text" id="hashValuesString" value=""/>

    )
}

export default Voucher

{/*

 */}
<file_sep>/src/components/Card.js
import React from "react";

// function submitForm() {
//   CalculateHash();
//   var IntegritySalt = document.getElementById("salt").innerText;
//   var hash = CryptoJS.HmacSHA256(
//     document.getElementById("hashValuesString").value,
//     IntegritySalt
//   );
//   document.getElementsByName("pp_SecureHash")[0].value = hash + "";

//   console.log("string: " + hashString);
//   console.log("hash: " + document.getElementsByName("pp_SecureHash")[0].value);

//   document.jsform.submit();
// }

function Card() {
  return (

by Card

JazzCash HTTP POST (Page Redirection) development phase

        <form
          name="jsform"
          method="post"
          action="https://sandbox.jazzcash.com.pk/CustomerPortal/transactionmanagement/merchantform/"
        >
          <input type="hidden" name="pp_Version" value="1.1" />
          <input type="hidden" name="pp_TxnType" value="MPAY" />
          <input type="hidden" name="pp_Language" value="EN" />
          <input type="hidden" name="pp_MerchantID" value="MC12607" />
          <input type="hidden" name="pp_SubMerchantID" value="" />
          <input type="hidden" name="pp_Password" value="<PASSWORD>" />
          <input type="hidden" name="pp_BankID" value="TBANK" />
          <input type="hidden" name="pp_ProductID" value="RETL" />

            pp_TxnRefNo:
            <input
              type="text"
              name="pp_TxnRefNo"
              id="pp_TxnRefNo"
              value="T20201109235742"
            />

            pp_Amount:
            <input type="text" name="pp_Amount" value="1000" />

          <input type="hidden" name="pp_TxnCurrency" value="PKR" />
          <input type="hidden" name="pp_TxnDateTime" value="20201109235742" />

            pp_BillReference:
            <input type="text" name="pp_BillReference" value="billRef" />

            pp_Description:
            <input
              type="text"
              name="pp_Description"
              value="Description of transaction"
            />

          <input
            type="hidden"
            name="pp_TxnExpiryDateTime"
            value="20201110235742"
          />

            pp_ReturnURL:
            <input type="text" name="pp_ReturnURL" value="ideotech-ma.com" />

          <input type="hidden" name="pp_SecureHash" value="" />
          <input type="hidden" name="ppmpf_1" value="1" />
          <input type="hidden" name="ppmpf_2" value="2" />
          <input type="hidden" name="ppmpf_3" value="3" />
          <input type="hidden" name="ppmpf_4" value="4" />
          <input type="hidden" name="ppmpf_5" value="5" />
          <button type="button" onclick="submitForm()">
            Submit
          </button>
        </form>
        {/* style="display:none;" */}
        {/*
          y914g075s3
         */}

          Hash values string:
          <input type="text" id="hashValuesString" value="" />

  );
}

export default Card;

{
  /*

 */
}
<file_sep>/src/App.js
import "./App.css";
import { BrowserRouter as Router, Route,  Switch } from "react-router-dom";
import MbileAccount from "./components/MbileAccount";
import Card from "./components/Card";
import Voucher from "./components/Voucher";
import NavBar from "./components/NavBar";

function App() {
  return (
    <Router>

        <NavBar/>
        <Switch>
          <Route path="/mAccount">
            <MbileAccount />
          </Route>
          <Route path="/voucher">
            <Voucher />
          </Route>
          <Route path="/">
            <Card />
          </Route>
        </Switch>

    </Router>
  );
}

export default App;

repo_language: JavaScript

repo_name: umairabbasDev/payment


text:
<repo_name>pysty1995/Swift<file_sep>/Test Serial Port v1.0/ReadASN/Examples/ORSSerialPortDemo/Swift/Sources/SerialPortDemoController.swift

import Cocoa

class SerialPortDemoController: NSObject, NSApplicationDelegate, ORSSerialPortDelegate, NSUserNotificationCenterDelegate {

    @IBOutlet weak var open_close_port: NSButton!
    @IBOutlet var incoming_data: NSTextView!

    @IBOutlet weak var U1_data: NSTextField!
    @IBOutlet weak var U5_length_data: NSTextField!
    @IBOutlet weak var U5_OTP_CODE: NSTextField!
    @IBOutlet weak var U1_data_length: NSTextField!
    @IBOutlet weak var U1_otp_code: NSTextField!
    @IBOutlet weak var status: NSTextField!
    @IBOutlet weak var result_text: NSTextFieldCell!
    @IBOutlet weak var time_start: NSTextField!
    @IBOutlet weak var time_end: NSTextField!
    @IBOutlet weak var duration: NSTextField!
    @IBOutlet weak var pass_count: NSTextField!
    @IBOutlet weak var fail_count: NSTextField!
    @IBOutlet weak var total_count: NSTextField!
    @IBOutlet weak var rate: NSTextField!

    var U5_otp_code: String = ""
    var timer0 = Timer()

    var allow: Bool = false
    var error_time: Bool = false
    var run_time = 0

    let format_date = DateFormatter()
    let format_time = DateFormatter()
    var start: Double = 0
    var end: Double = 0
    var i = 0
    var pass: Int = 0
    var fail: Int = 0
    var total: Int = 0
    var rate_success: Float = 0.0

    @IBAction func U1_input(_ sender: NSTextField) {

        let currentTime = Date()
        format_time.dateFormat = "HH:mm:ss"

        time_start.stringValue = ""
        time_end.stringValue = ""
        U1_data_length.stringValue = ""
        U1_otp_code.stringValue = ""
        U5_length_data.stringValue = ""
        U5_OTP_CODE.stringValue = ""
        result_text.stringValue = ""
        duration.stringValue = ""

        result_text.placeholderString = "Waiting"

        time_start.stringValue = format_time.string(from: currentTime)
        start = currentTime.timeIntervalSinceReferenceDate

        if allow == true{
        let u1_data: String = U1_data.stringValue
        print(u1_data)
        if u1_data == ""{
                status.stringValue = "No U1 input"
            }else{

                if u1_data.prefix(9) == "Accessory"{
                U1_data_length.stringValue = String(u1_data.count)
                        if u1_data.count == 42{
                            let index1 = u1_data.index(u1_data.startIndex, offsetBy: 25)
                            let index2 = u1_data.index(u1_data.startIndex, offsetBy: 41)
                            U1_otp_code.stringValue = String(u1_data[index1...index2])
                            }
                        else
                        {
                            U1_otp_code.stringValue = "Wrong U1 data"
                                    }
                    process()

            }

            }
        }
    }

    @IBAction func Start(_ sender: NSButton) {
        process()
    }

    func process(){

        timer0.invalidate()
        timer0 = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(Send1), userInfo: nil, repeats: false)
        timer0 = Timer.scheduledTimer(timeInterval: 0.55, target: self, selector: #selector(Send2), userInfo: nil, repeats: false)
        timer0 = Timer.scheduledTimer(timeInterval: 0.8, target: self, selector: #selector(U5_data_process), userInfo: nil, repeats: false)
        timer0 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(createCSV), userInfo: nil, repeats: false)

    }
    ///// Func to get the OTP code from U5, output is U5_otp_code
    @objc func U5_data_process(){
        let U5_data: String = incoming_data.string
        let U5_length = U5_data.count
        if U5_length > 200{
            U5_length_data.stringValue = String(U5_length)
            let index1 = U5_data.index(U5_data.startIndex, offsetBy: 160)
            let index2 = U5_data.index(U5_data.startIndex, offsetBy: 176)
            U5_otp_code = String(U5_data[index1...index2])
            U5_OTP_CODE.stringValue = String(U5_otp_code)
             check_code()

        }else
            {
                error_time = true
                let currentTime = Date()
                format_time.dateFormat = "HH:mm:ss"
                status.stringValue = "Can not read U5 otp!"
                U5_length_data.stringValue = ""
                U5_OTP_CODE.stringValue = ""
                result_text.stringValue = "NG"
                result_text.textColor = NSColor.red
                time_end.stringValue = format_time.string(from: currentTime)
                end = currentTime.timeIntervalSinceReferenceDate
                let result: Float = Float(end - start)
                if result > 0.7 && error_time == true{
                    fail += 1
                    duration.stringValue = "\(result)s"

                }
        }

    pass_count.stringValue = String(pass)
    fail_count.stringValue = String(fail)
    total = fail + pass
    rate_success = Float(pass) / Float(total) * 100
    print(rate_success)
    total_count.stringValue = String(total)
    let display_rate = NSString(format: "%.2f", rate_success)
    rate.stringValue = "\(display_rate)%"

    }

    ////// check result between U1 and U5 code
    @objc func check_code(){

        print("U5 is: \(U5_OTP_CODE.stringValue)")
        print("U1 is: \(U1_otp_code.stringValue)")
        let currentTime = Date()
        format_time.dateFormat = "HH:mm:ss"
        if U5_OTP_CODE.stringValue == U1_otp_code.stringValue{
            status.stringValue = "OTP is matched!"
            result_text.stringValue = "OK"
            result_text.textColor = NSColor.green
            time_end.stringValue = format_time.string(from: currentTime)
            end = currentTime.timeIntervalSinceReferenceDate
            let result: Float = Float(end - start)

            if result > 0.5{
            pass += 1
            duration.stringValue = "\(result)s"
            }
        }else{
            status.stringValue = "OTP is not matched!"
            result_text.stringValue = "NG"
            result_text.textColor = NSColor.red
            time_end.stringValue = format_time.string(from: currentTime)
            end = currentTime.timeIntervalSinceReferenceDate
            let result: Float = Float(end - start)

            if result > 0.5{
                fail += 1
                duration.stringValue = "\(result)s"

            }

        }

    }

    // MARK: -------> Send command:

      @objc func Send1() {
        incoming_data.string = ""
        let string1 = "quick_config" + "\r\n"
        let data1 = string1.data(using: String.Encoding.utf8)
        self.serialPort?.send(data1!)
    }
     @objc func Send2() {
        let string2 = "otp asnread 124" + "\r\n"
        let data2 = string2.data(using: String.Encoding.utf8)
        self.serialPort?.send(data2!)
    }
    // Clear the screen
    @IBAction func clear_func(_ sender: NSButton) {
        incoming_data.string = ""
        U1_data.stringValue = ""
        U1_otp_code.stringValue = ""
        U1_data_length.stringValue = ""
        U5_otp_code = ""
        U5_length_data.stringValue = ""
        U5_OTP_CODE.stringValue = ""
        result_text.stringValue = ""
        status.stringValue = ""
        pass_count.stringValue = ""
        fail_count.stringValue = ""
        total_count.stringValue = ""
        time_start.stringValue = ""
        time_end.stringValue = ""
        duration.stringValue = ""
        rate.stringValue = ""
    }
    @objc func clear(){
        incoming_data.string = ""
        U5_otp_code = ""
        U5_length_data.stringValue = ""
        U5_OTP_CODE.stringValue = ""

    }
    // Func to create .csv file

    @objc func createCSV() -> Void
    {

        let currentDate = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd-MM-yy"
        let date = dateFormatter.string(from: currentDate)
        let fileName = "Test." + "\(date)"
        let DocumentDirURL = try! FileManager.default.url(for: .desktopDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let fileURL = DocumentDirURL.appendingPathComponent("/Data/\(fileName)").appendingPathExtension("csv")
        var writeString = ""

        if let filehandle = try?FileHandle(forUpdating: fileURL)
        {

            filehandle.seekToEndOfFile()
            let newLine = "\(i),\(U5_OTP_CODE.stringValue),\(U1_otp_code.stringValue),\(result_text.stringValue),\(time_start.stringValue),\(duration.stringValue)\r\n"
            writeString.append(newLine)
            filehandle.write(writeString.data(using: .utf8)!)
            i = i + 1
        } else {
            do {

                writeString = "STT,U5 OTP Code,U1 OTP Code,Test result,Time test,Duration\r\n"
                let newLine = "\r\n"
                writeString.append(newLine)
                try "\(writeString)".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)

            } catch let error as NSError {
                print("Fail to write to URL")
                print(error)

            }

        }

    }

    //MARK:-------------------------------------------------------->SerialPort

    @objc let serialPortManager = ORSSerialPortManager.shared()

    @objc let availableBaudRates = [300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200, 230400]

    @objc dynamic var serialPort: ORSSerialPort? {
        didSet {
            oldValue?.close()
            oldValue?.delegate = nil
            serialPort?.delegate = self
        }
    }

    @IBAction func action_close_open_port(_ sender: NSButton) {
        if let port = self.serialPort{
            if(port.isOpen){
                port.close()
            }else{
                port.open()
            }
        }
    }
	// MARK: - ORSSerialPortDelegate
   @objc func listPort() {
        let availablePorts = ORSSerialPortManager.shared().availablePorts
        var i = 0
        for port in availablePorts {
            print("\(i). \(port.name)")
            i += 1

        }
    }
    @IBAction func stop_bit1(_ sender: NSMenuItem) {
        serialPort?.numberOfStopBits = 1
    }
    @IBAction func stop_bit_2(_ sender: NSMenuItem) {
        serialPort?.numberOfStopBits = 2
    }

       func serialPortWasOpened(_ serialPort: ORSSerialPort) {
        self.open_close_port.title = "Close"
        //serialPort.numberOfDataBits = 8
        //serialPort.dtr = true
        //serialPort.rts = true
        //serialPort.baudRate = 115200
        //serialPort.numberOfStopBits = 1
        //serialPort.parity = .none
        status.stringValue = "Serial port was opened!"
        allow = true
        print(serialPort.baudRate)
        print(serialPort.numberOfDataBits)
        print(serialPort.numberOfStopBits)
        print(serialPort.dtr)
        print(serialPort.rts)
        print(self.serialPort as Any)

	}

    func serialPortWasClosed(_ serialPort: ORSSerialPort) {
        self.open_close_port.title = "Open"
        status.stringValue = "Serial port was closed!"
        allow = false
    }

	func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
		if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {

            self.incoming_data.textStorage?.mutableString.append(string as String)
            self.incoming_data.needsDisplay = true
		}
	}

	func serialPortWasRemovedFromSystem(_ serialPort: ORSSerialPort) {
		self.serialPort = nil
        self.open_close_port.title = "Open"
        status.stringValue = "Serial port was removed!"
	}

	func serialPort(_ serialPort: ORSSerialPort, didEncounterError error: Error) {
		print("SerialPort \(serialPort) encountered an error: \(error)")
	}

	// MARK: - NSUserNotifcationCenterDelegate

	func userNotificationCenter(_ center: NSUserNotificationCenter, didDeliver notification: NSUserNotification) {
		let popTime = DispatchTime.now() + Double(Int64(3.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
		DispatchQueue.main.asyncAfter(deadline: popTime) { () -> Void in
			center.removeDeliveredNotification(notification)
		}
	}

	func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
		return true
	}

    override init() {
        super.init()

        let nc = NotificationCenter.default
        nc.addObserver(self, selector: #selector(serialPortsWereConnected(_:)), name: NSNotification.Name.ORSSerialPortsWereConnected, object: nil)
        nc.addObserver(self, selector: #selector(serialPortsWereDisconnected(_:)), name: NSNotification.Name.ORSSerialPortsWereDisconnected, object: nil)
        NSUserNotificationCenter.default.delegate = self
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

   //  MARK: - Notifications at System

    @objc func serialPortsWereConnected(_ notification: Notification) {
        if let userInfo = notification.userInfo {
            let connectedPorts = userInfo[ORSConnectedSerialPortsKey] as! [ORSSerialPort]
            status.stringValue = "Ports were connected: \(connectedPorts)"
        }
    }

    @objc func serialPortsWereDisconnected(_ notification: Notification) {
        if let userInfo = notification.userInfo {
            let disconnectedPorts: [ORSSerialPort] = userInfo[ORSDisconnectedSerialPortsKey] as! [ORSSerialPort]
            status.stringValue = "Ports were disconn: \(disconnectedPorts)"
        }
    }

}

repo_language: Swift


text:
<repo_name>sirben181/project<file_sep>/READme.md
am enjoying js projects..this a timer using js

branch_name: refs/heads/main

repo_language: Markdown


text:
<file_sep>"""
Author: <NAME>
GitHub: http://github.com/avannaldas/PythonLogger
"""

import datetime

class Logger:
  """
  Standard output printing helper which prefixes useful info with message.
  Can be used with long running operations to indicate progress/running time.
  All options can be configured through constructor and has sensible defaults.
  """

  def __init__(self,
    startTime=datetime.datetime.now(),
    showDate=False,
    showTime=True,
    showTotalElapsed=False,
    showElapsedSinceLastLog=True,
    showLoggerInitMessage=True,
    addLineBreaks=False,
    returnLogStringInstead=False,
    referenceId="NA"):

    self.startTime = startTime
    self.showDate = showDate
    self.showTime = showTime
    self.showTotalElapsed = showTotalElapsed
    self.showElapsedSinceLastLog = showElapsedSinceLastLog
    self.previousLogTime = startTime
    self.referenceId = referenceId
    self.addLineBreaks = addLineBreaks
    self.returnLogStringInstead = returnLogStringInstead
    self.eventsDict = { }

    if(showLoggerInitMessage):
      print(self.getLogString("Logger initialized"))

  def getLogString(self, msg="", eventName="", elapsed=None):
    now = datetime.datetime.now()
    msgStr = ""
    if(self.referenceId != "NA"):
      msgStr = "[ReferenceId:" + self.referenceId + "]:"

    if(self.showDate == True and self.showTime == False):
      msgStr = msgStr + '[' + now.strftime("%d-%m-%Y") + ']:'
    elif(self.showDate == False and self.showTime == True):
      msgStr = msgStr + '[' + now.strftime("%H:%M:%S") + ']:'
    elif (self.showDate and self.showTime):
      msgStr = msgStr + '[' + now.strftime("%d-%m-%Y %H:%M:%S") + ']:'

    if(self.showTotalElapsed):
      msgStr = msgStr + '[Total Elapsed Seconds:' + str(int((now - self.startTime).total_seconds())) + ']:'

    if(elapsed is None and self.showElapsedSinceLastLog):
      msgStr = msgStr + '[Elapsed Seconds (diff):' + str(int((now - self.previousLogTime).total_seconds())) + ']:'
    elif(elapsed is not None):
      msgStr = msgStr + '[Elapsed Seconds:' + elapsed + ']:'
    self.previousLogTime = now

    if(eventName is not None and len(eventName)>0):
      msgStr = msgStr + '[Event:' + eventName + ']:'

    if(self.addLineBreaks):
      msgStr = msgStr + "\n"

    return (msgStr + msg)

  def log(self, msg="", eventName="", elapsed=None):
    if(self.returnLogStringInstead):
      return self.getLogString(msg, eventName, elapsed)
    print(self.getLogString(msg, eventName, elapsed))

  def logStartEvent(self, name):
    self.eventsDict[name] = datetime.datetime.now()
    return self.log("Event started.", name)

  def logEndEvent(self, name):
    now = datetime.datetime.now()
    if (name in self.eventsDict):
      startEvent = self.eventsDict[name]
      del self.eventsDict[name]
      return self.log("Event complete.", name, str(int((now - startEvent).total_seconds())))
    else:
      return self.log("Event complete, logStartEvent() not called or logEndEvent() already called.", name)
<file_sep># Python Logger
This is a python standard output printing helper which prefixes useful info to the message to be printed. Can be used in long running operations as an indication of progress and running time. Has several options which can be configured through constructor. All options have sensible defaults, so that you can just instantiate an object and start using.

## Motivation
As I was working on a ML problem, there were many bits of code which really took long time. I started adding print() statements to log and track the progress. Then I included timestamp in every print, helps when a same message is printed in a long running loop. Then I added elapsed time. Then made a helper function to prefix the metadata - timestamp, elapsed time, etc. in print statement. And, as the ML program was still training, one hour later, this is what a single line of code turned into!

languages: Markdown Python

repo_name: avannaldas/PythonLogger


text:
<file_sep>package br.edu.infnet.appatrobsonm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttribute;

import br.edu.infnet.appatrobsonm.model.negocio.Pedido;
import br.edu.infnet.appatrobsonm.model.negocio.Usuario;
import br.edu.infnet.appatrobsonm.model.service.ClienteService;
import br.edu.infnet.appatrobsonm.model.service.PedidoService;

@Controller
public class PedidoController {

	@Autowired
	private PedidoService pedidoService;

	@Autowired
	private ClienteService clienteService;

	@GetMapping(value = "/pedido")
	public String showDetalhe(Model model, @SessionAttribute("user") Usuario usuario) {

		model.addAttribute("lista", pedidoService.obterLista());
		model.addAttribute("cliente", clienteService .obterLista());

		return "pedido/detalhe";
	}

	@PostMapping(value = "/pedido/incluir")
	public String incluir (Pedido pedido, @SessionAttribute("user") Usuario usuario) {

		pedido.setUsuario(usuario);

		pedidoService.incluir(pedido);

		return "redirect:/pedido";

	}

	@GetMapping(value ="/pedido/{id}/excluir")
	public String excluir(@PathVariable Integer id ) {

		return "redirect:/pedido";
	}

}
<file_sep>package br.edu.infnet.appatrobsonm.model.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import br.edu.infnet.appatrobsonm.model.negocio.Usuario;
import br.edu.infnet.appatrobsonm.model.repository.IUsuarioRepository;

@Service
public class UsuarioService {

	@Autowired
	private IUsuarioRepository usuarioRepository;

	public Usuario autenticacao(String email, String senha) {
		return usuarioRepository.autenticacao(email,senha);
	}

	public List<Usuario> obterLista() {

		return (List<Usuario>)usuarioRepository.findAll();
	}

	public void incluir(Usuario usuario) {
		usuarioRepository.save(usuario);
	}

	public void excluir(Integer id) {
		usuarioRepository.deleteById(id);
	}

}
<file_sep>package br.edu.infnet.appatrobsonm.model.repository;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import br.edu.infnet.appatrobsonm.model.negocio.Usuario;

@Repository
public interface IUsuarioRepository extends CrudRepository<Usuario, Integer> {

	@Query ("from Usuario u where u.email=:email and u.senha=:senha")
	Usuario autenticacao(String email, String senha);

}
<file_sep>package br.edu.infnet.appatrobsonm.model.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import br.edu.infnet.appatrobsonm.model.negocio.Pedido;
import br.edu.infnet.appatrobsonm.model.negocio.Usuario;
import br.edu.infnet.appatrobsonm.model.repository.IPedidoRepository;

@Service
public class PedidoService {

	@Autowired
	private IPedidoRepository pedidoRepository;

	public void incluir (Pedido pedido) {
		pedidoRepository.save(pedido);
	}

	public void excluir (Integer id) {
		pedidoRepository.deleteById(id);
	}

	public List<Pedido> obterLista() {
		return (List<Pedido>)pedidoRepository.findAll();
	}

	public List<Pedido> obterLista(Usuario usuario) {
		return (List<Pedido>)pedidoRepository.obterLista(usuario.getIdUsuario(), Sort.by(Sort.Direction.ASC, "descricao"));
	}
}
<file_sep>spring.datasource.url=spring.datasource.url=jdbc:mysql://localhost:8080/dbatrob?createDatabaseIfNotExist=true&useTimezone=true&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.mc.view.prefix=/WEB-INF/jsp/
spring.mc.view.suffix=.jsp

languages: Java INI

repo_language: Java

repo_name: robsonbborges/atjavaee


text:
<repo_name>sclchic/lerna_test6<file_sep>/lerna_test6/packages/scl_443_pkg2/__tests__/scl_443_pkg2.test.js
'use strict';

const scl443Pkg2 = require('..');

describe('scl_443_pkg2', () => {
    it('needs tests');
});
<file_sep>/lerna_test6/packages/scl_443_pkg1/README.md
# `scl_443_pkg1`

> TODO: description

## Usage

```
const scl443Pkg1 = require('scl_443_pkg1');

// TODO: DEMONSTRATE API
```

languages: Markdown JavaScript


text:
<file_sep>import React from "react";

function SectionHeadline({ text }) {
  return (

      {text}

  );
}

export default SectionHeadline;
<file_sep>import React from "react";
import "./Tabs.css";

export const TABS = [
  "Address Analysis",
  "Overall Summary",
  "Daily Trend - Sales",
  "Daily Trend - Siring"
];

const Tab = ({ title, active, setActiveTab }) => {
  return (

 setActiveTab(title)}
    >

{title}

  );
};

function Tabs({ activeTab, setActiveTab }) {
  return (

      {TABS.map(t => {
        return (
          <Tab
            key={t}
            title={t}
            active={t === activeTab}
            setActiveTab={setActiveTab}
          />
        );
      })}

  );
}

export default Tabs;
<file_sep>import React, { useState } from "react";
import Tabs, { TABS } from "./Tabs";
import SalesSummary from "./SalesSummary";
import AuctionSummary from "./Auction/AuctionSummary";
import MyAnalysis from "./Masters/MyAnalysis";
import DailyTrends from "./Trends/DailyTrends";
import SiringDailyTrends from "./Trends/SiringDailyTrends";
import "./Home.css";

function Home() {
  const [activeTab, setActiveTab] = useState(TABS[0]);

  const activeView = () => {
    switch (activeTab) {
      case TABS[0]: {
        return <MyAnalysis />;
      }

      case TABS[1]: {
        return <AuctionSummary />;
      }

      case TABS[2]: {
        return <DailyTrends />;
      }

      case TABS[3]: {
        return <SiringDailyTrends />;
      }

      default:
        return null;
    }
  };

  return (

CryptoKitties Subgraph Dapp

        <Tabs activeTab={activeTab} setActiveTab={setActiveTab} />

{activeView()}

  );
}

export default Home;
<file_sep>import React, { useState } from "react";
import { Query } from "react-apollo";
import { GET_DAILY_TRENDS_SIRING } from "../../queries/siring";
import SectionHeadline from "../common/SectionHeadline";
import DatePickers from "../common/DatePickers";
import Loading from '../common/Loading';
import Error from '../common/Error';
import moment from "moment";
import ApolloClient from "apollo-boost";
import { InMemoryCache } from "apollo-cache-inmemory";
import { renderChart } from "./DailyTrends";

const cache = new InMemoryCache();

export const customClient = new ApolloClient({
  uri: "https://api.thegraph.com/subgraphs/name/sudeepb02/cryptokitties-siringauction",
  cache
});

function SiringDailyTrends() {
  const newDate = startBool => {
    const date = startBool
      ? moment().subtract(11, "days")
      : moment().subtract(1, "days");
    return date._d;
  };
  const [startDate, setStartDate] = useState(newDate(true));
  const [endDate, setEndDate] = useState(newDate(false));

  const formatDate = dateObject =>
    String(Math.floor(dateObject.getTime() / 1000 / 24 / 60 / 60));

  const formattedStartDate = formatDate(startDate);
  const formattedEndDate = formatDate(endDate);

  return (
    <Query
      query={GET_DAILY_TRENDS_SIRING}
      client={customClient}
      variables={{
        orderBy: "id",
        start: formattedStartDate,
        end: formattedEndDate
      }}
    >
      {({ loading, error, data, fetchMore }) => {
        if (loading) {
          return <Loading />
        }

        if (error) {
          return <Error />
        }

        return (

            <SectionHeadline text="Siring Auctions Created - 10 Day Trend" />
            <DatePickers
              startDate={startDate}
              setStartDate={setStartDate}
              endDate={endDate}
              setEndDate={setEndDate}
            />
            {renderChart(data, true)}

        );
      }}
    </Query>
  );
}

export default SiringDailyTrends;
<file_sep>import React from "react";
import { Query } from "react-apollo";
import { GET_AUCTIONS } from "../queries/auctionCreated";

function AuctionCreated() {
  return (
    <Query
      query={GET_AUCTIONS}
      variables={{
        itemsPerPage: 10
      }}
    >
      {({ loading, error, data, fetchMore }) => {
        if (loading) {
          return
loading...
;
        }

        if (error) {
          return
error...
;
        }

        const { auctionCreateds } = data;

        return
query success?
;
      }}
    </Query>
  );
}

export default AuctionCreated;<file_sep>import React, { useState } from "react";
import { Query } from "react-apollo";
import { GET_SIRING_SUMMARY } from "../../queries/siringSummary";
import { customClient } from "../Trends/SiringDailyTrends";
import Loading from "../common/Loading";
import Error from "../common/Error";
import SectionHeadline from "../common/SectionHeadline";
import InfoUnit from "../InfoUnit";

function SiringSummary() {
  return (
    <Query query={GET_SIRING_SUMMARY} client={customClient}>
      {({ loading, error, data, fetchMore }) => {
        if (loading) {
          return <Loading />;
        }

        if (error) {
          return <Error />;
        }

        const { siringSummaries } = data;
        const {
          auctionsCancelled,
          auctionsCompleted,
          auctionsCreated,
          valueCompleted,
          valueCancelled,
          valueCreated
        } = siringSummaries[0];
        const timedOut =
          auctionsCreated - auctionsCancelled - auctionsCompleted;
        console.log("data", data);

        return (

            <SectionHeadline text="Siring Summary" />
            <InfoUnit
              title="Completed"
              value={auctionsCompleted}
              pct={auctionsCompleted / auctionsCreated}
            />
            <InfoUnit
              title="Cancelled"
              value={auctionsCancelled}
              pct={auctionsCancelled / auctionsCreated}
            />
            <InfoUnit
              title="Timed Out"
              value={timedOut}
              pct={timedOut / auctionsCreated}
            />
            <InfoUnit
              title="All Time Auctions"
              value={auctionsCreated}
              pct={true}
            />
            <InfoUnit
              title="Value Completed"
              value={valueCompleted}
              wei={true}
              />
            <InfoUnit
              title="Value Created"
              value={valueCreated}
              wei={true}
              />
            <InfoUnit
              title="Value Cancelled"
              value={valueCancelled}
              wei={true}
            />

        );
      }}
    </Query>
  );
}

export default SiringSummary;
<file_sep>import React from "react";
import { Query } from "react-apollo";
import { GET_SALES_SUMMARY } from "../queries/salesSummary";
import InfoUnit from "./InfoUnit";
import SectionHeadline from "./common/SectionHeadline";
import Error from "./common/Error";
import Loading from "./common/Loading";
import "./SalesSummary.css";

function SalesSummary() {
  return (
    <Query
      query={GET_SALES_SUMMARY}
      variables={{
        id: 1
      }}
    >
      {({ loading, error, data, fetchMore }) => {
        if (loading) {
          return <Loading />;
        }

        if (error) {
          return <Error />;
        }

        const { salesSummary } = data;
        const { valueCompleted, valueCreated, valueCancelled } = salesSummary;

        return (

            <InfoUnit
              title="Value Completed"
              value={valueCompleted}
              wei={true}
            />
            <InfoUnit title="Value Created" value={valueCreated} wei={true} />
            <InfoUnit
              title="Value Cancelled"
              value={valueCancelled}
              wei={true}
            />

        );
      }}
    </Query>
  );
}

export default SalesSummary;
<file_sep>import React from "react";

function Error() {
  return
Error...please try again
;
}

export default Error;
<file_sep>import React from "react";
import NumberFormat from "react-number-format";
import Web3 from "web3";
import "./InfoUnit.css";

const web3 = new Web3();

function InfoUnit({ title, value, wei, pct }) {
  const sanitize = weiVal => {
    let val = web3.utils.fromWei(weiVal, "ether");
    return val;
  };

  return (

{title}

          <NumberFormat
            displayType="text"
            value={wei ? sanitize(value) : value}
            thousandSeparator={true}
            decimalScale={0}
          />{" "}
          {wei &&
Ξ
}
          {pct && (
              <div className={`${pct === true ? "ml-2" : "ml-3"}`}>{Math.floor(pct * 100) + "%"}

          )}

  );
}

export default InfoUnit;
<file_sep>import React from "react";
import { BarLoader } from "react-spinners";

function Loading() {
  return (

      <BarLoader />

  );
}

export default Loading;
<file_sep>import React, { useState } from "react";
import SectionHeadline from "../common/SectionHeadline";
import { GET_DAILY_TRENDS } from "../../queries/dailyTrends";
import { Query } from "react-apollo";
import LineChart from "react-linechart";
import Loading from "../common/Loading";
import Error from "../common/Error";
import Moment from "react-moment";
import moment from "moment";
import DatePickers from "../common/DatePickers";
import "react-datepicker/dist/react-datepicker.css";
import "../../../node_modules/react-linechart/dist/styles.css";
import "./Trends.css";

export const renderChart = (dataInput, siring) => {
  let xMin, xMax;
  const dailyStats = siring ? dataInput.dailyStatSirings : dataInput.dailyStats;
  const points = dailyStats.reverse().map((p, i) => {
    let date = <Moment unix={true}>{Number(p.id) * 24 * 60 * 60}</Moment>;

    date = date.props.children;
    date = new Date(date * 1000);
    date = date.toString().split(" ");
    date = String(date[1]) + " " + String(date[2]);

    if (i === 0) xMin = date;

    return {
      x: Number(p.id) * 24 * 60 * 60,
      y: p.auctionsCreatedToday
    };
  });

  const data = [
    {
      color: "steelblue",
      points
    }
  ];

  const xDisplay = xValue => {
    const d = new Date(xValue * 1000);

    const formattedTime =
      d.getMonth() + 1 + "/" + d.getDate() + "/" + d.getFullYear();
    return formattedTime;
  };

  return (
    <LineChart
      yMin={0}
      xDisplay={xDisplay}
      hideXLabel
      hideYLabel
      width={600}
      height={400}
      data={data}
    />
  );
};

function DailyTrends() {
  const newDate = startBool => {
    const date = startBool
      ? moment().subtract(11, "days")
       : moment().subtract(1, "days");
    return date._d;
  };
  const [startDate, setStartDate] = useState(newDate(true));
  const [endDate, setEndDate] = useState(newDate(false));

  const formatDate = dateObject =>
    String(Math.floor(dateObject.getTime() / 1000 / 24 / 60 / 60));

  const formattedStartDate = formatDate(startDate);
  const formattedEndDate = formatDate(endDate);

  return (

      <SectionHeadline text="Sales Auctions Created - 10 Day Trend" />
      <DatePickers
        startDate={startDate}
        setStartDate={setStartDate}
        endDate={endDate}
        setEndDate={setEndDate}
      />
      <Query
        query={GET_DAILY_TRENDS}
        variables={{
          orderBy: "id",
          start: formattedStartDate,
          end: formattedEndDate
        }}
      >
        {({ loading, error, data, fetchMore }) => {
          if (loading) {
            return <Loading />
          }

          if (error) {
            return <Error/>
          }

          return renderChart(data);
        }}
      </Query>

  );
}

export default DailyTrends;
<file_sep>import { gql } from "apollo-boost";

export const GET_MASTERS = gql`
  query Masters($id: ID!) {
    masters(where: { id: $id }) {
      id
      firstTransacted
      lastTransacted
      totalKittiesBought
      totalKittiesSold
      valueSpentBuying
      valueEarnedSelling
    }
  }
`;<file_sep>import React, { useState } from "react";
import { Query } from "react-apollo";
import { GET_MASTERS } from "../../queries/masters";
import SectionHeadline from "../common/SectionHeadline";
import Loading from "../common/Loading";
import Error from "../common/Error";
import EthAddress from "ethereum-address";
import Blockies from "react-blockies";
import Moment from "react-moment";
import Web3 from "web3";
import "./Masters.css";

const web3 = new Web3();

function MyAnalysis() {
  const [showData, toggleShowData] = useState(false);
  const [error, setError] = useState(null);
  const [analysisAddress, setAnalysisAddress] = useState("");

  const exampleAddress = "0x42dfa7e528cc9d9c69a855ef2eabf68a5afa8fbe"

  const sanitize = weiVal => {
    let val = web3.utils.fromWei(weiVal, "ether");
    return val.slice(0, 5);
  };

  const submit = () => {
    if (EthAddress.isAddress(analysisAddress)) {
      toggleShowData(true);
    } else {
      setError("Invalid Ethereum address");
      setTimeout(() => {
        setError(null);
      }, 2000);
    }
  };

  if (!showData) {
    return (

        <SectionHeadline text="Address Analysis" />

Enter an Ethereum address

            <input
              value={analysisAddress}
              onChange={evt => setAnalysisAddress(evt.target.value)}
              className="address-input"
            />

              Submit

  setAnalysisAddress(exampleAddress)}>Use example address

{error}

    );
  }

  return (
    <Query
      query={GET_MASTERS}
      variables={{
        id: analysisAddress
      }}
    >
      {({ loading, error, data, fetchMore }) => {
        if (loading) {
          return <Loading />;
        }

        if (error) {
          return <Error />
        }

        const { masters } = data;

        if (!masters || !masters[0] || !masters[0].id) {
          return
No results
;
        }

        const {
          firstTransacted,
          lastTransacted,
          totalKittiesBought,
          totalKittiesSold,
          valueSpentBuying,
          valueEarnedSelling
        } = masters[0];

        return (

            <SectionHeadline text="Address Analysis" />

              <Blockies seed={analysisAddress} size={10} />

First Transaction

                <Moment
                  fromNow={true}
                  unix={true}
                  className="mx-auto section-value"
                >
                  {firstTransacted}
                </Moment>

Last Transaction

                <Moment
                  fromNow={true}
                  unix={true}
                  className="mx-auto section-value"
                >
                  {lastTransacted}
                </Moment>

Kitties Bought

                  {totalKittiesBought}

Kitties Sold

{totalKittiesSold}

Spent on Kitties

                  {sanitize(valueSpentBuying)} Ξ

Earned on Kitties

                  {sanitize(valueEarnedSelling)} Ξ

        );
      }}
    </Query>
  );
}

export default MyAnalysis;
<file_sep>import { gql } from "apollo-boost";

export const GET_SALES_SUMMARY = gql`
  query SalesSummary($id: Int!) {
    salesSummary(id: $id) {
      id
      auctionsCreated
      auctionsCompleted
      auctionsCancelled
      valueCreated
      valueCompleted
      valueCancelled
    }
  }
`;<file_sep>import { gql } from "apollo-boost";

export const GET_DAILY_TRENDS = gql`
  query DailyStats($start: String!, $end: String!) {
    dailyStats(first: 10, orderBy: id, where: { id_gt: $start, id_lt: $end }) {
      id
      auctionsCreatedToday
      auctionsCompletedToday
    }
  }
`;
<file_sep>Front end for CryptoKitties Subgraph

`npm install && npm start`


text:
<repo_name>johanbuys/nupload<file_sep>/README.md
# This Fork #

Added methods to support https://s3.amazonaws.com/{bucketName} in FormBuilder. It didn't work for me with the https://{bucketname}.s3.amazonaws.com/ url.

Methods are as follows:
- BeginAsyncUploadFormAlt as apposed to BeginAsyncUploadForm, HtmlHelper extension this version will output https://s3.amazonaws.com/{bucketName}

# Introduction #

Nupload makes it easy to support signed object downloads and asynchronous CORS-enabled form uploads to and from Amazon S3 and Google Cloud Storage

# How to Use #

Check out the sample application or read [the blog post about using Nupload](http://blog.appharbor.com/2013/01/10/asynchronous-browser-uploads-to-s3-and-gcs-using-cors-aspnet-mvc)

repo_name: johanbuys/nupload


text:
<file_sep>
## f = function(x) ...

Numerical.differentiation = function(point,h,tol=1e-10,print.trace="FALSE"){

  options(digits=20)
  Bs = numeric()
  Bl = numeric()
  Bu = numeric()
  ### Step 1 initalize the boundaries for B

  ### Initial step size h
  f.x = f(point)
  f.x.h = f(point - h)

  ### Y = mX + B
  Y = f.x

  m = (f.x - f.x.h)/h

  mX = ((f.x - f.x.h)/h)*point

  B = f.x - ((f.x - f.x.h)/h)*point

  ### Initial interval for B given inputted h-step-value

  f.x.h.lower = f(point - h)
  f.x.h.upper = f(point + h)

  B1 = f.x - ((f.x - f.x.h.lower)/h)*point
  B2 = f.x - ((f.x.h.upper-f.x)/h)*point

  low.B = min(c(B1,B2))
  high.B = max(c(B1,B2))

  lower.B = low.B
  upper.B = high.B

  ## Return "Derivative Does Not Exist" if lower.B and upper.B are identical to 20 digits
  if(lower.B==upper.B){

    par(mfrow=c(1,2))
    plot(f, xlim = c(point-(100*h), point+(100*h)),col='blue',ylab='f(x)')
    points(point,f.x, pch=19,col='red')
    plot(f, xlim = c(point-1, point+1),col='blue',ylab='f(x)')
    points(point,f.x, pch=19,col='red')
    return(c("Derivative Does Not Exist"))}

  new.B = mean(c(lower.B,upper.B))

  i=1
  while(i>=1L){
    Bl[i] = lower.B
    Bu[i] = upper.B
    new.f = function(x) -f.x + ((f.x - f(point - x))/x)*point + new.B

    ###  SOLVE FOR h, we just need the negative or positive sign from the tested B
    ###  This can be better served with an exact solution

    inferred.h = uniroot(new.f, c(-2*h,2*h))$root

    if(print.trace=="TRUE") {print(c("Iteration"=i, "h"=inferred.h,"Lower B" = lower.B,"Upper B" = upper.B))}

    Bs[i]=new.B

    ## Stop when the inferred h is within the tolerance level
    if(abs(inferred.h)<tol) {

      final.B = mean(c(upper.B,lower.B))
      slope = solve(point, f.x-final.B)

      z = complex(real = point, imaginary = inferred.h)

      par(mfrow=c(1,3))

      ## Plot #1
      plot(f, xlim = c(min(c(point-(100*h), point+(100*h)),0),max(c(point-(100*h), point+(100*h)),0)),
           col='azure4',ylab='f(x)',lwd=2,
           ylim = c(min(c(min(c(B1,B2)),min(na.omit(f((point-(100*h)):(point+(100*h))))))),
        max(c(max(na.omit(f((point-(100*h)):(point+(100*h))))),
              max(c(B1,B2))))),
           main='f(x) and initial y-intercept range')
      abline(h=0,v=0,col='grey')
      points(point,f.x, pch=19,col='green')
      points(point-h,f.x.h.lower,col=ifelse(B1==high.B,'blue','red'),pch=19)
      points(point+h,f.x.h.upper,col=ifelse(B1==high.B,'red','blue'),pch=19)
      points(x=rep(0,2),y=c(B1,B2),col=c(ifelse(B1==high.B,'blue','red'),ifelse(B1==high.B,'red','blue')),pch=1)
      segments(0,B1,point-h,f.x.h.lower,col=ifelse(B1==high.B,'blue','red'),lty=2)
      segments(0,B2,point+h,f.x.h.upper,col=ifelse(B1==high.B,'red','blue'),lty=2)

      ## Plot #2
      plot(f,col='azure4',ylab='f(x)',lwd=3,main='f(x) narrowed range and secant lines',
          xlim = c(min(c(point-h,point+h,0)),max(c(point+h,point-h,0))),
          ylim= c(min(c(B1,B2,f.x.h.lower,f.x.h.upper)),max(c(B1,B2,f.x.h.lower,f.x.h.upper)))

          )
      abline(h=0,v=0,col='grey')
      points(point,f.x, pch=19,col='red')
      points(point-h,f.x.h.lower,col=ifelse(B1==high.B,'blue','red'),pch=19)
      points(point+h,f.x.h.upper,col=ifelse(B1==high.B,'red','blue'),pch=19)
      points(point,f.x, pch=19,col='green')
      segments(0,B1,point-h,f.x.h.lower,col=ifelse(B1==high.B,'blue','red'),lty=2)
      segments(0,B2,point+h,f.x.h.upper,col=ifelse(B1==high.B,'red','blue'),lty=2)
      points(x=rep(0,2),y=c(B1,B2),col=c(ifelse(B1==high.B,'blue','red'),ifelse(B1==high.B,'red','blue')),pch=1)

   ## Plot #3
      plot(Bs,ylim=c(min(c(Bl,Bu)),max(c(Bl,Bu))),xlab="Iterations",ylab="y-inetercept",col='green',pch=19,
           main='Iterated range of y-intercept')
      points(Bl,col='red',ylab='')
      points(Bu,col='blue',ylab='')

      legend('topright',c("Upper y-intercept","Lower y-intercept","Mean y-intercept"),col= c('blue','red','green'),pch=c(1,1,19))

      return(as.matrix(c("Value of f(x) at point"=f(point),
                         "Final y-intercept (B)" = final.B,
                         "DERIVATIVE"=slope,
                         "Inferred h" = inferred.h,
                         "iterations"=i,
                         Finite.step(point,h)[1:2],
                         "Averaged Finite Step Initial h "=Finite.step(point,h)[3],
                         "Inferred h"=Finite.step(point,inferred.h)[1:2],
                         "Inferred h Averaged Finite Step"=Finite.step(point,inferred.h)[3],
                        "Complex Step Derivative (Initial h)" = Im(f(z))/Im(z))))
    }

    ## NARROW THE RANGE OF B BASED ON SIGN OF INFERRED.H
    if(B1==high.B){
      if(sign(inferred.h) < 0) {
        lower.B = new.B
        upper.B = upper.B
      }

      else {
        upper.B = new.B
        lower.B = lower.B
      }}  else{
        if(sign(inferred.h) < 0) {
          lower.B = lower.B
          upper.B = new.B
        }
        else {
          upper.B = upper.B
          lower.B = new.B
        }}

    new.B = mean(c(lower.B,upper.B))

    i = i+1
  }

}

Finite.step = function(point,h){

  f.x = f(point)
  f.x.h.min = f(point - h)
  f.x.h.pos = f(point + h)

  neg.step = (f.x - f.x.h.min)/h
  pos.step = (f.x.h.pos - f.x)/h

  return((c("f(x-h)"=neg.step,"f(x+h)"=pos.step,mean(c(neg.step,pos.step)))))

}

<file_sep># VNoptim

Preliminary routines for optimization package

languages: Markdown R

repo_name: OVVO-Financial/VNoptim


text:
<repo_name>ljw1412/development_platform<file_sep>/src/components/Result/index.vue
<template>

      <slot name="image">

        <el-image v-else
          fit="contain"
          :src="icon">
        </el-image>
      </slot>

      <slot name="title">{{title}}</slot>

      <slot name="subTitle">{{subTitle}}</slot>

</template>

<file_sep>/src/views/Main/PM2/Details/index.vue
<template>

    <process-info v-bind="process"
      disableTitleClick>
    </process-info>

        实时日志

          <el-button type="danger"
            size="mini"
            @click="logList = []">清空</el-button>
          <el-button type="primary"
            size="mini"
            @click="onSaveLogClick">保存</el-button>

{{log}}

</template>

<file_sep>/src/views/Main/Personal/index.vue
<template>

    <transition name="el-zoom-in-center">
      <id-card v-show="isDisplayIdCard"
        class="personal__card"
        :user="user"
        @editClick="onEditClick"></id-card>
    </transition>
    <transition name="el-zoom-in-center">
      <info-card v-show="isDisplayInfoCard"
        class="personal__card"
        :user="user"
        @back="onCardBack"
        @change="onInfoChange"></info-card>
    </transition>
    <transition name="el-zoom-in-center">
      <password-card v-show="isDisplayPasswordCard"
        id="password-card"
        class="personal__card"
        @back="onCardBack"></password-card>
    </transition>
    <transition name="el-zoom-in-center">
      <avatar-card v-show="isDisplayAvatarCard"
        class="personal__card"
        @back="onCardBack"></avatar-card>
    </transition>

</template>

<file_sep>/src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from './user'
import layout from './layout'

Vue.use(Vuex)

const defaultStore = {}

defaultStore.modules = {
  user,
  layout
}

export default new Vuex.Store(defaultStore)
<file_sep>/src/views/Main/Setting/index.vue
<template>

    <router-view style="height: 100%;" />

</template>

<file_sep>/src/components/MDEditor/config.js
export const toolbarButtons = [
  'undo',
  'redo',
  '|',
  'bold',
  'italic',
  'heading',
  'strikethrough',
  '|',
  // 'heading-smaller',
  // 'heading-bigger',
  // 'heading-1',
  // 'heading-2',
  // 'heading-3',
  // '|',
  'unordered-list',
  'ordered-list',
  '|',
  'quote',
  'code',
  'table',
  'link',
  'image',
  'horizontal-rule',
  '|',
  // 'clean-block',
  // '|',
  'preview',
  'side-by-side',
  'fullscreen',
  '|',
  'guide'
]
<file_sep>/src/views/Main/Project/Details/components/Advanced.vue
<template>

    <el-collapse accordion
      @change="onCollapseChange">
      <el-collapse-item name="1">

重命名项目 / Rename project

        <el-form ref="renameForm"
          class="rename-form"
          :model="renameForm">
          <el-form-item label="项目名称"
            prop="name"
            :rules="{required: true,trigger: 'blur',message: '请输入新项目名称'}">
            <el-input v-model="renameForm.name"
              placeholder="请输入新的项目名称"
              maxlength="30"
              show-word-limit></el-input>
          </el-form-item>
          <el-form-item>

修改项目名称不会修改项目最终路径

          </el-form-item>
          <el-button type="warning"
            @click="onRenameClick">修改</el-button>
        </el-form>
      </el-collapse-item>
      <el-collapse-item name="2">

删除项目 / Remove project

删除项目将会……(现在还没想好)

          <el-button type="danger"
            @click="isDisplayDeleteDialog = true">删除</el-button>

      </el-collapse-item>
    </el-collapse>

    <el-dialog title="警告"
      class="delete-dialog"
      :visible.sync="isDisplayDeleteDialog"
      @open="onDeleteDialogOpen">

将要删除 {{project.name}}。删除后将无法恢复！确定执行此操作？

此操作可能导致数据丢失。为了防止意外行为，我们要求您确认您的意图。
请输入 {{project.name}} 以继续，或关闭弹窗来取消。

      <el-input v-model="deleteForm.name"></el-input>
      <el-button type="danger"
        slot="footer"
        :disabled="isDisabledDelete"
        @click="reDelProject">删除</el-button>
    </el-dialog>

</template>

<file_sep>/src/theme/index.scss
@import './var.scss';
@import '~element-ui/packages/theme-chalk/src/common/var.scss';
@import './mixin.scss';
<file_sep>/src/views/Main/components/PlatformNavbar.vue
<template>
  <el-menu ref="menu"
    class="menu"
    unique-opened
    :default-active="activeIndex"
    :collapse="isCollapsed">

        研发管理平台

    <template v-for="item of menuList">
      <el-submenu v-if="item.children && item.children.length"
        :key="item.id"
        :index="item.id">
        <template slot="title">

          {{item.title}}
        </template>
        <el-menu-item v-for="el of item.children"
          :key="el.id"
          :index="el.route.name"
          @click="onMenuItemClick(el,item)">

          {{el.title}}
        </el-menu-item>
      </el-submenu>
      <el-menu-item v-else
        :key="item.id"
        :index="item.route.name"
        @click="onMenuItemClick(item)">

        {{item.title}}
      </el-menu-item>
    </template>
  </el-menu>
</template>

<file_sep>/src/inject.js
import Vue from 'vue'
import VScrollbar from '@/components/VScrollbar'
import BaseListLayout from '@/components/layout/BaseListLayout'
import ECharts from '@/components/ECharts'
import Result from '@/components/Result'
import ElementUI from 'element-ui'
import '@/theme/element-variables.scss'
import '@/theme/global.scss'
import callApi from './utils/api'
import Store from 'store'
import expirePlugin from 'store/plugins/expire'

Vue.prototype.$callApi = callApi

Vue.use(ElementUI, { size: 'small' })

Vue.component('Scrollbar', VScrollbar)
Vue.component('BaseListLayout', BaseListLayout)
Vue.component('ECharts', ECharts)
Vue.component(Result.name, Result)

Store.addPlugin(expirePlugin)
window.Store = Store
<file_sep>/src/views/Main/Project/Details/components/Publish/Edit.vue
<template>
  <el-drawer size="90%"
    direction="btt"
    :visible.sync="mVisible">

编辑发布流程 - {{flow.name}}

    <base-list-layout class="pubish-edit">

        <el-tooltip v-for="item of actionList"
          effect="dark"
          placement="top"
          :content="item.name"
          :key="item.type">
          <el-link :icon="item.icon"
            :underline="false"
            @click="onActionClick(item.type)"></el-link>
        </el-tooltip>

        <node-editor :node-list="nodeList"></node-editor>

        <el-button type="primary">保存</el-button>

    </base-list-layout>

    <el-dialog append-to-body
      title="添加节点"
      width="500px"
      :visible.sync="isDisplayAddNodeDialog"
      @close="onAddNodeClose">
      <el-form ref="nodeForm"
        :model="node">
        <el-form-item label="节点名称"
          prop="name"
          :rules="[
            { required: true, max:16, message: '节点名称不能为空，最多16个字符'}
          ]">
          <el-input v-model="node.name"
            placeholder="请输入节点名称(最多16个字符)"></el-input>
        </el-form-item>
        <el-form-item label="节点指令"
          prop="code"
          :rules="{ required: true, message: '节点指令不能为空'}">
          <el-input v-model="node.code"
            type="textarea"
            :autosize="{ minRows: 5, maxRows: 10}"></el-input>
        </el-form-item>
      </el-form>
      <el-button slot="footer"
        type="primary"
        @click="addNode">添加</el-button>
    </el-dialog>
  </el-drawer>
</template>

<file_sep>/src/views/Main/Personal/components/PasswordCard.vue
<template>
  <base-card title="密码修改"
    @back="onBack">
    <el-form :model="user"
      ref="form"
      class="form"
      hide-required-asterisk
      label-width="80px">
      <el-form-item label="当前密码"
        prop="password"
        :rules="{required: true,trigger: 'blur',message: '请输入当前密码'}">
        <el-input v-model="user.password"
          type="password"
          placeholder="请输入当前密码"></el-input>
      </el-form-item>
      <el-form-item label="修改密码"
        prop="modifyPassword"
        :rules="{min: 6,required: true,trigger: 'blur',
          message: '请输入字符长度大于 6 的密码'}">
        <el-input v-model="user.modifyPassword"
          type="password"
          placeholder="请输入修改密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码"
        prop="confirmPassword"
        :rules="{ validator: validatePass, trigger: 'blur' }">
        <el-input v-model="user.confirmPassword"
          type="password"
          placeholder="请再次输入修改密码"></el-input>
      </el-form-item>

        {{error}}
        <el-button type="primary"
          icon="el-icon-refresh"
          @click="onSubmit">修改</el-button>

    </el-form>
  </base-card>
</template>

<file_sep>/src/views/Main/Personal/components/cardFormStyle.scss
.form {
  padding: 20px 30px;
  /deep/ .el-form-item__label {
    color: #fff;
  }
  /deep/ .el-input input {
    padding: 0;
    border-width: 0 0 1px 0;
    border-radius: 0;
    background-color: transparent;
    height: 24px;
    color: #ccc;
    transition: background-color 0.4s;
    &:focus {
      background-color: rgba($color: #fff, $alpha: 0.2);
    }
  }
  &__error {
    color: #f56c6c;
    margin-right: 10px;
  }
  &__footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}
<file_sep>/src/views/Main/components/PlatformHeader/ProfileInfo.vue
<template>
  <el-dropdown size="medium"
    :show-timeout="100"
    @command="onCommand">

      <el-avatar class="profile-info__avatar"
        :size="32"></el-avatar>

{{username}}

    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item icon="el-icon-user-solid"
        command="personal">个人中心</el-dropdown-item>
      <el-dropdown-item divided
        icon="el-icon-error"
        command="logout">退出</el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<file_sep>/src/components/VScrollbar.vue
<template>

      <slot></slot>

</template>

<file_sep>/src/views/Main/FileBrowser/index.vue
<template>

    <file-manager></file-manager>

</template>

<file_sep>/src/App.vue
<template>

    <transition name="el-fade-in-linear">
      <router-view />
    </transition>

</template>

<file_sep>/src/views/Main/Home/components/ServerState.vue
<template>
  <session-card class="server-state">
    <template #header>状态</template>

内存

      <el-progress type="dashboard"
        :percentage="memoryPercentage"
        :color="colors"></el-progress>

CPU

      <el-progress type="dashboard"
        :percentage="cpuPercentage"
        :color="colors"></el-progress>

平均负载

          {{item.label}}:
          {{item.value.toFixed(2)}}

  </session-card>
</template>

<file_sep>/src/views/Login/LoginCard.vue
<template>
  <el-card class="card-login"
    shadow="hover"
    :body-style="{padding:'50px 56px'}">
    <el-form ref="form"
      :model="user">
      <el-form-item prop="username"
        :rules="{ required: true, message: '登录名不能为空'}">
        <el-input v-model="user.username"
          ref="username"
          type="text"
          size="large"
          placeholder="请输入用户名或邮箱"
          prefix-icon="el-icon-user"
          @keydown.native.enter="$refs.password.focus()"></el-input>
      </el-form-item>
      <el-form-item prop="password"
        :rules="{ required: true, message: '登录密码不能为空'}">
        <el-input v-model="user.password"
          ref="password"
          size="large"
          type="password"
          prefix-icon="el-icon-key"
          placeholder="请输入登录密码"
          show-password
          @keydown.native.enter="onLoginClick"></el-input>
      </el-form-item>

        <el-button v-if="false"
          class="btn-login"
          size="large"
          @click="onGuestClick">游客登录</el-button>
        <el-button class="btn-login"
          type="primary"
          size="large"
          @click="onLoginClick">用户登录</el-button>

    </el-form>
  </el-card>
</template>

<file_sep>/src/components/layout/BaseListLayout.vue
<template>

      <slot name="action"></slot>

      <slot></slot>

      <slot name="footer"></slot>

</template>

<file_sep>/src/views/Main/Setting/MenuEdit/index.vue
<template>

    <el-button type="danger"
      @click="onResetClick">重新生成菜单</el-button>
    <quill-editor v-model="html"></quill-editor>

    <md-editor v-model="markdown"></md-editor>

</template>

<file_sep>/src/views/Main/Project/Create/components/ProjectComplete.vue
<template>

    <result title="项目创建成功"
      icon="el-icon-circle-check"
      icon-color="#67C23A">
      <template #subTitle>
        {{id?'进入项目':'返回列表'}}
      </template>
    </result>

</template>

<file_sep>/src/views/Main/Project/List/index.vue
<template>
  <base-list-layout class="project main-content-wrapper">
    <template #action>
      <el-button type="primary"
        @click="$router.push({name:'projectCreate'})">创建项目</el-button>
    </template>

    <el-table :data="projectList"
      :show-header="!!projectList.length"
      :row-style="{cursor: 'pointer'}"
      @row-click="onRowClick">
      <result v-if="isLoaded"
        slot="empty"
        title="您还未创建任何项目"
        iconHeight="200px"
        style="padding:40px 0;"
        :icon="require('@/assets/no-data.svg')"></result>
      <el-table-column label="名称"
        prop="name"></el-table-column>
      <el-table-column label="源">

          <el-image v-if="scope.row.origin === 'git'"
            style="width:22px;height:22px;"
            :src="require('@/assets/icon-git.svg')"></el-image>

      </el-table-column>
      <el-table-column label="状态">

          {{getProjectStateStr(scope.row.state)}}
      </el-table-column>
    </el-table>
  </base-list-layout>
</template>

<file_sep>/src/store/layout.js
// 遍历菜单查找当前路由名称的标题
function findMenu(list, name) {
  for (let i = 0; i < list.length; i++) {
    const menu = list[i]
    let title = menu.title
    if (menu.route.name === name) return title
    if (menu.children && menu.children.length) {
      let subTitle = findMenu(menu.children, name)
      if (subTitle) return title + ' / ' + subTitle
    }
  }
  return ''
}

const getTitleFromStorage = routeName => {
  const menu = Store.get('menu')
  if (!menu) return ''
  return findMenu(menu, routeName)
}

const defaultState = () => {
  return {
    isMenuCollapsed: true,
    /* 用于 PageHeader */
    // 控制是否为返回模式，如果为 false 者返回首页
    isBack: false,
    title: ''
  }
}

export default {
  namespaced: true,
  state: defaultState(),
  getters: {},
  mutations: {
    clearLayout(state) {
      Object.assign(state, defaultState())
    },
    updateLayout(state, layout) {
      Object.assign(state, layout)
      Store.set('layout', state)
    }
  },
  actions: {
    // 同步界面布局
    syncLayout({ commit }, routeName) {
      let layout = Store.get('layout')
      if (layout) {
        if (routeName) layout.title = getTitleFromStorage(routeName)
        Object.assign(layout, {
          isBack: false
        })
        commit('updateLayout', layout)
      } else {
        commit('clearLayout')
      }
    },
    // 根据路由同步界面标题
    syncTitle({ commit }, routeName) {
      commit('updateLayout', { title: getTitleFromStorage(routeName) })
    },
    // 修改标题
    updateTitle({ commit }, data) {
      commit('updateLayout', typeof data === 'string' ? { title: data } : data)
    },
    // 更新菜单栏折叠状态
    updateMenuCollapsed({ commit }, isCollapsed) {
      commit('updateLayout', { isMenuCollapsed: isCollapsed })
    }
  }
}
<file_sep>/src/views/Main/PM2/List/index.vue
<template>

      当前进程数:{{count}}
      使用内存:{{totalUsedMemory}}
      CPU使用率:{{totalUsedCpu}}

    <process-info v-for="item of list"
      v-bind="item"
      :key="item.pmid"
      @stateChange="onProcessStateChange"></process-info>

</template>

<file_sep>/src/views/Main/Project/Details/components/Info.vue

<template>

{{project.description}}

    <el-form label-width="100px">
      <el-form-item v-for="info of infoList"
        :key="info.key"
        :label="info.label">{{info.value}}</el-form-item>
      <el-form-item v-if="project.origin === 'git'"
        label="当前分支">{{project.status.current}}</el-form-item>
    </el-form>

</template>

<file_sep>/src/store/user.js
// 默认 State
const defaultState = () => {
  return {
    id: '',
    username: '',
    nickname: '',
    token: ''
  }
}

export default {
  namespaced: true,
  state: defaultState(),
  getters: {},
  mutations: {
    // 更新用户信息
    updateUser(state, user) {
      Object.assign(state, user)
    },

    //清除用户信息
    clearUser(state) {
      Object.assign(state, defaultState())
    }
  },
  actions: {
    // 同步用户信息
    syncUser({ commit }) {
      const user = Store.get('user')
      if (user) {
        commit('updateUser', user)
      } else {
        commit('clearUser')
      }
    }
  }
}
<file_sep>/src/components/ImageEditor/index.vue
<template>

</template>

<file_sep>/src/views/Main/Project/Create/index.vue
<template>
  <base-list-layout class="project-create"
    :class="wrapperClasses">
    <template #action>
      <el-steps simple
        :active="activeIndex">
        <el-step v-for="(step,index) of stepList"
          :key="mode+'-'+index"
          :title="step.title"
          :icon="step.icon"></el-step>
      </el-steps>
    </template>

    <component :is="currentComponent"
      :id="id"></component>

  </base-list-layout>
</template>

<file_sep>/src/components/QuillEditor/index.vue
<template>

</template>

<file_sep>/src/views/Login/index.vue
<template>

      <login-card></login-card>

</template>

<file_sep>/src/views/Main/Home/components/ServerInfo.vue
<template>
  <session-card class="server-info">

        {{ hostname }}

        系统: {{ os }}

        不间断运行时间: {{formatUptime}}

  </session-card>
</template>

<file_sep>/src/views/Main/components/PlatformHeader/index.vue
<template>

      <page-title class="page-title"></page-title>

      <profile-info></profile-info>

</template>

<file_sep>/src/views/Main/Personal/components/BaseCard.vue
<template>
  <el-card class="base-card"
    shadow="hover"
    :body-style="{padding:0, height:'100%'}">

      {{title}}

    <slot></slot>
  </el-card>
</template>

<file_sep>/src/utils/api.js
import Vue from 'vue'
import axios from 'axios'
import url from 'url'
import qs from 'qs'
const vue = new Vue()

const methodList = ['get', 'post', 'put', 'patch', 'options', 'head', 'delete']

const locationUrl = url.parse(window.location.origin)
const base = locationUrl.protocol + '//' + locationUrl.hostname

console.log(process.env)

axios.defaults.baseURL = `${base}:3333/`
axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded; charset=UTF-8'
axios.defaults.timeout = 20000
axios.defaults.withCredentials = true

function printError({ method, api, param, config, error }) {
  console.error(`${method.toUpperCase()} ["${api}"] 调用失败: ${error.message}`)
  console.log(JSON.stringify({ api, param, config }, null, 2))
}

// dispose request parameters
function disposeParam(method, param) {
  switch (method) {
    case 'get':
      return { params: param }
    case 'post':
      return qs.stringify(param)
  }
  return param
}

const callApi = ({
  method = 'get',
  api,
  param,
  config = {},
  noNotify = false
} = {}) => {
  const $ = axios.create(config)
  if (!methodList.includes(method.toLowerCase())) {
    method = methodList[0]
  }
  const mParam = disposeParam(method, param)
  return $[method](api, mParam)
    .then(data => {
      return Promise.resolve(data.data)
    })
    .catch(error => {
      printError({ method, api, param, config, error })
      error =
        (error.response && error.response.data && error.response.data.error) ||
        error.message
      if (error.includes('Network Error')) {
        error = '服务器异常! /(ㄒoㄒ)/~~'
      }
      if (!noNotify) {
        vue.$notify.error({
          title: '错误',
          message: error
        })
      }
      return Promise.reject(error)
    })
}

export default callApi
<file_sep>/src/views/Main/Project/helper.js
export function getProjectStateStr(state) {
  const map = {
    0: '未初始化',
    1: '初始化中',
    2: '正常',
    3: '存在错误'
  }
  return map[state]
}
<file_sep>/src/views/Main/Personal/components/IdCard.vue
<template>
  <base-card>

{{ user.nickname || '无名氏'}}

用户名：{{ user.username }}

邮箱：{{ user.email }}

创建时间：{{ user.createDateTime }}

修改时间：{{ user.updateDateTime }}

最近登陆：{{ user.lastLoginDateTime }}

{{ user.roleName || '无身份'}}

      <el-collapse-transition>

修改信息

修改密码

      </el-collapse-transition>

  </base-card>
</template>

<file_sep>/src/views/Main/Project/Details/components/Publish/NodeEditor.vue
<template>

    <template v-for="(node,index) of nodeList">

        <el-tooltip effect="dark"
          placement="top"
          :content="node.name+':'+node.code">
          {{node.name}}
        </el-tooltip>

    </template>

</template>

<file_sep>/src/views/Main/PM2/helper.js
const tagLabelList = ['watch', 'protect']

function getStatusType(status) {
  const map = {
    online: 'success',
    stopping: 'info',
    stopped: 'info',
    launching: '',
    'one-launch-status': '',
    errored: 'danger'
  }
  return map[status] || 'warning'
}

export function setTags(obj) {
  obj.tags = []
  tagLabelList.forEach(label => {
    if (obj[label]) obj.tags.push({ label, type: '' })
  })
  obj.tags.push({
    label: obj.status,
    type: getStatusType(obj.status)
  })
  return obj
}
<file_sep>/src/views/Main/Home/components/SessionCard.vue
<template>

      <slot name="header"></slot>

    <slot></slot>

</template>

<file_sep>/src/components/ECharts/index.vue
<template>

</template>

<file_sep>/src/views/Main/index.vue
<template>

    <platform-navbar></platform-navbar>
    <platform-header></platform-header>
    <main :class="`sidebar--${isMenuCollapsed?'fold':'unfold'}`">
      <router-view></router-view>

</template>

<file_sep>/src/views/Main/Project/Create/components/ProjectCreator.vue
<template>

    <el-form :model="project"
      ref="form"
      label-position="top"
      status-icon
      hide-required-asterisk>
      <el-form-item label="来源"
        class="project-creator__origin">
        <el-radio-group v-model="project.origin"
          size="medium"
          @change="onOriginChange">
          <el-radio-button label="git"></el-radio-button>
          <el-radio-button label="custom"></el-radio-button>
        </el-radio-group>
      </el-form-item>
      <template v-if="project.origin">
        <el-form-item v-if="isFromGit"
          label="git仓库地址"
          prop="git"
          :rules="[{ validator: isGitUrl, trigger: 'blur' }]">
          <el-input v-model="project.git"
            placeholder="请输入git仓库地址"></el-input>
        </el-form-item>
        <el-form-item label="项目名称"
          ref="projectName"
          prop="name"
          :rules="[
            { required: true, message: '请输入项目名称', trigger: 'blur' },
            { max:30, message:'名称最多为 30 字', trigger: 'blur' }
          ]">
          <el-input v-model="project.name"
            maxlength="30"
            show-word-limit
            placeholder="请输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="项目目标文件夹"
          ref="dirPathInput"
          prop="dirPath"
          :rules="[{ validator: isExists, trigger: 'blur' }]">
          <el-input v-model="project.dirPath"
            placeholder="请输入项目目标文件夹">
            <el-button slot="append"
              type="primary"
              @click="isDisplayDrawer = true">浏览</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="项目实际路径">
          <el-input :value="finalProjectPath"
            disabled
            placeholder="自动生成"></el-input>
        </el-form-item>
        <el-form-item label="项目描述(选填)">
          <el-input v-model="project.description"
            show-word-limit
            maxlength="200"
            type="textarea"
            rows="5"
            resize="none"></el-input>
        </el-form-item>

          <el-button type="primary"
            :loading="isSaving"
            @click="onCreateClick">创建</el-button>

      </template>
    </el-form>

    <el-drawer title="请选择文件夹"
      direction="rtl"
      class="file-manager-drawer"
      size="500px"
      :visible.sync="isDisplayDrawer">
      <file-manager onlyDir
        isSelect
        @selectChange="onFileManagerSelectChange"></file-manager>

{{selectedPath}}

        <el-button size="medium"
          @click="isDisplayDrawer = false">取消</el-button>
        <el-button size="medium"
          type="primary"
          @click="onDrawerSelectClick">选择</el-button>

    </el-drawer>

</template>

<file_sep>/src/views/Main/Setting/UserEdit/index.vue
<template>

      <el-input class="action__search"
        v-model="keyword"
        placeholder="请输入关键词(支持正则)">

      </el-input>
      <el-button class="action__button"
        type="primary"
        @click="onAddUserClick">新增</el-button>

    <el-table :data="userList">
      <el-table-column label="用户名"
        prop="username"></el-table-column>
      <el-table-column label="身份">
        <el-tag v-if="scope.row.roleName"
          slot-scope="scope"
          :type="scope.row.isSuperAdmin?'success':''">{{scope.row.roleName}}</el-tag>
      </el-table-column>
      <el-table-column label="昵称"
        prop="nickname"></el-table-column>
      <el-table-column label="邮箱"
        prop="email"></el-table-column>
      <el-table-column label="创建时间"
        prop="createDateTime"></el-table-column>
      <el-table-column label="最后登录时间"
        prop="lastLoginDateTime"></el-table-column>
      <el-table-column label="操作"
        width="100">

          <template v-if="!scope.row.isSuperAdmin">
            <el-button circle
              icon="el-icon-edit"
              @click="onEditClick(scope.row)"></el-button>
            <el-button circle
              type="danger"
              icon="el-icon-delete"
              @click="onDeleteClick(scope.row)"></el-button>
          </template>

      </el-table-column>
    </el-table>
    <user-edit-dialog ref="userEditDialog"
      v-model="isDisplayUserEditDialog"
      :isAdd="isAddUser"
      :roleList="roleList"
      @change="onUserChange"></user-edit-dialog>

</template>

<file_sep>/src/views/Main/PM2/components/ProcessInfo.vue
<template>

      {{name}}
      {{path}}

        <el-tag v-for="tag of tags"
          :key="tag.label"
          :type="tag.type">{{tag.label}}</el-tag>

{{item.label}}

{{item.value}}

操作

          <template v-for="item of actionList">
            <el-tooltip v-if="item.isDisplay"
              placement="bottom"
              :key="item.type"
              :content="item.label">

            </el-tooltip>
          </template>

</template>

<file_sep>/vue.config.js
const webpack = require('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
  .BundleAnalyzerPlugin

const isDevelopment = process.env.NODE_ENV !== 'production'
const isAnalyzer = process.env.npm_lifecycle_event === 'analyzer'

module.exports = {
  publicPath: isDevelopment ? '/' : '',
  productionSourceMap: false,
  devServer: {
    compress: true,
    port: 8998
  },
  configureWebpack: config => {
    const customConfig = {
      //警告 webpack 的性能提示
      performance: {
        hints: 'warning',
        //入口起点的最大体积
        maxEntrypointSize: 50000000,
        //生成文件的最大体积
        maxAssetSize: 30000000,
        //只给出 js 文件的性能提示
        assetFilter: function(assetFilename) {
          return assetFilename.endsWith('.js')
        }
      },
      plugins: [
        new webpack.BannerPlugin({
          banner: `Builder: ljw1412\nBuild time: ${new Date()}`
        }),
        new webpack.ProvidePlugin({
          moment: 'moment',
          Cookies: 'js-cookie'
        }),
        new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn/)
      ]
    }
    if (isAnalyzer) customConfig.plugins.push(new BundleAnalyzerPlugin())
    return customConfig
  }
}
<file_sep>/src/views/Main/Project/Details/components/Publish/index.vue
<template>

    <template v-if="publishList.length">

发布流程总数: {{publishList.length}}

          <el-link class="el-icon-plus"
            :underline="false"
            @click="onCreateClick" />
          <el-link :class="isEdit?'el-icon-close':'el-icon-setting'"
            :underline="false"
            @click="isEdit = !isEdit" />

{{item.name}}

              <el-link class="el-icon-edit"
                :underline="false"
                @click="onEditFlowClick(item)" />
              <el-link class="el-icon-delete"
                type="danger"
                :underline="false"
                @click="onDeleteFlowClick(item)" />

    </template>

    <result v-else-if="isLoaded"
      title="您还未创建任何发布流程"
      icon="el-icon-truck"
      icon-color="#606266">
      <template #subTitle>
        <el-link type="primary"
          @click="onCreateClick">
          立刻创建

        </el-link>
      </template>
    </result>

    <el-table border
      style="margin-top:10px;">
      <el-table-column label="发布名称"></el-table-column>
      <el-table-column label="信息"></el-table-column>
      <el-table-column label="状态"></el-table-column>
      <el-table-column label="操作"></el-table-column>
    </el-table>

    <edit :visible.sync="isDisplayEdit"
      :flow="currentFlow"></edit>

</template>

<file_sep>/src/views/Main/Personal/components/InfoCard.vue
<template>
  <base-card title="修改信息"
    @back="onBack">

      <el-form ref="form"
        class="form"
        hide-required-asterisk
        :model="userInfo">
        <el-form-item label="昵称"
          prop="nickname"
          :rules="{required: true,trigger: 'blur',message: '请输入昵称'}">
          <el-input v-model="userInfo.nickname"
            type="text"
            placeholder="请输入昵称（最多10个字符）"
            :maxlength="10" />
        </el-form-item>

          <el-button type="primary"
            @click="onSubmit">保存</el-button>

      </el-form>

  </base-card>
</template>

<file_sep>/src/views/Main/Home/index.vue
<template>

    <server-info v-bind="base"
      :uptime="state.uptime"></server-info>
    <server-state v-bind="state"></server-state>
    <cpu-info :cpus="state.cpus || []"></cpu-info>
    <network-info :network="state.networkInterfaces||{}"></network-info>

</template>

<file_sep>/src/components/MDEditor/index.vue
<template>

    <textarea ref="editor"
      class="md-editor"></textarea>

</template>

<file_sep>/src/views/Main/components/PageTitle.vue
<template>

    <transition name="collapse-left">

返回

    </transition>
    {{title}}

</template>

<file_sep>/src/views/Main/Project/Details/components/Timeline.vue
<template>

    <el-timeline>
      <el-timeline-item v-for="item of timelineList"
        hide-timestamp
        :key="item.id">

          {{item.time}}
          {{item.user.nickname || item.user.username}}

{{item.title}}

{{item.log}}

      </el-timeline-item>
    </el-timeline>

</template>

<file_sep>/src/theme/global.scss
.main-content-wrapper {
  padding: 16px 24px;
}

.fill-content-wrapper {
  box-sizing: border-box;
  height: 100%;
}

// 动画过渡效果
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}

// 覆盖 element 样式
.el-notification {
  word-break: break-all;
}
<file_sep>/src/components/FileManager/index.vue
<template>

    <el-breadcrumb class="file-manager__breadcrumb"
      separator="/">
      <el-breadcrumb-item v-for="(item,index) of pathList"
        :key="index"
        class="file-manager__breadcrumb-item"
        :class="{'isLast':(index === pathList.length - 1)}"
        @click.native="onNavClick(item)">{{item.name}}</el-breadcrumb-item>
    </el-breadcrumb>

    <el-table class="table"
      height="100%"
      :empty-text="isLoading?'加载中……':'该文件夹没有任何文件'"
      :data="fileList"
      :show-header="false"
      :highlight-current-row="isSelect"
      @row-click="onFileClick"
      @row-dblclick="onFileDblclick">
      <el-table-column label="名称">
        <template #default="scope">

            <el-image fit="contain"
              class="table__file-icon"
              :src="getFileIcon(scope.row)"></el-image>
            {{scope.row.name}}

        </template>
      </el-table-column>
    </el-table>

</template>

<file_sep>/src/views/Main/PM2/components/DetailsCharts.vue
<template>
  <e-charts :option="cpuChartsOption"
    height="300px"></e-charts>
</template>

<file_sep>/src/views/Main/Home/components/NetworkInfo.vue
<template>
  <session-card class="network-info">
    <template #header>网络接口</template>
    <el-tabs tab-position="left">
      <el-tab-pane v-for="( list, name ) of mNetwork"
        :key="name"
        :label="name">

<template v-for="item of list">{{item}}</template>

      </el-tab-pane>
    </el-tabs>
  </session-card>
</template>

<file_sep>/src/views/Main/Personal/components/AvatarCard.vue
<template>
  <base-card title="修改头像"
    @back="onBack">
    <el-upload v-if="!imageUrl"
      drag
      action="#"
      class="upload"
      :show-file-list="false"
      :auto-upload="false"
      :on-change="onUploadChange">

点击上传，或将文件拖到此处

只能上传jpg/png文件，且不超过500kb

    </el-upload>

      <image-editor :image-src="imageUrl"
        @preview="onImagePreview"></image-editor>
      <el-button type="primary"
        size="mini"
        @click="imageUrl =''">重新上传</el-button>

  </base-card>
</template>

<file_sep>/src/views/Main/Project/Details/index.vue
<template>
  <base-list-layout class="project-details">
    <template #action>

        <el-col class="project-details__title"
          :span="18">
          {{project.name}}
          <el-image v-if="project.origin === 'git'"
            style="width:22px;height:22px;"
            :src="require('@/assets/icon-git.svg')"></el-image>
        </el-col>
        <el-col class="project-details__action"
          :span="6">
          {{project.stateStr}}
          <el-button v-if="project.origin === 'git'&& project.state === 0"
            type="primary"
            size="mini"
            :loading="isIniting"
            @click="onInitClick">初始化</el-button>
        </el-col>

      <el-tabs v-model="currentTab"
        type="card">
        <el-tab-pane v-for="tab of tabList"
          :key="tab.name"
          :label="tab.label"
          :name="tab.name">
        </el-tab-pane>
      </el-tabs>
    </template>

    <component v-if="isLoaded"
      :is="currentComponent"
      :project="project"
      @nameChange="reFindProject"></component>
  </base-list-layout>
</template>

<file_sep>/src/views/Main/Setting/UserEdit/UserEditDialog.vue
<template>
  <el-dialog width="400px"
    :visible="value"
    :title="title"
    @close="$emit('input',false)">
    <el-form ref="form"
      class="form-user"
      label-position="right"
      label-width="70px"
      :model="user"
      :rules="ruleList">
      <el-form-item label="用户名"
        prop="username">
        <el-input v-model="user.username"
          placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item v-if="isAdd"
        label="密码"
        prop="password">
        <el-input v-model="user.password"
          type="<PASSWORD>"
          show-password
          placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item v-else
        label="密码">
        <el-input v-model="user.password"
          type="<PASSWORD>"
          show-password
          placeholder="如果要修改密码请填写"></el-input>
      </el-form-item>
      <el-form-item label="邮箱"
        prop="email">
        <el-input v-model="user.email"
          type="email"
          placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="权限"
        prop="role">
        <el-select v-model="user.role"
          style="width:100%;"
          placeholder="请选择权限">
          <el-option v-for="role of roleList"
            :key="role.id"
            :value="role.id"
            :label="role.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="user.nickname"
          placeholder="请输入昵称(选填)"></el-input>
      </el-form-item>

        <el-button @click="$emit('input',false)">取消</el-button>
        <el-button type="primary"
          @click="submit">保存</el-button>

    </el-form>
  </el-dialog>
</template>

<file_sep>/src/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './inject'

Vue.config.productionTip = false
// 禁止在定时里跑，当开两个页面的时候，定时任务会影响另一个页面的正常界面状态
Vue.prototype.$setPageTitle = data => {
  store.dispatch('layout/updateTitle', data)
}

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

router.beforeResolve((to, from, next) => {
  if (to.name !== from.name) {
    store.dispatch('user/syncUser')
    store.dispatch('layout/syncLayout', to.name)
  }
  next()
})

router.afterEach((to, from) => {
  if (!Cookies.get('token')) router.replace({ name: 'login' })
})
<file_sep>/src/views/Main/Home/components/CpuInfo.vue
<template>
  <session-card class="cpu-info">
    <template #header>CPU状态</template>

#{{index}}: {{ cpu.model }}

          <span v-for="(time,name) in cpu.times"
            :key="`${name}-${index}`">
            {{name}}:{{time}}

  </session-card>
</template>

<file_sep>/src/views/Main/Project/Create/components/ModeChoise.vue
<template>

    <el-card class="select-card"
      shadow="hover"
      @click.native="onModeCardClick('create')">

新建项目

从头开始创建项目

    </el-card>
    <el-card class="select-card"
      shadow="hover"
      @click.native="onModeCardClick('import')">

导入项目

导入服务器现有的项目

    </el-card>

</template>

languages: SCSS Vue JavaScript

repo_language: SCSS


text:
<repo_name>liymax/mycommand<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.3)
project(mycommand)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES  hello.c cat/cat.c cp/cp.c ls/ls.c rm/rm.c)
add_executable(mycommand ${SOURCE_FILES})<file_sep>/rm/rm.c
#include <stdio.h>

int main(int argc,char** argv)
{
    for(int i=1;i<argc;i++){
        if(remove(argv[i])!=0){
            perror("remove");
        }
    }
    return 0;
}
<file_sep>/cp/cp.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

char* join(char *s1,char *s2){
    char *result = malloc(strlen(s1)+strlen(s2)+1);
    if(result == NULL) exit(1);
    strcpy(result,s1);
    strcat(result,s2);
    return result;
}

int main(int argc,char** argv)
{
    if(argc!=3){
        printf("参数错误!");
        return 0;
    }
    FILE *sfp,*dfp;
    int c;
    sfp=fopen(argv[1],"rb");

    struct stat buf;
    stat(argv[2],&buf);
    if(_S_IFDIR & buf.st_mode){
        char *separate="\\";
        char *tmp_name=join(separate,argv[1]);
        char *file_path=join(argv[2],tmp_name);
        dfp=fopen(file_path,"wb");
    } else{
        dfp=fopen(argv[2],"wb");
    }

    if(sfp==NULL || dfp==NULL){
        printf("open file failed!");
        if(sfp) fclose(sfp);
        if(dfp) fclose(dfp);
        return 0;
    }else{
        while((c=fgetc(sfp))!=EOF){
            fputc(c,dfp);
        }
        fclose(sfp);
        fclose(dfp);
    }
    return 0;
}

<file_sep>/hello.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/*long factorial(int n){
    return n==1?1:n*factorial(n-1);
}*/
char* join(char *s1,char *s2){
    char *result = malloc(strlen(s1)+strlen(s2)+1);
    if(result == NULL) exit(1);
    strcpy(result,s1);
    strcat(result,s2);
    return result;
}

int main()
{
    /*FILE *fp=NULL;
    int ch;
    fp=fopen("show.txt","r+");
    if(fp==NULL){
        return 0;
    }
    ch=getc(fp);
    while(ch!=EOF){
        putchar(ch);
        ch=getc(fp);
    }

    char str[] ="liyang";
    for(int i=0;i<strlen(str);i++){
        putc(str[i],fp);
    }
    fclose(fp);*/

    //char *separate="\\";
   /* char *hel="hello";
    printf("%s",join("\\",hel));*/
    FILE *fp;
    char str[22];
    if((fp=fopen("History.xml","r"))==NULL){
        printf("open file failed！\n");exit(1);
    }
    char *ret=fgets(str,22,fp);
    printf("%d\n",ret==str);
    while(ret){
        printf("%s",ret);
        ret=fgets(str,22,fp);
    }
    fclose(fp);
    return 0;
}

<file_sep>/cat/cat.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

int isDir(char *str){
    struct stat buf;
    stat(str,&buf);
    if(_S_IFDIR & buf.st_mode){
        return 1;
    } else{
        return 0;
    }
}
int main(int argc,char** argv)
{
    if(isDir(argv[1])){
        printf("file is dir!\n");exit(1);
    }
    FILE *fp;
    char str[22];
    if(argv[1]==NULL) exit(1);
    if((fp=fopen(argv[1],"r"))==NULL){
        printf("open file failed\n");exit(1);
    }
    while(!feof(fp)){
        fgets(str,22,fp);
        printf("%s",str);
    }
    fclose(fp);
}

<file_sep>/ls/ls.c
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>

int isDir(char *str){
    struct stat buf;
    stat(str,&buf);
    if(_S_IFDIR & buf.st_mode){
        return 1;
    } else{
        return 0;
    }
}
int main(int argc,char** argv)
{
    DIR *dir;
    struct dirent *ptr;
    int n=0;
    char *dir_name="./";
    if(argv[1]!=NULL) dir_name=argv[1];
    if(!isDir(dir_name)){
        printf("file can't show list!\n");exit(1);
    }
    dir=opendir(dir_name);
    while ((ptr=readdir(dir))!=NULL){
        const char *s1=".";
        const char *s2="..";
        if(strcmp(s1,ptr->d_name)!=0 && strcmp(s2,ptr->d_name)!=0 ){
            printf("  %s ",ptr->d_name); n++;
        }
        if(n!=0 && n%8==0){
            printf("\n");
        }
    }
    closedir(dir);
    return 0;
}

languages: C CMake

repo_language: C

repo_name: liymax/mycommand


text:
<file_sep>name := "play-crate"

organization := "io.crate"

version := "1.0"

scalaVersion := "2.11.1"

libraryDependencies ++= Seq(
  "com.typesafe.play" %% "play" % "2.3.3" % "provided",
  "io.crate" %% "crate-scala" % "1.0"
)

resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"<file_sep># Play Crate

A Play plugin for the [Crate](https://crate.io) Scala driver, making it really easy to get started with Crate in Play.

## Get started

Add the following dependency to your build.sbt

	"io.crate" %% "play-crate" % "1.0"

Add the following to conf/play.plugins (create it if it doesn't exist)

	300:io.crate.client.CratePlugin

Add the following to your conf/application.conf to specify the server addresses

	crate.servers = ["localhost:4300"]

## Usage

An example:

	import io.crate.client.CratePlugin

	lazy val client = CratePlugin.client

	val request = client.sql("SELECT * FROM sys.nodes").map { response =>
		println("Crate Nodes: " + response.cols.length)
	}

	// Blocking for example only
	Await.result(request, 5 seconds)

## Building

This project requires SBT to compile.

	$ sbt clean compile

## Publishing

Currently you can publish to your local ivy repo to include as a dependency.

	$ sbt publish-local<file_sep>package io.crate.client

import scala.collection.JavaConverters._

import play.api._

class CratePlugin(application: Application) extends Plugin {

  private var started = false

  val DefaultHost = "localhost:4300"

  lazy val client = {
    import com.typesafe.config.ConfigFactory
    val config = ConfigFactory.load()
    val servers = Option(config.getStringList("crate.servers")) match {
      case Some(list) => list.asScala.toArray
      case None => Array(DefaultHost)
    }
    val client = ReactiveCrateClient(servers: _*)
    started = true
    Logger.info("Crate Plugin has started")
    client
  }

  override def onStart {
    client
  }

  override def onStop {
    if (started && Play.current.mode != Mode.Test) {
      client.close()
      Logger.info("Crate Plugin has stopped")
    }
  }
}

object CratePlugin {

  def client(implicit app: Application) = current.client

  def current(implicit app: Application): CratePlugin = app.plugin[CratePlugin] match {
    case Some(plugin) => plugin
    case _ => throw new PlayException("CratePlugin Error", "The CratePlugin has not been initialized! Please edit your conf/play.plugins file and add the following line: '300:io.crate.client.CratePlugin' (300 is an arbitrary priority and may be changed to match your needs).")
  }

}

languages: Markdown Scala

repo_name: alexanderjarvis/play-crate


text:
<file_sep>#!/usr/bin/env python

class Hostname(object):

	def __init__(self, module):
		self.name = module.params['name']
		self.file = '/etc/hostname'
		self.err = None

	def set(self, name):
		try:
			file = open(self.file, 'w')
			file.write(self.name)
			file.close()
		except IOError as e:
			self.err = 'Cannot open {}'.format(self.file)
			return False
		return True

def main():

	module = AnsibleModule(
		argument_spec = dict(
			name = dict(required=True),
		)
	)

	host = Hostname(module)

	if host.set(host.name):
		module.exit_json(changed=True)

	module.fail_json(name=host.name, msg=host.err)

from ansible.module_utils.basic import *
main()

repo_language: Python

repo_name: rsicart/ansible-hostname